From 1f825d3c23474a9cb88aaca4df9b21bcc6eb3a5e Mon Sep 17 00:00:00 2001 From: Joseph Petersen Date: Wed, 12 Jan 2022 22:16:35 +0100 Subject: [PATCH] use ESM and update most dependencies (#1003) --- .eslintrc | 9 +- .github/workflows/tests.yml | 3 +- .vscode/launch.json | 36 +- action.js | 10 +- action.yml | 2 +- bin/generate-fixtures.js | 15 +- bin/generate-schema.js | 24 +- dist/index.js | 185087 ++++++++++++++------------------ dist/package.json | 3 + index.js | 66 +- lib/commits.js | 16 +- lib/config.js | 21 +- lib/default-config.js | 6 +- lib/log.js | 2 +- lib/pagination.js | 12 +- lib/releases.js | 92 +- lib/schema.js | 22 +- lib/sort-pull-requests.js | 19 +- lib/template.js | 51 +- lib/triggerable-reference.js | 14 +- lib/utils.js | 6 +- lib/versions.js | 44 +- output.log | 22 + package.json | 48 +- test/config.test.js | 9 +- test/helpers/config-mock.js | 17 +- test/index.test.js | 643 +- test/pagination.test.js | 17 +- test/releases.test.js | 4 +- test/schema.test.js | 17 +- test/template.test.js | 2 +- test/versions.test.js | 7 +- yarn.lock | 3491 +- 33 files changed, 80306 insertions(+), 109531 deletions(-) create mode 100644 dist/package.json create mode 100644 output.log diff --git a/.eslintrc b/.eslintrc index 6b74ceb95..a92fc4ad5 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,13 +1,16 @@ { - "extends": ["eslint:recommended", "prettier"], + "extends": ["eslint:recommended", "prettier", "plugin:unicorn/recommended"], "plugins": ["prettier"], "parserOptions": { - "ecmaVersion": 9 + "ecmaVersion": 12, + "sourceType": "module" }, "env": { "node": true, "es6": true }, "rules": { "prettier/prettier": "warn", "no-console": "off", - "no-unused-vars": "warn" + "no-unused-vars": "warn", + "unicorn/no-null": "off", + "unicorn/prevent-abbreviations": "off" } } diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b2f80083d..24b8b0c57 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,7 +13,8 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: - node-version: '13' + node-version: '16' + cache: 'yarn' - run: yarn install --frozen-lockfile - run: yarn test - run: yarn lint --fix diff --git a/.vscode/launch.json b/.vscode/launch.json index 70d6af97b..a614e4e22 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,40 +8,42 @@ "type": "node", "request": "launch", "name": "Jest All", - "program": "${workspaceFolder}/node_modules/.bin/jest", - "args": ["--runInBand"], + "args": [ + "--experimental-vm-modules", + "${workspaceFolder}/node_modules/.bin/jest", + "--runInBand" + ], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", - "disableOptimisticBPs": true, - "windows": { - "program": "${workspaceFolder}/node_modules/jest/bin/jest" - } + "disableOptimisticBPs": true }, { "type": "node", "request": "launch", "name": "Jest Current File", - "program": "${workspaceFolder}/node_modules/.bin/jest", - "args": ["${fileBasenameNoExtension}"], + "args": [ + "--experimental-vm-modules", + "${workspaceFolder}/node_modules/.bin/jest", + "${fileBasenameNoExtension}" + ], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", - "disableOptimisticBPs": true, - "windows": { - "program": "${workspaceFolder}/node_modules/jest/bin/jest" - } + "disableOptimisticBPs": true }, { "type": "node", "request": "launch", "name": "Jest Run Selected Test", - "program": "${workspaceFolder}/node_modules/.bin/jest", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "disableOptimisticBPs": true, - "windows": { - "program": "${workspaceFolder}/node_modules/jest/bin/jest" - }, - "args": ["${fileBasenameNoExtension}", "-t", "${selectedText}"] + "args": [ + "--experimental-vm-modules", + "${workspaceFolder}/node_modules/.bin/jest", + "${fileBasenameNoExtension}", + "-t", + "${selectedText}" + ] } ] } diff --git a/action.js b/action.js index 5a98cdb15..0eeb06530 100644 --- a/action.js +++ b/action.js @@ -1,7 +1,7 @@ -const core = require('@actions/core') -const { run } = require('@probot/adapter-github-actions') -const app = require('./index') +import core from '@actions/core' +import { run } from '@probot/adapter-github-actions' +import { app } from './index' -run(app).catch((err) => { - core.setFailed(`💥 Release drafter failed with error: ${err.message}`) +run(app).catch((error) => { + core.setFailed(`💥 Release drafter failed with error: ${error.message}`) }) diff --git a/action.yml b/action.yml index 69fb76b28..6d02f059f 100644 --- a/action.yml +++ b/action.yml @@ -1,7 +1,7 @@ name: 'Release Drafter' description: 'Drafts your next release notes as pull requests are merged into master.' runs: - using: 'node12' + using: 'node16' main: 'dist/index.js' branding: icon: edit-2 diff --git a/bin/generate-fixtures.js b/bin/generate-fixtures.js index 4a6ac6a32..29e942d0c 100755 --- a/bin/generate-fixtures.js +++ b/bin/generate-fixtures.js @@ -1,9 +1,10 @@ #!/usr/bin/env node -const fs = require('fs') -const path = require('path') -const fetch = require('node-fetch') -const { findCommitsWithAssociatedPullRequestsQuery } = require('../lib/commits') +import fs from 'node:fs' +import path from 'node:path' +import url from 'node:url' +import fetch from 'node-fetch' +import { findCommitsWithAssociatedPullRequestsQuery } from '../lib/commits' const REPO_NAME = 'release-drafter-test-repo' const GITHUB_GRAPHQL_API_ENDPOINT = 'https://api.github.com/graphql' @@ -38,7 +39,7 @@ const repos = [ }, ] -repos.forEach((repo) => { +for (const repo of repos) { const options = { method: 'POST', headers: { @@ -68,7 +69,7 @@ repos.forEach((repo) => { ) fs.writeFileSync( path.resolve( - __dirname, + path.dirname(url.fileURLToPath(import.meta.url)), '../test/fixtures/__generated__', `graphql-commits-${repo.branch}.json` ), @@ -76,4 +77,4 @@ repos.forEach((repo) => { ) }) .catch(console.error) -}) +} diff --git a/bin/generate-schema.js b/bin/generate-schema.js index 0e5204ab4..2d0df6518 100644 --- a/bin/generate-schema.js +++ b/bin/generate-schema.js @@ -1,13 +1,12 @@ // joi-to-json-schema currently does not support v16 of Joi (https://github.com/lightsofapollo/joi-to-json-schema/issues/57) -const convert = require('joi-to-json-schema') -const fs = require('fs') -const { schema } = require('../lib/schema') -const args = process.argv.slice(2) || [] +import convert from 'joi-to-json-schema' +import fs from 'node:fs' +import { schema } from '../lib/schema' +const inputArguments = process.argv.slice(2) || [] -const jsonSchema = { +export const jsonSchema = { title: 'JSON schema for Release Drafter yaml files', - id: - 'https://github.com/release-drafter/release-drafter/blob/master/schema.json', + id: 'https://github.com/release-drafter/release-drafter/blob/master/schema.json', $schema: 'http://json-schema.org/draft-04/schema#', ...convert(schema()), } @@ -15,14 +14,15 @@ const jsonSchema = { // template is only required after deep merged, should not be required in the JSON schema // we should also remove the required field in case nothing remains after the filtering to keep draft04 compatibility const requiredField = jsonSchema.required.filter((item) => item !== 'template') -if (requiredField.length) { +if (requiredField.length > 0) { jsonSchema.required = requiredField } else { delete jsonSchema.required } -if (args[0] === 'print') { - fs.writeFileSync('./schema.json', `${JSON.stringify(jsonSchema, null, 2)}\n`) +if (inputArguments[0] === 'print') { + fs.writeFileSync( + './schema.json', + `${JSON.stringify(jsonSchema, undefined, 2)}\n` + ) } - -module.exports.jsonSchema = jsonSchema diff --git a/dist/index.js b/dist/index.js index f3b0c75f9..650a8c1ea 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,1476 +1,32 @@ -/******/ (() => { // webpackBootstrap -/******/ var __webpack_modules__ = ({ - -/***/ 82542: -/***/ ((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"}'); - -/***/ }), - -/***/ 32932: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { getConfig } = __nccwpck_require__(20088) -const { isTriggerableReference } = __nccwpck_require__(38350) -const { - findReleases, - generateReleaseInfo, - createRelease, - updateRelease, -} = __nccwpck_require__(15715) -const { findCommitsWithAssociatedPullRequests } = __nccwpck_require__(23916) -const { sortPullRequests } = __nccwpck_require__(16445) -const log = __nccwpck_require__(13817) -const core = __nccwpck_require__(42186) -const { runnerIsActions } = __nccwpck_require__(50918) -const ignore = __nccwpck_require__(91230) - -module.exports = (app, { getRouter }) => { - const event = runnerIsActions() ? '*' : 'push' - - if (!runnerIsActions() && typeof getRouter === 'function') { - getRouter().get('/healthz', (req, res) => { - res.status(200).json({ status: 'pass' }) - }) - } - - app.on( - [ - 'pull_request.opened', - 'pull_request.reopened', - 'pull_request.synchronize', - 'pull_request.edited', - 'pull_request_target.opened', - 'pull_request_target.reopened', - 'pull_request_target.synchronize', - 'pull_request_target.edited', - ], - async (context) => { - const { disableAutolabeler } = getInput() - - const config = await getConfig({ - context, - configName: core.getInput('config-name'), - }) - - if (config === null || disableAutolabeler) return - - let issue = { - ...context.issue({ pull_number: context.payload.pull_request.number }), - } - const changedFiles = await context.octokit.paginate( - context.octokit.pulls.listFiles.endpoint.merge(issue), - (res) => res.data.map((file) => file.filename) - ) - const labels = new Set() - - for (const autolabel of config['autolabeler']) { - let found = false - // check modified files - if (!found && autolabel.files.length > 0) { - const matcher = ignore().add(autolabel.files) - if (changedFiles.find((file) => matcher.ignores(file))) { - labels.add(autolabel.label) - found = true - log({ - context, - message: `Found label for files: '${autolabel.label}'`, - }) - } - } - // check branch names - if (!found && autolabel.branch.length > 0) { - for (const matcher of autolabel.branch) { - if (context.payload.pull_request.head.ref.match(matcher)) { - labels.add(autolabel.label) - found = true - log({ - context, - message: `Found label for branch: '${autolabel.label}'`, - }) - break - } - } - } - // check pr title - if (!found && autolabel.title.length > 0) { - for (const matcher of autolabel.title) { - if (context.payload.pull_request.title.match(matcher)) { - labels.add(autolabel.label) - found = true - log({ - context, - message: `Found label for title: '${autolabel.label}'`, - }) - break - } - } - } - // check pr body - if ( - !found && - context.payload.pull_request.body != null && - autolabel.body.length > 0 - ) { - for (const matcher of autolabel.body) { - if (context.payload.pull_request.body.match(matcher)) { - labels.add(autolabel.label) - found = true - log({ - context, - message: `Found label for body: '${autolabel.label}'`, - }) - break - } - } - } - } - - const labelsToAdd = Array.from(labels) - if (labelsToAdd.length > 0) { - let labelIssue = { - ...context.issue({ - issue_number: context.payload.pull_request.number, - labels: labelsToAdd, - }), - } - await context.octokit.issues.addLabels(labelIssue) - if (runnerIsActions()) { - core.setOutput('number', context.payload.pull_request.number) - core.setOutput('labels', labelsToAdd.join(',')) - } - return - } - } - ) - - app.on(event, async (context) => { - const { - shouldDraft, - configName, - version, - tag, - name, - disableReleaser, - commitish, - } = getInput() - - const config = await getConfig({ - context, - configName, - }) - - const { isPreRelease } = getInput({ config }) - - if (config === null || disableReleaser) return - - // GitHub Actions merge payloads slightly differ, in that their ref points - // to the PR branch instead of refs/heads/master - const ref = process.env['GITHUB_REF'] || context.payload.ref - - if (!isTriggerableReference({ ref, context, config })) { - return - } - - const { draftRelease, lastRelease } = await findReleases({ - ref, - context, - config, - }) - const { - commits, - pullRequests: mergedPullRequests, - } = await findCommitsWithAssociatedPullRequests({ - context, - ref, - lastRelease, - config, - }) - - const sortedMergedPullRequests = sortPullRequests( - mergedPullRequests, - config['sort-by'], - config['sort-direction'] - ) - - const releaseInfo = generateReleaseInfo({ - commits, - config, - lastRelease, - mergedPullRequests: sortedMergedPullRequests, - version, - tag, - name, - isPreRelease, - shouldDraft, - commitish, - }) - - let createOrUpdateReleaseResponse - if (!draftRelease) { - log({ context, message: 'Creating new release' }) - createOrUpdateReleaseResponse = await createRelease({ - context, - releaseInfo, - config, - }) - } else { - log({ context, message: 'Updating existing release' }) - createOrUpdateReleaseResponse = await updateRelease({ - context, - draftRelease, - releaseInfo, - config, - }) - } - - if (runnerIsActions()) { - setActionOutput(createOrUpdateReleaseResponse, releaseInfo) - } - }) -} - -function getInput({ config } = {}) { - // Returns all the inputs that doesn't need a merge with the config file - if (!config) { - return { - shouldDraft: core.getInput('publish').toLowerCase() !== 'true', - configName: core.getInput('config-name'), - version: core.getInput('version') || undefined, - tag: core.getInput('tag') || undefined, - name: core.getInput('name') || undefined, - disableReleaser: - core.getInput('disable-releaser').toLowerCase() === 'true', - disableAutolabeler: - core.getInput('disable-autolabeler').toLowerCase() === 'true', - commitish: core.getInput('commitish') || undefined, - } - } - - // Merges the config file with the input - // the input takes precedence, because it's more easy to change at runtime - const preRelease = core.getInput('prerelease').toLowerCase() - return { - isPreRelease: preRelease === 'true' || (!preRelease && config.prerelease), - } -} - -function setActionOutput(releaseResponse, { body }) { - const { - data: { - id: releaseId, - html_url: htmlUrl, - upload_url: uploadUrl, - tag_name: tagName, - name: name, - }, - } = releaseResponse - if (releaseId && Number.isInteger(releaseId)) - core.setOutput('id', releaseId.toString()) - if (htmlUrl) core.setOutput('html_url', htmlUrl) - if (uploadUrl) core.setOutput('upload_url', uploadUrl) - if (tagName) core.setOutput('tag_name', tagName) - if (name) core.setOutput('name', name) - core.setOutput('body', body) -} - - -/***/ }), - -/***/ 23916: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const log = __nccwpck_require__(13817) -const paginate = __nccwpck_require__(34389) -const _ = __nccwpck_require__(90250) - -module.exports.findCommitsWithAssociatedPullRequestsQuery = /* GraphQL */ ` - query findCommitsWithAssociatedPullRequests( - $name: String! - $owner: String! - $ref: String! - $withPullRequestBody: Boolean! - $withPullRequestURL: Boolean! - $since: GitTimestamp - $after: String - $withBaseRefName: Boolean! - $withHeadRefName: Boolean! - ) { - repository(name: $name, owner: $owner) { - object(expression: $ref) { - ... on Commit { - history(first: 100, since: $since, after: $after) { - totalCount - pageInfo { - hasNextPage - endCursor - } - nodes { - id - committedDate - message - author { - name - user { - login - } - } - associatedPullRequests(first: 5) { - nodes { - title - number - url @include(if: $withPullRequestURL) - body @include(if: $withPullRequestBody) - author { - login - } - baseRepository { - nameWithOwner - } - mergedAt - isCrossRepository - labels(first: 10) { - nodes { - name - } - } - baseRefName @include(if: $withBaseRefName) - headRefName @include(if: $withHeadRefName) - } - } - } - } - } - } - } - } -` - -module.exports.findCommitsWithAssociatedPullRequests = async ({ - context, - ref, - lastRelease, - config, -}) => { - const { owner, repo } = context.repo() - const variables = { - name: repo, - owner, - ref, - withPullRequestBody: config['change-template'].includes('$BODY'), - withPullRequestURL: config['change-template'].includes('$URL'), - withBaseRefName: config['change-template'].includes('$BASE_REF_NAME'), - withHeadRefName: config['change-template'].includes('$HEAD_REF_NAME'), - } - const dataPath = ['repository', 'object', 'history'] - const repoNameWithOwner = `${owner}/${repo}` - - let data, commits - if (lastRelease) { - log({ - context, - message: `Fetching all commits for reference ${ref} since ${lastRelease.created_at}`, - }) - - data = await paginate( - context.octokit.graphql, - module.exports.findCommitsWithAssociatedPullRequestsQuery, - { ...variables, since: lastRelease.created_at }, - dataPath - ) - // GraphQL call is inclusive of commits from the specified dates. This means the final - // commit from the last tag is included, so we remove this here. - commits = _.get(data, [...dataPath, 'nodes']).filter( - (commit) => commit.committedDate != lastRelease.created_at - ) - } else { - log({ context, message: `Fetching all commits for reference ${ref}` }) - - data = await paginate( - context.octokit.graphql, - module.exports.findCommitsWithAssociatedPullRequestsQuery, - variables, - dataPath - ) - commits = _.get(data, [...dataPath, 'nodes']) - } - - const pullRequests = _.uniqBy( - _.flatten(commits.map((commit) => commit.associatedPullRequests.nodes)), - 'number' - ).filter((pr) => pr.baseRepository.nameWithOwner === repoNameWithOwner) - - return { commits, pullRequests } -} - - -/***/ }), - -/***/ 20088: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const core = __nccwpck_require__(42186) -const { validateSchema } = __nccwpck_require__(5171) -const log = __nccwpck_require__(13817) -const { runnerIsActions } = __nccwpck_require__(50918) -const Table = __nccwpck_require__(2101) - -const DEFAULT_CONFIG_NAME = 'release-drafter.yml' - -module.exports.getConfig = async function getConfig({ context, configName }) { - try { - const repoConfig = await context.config( - configName || DEFAULT_CONFIG_NAME, - null - ) - if (repoConfig == null) { - // noinspection ExceptionCaughtLocallyJS - throw new Error( - 'Configuration file .github/' + - (configName || DEFAULT_CONFIG_NAME) + - ' is not found. The configuration file must reside in your default branch.' - ) - } - - const config = validateSchema(context, repoConfig) - - return config - } catch (error) { - log({ context, error, message: 'Invalid config file' }) - - if (error.isJoi) { - log({ - context, - message: - 'Config validation errors, please fix the following issues in ' + - (configName || DEFAULT_CONFIG_NAME) + - ':\n' + - joiValidationErrorsAsTable(error), - }) - } - - if (runnerIsActions()) { - core.setFailed('Invalid config file') - } - return null - } -} - -function joiValidationErrorsAsTable(error) { - const table = new Table({ head: ['Property', 'Error'] }) - error.details.forEach(({ path, message }) => { - const prettyPath = path - .map((pathPart) => - Number.isInteger(pathPart) ? `[${pathPart}]` : pathPart - ) - .join('.') - table.push([prettyPath, message]) - }) - return table.toString() -} - - -/***/ }), - -/***/ 25586: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { SORT_BY, SORT_DIRECTIONS } = __nccwpck_require__(16445) - -const DEFAULT_CONFIG = Object.freeze({ - 'name-template': '', - 'tag-template': '', - 'change-template': `* $TITLE (#$NUMBER) @$AUTHOR`, - 'change-title-escapes': '', - 'no-changes-template': `* No changes`, - 'version-template': `$MAJOR.$MINOR.$PATCH`, - 'version-resolver': { - major: { labels: [] }, - minor: { labels: [] }, - patch: { labels: [] }, - default: 'patch', - }, - categories: [], - 'exclude-labels': [], - 'include-labels': [], - 'exclude-contributors': [], - 'no-contributors-template': 'No contributors', - replacers: [], - autolabeler: [], - 'sort-by': SORT_BY.mergedAt, - 'sort-direction': SORT_DIRECTIONS.descending, - prerelease: false, - 'filter-by-commitish': false, - commitish: '', - 'category-template': `## $TITLE`, -}) - -module.exports.DEFAULT_CONFIG = DEFAULT_CONFIG - - -/***/ }), - -/***/ 13817: -/***/ ((module) => { - -module.exports = ({ context, message, error }) => { - const repo = context.payload.repository - const prefix = repo ? `${repo.full_name}: ` : '' - const logString = `${prefix}${message}` - if (error) { - context.log.warn(error, logString) - } else { - context.log.info(logString) - } -} - - -/***/ }), - -/***/ 34389: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const _ = __nccwpck_require__(90250) - -/** - * Utility function to paginate a GraphQL function using Relay-style cursor pagination. - * - * @param {Function} queryFn - function used to query the GraphQL API - * @param {string} query - GraphQL query, must include `nodes` and `pageInfo` fields for the field that will be paginated - * @param {Object} variables - * @param {string[]} paginatePath - path to field to paginate - */ -async function paginate(queryFn, query, variables, paginatePath) { - const nodesPath = [...paginatePath, 'nodes'] - const pageInfoPath = [...paginatePath, 'pageInfo'] - const endCursorPath = [...pageInfoPath, 'endCursor'] - const hasNextPagePath = [...pageInfoPath, 'hasNextPage'] - const hasNextPage = (data) => _.get(data, hasNextPagePath) - - let data = await queryFn(query, variables) - - if (!_.has(data, nodesPath)) { - throw new Error( - "Data doesn't contain `nodes` field. Make sure the `paginatePath` is set to the field you wish to paginate and that the query includes the `nodes` field." - ) - } - - if ( - !_.has(data, pageInfoPath) || - !_.has(data, endCursorPath) || - !_.has(data, hasNextPagePath) - ) { - throw new Error( - "Data doesn't contain `pageInfo` field with `endCursor` and `hasNextPage` fields. Make sure the `paginatePath` is set to the field you wish to paginate and that the query includes the `pageInfo` field." - ) - } - - while (hasNextPage(data)) { - const newData = await queryFn(query, { - ...variables, - after: _.get(data, [...pageInfoPath, 'endCursor']), - }) - const newNodes = _.get(newData, nodesPath) - const newPageInfo = _.get(newData, pageInfoPath) - - _.set(data, pageInfoPath, newPageInfo) - _.update(data, nodesPath, (d) => d.concat(newNodes)) - } - - return data -} - -module.exports = paginate - - -/***/ }), - -/***/ 15715: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const compareVersions = __nccwpck_require__(89296) -const regexEscape = __nccwpck_require__(98691) - -const { getVersionInfo } = __nccwpck_require__(57332) -const { template } = __nccwpck_require__(25032) -const log = __nccwpck_require__(13817) - -const sortReleases = (releases) => { - // For semver, we find the greatest release number - // For non-semver, we use the most recently merged - try { - return releases.sort((r1, r2) => compareVersions(r1.tag_name, r2.tag_name)) - } catch (error) { - return releases.sort( - (r1, r2) => new Date(r1.created_at) - new Date(r2.created_at) - ) - } -} - -module.exports.findReleases = async ({ ref, context, config }) => { - let releases = await context.octokit.paginate( - context.octokit.repos.listReleases.endpoint.merge( - context.repo({ - per_page: 100, - }) - ) - ) - - log({ context, message: `Found ${releases.length} releases` }) - - const { 'filter-by-commitish': filterByCommitish } = config - const filteredReleases = filterByCommitish - ? releases.filter((r) => ref.match(`/${r.target_commitish}$`)) - : releases - const sortedPublishedReleases = sortReleases( - filteredReleases.filter((r) => !r.draft) - ) - const draftRelease = filteredReleases.find((r) => r.draft) - const lastRelease = - sortedPublishedReleases[sortedPublishedReleases.length - 1] - - if (draftRelease) { - log({ context, message: `Draft release: ${draftRelease.tag_name}` }) - } else { - log({ context, message: `No draft release found` }) - } - - if (lastRelease) { - log({ context, message: `Last release: ${lastRelease.tag_name}` }) - } else { - log({ context, message: `No last release found` }) - } - - return { draftRelease, lastRelease } -} - -const contributorsSentence = ({ commits, pullRequests, config }) => { - const { 'exclude-contributors': excludeContributors } = config - - const contributors = new Set() - - commits.forEach((commit) => { - if (commit.author.user) { - if (!excludeContributors.includes(commit.author.user.login)) { - contributors.add(`@${commit.author.user.login}`) - } - } else { - contributors.add(commit.author.name) - } - }) - - pullRequests.forEach((pullRequest) => { - if ( - pullRequest.author && - !excludeContributors.includes(pullRequest.author.login) - ) { - contributors.add(`@${pullRequest.author.login}`) - } - }) - - const sortedContributors = Array.from(contributors).sort() - if (sortedContributors.length > 1) { - return ( - sortedContributors.slice(0, sortedContributors.length - 1).join(', ') + - ' and ' + - sortedContributors.slice(-1) - ) - } else if (sortedContributors.length === 1) { - return sortedContributors[0] - } else { - return config['no-contributors-template'] - } -} - -const getFilterExcludedPullRequests = (excludeLabels) => { - return (pullRequest) => { - const labels = pullRequest.labels.nodes - if (labels.some((label) => excludeLabels.includes(label.name))) { - return false - } - return true - } -} - -const getFilterIncludedPullRequests = (includeLabels) => { - return (pullRequest) => { - const labels = pullRequest.labels.nodes - if ( - includeLabels.length == 0 || - labels.some((label) => includeLabels.includes(label.name)) - ) { - return true - } - return false - } -} - -const categorizePullRequests = (pullRequests, config) => { - const { - 'exclude-labels': excludeLabels, - 'include-labels': includeLabels, - categories, - } = config - const allCategoryLabels = categories.flatMap((category) => category.labels) - const uncategorizedPullRequests = [] - const categorizedPullRequests = [...categories].map((category) => { - return { ...category, pullRequests: [] } - }) - - const filterUncategorizedPullRequests = (pullRequest) => { - const labels = pullRequest.labels.nodes - - if ( - labels.length === 0 || - !labels.some((label) => allCategoryLabels.includes(label.name)) - ) { - uncategorizedPullRequests.push(pullRequest) - return false - } - return true - } - - // we only want pull requests that have yet to be categorized - const filteredPullRequests = pullRequests - .filter(getFilterExcludedPullRequests(excludeLabels)) - .filter(getFilterIncludedPullRequests(includeLabels)) - .filter(filterUncategorizedPullRequests) - - categorizedPullRequests.map((category) => { - filteredPullRequests.map((pullRequest) => { - // lets categorize some pull request based on labels - // note that having the same label in multiple categories - // then it is intended to "duplicate" the pull request into each category - const labels = pullRequest.labels.nodes - if (labels.some((label) => category.labels.includes(label.name))) { - category.pullRequests.push(pullRequest) - } - }) - }) - - return [uncategorizedPullRequests, categorizedPullRequests] -} - -const generateChangeLog = (mergedPullRequests, config) => { - if (mergedPullRequests.length === 0) { - return config['no-changes-template'] - } - - const [ - uncategorizedPullRequests, - categorizedPullRequests, - ] = categorizePullRequests(mergedPullRequests, config) - - const escapeTitle = (title) => - // If config['change-title-escapes'] contains backticks, then they will be escaped along with content contained inside backticks - // If not, the entire backtick block is matched so that it will become a markdown code block without escaping any of its content - title.replace( - new RegExp( - `[${regexEscape(config['change-title-escapes'])}]|\`.*?\``, - 'g' - ), - (match) => { - if (match.length > 1) return match - if (match == '@' || match == '#') return `${match}` - return `\\${match}` - } - ) - - const pullRequestToString = (pullRequests) => - pullRequests - .map((pullRequest) => - template(config['change-template'], { - $TITLE: escapeTitle(pullRequest.title), - $NUMBER: pullRequest.number, - $AUTHOR: pullRequest.author ? pullRequest.author.login : 'ghost', - $BODY: pullRequest.body, - $URL: pullRequest.url, - $BASE_REF_NAME: pullRequest.baseRefName, - $HEAD_REF_NAME: pullRequest.headRefName, - }) - ) - .join('\n') - - const changeLog = [] - - if (uncategorizedPullRequests.length) { - changeLog.push(pullRequestToString(uncategorizedPullRequests)) - changeLog.push('\n\n') - } - - categorizedPullRequests.map((category, index) => { - if (category.pullRequests.length) { - changeLog.push( - template(config['category-template'], { $TITLE: category.title }) - ) - changeLog.push('\n\n') - - changeLog.push(pullRequestToString(category.pullRequests)) - - if (index + 1 !== categorizedPullRequests.length) changeLog.push('\n\n') - } - }) - - return changeLog.join('').trim() -} - -const resolveVersionKeyIncrement = (mergedPullRequests, config) => { - const priorityMap = { - patch: 1, - minor: 2, - major: 3, - } - const labelToKeyMap = Object.fromEntries( - Object.keys(priorityMap) - .flatMap((key) => [ - config['version-resolver'][key].labels.map((label) => [label, key]), - ]) - .flat() - ) - const keys = mergedPullRequests - .filter(getFilterExcludedPullRequests(config['exclude-labels'])) - .filter(getFilterIncludedPullRequests(config['include-labels'])) - .flatMap((pr) => pr.labels.nodes.map((node) => labelToKeyMap[node.name])) - .filter(Boolean) - const keyPriorities = keys.map((key) => priorityMap[key]) - const priority = Math.max(...keyPriorities) - const versionKey = Object.keys(priorityMap).find( - (key) => priorityMap[key] === priority - ) - return versionKey || config['version-resolver'].default -} - -module.exports.generateChangeLog = generateChangeLog - -module.exports.generateReleaseInfo = ({ - commits, - config, - lastRelease, - mergedPullRequests, - version = undefined, - tag = undefined, - name = undefined, - isPreRelease, - shouldDraft, - commitish = undefined, -}) => { - let body = config.template - - body = template( - body, - { - $PREVIOUS_TAG: lastRelease ? lastRelease.tag_name : '', - $CHANGES: generateChangeLog(mergedPullRequests, config), - $CONTRIBUTORS: contributorsSentence({ - commits, - pullRequests: mergedPullRequests, - config, - }), - }, - config.replacers - ) - - const versionInfo = getVersionInfo( - lastRelease, - config['version-template'], - // Use the first override parameter to identify - // a version, from the most accurate to the least - version || tag || name, - resolveVersionKeyIncrement(mergedPullRequests, config) - ) - - if (versionInfo) { - body = template(body, versionInfo) - } - - if (tag === undefined) { - tag = versionInfo ? template(config['tag-template'] || '', versionInfo) : '' - } - - if (name === undefined) { - name = versionInfo - ? template(config['name-template'] || '', versionInfo) - : '' - } - - if (commitish === undefined) { - commitish = config['commitish'] || '' - } - - return { - name, - tag, - body, - commitish, - prerelease: isPreRelease, - draft: shouldDraft, - } -} - -module.exports.createRelease = ({ context, releaseInfo }) => { - return context.octokit.repos.createRelease( - context.repo({ - target_commitish: releaseInfo.commitish, - name: releaseInfo.name, - tag_name: releaseInfo.tag, - body: releaseInfo.body, - draft: releaseInfo.draft, - prerelease: releaseInfo.prerelease, - }) - ) -} - -module.exports.updateRelease = ({ context, draftRelease, releaseInfo }) => { - const updateReleaseParams = updateDraftReleaseParams({ - name: releaseInfo.name || draftRelease.name, - tag_name: releaseInfo.tag || draftRelease.tag_name, - }) - - return context.octokit.repos.updateRelease( - context.repo({ - release_id: draftRelease.id, - body: releaseInfo.body, - draft: releaseInfo.draft, - prerelease: releaseInfo.prerelease, - ...updateReleaseParams, - }) - ) -} - -function updateDraftReleaseParams(params) { - const updateReleaseParams = { ...params } - - // Let GitHub figure out `name` and `tag_name` if undefined - if (!updateReleaseParams.name) { - delete updateReleaseParams.name - } - if (!updateReleaseParams.tag_name) { - delete updateReleaseParams.tag_name - } - - return updateReleaseParams -} - - -/***/ }), - -/***/ 5171: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const _ = __nccwpck_require__(90250) -const Joi = __nccwpck_require__(44010) -const { SORT_BY, SORT_DIRECTIONS } = __nccwpck_require__(16445) -const { DEFAULT_CONFIG } = __nccwpck_require__(25586) -const { validateReplacers, validateAutolabeler } = __nccwpck_require__(25032) - -const schema = (context) => { - const defaultBranch = _.get( - context, - 'payload.repository.default_branch', - 'master' - ) - return Joi.object() - .keys({ - references: Joi.array().items(Joi.string()).default([defaultBranch]), - - 'change-template': Joi.string().default( - DEFAULT_CONFIG['change-template'] - ), - - 'change-title-escapes': Joi.string() - .allow('') - .default(DEFAULT_CONFIG['change-title-escapes']), - - 'no-changes-template': Joi.string().default( - DEFAULT_CONFIG['no-changes-template'] - ), - - 'version-template': Joi.string().default( - DEFAULT_CONFIG['version-template'] - ), - - 'name-template': Joi.string() - .allow('') - .default(DEFAULT_CONFIG['name-template']), - - 'tag-template': Joi.string() - .allow('') - .default(DEFAULT_CONFIG['tag-template']), - - 'exclude-labels': Joi.array() - .items(Joi.string()) - .default(DEFAULT_CONFIG['exclude-labels']), - - 'include-labels': Joi.array() - .items(Joi.string()) - .default(DEFAULT_CONFIG['include-labels']), - - 'exclude-contributors': Joi.array() - .items(Joi.string()) - .default(DEFAULT_CONFIG['exclude-contributors']), - - 'no-contributors-template': Joi.string().default( - DEFAULT_CONFIG['no-contributors-template'] - ), - - 'sort-by': Joi.string() - .valid(SORT_BY.mergedAt, SORT_BY.title) - .default(DEFAULT_CONFIG['sort-by']), - - 'sort-direction': Joi.string() - .valid(SORT_DIRECTIONS.ascending, SORT_DIRECTIONS.descending) - .default(DEFAULT_CONFIG['sort-direction']), - - prerelease: Joi.boolean().default(DEFAULT_CONFIG.prerelease), - - 'filter-by-commitish': Joi.boolean().default( - DEFAULT_CONFIG['filter-by-commitish'] - ), - - commitish: Joi.string().allow('').default(DEFAULT_CONFIG['commitish']), - - replacers: Joi.array() - .items( - Joi.object().keys({ - search: Joi.string() - .required() - .error( - () => '"search" is required and must be a regexp or a string' - ), - replace: Joi.string().allow('').required(), - }) - ) - .default(DEFAULT_CONFIG.replacers), - - autolabeler: Joi.array() - .items( - Joi.object().keys({ - label: Joi.string().required(), - files: Joi.array().items(Joi.string()).single().default([]), - branch: Joi.array().items(Joi.string()).single().default([]), - title: Joi.array().items(Joi.string()).single().default([]), - body: Joi.array().items(Joi.string()).single().default([]), - }) - ) - .default(DEFAULT_CONFIG.autolabeler), - - categories: Joi.array() - .items( - Joi.object() - .keys({ - title: Joi.string().required(), - label: Joi.string(), - labels: Joi.array().items(Joi.string()).single().default([]), - }) - .rename('label', 'labels', { - ignoreUndefined: true, - override: true, - }) - ) - .default(DEFAULT_CONFIG.categories), - - 'version-resolver': Joi.object() - .keys({ - major: Joi.object({ - labels: Joi.array().items(Joi.string()).single(), - }), - minor: Joi.object({ - labels: Joi.array().items(Joi.string()).single(), - }), - patch: Joi.object({ - labels: Joi.array().items(Joi.string()).single(), - }), - default: Joi.string() - .valid('major', 'minor', 'patch') - .default('patch'), - }) - .default(DEFAULT_CONFIG['version-resolver']), - - 'category-template': Joi.string() - .allow('') - .default(DEFAULT_CONFIG['category-template']), - - template: Joi.string().required(), - - _extends: Joi.string(), - }) - .rename('branches', 'references', { - ignoreUndefined: true, - override: true, - }) -} - -module.exports.schema = schema - -const validateSchema = (context, repoConfig) => { - const { error, value: config } = schema(context).validate(repoConfig, { - abortEarly: false, - allowUnknown: true, - }) - - if (error) throw error - - try { - config.replacers = validateReplacers({ - context, - replacers: config.replacers, - }) - } catch (error) { - config.replacers = [] - } - - try { - config.autolabeler = validateAutolabeler({ - context, - autolabeler: config.autolabeler, - }) - } catch (error) { - config.autolabeler = [] - } - - return config -} - -module.exports.validateSchema = validateSchema - - -/***/ }), - -/***/ 16445: -/***/ ((module) => { - -const SORT_BY = { - mergedAt: 'merged_at', - title: 'title', -} - -const SORT_DIRECTIONS = { - ascending: 'ascending', - descending: 'descending', -} - -module.exports.SORT_BY = SORT_BY -module.exports.SORT_DIRECTIONS = SORT_DIRECTIONS - -module.exports.sortPullRequests = (pullRequests, sortBy, sortDirection) => { - const getSortFieldFn = sortBy === SORT_BY.title ? getTitle : getMergedAt - - const sortFn = - sortDirection === SORT_DIRECTIONS.ascending - ? dateSortAscending - : dateSortDescending - - return pullRequests - .slice() - .sort((a, b) => sortFn(getSortFieldFn(a), getSortFieldFn(b))) -} - -function getMergedAt(pullRequest) { - return new Date(pullRequest.mergedAt) -} - -function getTitle(pullRequest) { - return pullRequest.title -} - -function dateSortAscending(date1, date2) { - if (date1 > date2) return 1 - if (date1 < date2) return -1 - return 0 -} - -function dateSortDescending(date1, date2) { - if (date1 > date2) return -1 - if (date1 < date2) return 1 - return 0 -} - - -/***/ }), - -/***/ 25032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const log = __nccwpck_require__(13817) -const regexParser = __nccwpck_require__(14542) -const regexEscape = __nccwpck_require__(98691) - -/** - * replaces all uppercase dollar templates with their string representation from obj - * if replacement is undefined in obj the dollar template string is left untouched - */ - -const template = (string, obj, customReplacers) => { - let str = string.replace(/(\$[A-Z_]+)/g, (_, k) => { - let result - if (obj[k] === undefined || obj[k] === null) { - result = k - } else if (typeof obj[k] === 'object') { - result = template(obj[k].template, obj[k]) - } else { - result = `${obj[k]}` - } - return result - }) - if (customReplacers) { - customReplacers.forEach(({ search, replace }) => { - str = str.replace(search, replace) - }) - } - return str -} - -function toRegex(search) { - if (search.match(/^\/.+\/[gmixXsuUAJ]*$/)) { - return regexParser(search) - } else { - // plain string - return new RegExp(regexEscape(search), 'g') - } -} - -function validateReplacers({ context, replacers }) { - return replacers - .map((replacer) => { - try { - return { ...replacer, search: toRegex(replacer.search) } - } catch (e) { - log({ - context, - message: `Bad replacer regex: '${replacer.search}'`, - }) - return false - } - }) - .filter(Boolean) -} - -function validateAutolabeler({ context, autolabeler }) { - return autolabeler - .map((autolabel) => { - try { - return { - ...autolabel, - branch: autolabel.branch.map((reg) => { - return toRegex(reg) - }), - title: autolabel.title.map((reg) => { - return toRegex(reg) - }), - body: autolabel.body.map((reg) => { - return toRegex(reg) - }), - } - } catch (e) { - log({ - context, - message: `Bad autolabeler regex: '${autolabel.branch}', '${autolabel.title}' or '${autolabel.body}'`, - }) - return false - } - }) - .filter(Boolean) -} - -module.exports.template = template -module.exports.validateReplacers = validateReplacers -module.exports.validateAutolabeler = validateAutolabeler - - -/***/ }), - -/***/ 38350: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const log = __nccwpck_require__(13817) - -module.exports.isTriggerableReference = ({ context, ref, config }) => { - const { GITHUB_ACTIONS } = process.env - if (GITHUB_ACTIONS) { - // Let GitHub Action determine when to run the action based on the workflow's on syntax - // See https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#on - return true - } - const refRegex = /^refs\/(?:heads|tags)\// - const refernces = config.references.map((r) => r.replace(refRegex, '')) - const shortRef = ref.replace(refRegex, '') - const validReference = new RegExp(refernces.join('|')) - const relevant = validReference.test(shortRef) - if (!relevant) { - log({ - context, - message: `Ignoring push. ${shortRef} does not match: ${refernces.join( - ', ' - )}`, - }) - } - return relevant -} - - -/***/ }), - -/***/ 50918: -/***/ ((module) => { - -function runnerIsActions() { - return process.env['GITHUB_ACTION'] !== undefined -} - -module.exports.runnerIsActions = runnerIsActions - - -/***/ }), - -/***/ 57332: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const semver = __nccwpck_require__(11383) - -const splitSemVer = (input, versionKey = 'version') => { - if (!input[versionKey]) { - return null - } - - const version = input.inc - ? semver.inc(input[versionKey], input.inc, true) - : input[versionKey].version - - return { - ...input, - version, - $MAJOR: semver.major(version), - $MINOR: semver.minor(version), - $PATCH: semver.patch(version), - $COMPLETE: version, - } -} - -const getTemplatableVersion = (input) => { - const templatableVersion = { - $NEXT_MAJOR_VERSION: splitSemVer({ ...input, inc: 'major' }), - $NEXT_MAJOR_VERSION_MAJOR: splitSemVer({ - ...input, - inc: 'major', - template: '$MAJOR', - }), - $NEXT_MAJOR_VERSION_MINOR: splitSemVer({ - ...input, - inc: 'major', - template: '$MINOR', - }), - $NEXT_MAJOR_VERSION_PATCH: splitSemVer({ - ...input, - inc: 'major', - template: '$PATCH', - }), - $NEXT_MINOR_VERSION: splitSemVer({ ...input, inc: 'minor' }), - $NEXT_MINOR_VERSION_MAJOR: splitSemVer({ - ...input, - inc: 'minor', - template: '$MAJOR', - }), - $NEXT_MINOR_VERSION_MINOR: splitSemVer({ - ...input, - inc: 'minor', - template: '$MINOR', - }), - $NEXT_MINOR_VERSION_PATCH: splitSemVer({ - ...input, - inc: 'minor', - template: '$PATCH', - }), - $NEXT_PATCH_VERSION: splitSemVer({ ...input, inc: 'patch' }), - $NEXT_PATCH_VERSION_MAJOR: splitSemVer({ - ...input, - inc: 'patch', - template: '$MAJOR', - }), - $NEXT_PATCH_VERSION_MINOR: splitSemVer({ - ...input, - inc: 'patch', - template: '$MINOR', - }), - $NEXT_PATCH_VERSION_PATCH: splitSemVer({ - ...input, - inc: 'patch', - template: '$PATCH', - }), - $INPUT_VERSION: splitSemVer(input, 'inputVersion'), - $RESOLVED_VERSION: splitSemVer({ - ...input, - inc: input.versionKeyIncrement || 'patch', - }), - } - - templatableVersion.$RESOLVED_VERSION = - templatableVersion.$INPUT_VERSION || templatableVersion.$RESOLVED_VERSION - - return templatableVersion -} - -const toSemver = (version) => { - const result = semver.parse(version) - if (result) { - return result - } - - // doesn't handle prerelease - return semver.coerce(version) -} - -const coerceVersion = (input) => { - if (!input) { - return null - } - - return typeof input === 'object' - ? toSemver(input.tag_name) || toSemver(input.name) - : toSemver(input) -} - -module.exports.getVersionInfo = ( - release, - template, - inputVersion = null, - versionKeyIncrement = null -) => { - const version = coerceVersion(release) - inputVersion = coerceVersion(inputVersion) - - if (!version && !inputVersion) { - return undefined - } - - return { - ...getTemplatableVersion({ - version, - template, - inputVersion, - versionKeyIncrement, - }), - } -} - - -/***/ }), +import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; +/******/ var __webpack_modules__ = ({ /***/ 87351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const os = __importStar(__nccwpck_require__(12087)); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(22037)); const utils_1 = __nccwpck_require__(5278); /** * Commands @@ -1546,30 +102,43 @@ function escapeProperty(s) { /***/ 42186: /***/ (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 __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); return result; }; +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 })); +exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __nccwpck_require__(87351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(12087)); -const path = __importStar(__nccwpck_require__(85622)); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const oidc_utils_1 = __nccwpck_require__(98041); /** * The code to exit an action */ @@ -1631,7 +200,9 @@ function addPath(inputPath) { } exports.addPath = addPath; /** - * Gets the value of an input. The value is also trimmed. + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. @@ -1642,9 +213,49 @@ function getInput(name, options) { if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } + if (options && options.trimWhitespace === false) { + return val; + } return val.trim(); } exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + return inputs; +} +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * @@ -1653,6 +264,7 @@ exports.getInput = getInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { + process.stdout.write(os.EOL); command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; @@ -1699,19 +311,30 @@ exports.debug = debug; /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. */ -function error(message) { - command_1.issue('error', message instanceof Error ? message.toString() : message); +function error(message, properties = {}) { + command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** - * Adds an warning issue + * Adds a warning issue * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. */ -function warning(message) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); +function warning(message, properties = {}) { + command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; /** * Writes info to log with console.log. * @param message info message @@ -1784,6 +407,12 @@ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; //# sourceMappingURL=core.js.map /***/ }), @@ -1791,21 +420,33 @@ exports.getState = getState; /***/ 717: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -"use strict"; // For internal use, subject to change. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.issueCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(35747)); -const os = __importStar(__nccwpck_require__(12087)); +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); const utils_1 = __nccwpck_require__(5278); function issueCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; @@ -1824,14 +465,97 @@ exports.issueCommand = issueCommand; /***/ }), +/***/ 98041: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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 })); +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(39925); +const auth_1 = __nccwpck_require__(23702); +const core_1 = __nccwpck_require__(42186); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); + } + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); + } + return token; + } + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); + } + return runtimeUrl; + } + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.result.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + core_1.debug(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + core_1.setSecret(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); + } +} +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map + +/***/ }), + /***/ 5278: /***/ ((__unused_webpack_module, exports) => { -"use strict"; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toCommandProperties = exports.toCommandValue = void 0; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string @@ -1846,38974 +570,23395 @@ function toCommandValue(input) { return JSON.stringify(input); } exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} +exports.toCommandProperties = toCommandProperties; //# sourceMappingURL=utils.js.map /***/ }), -/***/ 95541: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Url = __nccwpck_require__(78835); - - -const internals = { - minDomainSegments: 2, - nonAsciiRx: /[^\x00-\x7f]/, - domainControlRx: /[\x00-\x20@\:\/]/, // Control + space + separators - tldSegmentRx: /^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, - domainSegmentRx: /^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/, - URL: Url.URL || URL // $lab:coverage:ignore$ -}; - +/***/ 23702: +/***/ ((__unused_webpack_module, exports) => { -exports.analyze = function (domain, options = {}) { - if (typeof domain !== 'string') { - throw new Error('Invalid input: domain must be a string'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + + Buffer.from(this.username + ':' + this.password).toString('base64'); + } + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; } - - if (!domain) { - return { error: 'Domain must be a non-empty string' }; + handleAuthentication(httpClient, requestInfo, objs) { + return null; } - - if (domain.length > 256) { - return { error: 'Domain too long' }; +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; } - - const ascii = !internals.nonAsciiRx.test(domain); - if (!ascii) { - if (options.allowUnicode === false) { // Defaults to true - return { error: 'Domain contains forbidden Unicode characters' }; - } - - domain = domain.normalize('NFC'); + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = 'Bearer ' + this.token; } - - if (internals.domainControlRx.test(domain)) { - return { error: 'Domain contains invalid character' }; + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; } - - domain = internals.punycode(domain); - - // https://tools.ietf.org/html/rfc1035 section 2.3.1 - - const minDomainSegments = options.minDomainSegments || internals.minDomainSegments; - - const segments = domain.split('.'); - if (segments.length < minDomainSegments) { - return { error: 'Domain lacks the minimum required number of segments' }; + handleAuthentication(httpClient, requestInfo, objs) { + return null; } - - const tlds = options.tlds; - if (tlds) { - const tld = segments[segments.length - 1].toLowerCase(); - if (tlds.deny && tlds.deny.has(tld) || - tlds.allow && !tlds.allow.has(tld)) { - - return { error: 'Domain uses forbidden TLD' }; - } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; } - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (!segment.length) { - return { error: 'Domain contains empty dot-separated segment' }; - } - - if (segment.length > 63) { - return { error: 'Domain contains dot-separated segment that is too long' }; - } - - if (i < segments.length - 1) { - if (!internals.domainSegmentRx.test(segment)) { - return { error: 'Domain contains invalid character' }; - } - } - else { - if (!internals.tldSegmentRx.test(segment)) { - return { error: 'Domain contains invalid tld character' }; - } - } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + options.headers['Authorization'] = + 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); } -}; - - -exports.isValid = function (domain, options) { - - return !exports.analyze(domain, options); -}; - - -internals.punycode = function (domain) { - - try { - return new internals.URL(`http://${domain}`).host; + // This handler cannot handle 401 + canHandleAuthentication(response) { + return false; } - catch (err) { - return domain; + handleAuthentication(httpClient, requestInfo, objs) { + return null; } -}; +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; /***/ }), -/***/ 67318: +/***/ 39925: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - - -const Util = __nccwpck_require__(31669); - -const Domain = __nccwpck_require__(95541); - - -const internals = { - nonAsciiRx: /[^\x00-\x7f]/, - encoder: new (Util.TextEncoder || TextEncoder)() // $lab:coverage:ignore$ -}; - - -exports.analyze = function (email, options) { - - return internals.email(email, options); -}; - - -exports.isValid = function (email, options) { - - return !internals.email(email, options); -}; - - -internals.email = function (email, options = {}) { - if (typeof email !== 'string') { - throw new Error('Invalid input: email must be a string'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const http = __nccwpck_require__(13685); +const https = __nccwpck_require__(95687); +const pm = __nccwpck_require__(16443); +let tunnel; +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; +} +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); } - - if (!email) { - return { error: 'Address must be a non-empty string' }; +} +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; } - - // Unicode - - const ascii = !internals.nonAsciiRx.test(email); - if (!ascii) { - if (options.allowUnicode === false) { // Defaults to true - return { error: 'Address contains forbidden Unicode characters' }; + readBody() { + return new Promise(async (resolve, reject) => { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + }); + } +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + let parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + } + get(requestUrl, additionalHeaders) { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + } + del(requestUrl, additionalHeaders) { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + } + post(requestUrl, data, additionalHeaders) { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + } + patch(requestUrl, data, additionalHeaders) { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + } + put(requestUrl, data, additionalHeaders) { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + } + head(requestUrl, additionalHeaders) { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return this.request(verb, requestUrl, stream, additionalHeaders); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + async getJson(requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + let res = await this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async postJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async putJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + async patchJson(requestUrl, obj, additionalHeaders = {}) { + let data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + let res = await this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + async request(verb, requestUrl, data, headers) { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + let parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + while (numTries < maxTries) { + response = await this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (let i = 0; i < this.handlers.length; i++) { + if (this.handlers[i].canHandleAuthentication(response)) { + authenticationHandler = this.handlers[i]; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + let parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol == 'https:' && + parsedUrl.protocol != parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + await response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (let header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = await this.requestRaw(info, data); + redirectsRemaining--; + } + if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + await response.readBody(); + await this._performExponentialBackoff(numTries); + } } - - email = email.normalize('NFC'); + return response; } - - // Basic structure - - const parts = email.split('@'); - if (parts.length !== 2) { - return { error: parts.length > 2 ? 'Address cannot contain more than one @ character' : 'Address must contain one @ character' }; + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; } - - const [local, domain] = parts; - - if (!local) { - return { error: 'Address local part cannot be empty' }; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return new Promise((resolve, reject) => { + let callbackForResult = function (err, res) { + if (err) { + reject(err); + } + resolve(res); + }; + this.requestRawWithCallback(info, data, callbackForResult); + }); } - - if (!options.ignoreLength) { - if (email.length > 254) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3 - return { error: 'Address too long' }; + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + let socket; + if (typeof data === 'string') { + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } - - if (internals.encoder.encode(local).length > 64) { // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 - return { error: 'Address local part too long' }; + let callbackCalled = false; + let handleResult = (err, res) => { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + }; + let req = info.httpModule.request(info.options, (msg) => { + let res = new HttpClientResponse(msg); + handleResult(null, res); + }); + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error('Request timeout: ' + info.options.path), null); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err, null); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); } } - - // Validate parts - - return internals.local(local, ascii) || Domain.analyze(domain, options); -}; - - -internals.local = function (local, ascii) { - - const segments = local.split('.'); - for (const segment of segments) { - if (!segment.length) { - return { error: 'Address local part contains empty dot-separated segment' }; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + let parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + this.handlers.forEach(handler => { + handler.prepareRequest(info.options); + }); } - - if (ascii) { - if (!internals.atextRx.test(segment)) { - return { error: 'Address local part contains invalid character' }; + return info; + } + _mergeHeaders(headers) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; + } + _getAgent(parsedUrl) { + let agent; + let proxyUrl = pm.getProxyUrl(parsedUrl); + let useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (!!agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (!!this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + if (useProxy) { + // If using proxy, need tunnel + if (!tunnel) { + tunnel = __nccwpck_require__(74294); + } + const agentOptions = { + maxSockets: maxSockets, + keepAlive: this._keepAlive, + proxy: { + ...((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + }), + host: proxyUrl.hostname, + port: proxyUrl.port + } + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } - - continue; + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } - - for (const char of segment) { - if (internals.atextRx.test(char)) { - continue; - } - - const binary = internals.binary(char); - if (!internals.atomRx.test(binary)) { - return { error: 'Address local part contains invalid character' }; + return agent; + } + _performExponentialBackoff(retryNumber) { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + } + static dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + let a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; } } + return value; } -}; - - -internals.binary = function (char) { - - return Array.from(internals.encoder.encode(char)).map((v) => String.fromCharCode(v)).join(''); -}; - - -/* - From RFC 5321: - - Mailbox = Local-part "@" ( Domain / address-literal ) - - Local-part = Dot-string / Quoted-string - Dot-string = Atom *("." Atom) - Atom = 1*atext - atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" - - Domain = sub-domain *("." sub-domain) - sub-domain = Let-dig [Ldh-str] - Let-dig = ALPHA / DIGIT - Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig - - ALPHA = %x41-5A / %x61-7A ; a-z, A-Z - DIGIT = %x30-39 ; 0-9 - - From RFC 6531: - - sub-domain =/ U-label - atext =/ UTF8-non-ascii - - UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4 - - UTF8-2 = %xC2-DF UTF8-tail - UTF8-3 = %xE0 %xA0-BF UTF8-tail / - %xE1-EC 2( UTF8-tail ) / - %xED %x80-9F UTF8-tail / - %xEE-EF 2( UTF8-tail ) - UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / - %xF1-F3 3( UTF8-tail ) / - %xF4 %x80-8F 2( UTF8-tail ) - - UTF8-tail = %x80-BF - - Note: The following are not supported: - - RFC 5321: address-literal, Quoted-string - RFC 5322: obs-*, CFWS -*/ - - -internals.atextRx = /^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/; // _ included in \w - - -internals.atomRx = new RegExp([ - - // %xC2-DF UTF8-tail - '(?:[\\xc2-\\xdf][\\x80-\\xbf])', - - // %xE0 %xA0-BF UTF8-tail %xE1-EC 2( UTF8-tail ) %xED %x80-9F UTF8-tail %xEE-EF 2( UTF8-tail ) - '(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})', - - // %xF0 %x90-BF 2( UTF8-tail ) %xF1-F3 3( UTF8-tail ) %xF4 %x80-8F 2( UTF8-tail ) - '(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})' - -].join('|')); + async _processResponse(res, options) { + return new Promise(async (resolve, reject) => { + const statusCode = res.message.statusCode; + const response = { + statusCode: statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode == HttpCodes.NotFound) { + resolve(response); + } + let obj; + let contents; + // get the result from the body + try { + contents = await res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = 'Failed request: (' + statusCode + ')'; + } + let err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + }); + } +} +exports.HttpClient = HttpClient; /***/ }), -/***/ 9491: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Domain = __nccwpck_require__(95541); -const Email = __nccwpck_require__(67318); -const Tlds = __nccwpck_require__(5026); - - -const internals = { - defaultTlds: { allow: Tlds, deny: null } -}; - - -module.exports = { - domain: { - analyze(domain, options) { - - options = internals.options(options); - return Domain.analyze(domain, options); - }, - - isValid(domain, options) { - - options = internals.options(options); - return Domain.isValid(domain, options); - } - }, - email: { - analyze(email, options) { - - options = internals.options(options); - return Email.analyze(email, options); - }, +/***/ 16443: +/***/ ((__unused_webpack_module, exports) => { - isValid(email, options) { - options = internals.options(options); - return Email.isValid(email, options); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +function getProxyUrl(reqUrl) { + let usingSsl = reqUrl.protocol === 'https:'; + let proxyUrl; + if (checkBypass(reqUrl)) { + return proxyUrl; } -}; - - -internals.options = function (options) { - - if (!options) { - return { tlds: internals.defaultTlds }; + let proxyVar; + if (usingSsl) { + proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; } - - if (options.tlds === false) { // Defaults to true - return options; + else { + proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } - - if (!options.tlds || - options.tlds === true) { - - return Object.assign({}, options, { tlds: internals.defaultTlds }); + if (proxyVar) { + proxyUrl = new URL(proxyVar); } - - if (typeof options.tlds !== 'object') { - throw new Error('Invalid options: tlds must be a boolean or an object'); + return proxyUrl; +} +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - - if (options.tlds.deny) { - if (options.tlds.deny instanceof Set === false) { - throw new Error('Invalid options: tlds.deny must be a Set object'); - } - - if (options.tlds.allow) { - throw new Error('Invalid options: cannot specify both tlds.allow and tlds.deny lists'); - } - - return options; + let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; } - - if (options.tlds.allow === true) { - return Object.assign({}, options, { tlds: internals.defaultTlds }); + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); } - - if (options.tlds.allow instanceof Set === false) { - throw new Error('Invalid options: tlds.allow must be a Set object or true'); + else if (reqUrl.protocol === 'http:') { + reqPort = 80; } - - return options; -}; + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + let upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (let upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperReqHosts.some(x => x === upperNoProxyItem)) { + return true; + } + } + return false; +} +exports.checkBypass = checkBypass; /***/ }), -/***/ 5026: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -// http://data.iana.org/TLD/tlds-alpha-by-domain.txt -// # Version 2019091902, Last Updated Fri Sep 20 07: 07: 02 2019 UTC - - -internals.tlds = [ - 'AAA', - 'AARP', - 'ABARTH', - 'ABB', - 'ABBOTT', - 'ABBVIE', - 'ABC', - 'ABLE', - 'ABOGADO', - 'ABUDHABI', - 'AC', - 'ACADEMY', - 'ACCENTURE', - 'ACCOUNTANT', - 'ACCOUNTANTS', - 'ACO', - 'ACTOR', - 'AD', - 'ADAC', - 'ADS', - 'ADULT', - 'AE', - 'AEG', - 'AERO', - 'AETNA', - 'AF', - 'AFAMILYCOMPANY', - 'AFL', - 'AFRICA', - 'AG', - 'AGAKHAN', - 'AGENCY', - 'AI', - 'AIG', - 'AIGO', - 'AIRBUS', - 'AIRFORCE', - 'AIRTEL', - 'AKDN', - 'AL', - 'ALFAROMEO', - 'ALIBABA', - 'ALIPAY', - 'ALLFINANZ', - 'ALLSTATE', - 'ALLY', - 'ALSACE', - 'ALSTOM', - 'AM', - 'AMERICANEXPRESS', - 'AMERICANFAMILY', - 'AMEX', - 'AMFAM', - 'AMICA', - 'AMSTERDAM', - 'ANALYTICS', - 'ANDROID', - 'ANQUAN', - 'ANZ', - 'AO', - 'AOL', - 'APARTMENTS', - 'APP', - 'APPLE', - 'AQ', - 'AQUARELLE', - 'AR', - 'ARAB', - 'ARAMCO', - 'ARCHI', - 'ARMY', - 'ARPA', - 'ART', - 'ARTE', - 'AS', - 'ASDA', - 'ASIA', - 'ASSOCIATES', - 'AT', - 'ATHLETA', - 'ATTORNEY', - 'AU', - 'AUCTION', - 'AUDI', - 'AUDIBLE', - 'AUDIO', - 'AUSPOST', - 'AUTHOR', - 'AUTO', - 'AUTOS', - 'AVIANCA', - 'AW', - 'AWS', - 'AX', - 'AXA', - 'AZ', - 'AZURE', - 'BA', - 'BABY', - 'BAIDU', - 'BANAMEX', - 'BANANAREPUBLIC', - 'BAND', - 'BANK', - 'BAR', - 'BARCELONA', - 'BARCLAYCARD', - 'BARCLAYS', - 'BAREFOOT', - 'BARGAINS', - 'BASEBALL', - 'BASKETBALL', - 'BAUHAUS', - 'BAYERN', - 'BB', - 'BBC', - 'BBT', - 'BBVA', - 'BCG', - 'BCN', - 'BD', - 'BE', - 'BEATS', - 'BEAUTY', - 'BEER', - 'BENTLEY', - 'BERLIN', - 'BEST', - 'BESTBUY', - 'BET', - 'BF', - 'BG', - 'BH', - 'BHARTI', - 'BI', - 'BIBLE', - 'BID', - 'BIKE', - 'BING', - 'BINGO', - 'BIO', - 'BIZ', - 'BJ', - 'BLACK', - 'BLACKFRIDAY', - 'BLOCKBUSTER', - 'BLOG', - 'BLOOMBERG', - 'BLUE', - 'BM', - 'BMS', - 'BMW', - 'BN', - 'BNPPARIBAS', - 'BO', - 'BOATS', - 'BOEHRINGER', - 'BOFA', - 'BOM', - 'BOND', - 'BOO', - 'BOOK', - 'BOOKING', - 'BOSCH', - 'BOSTIK', - 'BOSTON', - 'BOT', - 'BOUTIQUE', - 'BOX', - 'BR', - 'BRADESCO', - 'BRIDGESTONE', - 'BROADWAY', - 'BROKER', - 'BROTHER', - 'BRUSSELS', - 'BS', - 'BT', - 'BUDAPEST', - 'BUGATTI', - 'BUILD', - 'BUILDERS', - 'BUSINESS', - 'BUY', - 'BUZZ', - 'BV', - 'BW', - 'BY', - 'BZ', - 'BZH', - 'CA', - 'CAB', - 'CAFE', - 'CAL', - 'CALL', - 'CALVINKLEIN', - 'CAM', - 'CAMERA', - 'CAMP', - 'CANCERRESEARCH', - 'CANON', - 'CAPETOWN', - 'CAPITAL', - 'CAPITALONE', - 'CAR', - 'CARAVAN', - 'CARDS', - 'CARE', - 'CAREER', - 'CAREERS', - 'CARS', - 'CARTIER', - 'CASA', - 'CASE', - 'CASEIH', - 'CASH', - 'CASINO', - 'CAT', - 'CATERING', - 'CATHOLIC', - 'CBA', - 'CBN', - 'CBRE', - 'CBS', - 'CC', - 'CD', - 'CEB', - 'CENTER', - 'CEO', - 'CERN', - 'CF', - 'CFA', - 'CFD', - 'CG', - 'CH', - 'CHANEL', - 'CHANNEL', - 'CHARITY', - 'CHASE', - 'CHAT', - 'CHEAP', - 'CHINTAI', - 'CHRISTMAS', - 'CHROME', - 'CHRYSLER', - 'CHURCH', - 'CI', - 'CIPRIANI', - 'CIRCLE', - 'CISCO', - 'CITADEL', - 'CITI', - 'CITIC', - 'CITY', - 'CITYEATS', - 'CK', - 'CL', - 'CLAIMS', - 'CLEANING', - 'CLICK', - 'CLINIC', - 'CLINIQUE', - 'CLOTHING', - 'CLOUD', - 'CLUB', - 'CLUBMED', - 'CM', - 'CN', - 'CO', - 'COACH', - 'CODES', - 'COFFEE', - 'COLLEGE', - 'COLOGNE', - 'COM', - 'COMCAST', - 'COMMBANK', - 'COMMUNITY', - 'COMPANY', - 'COMPARE', - 'COMPUTER', - 'COMSEC', - 'CONDOS', - 'CONSTRUCTION', - 'CONSULTING', - 'CONTACT', - 'CONTRACTORS', - 'COOKING', - 'COOKINGCHANNEL', - 'COOL', - 'COOP', - 'CORSICA', - 'COUNTRY', - 'COUPON', - 'COUPONS', - 'COURSES', - 'CR', - 'CREDIT', - 'CREDITCARD', - 'CREDITUNION', - 'CRICKET', - 'CROWN', - 'CRS', - 'CRUISE', - 'CRUISES', - 'CSC', - 'CU', - 'CUISINELLA', - 'CV', - 'CW', - 'CX', - 'CY', - 'CYMRU', - 'CYOU', - 'CZ', - 'DABUR', - 'DAD', - 'DANCE', - 'DATA', - 'DATE', - 'DATING', - 'DATSUN', - 'DAY', - 'DCLK', - 'DDS', - 'DE', - 'DEAL', - 'DEALER', - 'DEALS', - 'DEGREE', - 'DELIVERY', - 'DELL', - 'DELOITTE', - 'DELTA', - 'DEMOCRAT', - 'DENTAL', - 'DENTIST', - 'DESI', - 'DESIGN', - 'DEV', - 'DHL', - 'DIAMONDS', - 'DIET', - 'DIGITAL', - 'DIRECT', - 'DIRECTORY', - 'DISCOUNT', - 'DISCOVER', - 'DISH', - 'DIY', - 'DJ', - 'DK', - 'DM', - 'DNP', - 'DO', - 'DOCS', - 'DOCTOR', - 'DODGE', - 'DOG', - 'DOMAINS', - 'DOT', - 'DOWNLOAD', - 'DRIVE', - 'DTV', - 'DUBAI', - 'DUCK', - 'DUNLOP', - 'DUPONT', - 'DURBAN', - 'DVAG', - 'DVR', - 'DZ', - 'EARTH', - 'EAT', - 'EC', - 'ECO', - 'EDEKA', - 'EDU', - 'EDUCATION', - 'EE', - 'EG', - 'EMAIL', - 'EMERCK', - 'ENERGY', - 'ENGINEER', - 'ENGINEERING', - 'ENTERPRISES', - 'EPSON', - 'EQUIPMENT', - 'ER', - 'ERICSSON', - 'ERNI', - 'ES', - 'ESQ', - 'ESTATE', - 'ESURANCE', - 'ET', - 'ETISALAT', - 'EU', - 'EUROVISION', - 'EUS', - 'EVENTS', - 'EVERBANK', - 'EXCHANGE', - 'EXPERT', - 'EXPOSED', - 'EXPRESS', - 'EXTRASPACE', - 'FAGE', - 'FAIL', - 'FAIRWINDS', - 'FAITH', - 'FAMILY', - 'FAN', - 'FANS', - 'FARM', - 'FARMERS', - 'FASHION', - 'FAST', - 'FEDEX', - 'FEEDBACK', - 'FERRARI', - 'FERRERO', - 'FI', - 'FIAT', - 'FIDELITY', - 'FIDO', - 'FILM', - 'FINAL', - 'FINANCE', - 'FINANCIAL', - 'FIRE', - 'FIRESTONE', - 'FIRMDALE', - 'FISH', - 'FISHING', - 'FIT', - 'FITNESS', - 'FJ', - 'FK', - 'FLICKR', - 'FLIGHTS', - 'FLIR', - 'FLORIST', - 'FLOWERS', - 'FLY', - 'FM', - 'FO', - 'FOO', - 'FOOD', - 'FOODNETWORK', - 'FOOTBALL', - 'FORD', - 'FOREX', - 'FORSALE', - 'FORUM', - 'FOUNDATION', - 'FOX', - 'FR', - 'FREE', - 'FRESENIUS', - 'FRL', - 'FROGANS', - 'FRONTDOOR', - 'FRONTIER', - 'FTR', - 'FUJITSU', - 'FUJIXEROX', - 'FUN', - 'FUND', - 'FURNITURE', - 'FUTBOL', - 'FYI', - 'GA', - 'GAL', - 'GALLERY', - 'GALLO', - 'GALLUP', - 'GAME', - 'GAMES', - 'GAP', - 'GARDEN', - 'GAY', - 'GB', - 'GBIZ', - 'GD', - 'GDN', - 'GE', - 'GEA', - 'GENT', - 'GENTING', - 'GEORGE', - 'GF', - 'GG', - 'GGEE', - 'GH', - 'GI', - 'GIFT', - 'GIFTS', - 'GIVES', - 'GIVING', - 'GL', - 'GLADE', - 'GLASS', - 'GLE', - 'GLOBAL', - 'GLOBO', - 'GM', - 'GMAIL', - 'GMBH', - 'GMO', - 'GMX', - 'GN', - 'GODADDY', - 'GOLD', - 'GOLDPOINT', - 'GOLF', - 'GOO', - 'GOODYEAR', - 'GOOG', - 'GOOGLE', - 'GOP', - 'GOT', - 'GOV', - 'GP', - 'GQ', - 'GR', - 'GRAINGER', - 'GRAPHICS', - 'GRATIS', - 'GREEN', - 'GRIPE', - 'GROCERY', - 'GROUP', - 'GS', - 'GT', - 'GU', - 'GUARDIAN', - 'GUCCI', - 'GUGE', - 'GUIDE', - 'GUITARS', - 'GURU', - 'GW', - 'GY', - 'HAIR', - 'HAMBURG', - 'HANGOUT', - 'HAUS', - 'HBO', - 'HDFC', - 'HDFCBANK', - 'HEALTH', - 'HEALTHCARE', - 'HELP', - 'HELSINKI', - 'HERE', - 'HERMES', - 'HGTV', - 'HIPHOP', - 'HISAMITSU', - 'HITACHI', - 'HIV', - 'HK', - 'HKT', - 'HM', - 'HN', - 'HOCKEY', - 'HOLDINGS', - 'HOLIDAY', - 'HOMEDEPOT', - 'HOMEGOODS', - 'HOMES', - 'HOMESENSE', - 'HONDA', - 'HORSE', - 'HOSPITAL', - 'HOST', - 'HOSTING', - 'HOT', - 'HOTELES', - 'HOTELS', - 'HOTMAIL', - 'HOUSE', - 'HOW', - 'HR', - 'HSBC', - 'HT', - 'HU', - 'HUGHES', - 'HYATT', - 'HYUNDAI', - 'IBM', - 'ICBC', - 'ICE', - 'ICU', - 'ID', - 'IE', - 'IEEE', - 'IFM', - 'IKANO', - 'IL', - 'IM', - 'IMAMAT', - 'IMDB', - 'IMMO', - 'IMMOBILIEN', - 'IN', - 'INC', - 'INDUSTRIES', - 'INFINITI', - 'INFO', - 'ING', - 'INK', - 'INSTITUTE', - 'INSURANCE', - 'INSURE', - 'INT', - 'INTEL', - 'INTERNATIONAL', - 'INTUIT', - 'INVESTMENTS', - 'IO', - 'IPIRANGA', - 'IQ', - 'IR', - 'IRISH', - 'IS', - 'ISMAILI', - 'IST', - 'ISTANBUL', - 'IT', - 'ITAU', - 'ITV', - 'IVECO', - 'JAGUAR', - 'JAVA', - 'JCB', - 'JCP', - 'JE', - 'JEEP', - 'JETZT', - 'JEWELRY', - 'JIO', - 'JLL', - 'JM', - 'JMP', - 'JNJ', - 'JO', - 'JOBS', - 'JOBURG', - 'JOT', - 'JOY', - 'JP', - 'JPMORGAN', - 'JPRS', - 'JUEGOS', - 'JUNIPER', - 'KAUFEN', - 'KDDI', - 'KE', - 'KERRYHOTELS', - 'KERRYLOGISTICS', - 'KERRYPROPERTIES', - 'KFH', - 'KG', - 'KH', - 'KI', - 'KIA', - 'KIM', - 'KINDER', - 'KINDLE', - 'KITCHEN', - 'KIWI', - 'KM', - 'KN', - 'KOELN', - 'KOMATSU', - 'KOSHER', - 'KP', - 'KPMG', - 'KPN', - 'KR', - 'KRD', - 'KRED', - 'KUOKGROUP', - 'KW', - 'KY', - 'KYOTO', - 'KZ', - 'LA', - 'LACAIXA', - 'LADBROKES', - 'LAMBORGHINI', - 'LAMER', - 'LANCASTER', - 'LANCIA', - 'LANCOME', - 'LAND', - 'LANDROVER', - 'LANXESS', - 'LASALLE', - 'LAT', - 'LATINO', - 'LATROBE', - 'LAW', - 'LAWYER', - 'LB', - 'LC', - 'LDS', - 'LEASE', - 'LECLERC', - 'LEFRAK', - 'LEGAL', - 'LEGO', - 'LEXUS', - 'LGBT', - 'LI', - 'LIAISON', - 'LIDL', - 'LIFE', - 'LIFEINSURANCE', - 'LIFESTYLE', - 'LIGHTING', - 'LIKE', - 'LILLY', - 'LIMITED', - 'LIMO', - 'LINCOLN', - 'LINDE', - 'LINK', - 'LIPSY', - 'LIVE', - 'LIVING', - 'LIXIL', - 'LK', - 'LLC', - 'LOAN', - 'LOANS', - 'LOCKER', - 'LOCUS', - 'LOFT', - 'LOL', - 'LONDON', - 'LOTTE', - 'LOTTO', - 'LOVE', - 'LPL', - 'LPLFINANCIAL', - 'LR', - 'LS', - 'LT', - 'LTD', - 'LTDA', - 'LU', - 'LUNDBECK', - 'LUPIN', - 'LUXE', - 'LUXURY', - 'LV', - 'LY', - 'MA', - 'MACYS', - 'MADRID', - 'MAIF', - 'MAISON', - 'MAKEUP', - 'MAN', - 'MANAGEMENT', - 'MANGO', - 'MAP', - 'MARKET', - 'MARKETING', - 'MARKETS', - 'MARRIOTT', - 'MARSHALLS', - 'MASERATI', - 'MATTEL', - 'MBA', - 'MC', - 'MCKINSEY', - 'MD', - 'ME', - 'MED', - 'MEDIA', - 'MEET', - 'MELBOURNE', - 'MEME', - 'MEMORIAL', - 'MEN', - 'MENU', - 'MERCKMSD', - 'METLIFE', - 'MG', - 'MH', - 'MIAMI', - 'MICROSOFT', - 'MIL', - 'MINI', - 'MINT', - 'MIT', - 'MITSUBISHI', - 'MK', - 'ML', - 'MLB', - 'MLS', - 'MM', - 'MMA', - 'MN', - 'MO', - 'MOBI', - 'MOBILE', - 'MODA', - 'MOE', - 'MOI', - 'MOM', - 'MONASH', - 'MONEY', - 'MONSTER', - 'MOPAR', - 'MORMON', - 'MORTGAGE', - 'MOSCOW', - 'MOTO', - 'MOTORCYCLES', - 'MOV', - 'MOVIE', - 'MOVISTAR', - 'MP', - 'MQ', - 'MR', - 'MS', - 'MSD', - 'MT', - 'MTN', - 'MTR', - 'MU', - 'MUSEUM', - 'MUTUAL', - 'MV', - 'MW', - 'MX', - 'MY', - 'MZ', - 'NA', - 'NAB', - 'NADEX', - 'NAGOYA', - 'NAME', - 'NATIONWIDE', - 'NATURA', - 'NAVY', - 'NBA', - 'NC', - 'NE', - 'NEC', - 'NET', - 'NETBANK', - 'NETFLIX', - 'NETWORK', - 'NEUSTAR', - 'NEW', - 'NEWHOLLAND', - 'NEWS', - 'NEXT', - 'NEXTDIRECT', - 'NEXUS', - 'NF', - 'NFL', - 'NG', - 'NGO', - 'NHK', - 'NI', - 'NICO', - 'NIKE', - 'NIKON', - 'NINJA', - 'NISSAN', - 'NISSAY', - 'NL', - 'NO', - 'NOKIA', - 'NORTHWESTERNMUTUAL', - 'NORTON', - 'NOW', - 'NOWRUZ', - 'NOWTV', - 'NP', - 'NR', - 'NRA', - 'NRW', - 'NTT', - 'NU', - 'NYC', - 'NZ', - 'OBI', - 'OBSERVER', - 'OFF', - 'OFFICE', - 'OKINAWA', - 'OLAYAN', - 'OLAYANGROUP', - 'OLDNAVY', - 'OLLO', - 'OM', - 'OMEGA', - 'ONE', - 'ONG', - 'ONL', - 'ONLINE', - 'ONYOURSIDE', - 'OOO', - 'OPEN', - 'ORACLE', - 'ORANGE', - 'ORG', - 'ORGANIC', - 'ORIGINS', - 'OSAKA', - 'OTSUKA', - 'OTT', - 'OVH', - 'PA', - 'PAGE', - 'PANASONIC', - 'PARIS', - 'PARS', - 'PARTNERS', - 'PARTS', - 'PARTY', - 'PASSAGENS', - 'PAY', - 'PCCW', - 'PE', - 'PET', - 'PF', - 'PFIZER', - 'PG', - 'PH', - 'PHARMACY', - 'PHD', - 'PHILIPS', - 'PHONE', - 'PHOTO', - 'PHOTOGRAPHY', - 'PHOTOS', - 'PHYSIO', - 'PIAGET', - 'PICS', - 'PICTET', - 'PICTURES', - 'PID', - 'PIN', - 'PING', - 'PINK', - 'PIONEER', - 'PIZZA', - 'PK', - 'PL', - 'PLACE', - 'PLAY', - 'PLAYSTATION', - 'PLUMBING', - 'PLUS', - 'PM', - 'PN', - 'PNC', - 'POHL', - 'POKER', - 'POLITIE', - 'PORN', - 'POST', - 'PR', - 'PRAMERICA', - 'PRAXI', - 'PRESS', - 'PRIME', - 'PRO', - 'PROD', - 'PRODUCTIONS', - 'PROF', - 'PROGRESSIVE', - 'PROMO', - 'PROPERTIES', - 'PROPERTY', - 'PROTECTION', - 'PRU', - 'PRUDENTIAL', - 'PS', - 'PT', - 'PUB', - 'PW', - 'PWC', - 'PY', - 'QA', - 'QPON', - 'QUEBEC', - 'QUEST', - 'QVC', - 'RACING', - 'RADIO', - 'RAID', - 'RE', - 'READ', - 'REALESTATE', - 'REALTOR', - 'REALTY', - 'RECIPES', - 'RED', - 'REDSTONE', - 'REDUMBRELLA', - 'REHAB', - 'REISE', - 'REISEN', - 'REIT', - 'RELIANCE', - 'REN', - 'RENT', - 'RENTALS', - 'REPAIR', - 'REPORT', - 'REPUBLICAN', - 'REST', - 'RESTAURANT', - 'REVIEW', - 'REVIEWS', - 'REXROTH', - 'RICH', - 'RICHARDLI', - 'RICOH', - 'RIGHTATHOME', - 'RIL', - 'RIO', - 'RIP', - 'RMIT', - 'RO', - 'ROCHER', - 'ROCKS', - 'RODEO', - 'ROGERS', - 'ROOM', - 'RS', - 'RSVP', - 'RU', - 'RUGBY', - 'RUHR', - 'RUN', - 'RW', - 'RWE', - 'RYUKYU', - 'SA', - 'SAARLAND', - 'SAFE', - 'SAFETY', - 'SAKURA', - 'SALE', - 'SALON', - 'SAMSCLUB', - 'SAMSUNG', - 'SANDVIK', - 'SANDVIKCOROMANT', - 'SANOFI', - 'SAP', - 'SARL', - 'SAS', - 'SAVE', - 'SAXO', - 'SB', - 'SBI', - 'SBS', - 'SC', - 'SCA', - 'SCB', - 'SCHAEFFLER', - 'SCHMIDT', - 'SCHOLARSHIPS', - 'SCHOOL', - 'SCHULE', - 'SCHWARZ', - 'SCIENCE', - 'SCJOHNSON', - 'SCOR', - 'SCOT', - 'SD', - 'SE', - 'SEARCH', - 'SEAT', - 'SECURE', - 'SECURITY', - 'SEEK', - 'SELECT', - 'SENER', - 'SERVICES', - 'SES', - 'SEVEN', - 'SEW', - 'SEX', - 'SEXY', - 'SFR', - 'SG', - 'SH', - 'SHANGRILA', - 'SHARP', - 'SHAW', - 'SHELL', - 'SHIA', - 'SHIKSHA', - 'SHOES', - 'SHOP', - 'SHOPPING', - 'SHOUJI', - 'SHOW', - 'SHOWTIME', - 'SHRIRAM', - 'SI', - 'SILK', - 'SINA', - 'SINGLES', - 'SITE', - 'SJ', - 'SK', - 'SKI', - 'SKIN', - 'SKY', - 'SKYPE', - 'SL', - 'SLING', - 'SM', - 'SMART', - 'SMILE', - 'SN', - 'SNCF', - 'SO', - 'SOCCER', - 'SOCIAL', - 'SOFTBANK', - 'SOFTWARE', - 'SOHU', - 'SOLAR', - 'SOLUTIONS', - 'SONG', - 'SONY', - 'SOY', - 'SPACE', - 'SPORT', - 'SPOT', - 'SPREADBETTING', - 'SR', - 'SRL', - 'SRT', - 'SS', - 'ST', - 'STADA', - 'STAPLES', - 'STAR', - 'STATEBANK', - 'STATEFARM', - 'STC', - 'STCGROUP', - 'STOCKHOLM', - 'STORAGE', - 'STORE', - 'STREAM', - 'STUDIO', - 'STUDY', - 'STYLE', - 'SU', - 'SUCKS', - 'SUPPLIES', - 'SUPPLY', - 'SUPPORT', - 'SURF', - 'SURGERY', - 'SUZUKI', - 'SV', - 'SWATCH', - 'SWIFTCOVER', - 'SWISS', - 'SX', - 'SY', - 'SYDNEY', - 'SYMANTEC', - 'SYSTEMS', - 'SZ', - 'TAB', - 'TAIPEI', - 'TALK', - 'TAOBAO', - 'TARGET', - 'TATAMOTORS', - 'TATAR', - 'TATTOO', - 'TAX', - 'TAXI', - 'TC', - 'TCI', - 'TD', - 'TDK', - 'TEAM', - 'TECH', - 'TECHNOLOGY', - 'TEL', - 'TELEFONICA', - 'TEMASEK', - 'TENNIS', - 'TEVA', - 'TF', - 'TG', - 'TH', - 'THD', - 'THEATER', - 'THEATRE', - 'TIAA', - 'TICKETS', - 'TIENDA', - 'TIFFANY', - 'TIPS', - 'TIRES', - 'TIROL', - 'TJ', - 'TJMAXX', - 'TJX', - 'TK', - 'TKMAXX', - 'TL', - 'TM', - 'TMALL', - 'TN', - 'TO', - 'TODAY', - 'TOKYO', - 'TOOLS', - 'TOP', - 'TORAY', - 'TOSHIBA', - 'TOTAL', - 'TOURS', - 'TOWN', - 'TOYOTA', - 'TOYS', - 'TR', - 'TRADE', - 'TRADING', - 'TRAINING', - 'TRAVEL', - 'TRAVELCHANNEL', - 'TRAVELERS', - 'TRAVELERSINSURANCE', - 'TRUST', - 'TRV', - 'TT', - 'TUBE', - 'TUI', - 'TUNES', - 'TUSHU', - 'TV', - 'TVS', - 'TW', - 'TZ', - 'UA', - 'UBANK', - 'UBS', - 'UCONNECT', - 'UG', - 'UK', - 'UNICOM', - 'UNIVERSITY', - 'UNO', - 'UOL', - 'UPS', - 'US', - 'UY', - 'UZ', - 'VA', - 'VACATIONS', - 'VANA', - 'VANGUARD', - 'VC', - 'VE', - 'VEGAS', - 'VENTURES', - 'VERISIGN', - 'VERSICHERUNG', - 'VET', - 'VG', - 'VI', - 'VIAJES', - 'VIDEO', - 'VIG', - 'VIKING', - 'VILLAS', - 'VIN', - 'VIP', - 'VIRGIN', - 'VISA', - 'VISION', - 'VISTAPRINT', - 'VIVA', - 'VIVO', - 'VLAANDEREN', - 'VN', - 'VODKA', - 'VOLKSWAGEN', - 'VOLVO', - 'VOTE', - 'VOTING', - 'VOTO', - 'VOYAGE', - 'VU', - 'VUELOS', - 'WALES', - 'WALMART', - 'WALTER', - 'WANG', - 'WANGGOU', - 'WARMAN', - 'WATCH', - 'WATCHES', - 'WEATHER', - 'WEATHERCHANNEL', - 'WEBCAM', - 'WEBER', - 'WEBSITE', - 'WED', - 'WEDDING', - 'WEIBO', - 'WEIR', - 'WF', - 'WHOSWHO', - 'WIEN', - 'WIKI', - 'WILLIAMHILL', - 'WIN', - 'WINDOWS', - 'WINE', - 'WINNERS', - 'WME', - 'WOLTERSKLUWER', - 'WOODSIDE', - 'WORK', - 'WORKS', - 'WORLD', - 'WOW', - 'WS', - 'WTC', - 'WTF', - 'XBOX', - 'XEROX', - 'XFINITY', - 'XIHUAN', - 'XIN', - 'XN--11B4C3D', - 'XN--1CK2E1B', - 'XN--1QQW23A', - 'XN--2SCRJ9C', - 'XN--30RR7Y', - 'XN--3BST00M', - 'XN--3DS443G', - 'XN--3E0B707E', - 'XN--3HCRJ9C', - 'XN--3OQ18VL8PN36A', - 'XN--3PXU8K', - 'XN--42C2D9A', - 'XN--45BR5CYL', - 'XN--45BRJ9C', - 'XN--45Q11C', - 'XN--4GBRIM', - 'XN--54B7FTA0CC', - 'XN--55QW42G', - 'XN--55QX5D', - 'XN--5SU34J936BGSG', - 'XN--5TZM5G', - 'XN--6FRZ82G', - 'XN--6QQ986B3XL', - 'XN--80ADXHKS', - 'XN--80AO21A', - 'XN--80AQECDR1A', - 'XN--80ASEHDB', - 'XN--80ASWG', - 'XN--8Y0A063A', - 'XN--90A3AC', - 'XN--90AE', - 'XN--90AIS', - 'XN--9DBQ2A', - 'XN--9ET52U', - 'XN--9KRT00A', - 'XN--B4W605FERD', - 'XN--BCK1B9A5DRE4C', - 'XN--C1AVG', - 'XN--C2BR7G', - 'XN--CCK2B3B', - 'XN--CG4BKI', - 'XN--CLCHC0EA0B2G2A9GCD', - 'XN--CZR694B', - 'XN--CZRS0T', - 'XN--CZRU2D', - 'XN--D1ACJ3B', - 'XN--D1ALF', - 'XN--E1A4C', - 'XN--ECKVDTC9D', - 'XN--EFVY88H', - 'XN--ESTV75G', - 'XN--FCT429K', - 'XN--FHBEI', - 'XN--FIQ228C5HS', - 'XN--FIQ64B', - 'XN--FIQS8S', - 'XN--FIQZ9S', - 'XN--FJQ720A', - 'XN--FLW351E', - 'XN--FPCRJ9C3D', - 'XN--FZC2C9E2C', - 'XN--FZYS8D69UVGM', - 'XN--G2XX48C', - 'XN--GCKR3F0F', - 'XN--GECRJ9C', - 'XN--GK3AT1E', - 'XN--H2BREG3EVE', - 'XN--H2BRJ9C', - 'XN--H2BRJ9C8C', - 'XN--HXT814E', - 'XN--I1B6B1A6A2E', - 'XN--IMR513N', - 'XN--IO0A7I', - 'XN--J1AEF', - 'XN--J1AMH', - 'XN--J6W193G', - 'XN--JLQ61U9W7B', - 'XN--JVR189M', - 'XN--KCRX77D1X4A', - 'XN--KPRW13D', - 'XN--KPRY57D', - 'XN--KPU716F', - 'XN--KPUT3I', - 'XN--L1ACC', - 'XN--LGBBAT1AD8J', - 'XN--MGB9AWBF', - 'XN--MGBA3A3EJT', - 'XN--MGBA3A4F16A', - 'XN--MGBA7C0BBN0A', - 'XN--MGBAAKC7DVF', - 'XN--MGBAAM7A8H', - 'XN--MGBAB2BD', - 'XN--MGBAH1A3HJKRD', - 'XN--MGBAI9AZGQP6J', - 'XN--MGBAYH7GPA', - 'XN--MGBBH1A', - 'XN--MGBBH1A71E', - 'XN--MGBC0A9AZCG', - 'XN--MGBCA7DZDO', - 'XN--MGBERP4A5D4AR', - 'XN--MGBGU82A', - 'XN--MGBI4ECEXP', - 'XN--MGBPL2FH', - 'XN--MGBT3DHD', - 'XN--MGBTX2B', - 'XN--MGBX4CD0AB', - 'XN--MIX891F', - 'XN--MK1BU44C', - 'XN--MXTQ1M', - 'XN--NGBC5AZD', - 'XN--NGBE9E0A', - 'XN--NGBRX', - 'XN--NODE', - 'XN--NQV7F', - 'XN--NQV7FS00EMA', - 'XN--NYQY26A', - 'XN--O3CW4H', - 'XN--OGBPF8FL', - 'XN--OTU796D', - 'XN--P1ACF', - 'XN--P1AI', - 'XN--PBT977C', - 'XN--PGBS0DH', - 'XN--PSSY2U', - 'XN--Q9JYB4C', - 'XN--QCKA1PMC', - 'XN--QXA6A', - 'XN--QXAM', - 'XN--RHQV96G', - 'XN--ROVU88B', - 'XN--RVC1E0AM3E', - 'XN--S9BRJ9C', - 'XN--SES554G', - 'XN--T60B56A', - 'XN--TCKWE', - 'XN--TIQ49XQYJ', - 'XN--UNUP4Y', - 'XN--VERMGENSBERATER-CTB', - 'XN--VERMGENSBERATUNG-PWB', - 'XN--VHQUV', - 'XN--VUQ861B', - 'XN--W4R85EL8FHU5DNRA', - 'XN--W4RS40L', - 'XN--WGBH1C', - 'XN--WGBL6A', - 'XN--XHQ521B', - 'XN--XKC2AL3HYE2A', - 'XN--XKC2DL3A5EE0H', - 'XN--Y9A3AQ', - 'XN--YFRO4I67O', - 'XN--YGBI2AMMX', - 'XN--ZFR164B', - 'XXX', - 'XYZ', - 'YACHTS', - 'YAHOO', - 'YAMAXUN', - 'YANDEX', - 'YE', - 'YODOBASHI', - 'YOGA', - 'YOKOHAMA', - 'YOU', - 'YOUTUBE', - 'YT', - 'YUN', - 'ZA', - 'ZAPPOS', - 'ZARA', - 'ZERO', - 'ZIP', - 'ZM', - 'ZONE', - 'ZUERICH', - 'ZW' -]; - - -// Keep as upper-case to make updating from source easier +/***/ 47541: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = new Set(internals.tlds.map((tld) => tld.toLowerCase())); -/***/ }), +Object.defineProperty(exports, "__esModule", ({ value: true })); -/***/ 97174: -/***/ ((__unused_webpack_module, exports) => { +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -"use strict"; +var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(36234); +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; + } -const internals = { - suspectRx: /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*\:/ -}; + return obj; +} +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); -exports.parse = function (text, reviver, options) { + 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); + } - // Normalize arguments + return keys; +} - if (!options) { - if (reviver && - typeof reviver === 'object') { +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - options = reviver; - reviver = undefined; - } - else { - options = {}; - } + 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)); + }); } + } - // Parse normally, allowing exceptions + return target; +} - const obj = JSON.parse(text, reviver); +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - // options.protoAction: 'error' (default) / 'remove' / 'ignore' + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } - if (options.protoAction === 'ignore') { - return obj; - } + return target; +} - // Ignore null and non-objects +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; - if (!obj || - typeof obj !== 'object') { + var target = _objectWithoutPropertiesLoose(source, excluded); - return obj; - } + var key, i; - // Check original string for potential exploit + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - if (!text.match(internals.suspectRx)) { - return obj; + 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]; } + } - // Scan result for proto keys - - exports.scan(obj, options); - - return obj; -}; - - -exports.scan = function (obj, options) { - - options = options || {}; - - let next = [obj]; - - while (next.length) { - const nodes = next; - next = []; - - for (const node of nodes) { - if (Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly - if (options.protoAction !== 'remove') { - throw new SyntaxError('Object contains forbidden prototype property'); - } - - delete node.__proto__; - } - - for (const key in node) { - const value = node[key]; - if (value && - typeof value === 'object') { - - next.push(node[key]); - } - } - } - } -}; + return target; +} +// https://github.com/isaacs/node-lru-cache#readme +function getCache() { + return new LRU({ + // cache max. 15000 tokens, that will use less than 10mb memory + max: 15000, + // Cache for 1 minute less than GitHub expiry + maxAge: 1000 * 60 * 59 + }); +} +async function get(cache, options) { + const cacheKey = optionsToCacheKey(options); + const result = await cache.get(cacheKey); -exports.safeParse = function (text, reviver) { + if (!result) { + return; + } - try { - return exports.parse(text, reviver); - } - catch (ignoreError) { - return null; + const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|"); + const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => { + if (/!$/.test(string)) { + permissions[string.slice(0, -1)] = "write"; + } else { + permissions[string] = "read"; } -}; + return permissions; + }, {}); + return { + token, + createdAt, + expiresAt, + permissions, + repositoryIds: options.repositoryIds, + singleFileName, + repositorySelection: repositorySelection + }; +} +async function set(cache, options, data) { + const key = optionsToCacheKey(options); + const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(","); + const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|"); + await cache.set(key, value); +} -/***/ }), - -/***/ 85545: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function optionsToCacheKey({ + installationId, + permissions = {}, + repositoryIds = [] +}) { + 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("|"); +} -"use strict"; +function toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName +}) { + return Object.assign({ + type: "token", + tokenType: "installation", + token, + installationId, + permissions, + createdAt, + expiresAt, + repositorySelection + }, repositoryIds ? { + repositoryIds + } : null, singleFileName ? { + singleFileName + } : null); +} +async function getInstallationAuthentication(state, options, customRequest) { + const installationId = Number(options.installationId || state.installationId); -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Merge = __nccwpck_require__(60445); -const Utils = __nccwpck_require__(30417); + if (!installationId) { + throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); + } + if (options.factory) { + const { + type, + factory + } = options, + factoryAuthOptions = _objectWithoutProperties(options, ["type", "factory"]); // @ts-ignore if `options.factory` is set, the return type for `auth()` should be `Promise>` -const internals = {}; + return factory(Object.assign({}, state, factoryAuthOptions)); + } -module.exports = function (defaults, source, options = {}) { + const optionsWithInstallationTokenFromState = Object.assign({ + installationId + }, options); - Assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object'); - Assert(!source || source === true || typeof source === 'object', 'Invalid source value: must be true, falsy or an object'); - Assert(typeof options === 'object', 'Invalid options: must be an object'); + if (!options.refresh) { + const result = await get(state.cache, optionsWithInstallationTokenFromState); - if (!source) { // If no source, return null - return null; + if (result) { + const { + token, + createdAt, + expiresAt, + permissions, + repositoryIds, + singleFileName, + repositorySelection + } = result; + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + permissions, + repositorySelection, + repositoryIds, + singleFileName + }); } + } - if (options.shallow) { - return internals.applyToDefaultsWithShallow(defaults, source, options); + const appAuthentication = await getAppAuthentication(state); + const request = customRequest || state.request; + const { + data: { + token, + expires_at: expiresAt, + repositories, + permissions, + // @ts-ignore + repository_selection: repositorySelection, + // @ts-ignore + single_file: singleFileName } - - const copy = Clone(defaults); - - if (source === true) { // If source is set to true, use defaults - return copy; + } = await request("POST /app/installations/{installation_id}/access_tokens", { + installation_id: installationId, + repository_ids: options.repositoryIds, + permissions: options.permissions, + mediaType: { + previews: ["machine-man"] + }, + headers: { + authorization: `bearer ${appAuthentication.token}` } + }); + const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; + const createdAt = new Date().toISOString(); + await set(state.cache, optionsWithInstallationTokenFromState, { + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName + }); + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName + }); +} - const nullOverride = options.nullOverride !== undefined ? options.nullOverride : false; - return Merge(copy, source, { nullOverride, mergeArrays: false }); -}; - - -internals.applyToDefaultsWithShallow = function (defaults, source, options) { - - const keys = options.shallow; - Assert(Array.isArray(keys), 'Invalid keys'); +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. - options = Object.assign({}, options); - options.shallow = false; + 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); - const copy = Clone(defaults, { shallow: keys }); + 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) + }); + } - if (source === true) { // If source is set to true, use defaults - return copy; + const { + data: { + access_token: token, + scope } + } = response; + return { + type: "token", + tokenType: "oauth", + token, + scopes: scope.split(/,\s*/).filter(Boolean) + }; +} - const storage = Utils.store(source, keys); // Move shallow copy items to storage - Merge(copy, source, { mergeArrays: false, nullOverride: false }); // Deep copy the rest - Utils.restore(copy, source, storage); // Shallow copy the stored items and restore - return copy; -}; - +async function auth(state, options) { + if (options.type === "app") { + return getAppAuthentication(state); + } -/***/ }), + if (options.type === "installation") { + return getInstallationAuthentication(state, options); + } -/***/ 32718: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return getOAuthAuthentication(state, options); +} -"use strict"; +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) +// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js +function routeMatcher(paths) { + // EXAMPLE. For the following paths: -const AssertError = __nccwpck_require__(35563); + /* [ + "/orgs/{org}/invitations", + "/repos/{owner}/{repo}/collaborators/{username}" + ] */ + const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: -const internals = {}; + /* [ + '/orgs/(?:.+?)/invitations', + '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' + ] */ + const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: -module.exports = function (condition, ...args) { + /* + ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ + It may look scary, but paste it into https://www.debuggex.com/ + and it will make a lot more sense! + */ - if (condition) { - return; - } + return new RegExp(regex, "i"); +} - if (args.length === 1 && - args[0] instanceof Error) { +const REGEX = routeMatcher(PATHS); +function requiresAppAuth(url) { + return !!url && REGEX.test(url); +} - throw args[0]; - } +const FIVE_SECONDS_IN_MS = 5 * 1000; - throw new AssertError(args); -}; +function isNotTimeSkewError(error) { + return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/)); +} +async function hook(state, request, route, parameters) { + let endpoint = request.endpoint.merge(route, parameters); -/***/ }), + if (requiresAppAuth(endpoint.url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { + const { + token + } = await getAppAuthentication(state); + endpoint.headers.authorization = `bearer ${token}`; + let response; -/***/ 86999: -/***/ ((module) => { + try { + response = await request(endpoint); + } catch (error) { + // If there's an issue with the expiration, regenerate the token and try again. + // Otherwise rethrow the error for upstream handling. + if (isNotTimeSkewError(error)) { + throw error; + } // If the date header is missing, we can't correct the system time skew. + // Throw the error to be handled upstream. -"use strict"; + if (typeof error.headers.date === "undefined") { + throw error; + } -const internals = {}; + const diff = Math.floor((Date.parse(error.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 { + token + } = await getAppAuthentication(_objectSpread2(_objectSpread2({}, state), {}, { + timeDifference: diff + })); + endpoint.headers.authorization = `bearer ${token}`; + return request(endpoint); + } + return response; + } -module.exports = internals.Bench = class { + const { + token, + createdAt + } = await getInstallationAuthentication(state, {}, request); + endpoint.headers.authorization = `token ${token}`; + return sendRequestWithRetries(state, request, endpoint, createdAt); +} +/** + * Newly created tokens might not be accessible immediately after creation. + * In case of a 401 response, we retry with an exponential delay until more + * than five seconds pass since the creation of the token. + * + * @see https://github.com/octokit/auth-app.js/issues/65 + */ - constructor() { +async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { + const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); - this.ts = 0; - this.reset(); + try { + return await request(options); + } catch (error) { + if (error.status !== 401) { + throw error; } - reset() { + if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) { + if (retries > 0) { + error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; + } - this.ts = internals.Bench.now(); + throw error; } - elapsed() { + ++retries; + const awaitTime = retries * 1000; + state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`); + await new Promise(resolve => setTimeout(resolve, awaitTime)); + return sendRequestWithRetries(state, request, options, createdAt, retries); + } +} - return internals.Bench.now() - this.ts; - } +const VERSION = "2.10.5"; - static now() { +const createAppAuth = function createAppAuth(options) { + const log = Object.assign({ + warn: console.warn.bind(console) + }, options.log); - const ts = process.hrtime(); - return (ts[0] * 1e3) + (ts[1] / 1e6); - } + if ("id" in options) { + log.warn(new deprecation.Deprecation('[@octokit/auth-app] "createAppAuth({ id })" is deprecated, use "createAppAuth({ appId })" instead')); + } + + const state = Object.assign({ + request: request.request.defaults({ + headers: { + "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } + }), + cache: getCache() + }, options, { + appId: Number("appId" in options ? options.appId : options.id) + }, options.installationId ? { + installationId: Number(options.installationId) + } : {}, { + log + }); + return Object.assign(auth.bind(null, state), { + hook: hook.bind(null, state) + }); }; +exports.createAppAuth = createAppAuth; +//# sourceMappingURL=index.js.map -/***/ }), -/***/ 77820: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 40334: +/***/ ((__unused_webpack_module, exports) => { -const Ignore = __nccwpck_require__(12887); +Object.defineProperty(exports, "__esModule", ({ value: true })); -const internals = {}; +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}`; + } -module.exports = function () { + return `token ${token}`; +} - return new Promise(Ignore); // $lab:coverage:ignore$ -}; +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"); + } -/***/ 85578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; -"use strict"; +exports.createTokenAuth = createTokenAuth; +//# sourceMappingURL=index.js.map -const Types = __nccwpck_require__(84340); -const Utils = __nccwpck_require__(30417); +/***/ }), +/***/ 79567: +/***/ ((__unused_webpack_module, exports) => { -const internals = { - needsProtoHack: new Set([Types.set, Types.map, Types.weakSet, Types.weakMap]) -}; -module.exports = internals.clone = function (obj, options = {}, _seen = null) { +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (typeof obj !== 'object' || - obj === null) { +async function auth(reason) { + return { + type: "unauthenticated", + reason + }; +} - return obj; - } +function isRateLimitError(error) { + if (error.status !== 403) { + return false; + } + /* istanbul ignore if */ - let clone = internals.clone; - let seen = _seen; - if (options.shallow) { - if (options.shallow !== true) { - return internals.cloneWithShallow(obj, options); - } + if (!error.headers) { + return false; + } - clone = (value) => value; - } - else { - seen = seen || new Map(); + return error.headers["x-ratelimit-remaining"] === "0"; +} - const lookup = seen.get(obj); - if (lookup) { - return lookup; - } - } +const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; +function isAbuseLimitError(error) { + if (error.status !== 403) { + return false; + } - // Built-in object types + return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); +} - const baseProto = Types.getInternalProto(obj); - if (baseProto === Types.buffer) { - return Buffer && Buffer.from(obj); // $lab:coverage:ignore$ +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 (baseProto === Types.date) { - return new Date(obj.getTime()); + if (isRateLimitError(error)) { + error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; + throw error; } - if (baseProto === Types.regex) { - return new RegExp(obj); + if (isAbuseLimitError(error)) { + error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; + throw error; } - // Generic objects - - const newObj = internals.base(obj, baseProto, options); - if (newObj === obj) { - return obj; + if (error.status === 401) { + error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; + throw error; } - if (seen) { - seen.set(obj, newObj); // Set seen, since obj could recurse + if (error.status >= 400 && error.status < 500) { + error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); } - if (baseProto === Types.set) { - for (const value of obj) { - newObj.add(clone(value, options, seen)); - } - } - else if (baseProto === Types.map) { - for (const [key, value] of obj) { - newObj.set(key, clone(value, options, seen)); - } - } + throw error; + }); +} - const keys = Utils.keys(obj, options); - for (const key of keys) { - if (baseProto === Types.array && - key === 'length') { +const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { + if (!options || !options.reason) { + throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); + } - newObj.length = obj.length; - continue; - } + return Object.assign(auth.bind(null, options.reason), { + hook: hook.bind(null, options.reason) + }); +}; - const descriptor = Object.getOwnPropertyDescriptor(obj, key); - if (descriptor) { - if (descriptor.get || - descriptor.set) { +exports.createUnauthenticatedAuth = createUnauthenticatedAuth; +//# sourceMappingURL=index.js.map - Object.defineProperty(newObj, key, descriptor); - } - else if (descriptor.enumerable) { - newObj[key] = clone(obj[key], options, seen); - } - else { - Object.defineProperty(newObj, key, { enumerable: false, writable: true, configurable: true, value: clone(obj[key], options, seen) }); - } - } - else { - Object.defineProperty(newObj, key, { - enumerable: true, - writable: true, - configurable: true, - value: clone(obj[key], options, seen) - }); - } - } - return newObj; -}; +/***/ }), +/***/ 76762: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -internals.cloneWithShallow = function (source, options) { - const keys = options.shallow; - options = Object.assign({}, options); - options.shallow = false; - const storage = Utils.store(source, keys); // Move shallow copy items to storage - const copy = internals.clone(source, options); // Deep copy the rest - Utils.restore(copy, source, storage); // Shallow copy the stored items and restore - return copy; -}; +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); -internals.base = function (obj, baseProto, options) { +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - if (baseProto === Types.array) { - return []; - } + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } - if (options.prototype === false) { // Defaults to true - if (internals.needsProtoHack.has(baseProto)) { - return new baseProto.constructor(); - } + return target; +} - return {}; - } +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; - const proto = Object.getPrototypeOf(obj); - if (proto && - proto.isImmutable) { + var target = _objectWithoutPropertiesLoose(source, excluded); - return obj; - } + var key, i; - if (internals.needsProtoHack.has(baseProto)) { - const newObj = new proto.constructor(); - if (proto !== baseProto) { - Object.setPrototypeOf(newObj, proto); - } + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - return newObj; + 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 Object.create(proto); -}; - - -/***/ }), - -/***/ 39157: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + return target; +} +const VERSION = "3.2.4"; -const Assert = __nccwpck_require__(32718); -const DeepEqual = __nccwpck_require__(55801); -const EscapeRegex = __nccwpck_require__(91965); -const Utils = __nccwpck_require__(30417); +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: "" + } + }; // prepend default user agent with `options.userAgent` if set + requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); -const internals = {}; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } -module.exports = function (ref, values, options = {}) { // options: { deep, once, only, part, symbols } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } - /* - string -> string(s) - array -> item(s) - object -> key(s) - object -> object (key:value) - */ + 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 (typeof values !== 'object') { - values = [values]; - } + if (!options.authStrategy) { + if (!options.auth) { + // (1) + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + // (2) + const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ - Assert(!Array.isArray(values) || values.length, 'Values array cannot be empty'); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { + authStrategy + } = options, + otherOptions = _objectWithoutProperties(options, ["authStrategy"]); - // String + 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 ¯\_(ツ)_/¯ - if (typeof ref === 'string') { - return internals.string(ref, values, options); - } + hook.wrap("request", auth.hook); + this.auth = auth; + } // apply plugins + // https://stackoverflow.com/a/16345172 - // Array - if (Array.isArray(ref)) { - return internals.array(ref, values, options); - } + const classConstructor = this.constructor; + classConstructor.plugins.forEach(plugin => { + Object.assign(this, plugin(this, options)); + }); + } - // Object + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; - Assert(typeof ref === 'object', 'Reference must be string or an object'); - return internals.object(ref, values, options); -}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null)); + } -internals.array = function (ref, values, options) { + }; + return OctokitWithDefaults; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ - if (!Array.isArray(values)) { - values = [values]; - } - if (!ref.length) { - return false; - } + static plugin(...newPlugins) { + var _a; - if (options.only && - options.once && - ref.length !== values.length) { + const currentPlugins = this.plugins; + const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); + return NewOctokit; + } - return false; - } +} +Octokit.VERSION = VERSION; +Octokit.plugins = []; - let compare; +exports.Octokit = Octokit; +//# sourceMappingURL=index.js.map - // Map values - const map = new Map(); - for (const value of values) { - if (!options.deep || - !value || - typeof value !== 'object') { - - const existing = map.get(value); - if (existing) { - ++existing.allowed; - } - else { - map.set(value, { allowed: 1, hits: 0 }); - } - } - else { - compare = compare || internals.compare(options); +/***/ }), - let found = false; - for (const [key, existing] of map.entries()) { - if (compare(key, value)) { - ++existing.allowed; - found = true; - break; - } - } +/***/ 59440: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!found) { - map.set(value, { allowed: 1, hits: 0 }); - } - } - } - // Lookup values - let hits = 0; - for (const item of ref) { - let match; - if (!options.deep || - !item || - typeof item !== 'object') { +Object.defineProperty(exports, "__esModule", ({ value: true })); - match = map.get(item); - } - else { - for (const [key, existing] of map.entries()) { - if (compare(key, item)) { - match = existing; - break; - } - } - } +var isPlainObject = __nccwpck_require__(63287); +var universalUserAgent = __nccwpck_require__(45030); - if (match) { - ++match.hits; - ++hits; +function lowercaseKeys(object) { + if (!object) { + return {}; + } - if (options.once && - match.hits > match.allowed) { + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} - return false; - } - } +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; +} - // Validate results +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === undefined) { + delete obj[key]; + } + } - if (options.only && - hits !== ref.length) { + return obj; +} - return false; - } +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 - for (const match of map.values()) { - if (match.hits === match.allowed) { - continue; - } - if (match.hits < match.allowed && - !options.part) { + options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging - return false; - } - } + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten - return !!hits; -}; + 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; +} -internals.object = function (ref, values, options) { +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); - Assert(options.once === undefined, 'Cannot use option once with object'); + if (names.length === 0) { + return url; + } - const keys = Utils.keys(ref, options); - if (!keys.length) { - return false; + return url + separator + names.map(name => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } - // Keys list + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} - if (Array.isArray(values)) { - return internals.array(keys, values, options); - } +const urlVariableRegex = /\{[^}]+\}/g; - // Key value pairs +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); +} - const symbols = Object.getOwnPropertySymbols(values).filter((sym) => values.propertyIsEnumerable(sym)); - const targets = [...Object.keys(values), ...symbols]; +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); - const compare = internals.compare(options); - const set = new Set(targets); + if (!matches) { + return []; + } - for (const key of keys) { - if (!set.has(key)) { - if (options.only) { - return false; - } + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); +} - continue; - } +function omit(object, keysToOmit) { + return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); +} - if (!compare(values[key], ref[key])) { - return false; - } +// 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. - set.delete(key); +/* 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, "]"); } - if (set.size) { - return options.part ? set.size < targets.length : false; - } + return part; + }).join(""); +} - return true; -}; +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); -internals.string = function (ref, values, options) { + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} - // Empty string +function isDefined(value) { + return value !== undefined && value !== null; +} - if (ref === '') { - return values.length === 1 && values[0] === '' || // '' contains '' - !options.once && !values.some((v) => v !== ''); // '' contains multiple '' if !once - } +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} - // Map values +function getValues(context, operator, key, modifier) { + var value = context[key], + result = []; - const map = new Map(); - const patterns = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); - for (const value of values) { - Assert(typeof value === 'string', 'Cannot compare string reference to non-string value'); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } - if (value) { - const existing = map.get(value); - if (existing) { - ++existing.allowed; + 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 { - map.set(value, { allowed: 1, hits: 0 }); - patterns.push(EscapeRegex(value)); + }); + } + } 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())); } + }); } - else if (options.once || - options.only) { - return false; + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); } + } } - - if (!patterns.length) { // Non-empty string contains unlimited empty string - return true; + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); } + } - // Match patterns - - const regex = new RegExp(`(${patterns.join('|')})`, 'g'); - const leftovers = ref.replace(regex, ($0, $1) => { + return result; +} - ++map.get($1).hits; - return ''; // Remove from string - }); +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} - // Validate results +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; - if (options.only && - leftovers) { + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } - return false; - } + expression.split(/,/g).forEach(function (variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); - let any = false; - for (const match of map.values()) { - if (match.hits) { - any = true; - } + if (operator && operator !== "+") { + var separator = ","; - if (match.hits === match.allowed) { - continue; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; } - if (match.hits < match.allowed && - !options.part) { + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + }); +} - return false; - } +function parse(options) { + // https://fetch.spec.whatwg.org/#methods + let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - // match.hits > match.allowed + 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 - if (options.once) { - return false; - } - } + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); - return !!any; -}; + 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); -internals.compare = function (options) { + 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.deep) { - return internals.shallow; + 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 - const hasOnly = options.only !== undefined; - const hasPart = options.part !== undefined; - const flags = { - prototype: hasOnly ? options.only : hasPart ? !options.part : false, - part: hasOnly ? !options.only : hasPart ? options.part : false - }; + 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 - return (a, b) => DeepEqual(a, b, flags); -}; + 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 -internals.shallow = function (a, b) { - return a === b; -}; + 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); +} -/***/ 55801: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Types = __nccwpck_require__(84340); - - -const internals = { - mismatched: 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 + }); +} -module.exports = function (obj, ref, options) { +const VERSION = "6.0.10"; - options = Object.assign({ prototype: true }, options); +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. - return !!internals.isDeepEqual(obj, ref, options, []); +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); -internals.isDeepEqual = function (obj, ref, options, seen) { - - if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql - return obj !== 0 || 1 / obj === 1 / ref; - } - - const type = typeof obj; - - if (type !== typeof ref) { - return false; - } - - if (obj === null || - ref === null) { - - return false; - } - - if (type === 'function') { - if (!options.deepFunction || - obj.toString() !== ref.toString()) { +exports.endpoint = endpoint; +//# sourceMappingURL=index.js.map - return false; - } - // Continue as object - } - else if (type !== 'object') { - return obj !== obj && ref !== ref; // NaN - } +/***/ }), - const instanceType = internals.getSharedType(obj, ref, !!options.prototype); - switch (instanceType) { - case Types.buffer: - return Buffer && Buffer.prototype.equals.call(obj, ref); // $lab:coverage:ignore$ - case Types.promise: - return obj === ref; - case Types.regex: - return obj.toString() === ref.toString(); - case internals.mismatched: - return false; - } +/***/ 88467: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (let i = seen.length - 1; i >= 0; --i) { - if (seen[i].isSame(obj, ref)) { - return true; // If previous comparison failed, it would have stopped execution - } - } - seen.push(new internals.SeenEntry(obj, ref)); - try { - return !!internals.isDeepEqualObj(instanceType, obj, ref, options, seen); - } - finally { - seen.pop(); - } -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var request = __nccwpck_require__(36234); +var universalUserAgent = __nccwpck_require__(45030); -internals.getSharedType = function (obj, ref, checkPrototype) { +const VERSION = "4.5.8"; - if (checkPrototype) { - if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) { - return internals.mismatched; - } +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) - return Types.getInternalProto(obj); - } + /* istanbul ignore next */ - const type = Types.getInternalProto(obj); - if (type !== Types.getInternalProto(ref)) { - return internals.mismatched; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } + } - return type; -}; - - -internals.valueOf = function (obj) { +} - const objValueOf = obj.valueOf; - if (objValueOf === undefined) { - return obj; - } +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`)); + } - try { - return objValueOf.call(obj); - } - catch (err) { - return err; + 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; } -}; - - -internals.hasOwnEnumerableProperty = function (obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -}; - - -internals.isSetSimpleEqual = function (obj, ref) { - - for (const entry of obj) { - if (!ref.has(entry)) { - return false; - } + if (!result.variables) { + result.variables = {}; } - return true; -}; - - -internals.isDeepEqualObj = function (instanceType, obj, ref, options, seen) { - - const { isDeepEqual, valueOf, hasOwnEnumerableProperty } = internals; - const { keys, getOwnPropertySymbols } = Object; - - if (instanceType === Types.array) { - if (options.part) { - - // Check if any index match any other index - - for (const objValue of obj) { - for (const refValue of ref) { - if (isDeepEqual(objValue, refValue, options, seen)) { - return true; - } - } - } - } - else { - if (obj.length !== ref.length) { - return false; - } - - for (let i = 0; i < obj.length; ++i) { - if (!isDeepEqual(obj[i], ref[i], options, seen)) { - return false; - } - } - - return true; - } - } - else if (instanceType === Types.set) { - if (obj.size !== ref.size) { - return false; - } + 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 (!internals.isSetSimpleEqual(obj, ref)) { + const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; - // Check for deep equality + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } - const ref2 = new Set(ref); - for (const objEntry of obj) { - if (ref2.delete(objEntry)) { - continue; - } + return request(requestOptions).then(response => { + if (response.data.errors) { + const headers = {}; - let found = false; - for (const refEntry of ref2) { - if (isDeepEqual(objEntry, refEntry, options, seen)) { - ref2.delete(refEntry); - found = true; - break; - } - } + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } - if (!found) { - return false; - } - } - } + throw new GraphqlError(requestOptions, { + headers, + data: response.data + }); } - else if (instanceType === Types.map) { - if (obj.size !== ref.size) { - return false; - } - - for (const [key, value] of obj) { - if (value === undefined && !ref.has(key)) { - return false; - } - if (!isDeepEqual(value, ref.get(key), options, seen)) { - return false; - } - } - } - else if (instanceType === Types.error) { + return response.data.data; + }); +} - // Always check name and message +function withDefaults(request$1, newDefaults) { + const newRequest = request$1.defaults(newDefaults); - if (obj.name !== ref.name || - obj.message !== ref.message) { + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; - return false; - } - } + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: request.request.endpoint + }); +} - // Check .valueOf() +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" + }); +} - const valueOfObj = valueOf(obj); - const valueOfRef = valueOf(ref); - if ((obj !== valueOfObj || ref !== valueOfRef) && - !isDeepEqual(valueOfObj, valueOfRef, options, seen)) { +exports.graphql = graphql$1; +exports.withCustomRequest = withCustomRequest; +//# sourceMappingURL=index.js.map - return false; - } - // Check properties +/***/ }), - const objKeys = keys(obj); - if (!options.part && - objKeys.length !== keys(ref).length && - !options.skip) { +/***/ 25823: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return false; - } - let skipped = 0; - for (const key of objKeys) { - if (options.skip && - options.skip.includes(key)) { - if (ref[key] === undefined) { - ++skipped; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - continue; - } +var requestError = __nccwpck_require__(10537); - if (!hasOwnEnumerableProperty(ref, key)) { - return false; - } +const VERSION = "1.2.8"; - if (!isDeepEqual(obj[key], ref[key], options, seen)) { - return false; - } - } +function isIssueLabelsUpdateOrReplace({ + method, + url +}) { + if (!["POST", "PUT"].includes(method)) { + return false; + } - if (!options.part && - objKeys.length - skipped !== keys(ref).length) { + if (!/\/repos\/[^/]+\/[^/]+\/issues\/[^/]+\/labels/.test(url)) { + return false; + } - return false; - } + return true; +} - // Check symbols +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 - if (options.symbols !== false) { // Defaults to true - const objSymbols = getOwnPropertySymbols(obj); - const refSymbols = new Set(getOwnPropertySymbols(ref)); + /* istanbul ignore if */ - for (const key of objSymbols) { - if (!options.skip || - !options.skip.includes(key)) { + if (options.request.validate) { + delete options.request.validate.labels; + } - if (hasOwnEnumerableProperty(obj, key)) { - if (!hasOwnEnumerableProperty(ref, key)) { - return false; - } + return request(options); + } // TODO: implement fix for #62 here + // https://github.com/octokit/plugin-enterprise-compatibility.js/issues/60 - if (!isDeepEqual(obj[key], ref[key], options, seen)) { - return false; - } - } - else if (hasOwnEnumerableProperty(ref, key)) { - return false; - } - } - refSymbols.delete(key); + if (/\/orgs\/[^/]+\/teams/.test(options.url)) { + try { + return await request(options); + } catch (error) { + if (error.status !== 404) { + throw error; } - for (const key of refSymbols) { - if (hasOwnEnumerableProperty(ref, key)) { - return false; - } + if (!error.headers || !error.headers["x-github-enterprise-version"]) { + throw error; } - } - - return true; -}; - -internals.SeenEntry = class { - - constructor(obj, ref) { - - this.obj = obj; - this.ref = ref; - } - - isSame(obj, ref) { - - return this.obj === obj && this.ref === ref; + 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 + }); + } } -}; - - -/***/ }), - -/***/ 35563: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Stringify = __nccwpck_require__(37577); - - -const internals = {}; - - -module.exports = class extends Error { - constructor(args) { - - const msgs = args - .filter((arg) => arg !== '') - .map((arg) => { - - return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : Stringify(arg); - }); - - super(msgs.join(' ') || 'Unknown error'); + return request(options); + }); +} +enterpriseCompatibility.VERSION = VERSION; - if (typeof Error.captureStackTrace === 'function') { // $lab:coverage:ignore$ - Error.captureStackTrace(this, exports.assert); - } - } -}; +exports.enterpriseCompatibility = enterpriseCompatibility; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 199: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); - +/***/ 64193: +/***/ ((__unused_webpack_module, exports) => { -const internals = {}; -module.exports = function (attribute) { +Object.defineProperty(exports, "__esModule", ({ value: true })); - // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, " +const VERSION = "2.6.2"; - Assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')'); +/** + * 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. - return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash -}; + 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; + } -/***/ 24752: -/***/ ((module) => { + response.data.total_count = totalCount; + return response; +} -"use strict"; +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 + url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; + return { + value: normalizedResponse + }; + } -const internals = {}; + }) + }; +} +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = undefined; + } -module.exports = function (input) { + return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); +} - if (!input) { - return ''; +function gather(octokit, results, iterator, mapFn) { + return iterator.next().then(result => { + if (result.done) { + return results; } - let escaped = ''; - - for (let i = 0; i < input.length; ++i) { - - const charCode = input.charCodeAt(i); + let earlyExit = false; - if (internals.isSafe(charCode)) { - escaped += input[i]; - } - else { - escaped += internals.escapeHtmlChar(charCode); - } + function done() { + earlyExit = true; } - return escaped; -}; - - -internals.escapeHtmlChar = function (charCode) { - - const namedEscape = internals.namedHtml[charCode]; - if (typeof namedEscape !== 'undefined') { - return namedEscape; - } + results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - if (charCode >= 256) { - return '&#' + charCode + ';'; + if (earlyExit) { + return results; } - const hexValue = charCode.toString(16).padStart(2, '0'); - return `&#x${hexValue};`; -}; - - -internals.isSafe = function (charCode) { - - return (typeof internals.safeCharCodes[charCode] !== 'undefined'); -}; - - -internals.namedHtml = { - '38': '&', - '60': '<', - '62': '>', - '34': '"', - '160': ' ', - '162': '¢', - '163': '£', - '164': '¤', - '169': '©', - '174': '®' -}; - - -internals.safeCharCodes = (function () { - - const safe = {}; + return gather(octokit, results, iterator, mapFn); + }); +} - for (let i = 32; i < 123; ++i) { +const composePaginateRest = Object.assign(paginate, { + iterator +}); - if ((i >= 97) || // a-z - (i >= 65 && i <= 90) || // A-Z - (i >= 48 && i <= 57) || // 0-9 - i === 32 || // space - i === 46 || // . - i === 44 || // , - i === 45 || // - - i === 58 || // : - i === 95) { // _ +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ - safe[i] = null; - } - } +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION; - return safe; -}()); +exports.composePaginateRest = composePaginateRest; +exports.paginateRest = paginateRest; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 30112: -/***/ ((module) => { +/***/ 83044: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -const internals = {}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); -module.exports = function (input) { + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); - if (!input) { - return ''; + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); } - const lessThan = 0x3C; - const greaterThan = 0x3E; - const andSymbol = 0x26; - const lineSeperator = 0x2028; - - // replace method - let charCode; - return input.replace(/[<>&\u2028\u2029]/g, (match) => { - - charCode = match.charCodeAt(0); + keys.push.apply(keys, symbols); + } - if (charCode === lessThan) { - return '\\u003c'; - } + return keys; +} - if (charCode === greaterThan) { - return '\\u003e'; - } +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - if (charCode === andSymbol) { - return '\\u0026'; - } + 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)); + }); + } + } - if (charCode === lineSeperator) { - return '\\u2028'; - } + return target; +} - return '\\u2029'; +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; + } -/***/ 91965: -/***/ ((module) => { + return obj; +} -"use strict"; - - -const internals = {}; - - -module.exports = function (string) { - - // Escape ^$.*+-?=!:|\/()[]{}, - - return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); -}; - - -/***/ }), - -/***/ 69666: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = internals.flatten = function (array, target) { - - const result = target || []; - - for (let i = 0; i < array.length; ++i) { - if (Array.isArray(array[i])) { - internals.flatten(array[i], result); - } - else { - result.push(array[i]); - } - } - - return result; -}; - - -/***/ }), - -/***/ 12887: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function () { }; - - -/***/ }), - -/***/ 10904: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const internals = {}; - - -module.exports = { - applyToDefaults: __nccwpck_require__(85545), - assert: __nccwpck_require__(32718), - Bench: __nccwpck_require__(86999), - block: __nccwpck_require__(77820), - clone: __nccwpck_require__(85578), - contain: __nccwpck_require__(39157), - deepEqual: __nccwpck_require__(55801), - Error: __nccwpck_require__(35563), - escapeHeaderAttribute: __nccwpck_require__(199), - escapeHtml: __nccwpck_require__(24752), - escapeJson: __nccwpck_require__(30112), - escapeRegex: __nccwpck_require__(91965), - flatten: __nccwpck_require__(69666), - ignore: __nccwpck_require__(12887), - intersect: __nccwpck_require__(43221), - isPromise: __nccwpck_require__(14193), - merge: __nccwpck_require__(60445), - once: __nccwpck_require__(98926), - reach: __nccwpck_require__(18891), - reachTemplate: __nccwpck_require__(15517), - stringify: __nccwpck_require__(37577), - wait: __nccwpck_require__(69497) -}; - - -/***/ }), - -/***/ 43221: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (array1, array2, options = {}) { - - if (!array1 || - !array2) { - - return (options.first ? null : []); - } - - const common = []; - const hash = (Array.isArray(array1) ? new Set(array1) : array1); - const found = new Set(); - for (const value of array2) { - if (internals.has(hash, value) && - !found.has(value)) { - - if (options.first) { - return value; - } - - common.push(value); - found.add(value); - } - } - - return (options.first ? null : common); -}; - - -internals.has = function (ref, key) { - - if (typeof ref.has === 'function') { - return ref.has(key); - } - - return ref[key] !== undefined; -}; - - -/***/ }), - -/***/ 14193: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (promise) { - - return !!promise && typeof promise.then === 'function'; -}; - - -/***/ }), - -/***/ 60445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); -const Clone = __nccwpck_require__(85578); -const Utils = __nccwpck_require__(30417); - - -const internals = {}; - - -module.exports = internals.merge = function (target, source, options) { - - Assert(target && typeof target === 'object', 'Invalid target value: must be an object'); - Assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object'); - - if (!source) { - return target; - } - - options = Object.assign({ nullOverride: true, mergeArrays: true }, options); - - if (Array.isArray(source)) { - Assert(Array.isArray(target), 'Cannot merge array onto an object'); - if (!options.mergeArrays) { - target.length = 0; // Must not change target assignment - } - - for (let i = 0; i < source.length; ++i) { - target.push(Clone(source[i], { symbols: options.symbols })); - } - - return target; - } - - const keys = Utils.keys(source, options); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === '__proto__' || - !Object.prototype.propertyIsEnumerable.call(source, key)) { - - continue; - } - - const value = source[key]; - if (value && - typeof value === 'object') { - - if (!target[key] || - typeof target[key] !== 'object' || - (Array.isArray(target[key]) !== Array.isArray(value)) || - value instanceof Date || - (Buffer && Buffer.isBuffer(value)) || // $lab:coverage:ignore$ - value instanceof RegExp) { - - target[key] = Clone(value, { symbols: options.symbols }); - } - else { - internals.merge(target[key], value, options); - } - } - else { - if (value !== null && - value !== undefined) { // Explicit to preserve empty strings - - target[key] = value; - } - else if (options.nullOverride) { - target[key] = value; - } - } - } - - return target; -}; - - -/***/ }), - -/***/ 98926: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (method) { - - if (method._hoekOnce) { - return method; - } - - let once = false; - const wrapped = function (...args) { - - if (!once) { - once = true; - method(...args); - } - }; - - wrapped._hoekOnce = true; - return wrapped; -}; - - -/***/ }), - -/***/ 18891: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); - - -const internals = {}; - - -module.exports = function (obj, chain, options) { - - if (chain === false || - chain === null || - chain === undefined) { - - return obj; - } - - options = options || {}; - if (typeof options === 'string') { - options = { separator: options }; - } - - const isChainArray = Array.isArray(chain); - - Assert(!isChainArray || !options.separator, 'Separator option no valid for array-based chain'); - - const path = isChainArray ? chain : chain.split(options.separator || '.'); - let ref = obj; - for (let i = 0; i < path.length; ++i) { - let key = path[i]; - const type = options.iterables && internals.iterables(ref); - - if (Array.isArray(ref) || - type === 'set') { - - const number = Number(key); - if (Number.isInteger(number)) { - key = number < 0 ? ref.length + number : number; - } - } - - if (!ref || - typeof ref === 'function' && options.functions === false || // Defaults to true - !type && ref[key] === undefined) { - - Assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain); - Assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain); - ref = options.default; - break; - } - - if (!type) { - ref = ref[key]; - } - else if (type === 'set') { - ref = [...ref][key]; - } - else { // type === 'map' - ref = ref.get(key); - } - } - - return ref; -}; - - -internals.iterables = function (ref) { - - if (ref instanceof Set) { - return 'set'; - } - - if (ref instanceof Map) { - return 'map'; - } -}; - - -/***/ }), - -/***/ 15517: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Reach = __nccwpck_require__(18891); - - -const internals = {}; - - -module.exports = function (obj, template, options) { - - return template.replace(/{([^}]+)}/g, ($0, chain) => { - - const value = Reach(obj, chain, options); - return (value === undefined || value === null ? '' : value); - }); -}; - - -/***/ }), - -/***/ 37577: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (...args) { - - try { - return JSON.stringify.apply(null, args); - } - catch (err) { - return '[Cannot display object: ' + err.message + ']'; - } -}; - - -/***/ }), - -/***/ 84340: -/***/ ((module, exports) => { - -"use strict"; - - -const internals = {}; - - -exports = module.exports = { - array: Array.prototype, - buffer: Buffer && Buffer.prototype, // $lab:coverage:ignore$ - date: Date.prototype, - error: Error.prototype, - generic: Object.prototype, - map: Map.prototype, - promise: Promise.prototype, - regex: RegExp.prototype, - set: Set.prototype, - weakMap: WeakMap.prototype, - weakSet: WeakSet.prototype -}; - - -internals.typeMap = new Map([ - ['[object Error]', exports.error], - ['[object Map]', exports.map], - ['[object Promise]', exports.promise], - ['[object Set]', exports.set], - ['[object WeakMap]', exports.weakMap], - ['[object WeakSet]', exports.weakSet] -]); - - -exports.getInternalProto = function (obj) { - - if (Array.isArray(obj)) { - return exports.array; - } - - if (Buffer && obj instanceof Buffer) { // $lab:coverage:ignore$ - return exports.buffer; - } - - if (obj instanceof Date) { - return exports.date; - } - - if (obj instanceof RegExp) { - return exports.regex; - } - - if (obj instanceof Error) { - return exports.error; - } - - const objName = Object.prototype.toString.call(obj); - return internals.typeMap.get(objName) || exports.generic; -}; - - -/***/ }), - -/***/ 30417: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Reach = __nccwpck_require__(18891); - - -const internals = {}; - - -exports.keys = function (obj, options = {}) { - - return options.symbols !== false ? Reflect.ownKeys(obj) : Object.getOwnPropertyNames(obj); // Defaults to true -}; - - -exports.store = function (source, keys) { - - const storage = new Map(); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const value = Reach(source, key); - if (typeof value === 'object' || - typeof value === 'function') { - - storage.set(key, value); - internals.reachSet(source, key, undefined); - } - } - - return storage; -}; - - -exports.restore = function (copy, source, storage) { - - for (const [key, value] of storage) { - internals.reachSet(copy, key, value); - internals.reachSet(source, key, value); - } -}; - - -internals.reachSet = function (obj, key, value) { - - const path = Array.isArray(key) ? key : key.split('.'); - let ref = obj; - for (let i = 0; i < path.length; ++i) { - const segment = path[i]; - if (i + 1 === path.length) { - ref[segment] = value; - } - - ref = ref[segment]; - } -}; - - -/***/ }), - -/***/ 69497: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = function (timeout) { - - return new Promise((resolve) => setTimeout(resolve, timeout)); -}; - - -/***/ }), - -/***/ 16415: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -exports.schema = function (Joi, config) { - - if (config !== undefined && config !== null && typeof config === 'object') { - - if (config.isJoi) { - return config; - } - - if (Array.isArray(config)) { - return Joi.alternatives().try(config); - } - - if (config instanceof RegExp) { - return Joi.string().regex(config); - } - - if (config instanceof Date) { - return Joi.date().valid(config); - } - - return Joi.object().keys(config); - } - - if (typeof config === 'string') { - return Joi.string().valid(config); - } - - if (typeof config === 'number') { - return Joi.number().valid(config); - } - - if (typeof config === 'boolean') { - return Joi.boolean().valid(config); - } - - if (Ref.isRef(config)) { - return Joi.valid(config); - } - - Hoek.assert(config === null, 'Invalid schema content:', config); - - return Joi.valid(null); -}; - - -exports.ref = function (id) { - - return Ref.isRef(id) ? id : Ref.create(id); -}; - - -/***/ }), - -/***/ 32150: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Language = __nccwpck_require__(43910); - - -const internals = { - annotations: Symbol('joi-annotations') -}; - - -internals.stringify = function (value, wrapArrays) { - - const type = typeof value; - - if (value === null) { - return 'null'; - } - - if (type === 'string') { - return value; - } - - if (value instanceof exports.Err || type === 'function' || type === 'symbol') { - return value.toString(); - } - - if (type === 'object') { - if (Array.isArray(value)) { - let partial = ''; - - for (let i = 0; i < value.length; ++i) { - partial = partial + (partial.length ? ', ' : '') + internals.stringify(value[i], wrapArrays); - } - - return wrapArrays ? '[' + partial + ']' : partial; - } - - return value.toString(); - } - - return JSON.stringify(value); -}; - - -exports.Err = class { - - constructor(type, context, state, options, flags, message, template) { - - this.isJoi = true; - this.type = type; - this.context = context || {}; - this.context.key = state.path[state.path.length - 1]; - this.context.label = state.key; - this.path = state.path; - this.options = options; - this.flags = flags; - this.message = message; - this.template = template; - - const localized = this.options.language; - - if (this.flags.label) { - this.context.label = this.flags.label; - } - else if (localized && // language can be null for arrays exclusion check - (this.context.label === '' || - this.context.label === null)) { - this.context.label = localized.root || Language.errors.root; - } - } - - toString() { - - if (this.message) { - return this.message; - } - - let format; - - if (this.template) { - format = this.template; - } - - const localized = this.options.language; - - format = format || Hoek.reach(localized, this.type) || Hoek.reach(Language.errors, this.type); - - if (format === undefined) { - return `Error code "${this.type}" is not defined, your custom type is missing the correct language definition`; - } - - let wrapArrays = Hoek.reach(localized, 'messages.wrapArrays'); - if (typeof wrapArrays !== 'boolean') { - wrapArrays = Language.errors.messages.wrapArrays; - } - - if (format === null) { - const childrenString = internals.stringify(this.context.reason, wrapArrays); - if (wrapArrays) { - return childrenString.slice(1, -1); - } - - return childrenString; - } - - const hasKey = /{{!?label}}/.test(format); - const skipKey = format.length > 2 && format[0] === '!' && format[1] === '!'; - - if (skipKey) { - format = format.slice(2); - } - - if (!hasKey && !skipKey) { - const localizedKey = Hoek.reach(localized, 'key'); - if (typeof localizedKey === 'string') { - format = localizedKey + format; - } - else { - format = Hoek.reach(Language.errors, 'key') + format; - } - } - - const message = format.replace(/{{(!?)([^}]+)}}/g, ($0, isSecure, name) => { - - const value = Hoek.reach(this.context, name); - const normalized = internals.stringify(value, wrapArrays); - return (isSecure && this.options.escapeHtml ? Hoek.escapeHtml(normalized) : normalized); - }); - - this.toString = () => message; // Persist result of last toString call, it won't change - - return message; - } - -}; - - -exports.create = function (type, context, state, options, flags, message, template) { - - return new exports.Err(type, context, state, options, flags, message, template); -}; - - -exports.process = function (errors, object) { - - if (!errors) { - return null; - } - - // Construct error - - let message = ''; - const details = []; - - const processErrors = function (localErrors, parent, overrideMessage) { - - for (let i = 0; i < localErrors.length; ++i) { - const item = localErrors[i]; - - if (item instanceof Error) { - return item; - } - - if (item.flags.error && typeof item.flags.error !== 'function') { - if (!item.flags.selfError || !item.context.reason) { - return item.flags.error; - } - } - - let itemMessage; - if (parent === undefined) { - itemMessage = item.toString(); - message = message + (message ? '. ' : '') + itemMessage; - } - - // Do not push intermediate errors, we're only interested in leafs - - if (item.context.reason) { - const override = processErrors(item.context.reason, item.path, item.type === 'override' ? item.message : null); - if (override) { - return override; - } - } - else { - details.push({ - message: overrideMessage || itemMessage || item.toString(), - path: item.path, - type: item.type, - context: item.context - }); - } - } - }; - - const override = processErrors(errors); - if (override) { - return override; - } - - const error = new Error(message); - error.isJoi = true; - error.name = 'ValidationError'; - error.details = details; - error._object = object; - error.annotate = internals.annotate; - return error; -}; - - -// Inspired by json-stringify-safe - -internals.safeStringify = function (obj, spaces) { - - return JSON.stringify(obj, internals.serializer(), spaces); -}; - - -internals.serializer = function () { - - const keys = []; - const stack = []; - - const cycleReplacer = (key, value) => { - - if (stack[0] === value) { - return '[Circular ~]'; - } - - return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; - }; - - return function (key, value) { - - if (stack.length > 0) { - const thisPos = stack.indexOf(this); - if (~thisPos) { - stack.length = thisPos + 1; - keys.length = thisPos + 1; - keys[thisPos] = key; - } - else { - stack.push(this); - keys.push(key); - } - - if (~stack.indexOf(value)) { - value = cycleReplacer.call(this, key, value); - } - } - else { - stack.push(value); - } - - if (value) { - const annotations = value[internals.annotations]; - if (annotations) { - if (Array.isArray(value)) { - const annotated = []; - - for (let i = 0; i < value.length; ++i) { - if (annotations.errors[i]) { - annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`); - } - - annotated.push(value[i]); - } - - value = annotated; - } - else { - const errorKeys = Object.keys(annotations.errors); - for (let i = 0; i < errorKeys.length; ++i) { - const errorKey = errorKeys[i]; - value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey]; - value[errorKey] = undefined; - } - - const missingKeys = Object.keys(annotations.missing); - for (let i = 0; i < missingKeys.length; ++i) { - const missingKey = missingKeys[i]; - value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__'; - } - } - - return value; - } - } - - if (value === Infinity || value === -Infinity || Number.isNaN(value) || - typeof value === 'function' || typeof value === 'symbol') { - return '[' + value.toString() + ']'; - } - - return value; - }; -}; - - -internals.annotate = function (stripColorCodes) { - - const redFgEscape = stripColorCodes ? '' : '\u001b[31m'; - const redBgEscape = stripColorCodes ? '' : '\u001b[41m'; - const endColor = stripColorCodes ? '' : '\u001b[0m'; - - if (typeof this._object !== 'object') { - return this.details[0].message; - } - - const obj = Hoek.clone(this._object || {}); - - for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first - const pos = i + 1; - const error = this.details[i]; - const path = error.path; - let ref = obj; - for (let j = 0; ; ++j) { - const seg = path[j]; - - if (ref.isImmutable) { - ref = ref.clone(); // joi schemas are not cloned by hoek, we have to take this extra step - } - - if (j + 1 < path.length && - ref[seg] && - typeof ref[seg] !== 'string') { - - ref = ref[seg]; - } - else { - const refAnnotations = ref[internals.annotations] = ref[internals.annotations] || { errors: {}, missing: {} }; - const value = ref[seg]; - const cacheKey = seg || error.context.label; - - if (value !== undefined) { - refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || []; - refAnnotations.errors[cacheKey].push(pos); - } - else { - refAnnotations.missing[cacheKey] = pos; - } - - break; - } - } - } - - const replacers = { - key: /_\$key\$_([, \d]+)_\$end\$_"/g, - missing: /"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g, - arrayIndex: /\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g, - specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g - }; - - let message = internals.safeStringify(obj, 2) - .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`) - .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`) - .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`) - .replace(replacers.specials, ($0, $1) => $1); - - message = `${message}\n${redFgEscape}`; - - for (let i = 0; i < this.details.length; ++i) { - const pos = i + 1; - message = `${message}\n[${pos}] ${this.details[i].message}`; - } - - message = message + endColor; - - return message; -}; - - -/***/ }), - -/***/ 44010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Cast = __nccwpck_require__(16415); -const Errors = __nccwpck_require__(32150); -const Lazy = __nccwpck_require__(92187); -const Ref = __nccwpck_require__(71802); - - -const internals = { - alternatives: __nccwpck_require__(32797), - array: __nccwpck_require__(81500), - boolean: __nccwpck_require__(78578), - binary: __nccwpck_require__(2608), - date: __nccwpck_require__(46254), - func: __nccwpck_require__(28710), - number: __nccwpck_require__(18668), - object: __nccwpck_require__(38395), - string: __nccwpck_require__(67769), - symbol: __nccwpck_require__(62462) -}; - - -internals.callWithDefaults = function (schema, args) { - - Hoek.assert(this, 'Must be invoked on a Joi instance.'); - - if (this._defaults) { - schema = this._defaults(schema); - } - - schema._currentJoi = this; - - return schema._init(...args); -}; - - -internals.root = function () { - - const any = new Any(); - - const root = any.clone(); - Any.prototype._currentJoi = root; - root._currentJoi = root; - root._binds = new Set(['any', 'alternatives', 'alt', 'array', 'bool', 'boolean', 'binary', 'date', 'func', 'number', 'object', 'string', 'symbol', 'validate', 'describe', 'compile', 'assert', 'attempt', 'lazy', 'defaults', 'extend', 'allow', 'valid', 'only', 'equal', 'invalid', 'disallow', 'not', 'required', 'exist', 'optional', 'forbidden', 'strip', 'when', 'empty', 'default']); - - root.any = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.any() does not allow arguments.'); - - return internals.callWithDefaults.call(this, any, args); - }; - - root.alternatives = root.alt = function (...args) { - - return internals.callWithDefaults.call(this, internals.alternatives, args); - }; - - root.array = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.array() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.array, args); - }; - - root.boolean = root.bool = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.boolean() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.boolean, args); - }; - - root.binary = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.binary() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.binary, args); - }; - - root.date = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.date() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.date, args); - }; - - root.func = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.func() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.func, args); - }; - - root.number = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.number() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.number, args); - }; - - root.object = function (...args) { - - return internals.callWithDefaults.call(this, internals.object, args); - }; - - root.string = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.string() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.string, args); - }; - - root.symbol = function (...args) { - - Hoek.assert(args.length === 0, 'Joi.symbol() does not allow arguments.'); - - return internals.callWithDefaults.call(this, internals.symbol, args); - }; - - root.ref = function (...args) { - - return Ref.create(...args); - }; - - root.isRef = function (ref) { - - return Ref.isRef(ref); - }; - - root.validate = function (value, ...args /*, [schema], [options], callback */) { - - const last = args[args.length - 1]; - const callback = typeof last === 'function' ? last : null; - - const count = args.length - (callback ? 1 : 0); - if (count === 0) { - return any.validate(value, callback); - } - - const options = count === 2 ? args[1] : undefined; - const schema = this.compile(args[0]); - - return schema._validateWithOptions(value, options, callback); - }; - - root.describe = function (...args) { - - const schema = args.length ? this.compile(args[0]) : any; - return schema.describe(); - }; - - root.compile = function (schema) { - - try { - return Cast.schema(this, schema); - } - catch (err) { - if (err.hasOwnProperty('path')) { - err.message = err.message + '(' + err.path + ')'; - } - - throw err; - } - }; - - root.assert = function (value, schema, message) { - - this.attempt(value, schema, message); - }; - - root.attempt = function (value, schema, message) { - - const result = this.validate(value, schema); - const error = result.error; - if (error) { - if (!message) { - if (typeof error.annotate === 'function') { - error.message = error.annotate(); - } - - throw error; - } - - if (!(message instanceof Error)) { - if (typeof error.annotate === 'function') { - error.message = `${message} ${error.annotate()}`; - } - - throw error; - } - - throw message; - } - - return result.value; - }; - - root.reach = function (schema, path) { - - Hoek.assert(schema && schema instanceof Any, 'you must provide a joi schema'); - Hoek.assert(Array.isArray(path) || typeof path === 'string', 'path must be a string or an array of strings'); - - const reach = (sourceSchema, schemaPath) => { - - if (!schemaPath.length) { - return sourceSchema; - } - - const children = sourceSchema._inner.children; - if (!children) { - return; - } - - const key = schemaPath.shift(); - for (let i = 0; i < children.length; ++i) { - const child = children[i]; - if (child.key === key) { - return reach(child.schema, schemaPath); - } - } - }; - - const schemaPath = typeof path === 'string' ? (path ? path.split('.') : []) : path.slice(); - - return reach(schema, schemaPath); - }; - - root.lazy = function (...args) { - - return internals.callWithDefaults.call(this, Lazy, args); - }; - - root.defaults = function (fn) { - - Hoek.assert(typeof fn === 'function', 'Defaults must be a function'); - - let joi = Object.create(this.any()); - joi = fn(joi); - - Hoek.assert(joi && joi instanceof this.constructor, 'defaults() must return a schema'); - - Object.assign(joi, this, joi.clone()); // Re-add the types from `this` but also keep the settings from joi's potential new defaults - - joi._defaults = (schema) => { - - if (this._defaults) { - schema = this._defaults(schema); - Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema'); - } - - schema = fn(schema); - Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema'); - return schema; - }; - - return joi; - }; - - root.bind = function () { - - const joi = Object.create(this); - - joi._binds.forEach((bind) => { - - joi[bind] = joi[bind].bind(joi); - }); - - return joi; - }; - - root.extend = function (...args) { - - const extensions = Hoek.flatten(args); - Hoek.assert(extensions.length > 0, 'You need to provide at least one extension'); - - this.assert(extensions, root.extensionsSchema); - - const joi = Object.create(this.any()); - Object.assign(joi, this); - joi._currentJoi = joi; - joi._binds = new Set(joi._binds); - - for (let i = 0; i < extensions.length; ++i) { - let extension = extensions[i]; - - if (typeof extension === 'function') { - extension = extension(joi); - } - - this.assert(extension, root.extensionSchema); - - const base = (extension.base || this.any()).clone(); // Cloning because we're going to override language afterwards - const ctor = base.constructor; - const type = class extends ctor { // eslint-disable-line no-loop-func - - constructor() { - - super(); - if (extension.base) { - Object.assign(this, base); - } - - this._type = extension.name; - } - - }; - - if (extension.language) { - const lang = { - [extension.name]: extension.language - }; - type.prototype._language = Hoek.applyToDefaults(type.prototype._language || (base._settings && base._settings.language) || {}, lang); - } - - - if (extension.coerce) { - type.prototype._coerce = function (value, state, options) { - - if (ctor.prototype._coerce) { - const baseRet = ctor.prototype._coerce.call(this, value, state, options); - - if (baseRet.errors) { - return baseRet; - } - - value = baseRet.value; - } - - const ret = extension.coerce.call(this, value, state, options); - if (ret instanceof Errors.Err) { - return { value, errors: ret }; - } - - return { value: ret }; - }; - } - - if (extension.pre) { - type.prototype._base = function (value, state, options) { - - if (ctor.prototype._base) { - const baseRet = ctor.prototype._base.call(this, value, state, options); - - if (baseRet.errors) { - return baseRet; - } - - value = baseRet.value; - } - - const ret = extension.pre.call(this, value, state, options); - if (ret instanceof Errors.Err) { - return { value, errors: ret }; - } - - return { value: ret }; - }; - } - - if (extension.rules) { - for (let j = 0; j < extension.rules.length; ++j) { - const rule = extension.rules[j]; - const ruleArgs = rule.params ? - (rule.params instanceof Any ? rule.params._inner.children.map((k) => k.key) : Object.keys(rule.params)) : - []; - const validateArgs = rule.params ? Cast.schema(this, rule.params) : null; - - type.prototype[rule.name] = function (...rArgs) { // eslint-disable-line no-loop-func - - if (rArgs.length > ruleArgs.length) { - throw new Error('Unexpected number of arguments'); - } - - let hasRef = false; - let arg = {}; - - for (let k = 0; k < ruleArgs.length; ++k) { - arg[ruleArgs[k]] = rArgs[k]; - if (!hasRef && Ref.isRef(rArgs[k])) { - hasRef = true; - } - } - - if (validateArgs) { - arg = joi.attempt(arg, validateArgs); - } - - let schema; - if (rule.validate && !rule.setup) { - const validate = function (value, state, options) { - - return rule.validate.call(this, arg, value, state, options); - }; - - schema = this._test(rule.name, arg, validate, { - description: rule.description, - hasRef - }); - } - else { - schema = this.clone(); - } - - if (rule.setup) { - const newSchema = rule.setup.call(schema, arg); - if (newSchema !== undefined) { - Hoek.assert(newSchema instanceof Any, `Setup of extension Joi.${this._type}().${rule.name}() must return undefined or a Joi object`); - schema = newSchema; - } - - if (rule.validate) { - const validate = function (value, state, options) { - - return rule.validate.call(this, arg, value, state, options); - }; - - schema = schema._test(rule.name, arg, validate, { - description: rule.description, - hasRef - }); - } - } - - return schema; - }; - } - } - - if (extension.describe) { - type.prototype.describe = function () { - - const description = ctor.prototype.describe.call(this); - return extension.describe.call(this, description); - }; - } - - const instance = new type(); - joi[extension.name] = function (...extArgs) { - - return internals.callWithDefaults.call(this, instance, extArgs); - }; - - joi._binds.add(extension.name); - } - - return joi; - }; - - root.extensionSchema = internals.object.keys({ - base: internals.object.type(Any, 'Joi object'), - name: internals.string.required(), - coerce: internals.func.arity(3), - pre: internals.func.arity(3), - language: internals.object, - describe: internals.func.arity(1), - rules: internals.array.items(internals.object.keys({ - name: internals.string.required(), - setup: internals.func.arity(1), - validate: internals.func.arity(4), - params: [ - internals.object.pattern(/.*/, internals.object.type(Any, 'Joi object')), - internals.object.type(internals.object.constructor, 'Joi object') - ], - description: [internals.string, internals.func.arity(1)] - }).or('setup', 'validate')) - }).strict(); - - root.extensionsSchema = internals.array.items([internals.object, internals.func.arity(1)]).strict(); - - root.version = __nccwpck_require__(82542).version; - - return root; -}; - - -module.exports = internals.root(); - - -/***/ }), - -/***/ 43910: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const internals = {}; - - -exports.errors = { - root: 'value', - key: '"{{!label}}" ', - messages: { - wrapArrays: true - }, - any: { - unknown: 'is not allowed', - invalid: 'contains an invalid value', - empty: 'is not allowed to be empty', - required: 'is required', - allowOnly: 'must be one of {{valids}}', - default: 'threw an error when running default method' - }, - alternatives: { - base: 'not matching any of the allowed alternatives', - child: null - }, - array: { - base: 'must be an array', - includes: 'at position {{pos}} does not match any of the allowed types', - includesSingle: 'single value of "{{!label}}" does not match any of the allowed types', - includesOne: 'at position {{pos}} fails because {{reason}}', - includesOneSingle: 'single value of "{{!label}}" fails because {{reason}}', - includesRequiredUnknowns: 'does not contain {{unknownMisses}} required value(s)', - includesRequiredKnowns: 'does not contain {{knownMisses}}', - includesRequiredBoth: 'does not contain {{knownMisses}} and {{unknownMisses}} other required value(s)', - excludes: 'at position {{pos}} contains an excluded value', - excludesSingle: 'single value of "{{!label}}" contains an excluded value', - hasKnown: 'does not contain at least one required match for type "{{!patternLabel}}"', - hasUnknown: 'does not contain at least one required match', - min: 'must contain at least {{limit}} items', - max: 'must contain less than or equal to {{limit}} items', - length: 'must contain {{limit}} items', - ordered: 'at position {{pos}} fails because {{reason}}', - orderedLength: 'at position {{pos}} fails because array must contain at most {{limit}} items', - ref: 'references "{{ref}}" which is not a positive integer', - sparse: 'must not be a sparse array', - unique: 'position {{pos}} contains a duplicate value' - }, - boolean: { - base: 'must be a boolean' - }, - binary: { - base: 'must be a buffer or a string', - min: 'must be at least {{limit}} bytes', - max: 'must be less than or equal to {{limit}} bytes', - length: 'must be {{limit}} bytes' - }, - date: { - base: 'must be a number of milliseconds or valid date string', - strict: 'must be a valid date', - min: 'must be larger than or equal to "{{limit}}"', - max: 'must be less than or equal to "{{limit}}"', - less: 'must be less than "{{limit}}"', - greater: 'must be greater than "{{limit}}"', - isoDate: 'must be a valid ISO 8601 date', - timestamp: { - javascript: 'must be a valid timestamp or number of milliseconds', - unix: 'must be a valid timestamp or number of seconds' - }, - ref: 'references "{{ref}}" which is not a date' - }, - function: { - base: 'must be a Function', - arity: 'must have an arity of {{n}}', - minArity: 'must have an arity greater or equal to {{n}}', - maxArity: 'must have an arity lesser or equal to {{n}}', - ref: 'must be a Joi reference', - class: 'must be a class' - }, - lazy: { - base: '!!schema error: lazy schema must be set', - schema: '!!schema error: lazy schema function must return a schema' - }, - object: { - base: 'must be an object', - child: '!!child "{{!child}}" fails because {{reason}}', - min: 'must have at least {{limit}} children', - max: 'must have less than or equal to {{limit}} children', - length: 'must have {{limit}} children', - allowUnknown: '!!"{{!child}}" is not allowed', - with: '!!"{{mainWithLabel}}" missing required peer "{{peerWithLabel}}"', - without: '!!"{{mainWithLabel}}" conflict with forbidden peer "{{peerWithLabel}}"', - missing: 'must contain at least one of {{peersWithLabels}}', - xor: 'contains a conflict between exclusive peers {{peersWithLabels}}', - oxor: 'contains a conflict between optional exclusive peers {{peersWithLabels}}', - and: 'contains {{presentWithLabels}} without its required peers {{missingWithLabels}}', - nand: '!!"{{mainWithLabel}}" must not exist simultaneously with {{peersWithLabels}}', - assert: '!!"{{ref}}" validation failed because "{{ref}}" failed to {{message}}', - rename: { - multiple: 'cannot rename child "{{from}}" because multiple renames are disabled and another key was already renamed to "{{to}}"', - override: 'cannot rename child "{{from}}" because override is disabled and target "{{to}}" exists', - regex: { - multiple: 'cannot rename children {{from}} because multiple renames are disabled and another key was already renamed to "{{to}}"', - override: 'cannot rename children {{from}} because override is disabled and target "{{to}}" exists' - } - }, - type: 'must be an instance of "{{type}}"', - schema: 'must be a Joi instance' - }, - number: { - base: 'must be a number', - unsafe: 'must be a safe number', - min: 'must be larger than or equal to {{limit}}', - max: 'must be less than or equal to {{limit}}', - less: 'must be less than {{limit}}', - greater: 'must be greater than {{limit}}', - integer: 'must be an integer', - negative: 'must be a negative number', - positive: 'must be a positive number', - precision: 'must have no more than {{limit}} decimal places', - ref: 'references "{{ref}}" which is not a number', - multiple: 'must be a multiple of {{multiple}}', - port: 'must be a valid port' - }, - string: { - base: 'must be a string', - min: 'length must be at least {{limit}} characters long', - max: 'length must be less than or equal to {{limit}} characters long', - length: 'length must be {{limit}} characters long', - alphanum: 'must only contain alpha-numeric characters', - token: 'must only contain alpha-numeric and underscore characters', - regex: { - base: 'with value "{{!value}}" fails to match the required pattern: {{pattern}}', - name: 'with value "{{!value}}" fails to match the {{name}} pattern', - invert: { - base: 'with value "{{!value}}" matches the inverted pattern: {{pattern}}', - name: 'with value "{{!value}}" matches the inverted {{name}} pattern' - } - }, - email: 'must be a valid email', - uri: 'must be a valid uri', - uriRelativeOnly: 'must be a valid relative uri', - uriCustomScheme: 'must be a valid uri with a scheme matching the {{scheme}} pattern', - isoDate: 'must be a valid ISO 8601 date', - guid: 'must be a valid GUID', - hex: 'must only contain hexadecimal characters', - hexAlign: 'hex decoded representation must be byte aligned', - base64: 'must be a valid base64 string', - dataUri: 'must be a valid dataUri string', - hostname: 'must be a valid hostname', - normalize: 'must be unicode normalized in the {{form}} form', - lowercase: 'must only contain lowercase characters', - uppercase: 'must only contain uppercase characters', - trim: 'must not have leading or trailing whitespace', - creditCard: 'must be a credit card', - ref: 'references "{{ref}}" which is not a number', - ip: 'must be a valid ip address with a {{cidr}} CIDR', - ipVersion: 'must be a valid ip address of one of the following versions {{version}} with a {{cidr}} CIDR' - }, - symbol: { - base: 'must be a symbol', - map: 'must be one of {{map}}' - } -}; - - -/***/ }), - -/***/ 71802: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - - -const internals = {}; - - -exports.create = function (key, options) { - - Hoek.assert(typeof key === 'string', 'Invalid reference key:', key); - - const settings = Hoek.clone(options); // options can be reused and modified - - const ref = function (value, validationOptions) { - - return Hoek.reach(ref.isContext ? validationOptions.context : value, ref.key, settings); - }; - - ref.isContext = (key[0] === ((settings && settings.contextPrefix) || '$')); - ref.key = (ref.isContext ? key.slice(1) : key); - ref.path = ref.key.split((settings && settings.separator) || '.'); - ref.depth = ref.path.length; - ref.root = ref.path[0]; - ref.isJoi = true; - - ref.toString = function () { - - return (ref.isContext ? 'context:' : 'ref:') + ref.key; - }; - - return ref; -}; - - -exports.isRef = function (ref) { - - return typeof ref === 'function' && ref.isJoi; -}; - - -exports.push = function (array, ref) { - - if (exports.isRef(ref) && - !ref.isContext) { - - array.push(ref.root); - } -}; - - -/***/ }), - -/***/ 13723: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Joi = __nccwpck_require__(44010); - - -const internals = {}; - - -exports.options = Joi.object({ - abortEarly: Joi.boolean(), - convert: Joi.boolean(), - allowUnknown: Joi.boolean(), - skipFunctions: Joi.boolean(), - stripUnknown: [Joi.boolean(), Joi.object({ arrays: Joi.boolean(), objects: Joi.boolean() }).or('arrays', 'objects')], - language: Joi.object(), - presence: Joi.string().only('required', 'optional', 'forbidden', 'ignore'), - context: Joi.object(), - noDefaults: Joi.boolean(), - escapeHtml: Joi.boolean() -}).strict(); - - -/***/ }), - -/***/ 39417: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -internals.extendedCheckForValue = function (value, insensitive) { - - const valueType = typeof value; - - if (valueType === 'object') { - if (value instanceof Date) { - return (item) => { - - return item instanceof Date && value.getTime() === item.getTime(); - }; - } - - if (Buffer.isBuffer(value)) { - return (item) => { - - return Buffer.isBuffer(item) && value.length === item.length && value.toString('binary') === item.toString('binary'); - }; - } - } - else if (insensitive && valueType === 'string') { - const lowercaseValue = value.toLowerCase(); - return (item) => { - - return typeof item === 'string' && lowercaseValue === item.toLowerCase(); - }; - } - - return null; -}; - - -module.exports = class InternalSet { - - constructor(from) { - - this._set = new Set(from); - this._hasRef = false; - } - - add(value, refs) { - - const isRef = Ref.isRef(value); - if (!isRef && this.has(value, null, null, false)) { - - return this; - } - - if (refs !== undefined) { // If it's a merge, we don't have any refs - Ref.push(refs, value); - } - - this._set.add(value); - - this._hasRef |= isRef; - - return this; - } - - merge(add, remove) { - - for (const item of add._set) { - this.add(item); - } - - for (const item of remove._set) { - this.remove(item); - } - - return this; - } - - remove(value) { - - this._set.delete(value); - return this; - } - - has(value, state, options, insensitive) { - - return !!this.get(value, state, options, insensitive); - } - - get(value, state, options, insensitive) { - - if (!this._set.size) { - return false; - } - - const hasValue = this._set.has(value); - if (hasValue) { - return { value }; - } - - const extendedCheck = internals.extendedCheckForValue(value, insensitive); - if (!extendedCheck) { - if (state && this._hasRef) { - for (let item of this._set) { - if (Ref.isRef(item)) { - item = [].concat(item(state.reference || state.parent, options)); - const found = item.indexOf(value); - if (found >= 0) { - return { value: item[found] }; - } - } - } - } - - return false; - } - - return this._has(value, state, options, extendedCheck); - } - - _has(value, state, options, check) { - - const checkRef = !!(state && this._hasRef); - - const isReallyEqual = function (item) { - - if (value === item) { - return true; - } - - return check(item); - }; - - for (let item of this._set) { - if (checkRef && Ref.isRef(item)) { // Only resolve references if there is a state, otherwise it's a merge - item = item(state.reference || state.parent, options); - - if (Array.isArray(item)) { - const found = item.findIndex(isReallyEqual); - if (found >= 0) { - return { - value: item[found] - }; - } - - continue; - } - } - - if (isReallyEqual(item)) { - return { - value: item - }; - } - } - - return false; - } - - values(options) { - - if (options && options.stripUndefined) { - const values = []; - - for (const item of this._set) { - if (item !== undefined) { - values.push(item); - } - } - - return values; - } - - return Array.from(this._set); - } - - slice() { - - const set = new InternalSet(this._set); - set._hasRef = this._hasRef; - return set; - } - - concat(source) { - - const set = new InternalSet([...this._set, ...source._set]); - set._hasRef = !!(this._hasRef | source._hasRef); - return set; - } -}; - - -/***/ }), - -/***/ 32797: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Cast = __nccwpck_require__(16415); -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -internals.Alternatives = class extends Any { - - constructor() { - - super(); - this._type = 'alternatives'; - this._invalids.remove(null); - this._inner.matches = []; - } - - _init(...args) { - - return args.length ? this.try(...args) : this; - } - - _base(value, state, options) { - - const errors = []; - const il = this._inner.matches.length; - const baseType = this._baseType; - - for (let i = 0; i < il; ++i) { - const item = this._inner.matches[i]; - if (!item.schema) { - const schema = item.peek || item.is; - const input = item.is ? item.ref(state.reference || state.parent, options) : value; - const failed = schema._validate(input, null, options, state.parent).errors; - - if (failed) { - if (item.otherwise) { - return item.otherwise._validate(value, state, options); - } - } - else if (item.then) { - return item.then._validate(value, state, options); - } - - if (i === (il - 1) && baseType) { - return baseType._validate(value, state, options); - } - - continue; - } - - const result = item.schema._validate(value, state, options); - if (!result.errors) { // Found a valid match - return result; - } - - errors.push(...result.errors); - } - - if (errors.length) { - return { errors: this.createError('alternatives.child', { reason: errors }, state, options) }; - } - - return { errors: this.createError('alternatives.base', null, state, options) }; - } - - try(...schemas) { - - schemas = Hoek.flatten(schemas); - Hoek.assert(schemas.length, 'Cannot add other alternatives without at least one schema'); - - const obj = this.clone(); - - for (let i = 0; i < schemas.length; ++i) { - const cast = Cast.schema(this._currentJoi, schemas[i]); - if (cast._refs.length) { - obj._refs.push(...cast._refs); - } - - obj._inner.matches.push({ schema: cast }); - } - - return obj; - } - - when(condition, options) { - - let schemaCondition = false; - Hoek.assert(Ref.isRef(condition) || typeof condition === 'string' || (schemaCondition = condition instanceof Any), 'Invalid condition:', condition); - Hoek.assert(options, 'Missing options'); - Hoek.assert(typeof options === 'object', 'Invalid options'); - if (schemaCondition) { - Hoek.assert(!options.hasOwnProperty('is'), '"is" can not be used with a schema condition'); - } - else { - Hoek.assert(options.hasOwnProperty('is'), 'Missing "is" directive'); - } - - Hoek.assert(options.then !== undefined || options.otherwise !== undefined, 'options must have at least one of "then" or "otherwise"'); - - const obj = this.clone(); - let is; - if (!schemaCondition) { - is = Cast.schema(this._currentJoi, options.is); - - if (options.is === null || !(Ref.isRef(options.is) || options.is instanceof Any)) { - - // Only apply required if this wasn't already a schema or a ref, we'll suppose people know what they're doing - is = is.required(); - } - } - - const item = { - ref: schemaCondition ? null : Cast.ref(condition), - peek: schemaCondition ? condition : null, - is, - then: options.then !== undefined ? Cast.schema(this._currentJoi, options.then) : undefined, - otherwise: options.otherwise !== undefined ? Cast.schema(this._currentJoi, options.otherwise) : undefined - }; - - if (obj._baseType) { - - item.then = item.then && obj._baseType.concat(item.then); - item.otherwise = item.otherwise && obj._baseType.concat(item.otherwise); - } - - if (!schemaCondition) { - Ref.push(obj._refs, item.ref); - obj._refs.push(...item.is._refs); - } - - if (item.then && item.then._refs.length) { - obj._refs.push(...item.then._refs); - } - - if (item.otherwise && item.otherwise._refs.length) { - obj._refs.push(...item.otherwise._refs); - } - - obj._inner.matches.push(item); - - return obj; - } - - label(name) { - - const obj = super.label(name); - obj._inner.matches = obj._inner.matches.map((match) => { - - if (match.schema) { - return { schema: match.schema.label(name) }; - } - - match = Object.assign({}, match); - if (match.then) { - match.then = match.then.label(name); - } - - if (match.otherwise) { - match.otherwise = match.otherwise.label(name); - } - - return match; - }); - return obj; - } - - describe() { - - const description = super.describe(); - const alternatives = []; - for (let i = 0; i < this._inner.matches.length; ++i) { - const item = this._inner.matches[i]; - if (item.schema) { - - // try() - - alternatives.push(item.schema.describe()); - } - else { - - // when() - - const when = item.is ? { - ref: item.ref.toString(), - is: item.is.describe() - } : { - peek: item.peek.describe() - }; - - if (item.then) { - when.then = item.then.describe(); - } - - if (item.otherwise) { - when.otherwise = item.otherwise.describe(); - } - - alternatives.push(when); - } - } - - description.alternatives = alternatives; - return description; - } - -}; - - -module.exports = new internals.Alternatives(); - - -/***/ }), - -/***/ 77641: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Cast = __nccwpck_require__(16415); -const Settings = __nccwpck_require__(29804); -const Ref = __nccwpck_require__(71802); -const Errors = __nccwpck_require__(32150); -const State = __nccwpck_require__(13538); -const Symbols = __nccwpck_require__(52252); - -const Pkg = __nccwpck_require__(82542); - -let Alternatives = null; // Delay-loaded to prevent circular dependencies -let Schemas = null; - - -const internals = { - Set: __nccwpck_require__(39417), - symbol: Symbol.for('@hapi/joi/schema') -}; - - -internals.defaults = { - abortEarly: true, - convert: true, - allowUnknown: false, - skipFunctions: false, - stripUnknown: false, - language: {}, - presence: 'optional', - noDefaults: false, - escapeHtml: false - - // context: null -}; - - -module.exports = internals.Any = class { - - constructor() { - - this.isJoi = true; - this._type = 'any'; - this._settings = null; - this._valids = new internals.Set(); - this._invalids = new internals.Set(); - this._tests = []; - this._refs = []; - this._flags = { - /* - presence: 'optional', // optional, required, forbidden, ignore - allowOnly: false, - allowUnknown: undefined, - default: undefined, - forbidden: false, - encoding: undefined, - insensitive: false, - trim: false, - normalize: undefined, // NFC, NFD, NFKC, NFKD - case: undefined, // upper, lower - empty: undefined, - func: false, - raw: false - */ - }; - - this._description = null; - this._unit = null; - this._notes = []; - this._tags = []; - this._examples = []; - this._meta = []; - - this._inner = {}; // Hash of arrays of immutable objects - } - - _init() { - - return this; - } - - get schemaType() { - - return this._type; - } - - createError(type, context, state, options, flags = this._flags) { - - return Errors.create(type, context, state, options, flags); - } - - createOverrideError(type, context, state, options, message, template) { - - return Errors.create(type, context, state, options, this._flags, message, template); - } - - checkOptions(options) { - - Schemas = Schemas || __nccwpck_require__(13723); - - const result = Schemas.options.validate(options); - - if (result.error) { - throw new Error(result.error.details[0].message); - } - } - - clone() { - - const obj = Object.create(Object.getPrototypeOf(this)); - - obj.isJoi = true; - obj._currentJoi = this._currentJoi; - obj._type = this._type; - obj._settings = this._settings; - obj._baseType = this._baseType; - obj._valids = this._valids.slice(); - obj._invalids = this._invalids.slice(); - obj._tests = this._tests.slice(); - obj._refs = this._refs.slice(); - obj._flags = Hoek.clone(this._flags); - - obj._description = this._description; - obj._unit = this._unit; - obj._notes = this._notes.slice(); - obj._tags = this._tags.slice(); - obj._examples = this._examples.slice(); - obj._meta = this._meta.slice(); - - obj._inner = {}; - const inners = Object.keys(this._inner); - for (let i = 0; i < inners.length; ++i) { - const key = inners[i]; - obj._inner[key] = this._inner[key] ? this._inner[key].slice() : null; - } - - return obj; - } - - concat(schema) { - - Hoek.assert(schema instanceof internals.Any, 'Invalid schema object'); - Hoek.assert(this._type === 'any' || schema._type === 'any' || schema._type === this._type, 'Cannot merge type', this._type, 'with another type:', schema._type); - - let obj = this.clone(); - - if (this._type === 'any' && schema._type !== 'any') { - - // Reset values as if we were "this" - const tmpObj = schema.clone(); - const keysToRestore = ['_settings', '_valids', '_invalids', '_tests', '_refs', '_flags', '_description', '_unit', - '_notes', '_tags', '_examples', '_meta', '_inner']; - - for (let i = 0; i < keysToRestore.length; ++i) { - tmpObj[keysToRestore[i]] = obj[keysToRestore[i]]; - } - - obj = tmpObj; - } - - obj._settings = obj._settings ? Settings.concat(obj._settings, schema._settings) : schema._settings; - obj._valids.merge(schema._valids, schema._invalids); - obj._invalids.merge(schema._invalids, schema._valids); - obj._tests.push(...schema._tests); - obj._refs.push(...schema._refs); - if (obj._flags.empty && schema._flags.empty) { - obj._flags.empty = obj._flags.empty.concat(schema._flags.empty); - const flags = Object.assign({}, schema._flags); - delete flags.empty; - Hoek.merge(obj._flags, flags); - } - else if (schema._flags.empty) { - obj._flags.empty = schema._flags.empty; - const flags = Object.assign({}, schema._flags); - delete flags.empty; - Hoek.merge(obj._flags, flags); - } - else { - Hoek.merge(obj._flags, schema._flags); - } - - obj._description = schema._description || obj._description; - obj._unit = schema._unit || obj._unit; - obj._notes.push(...schema._notes); - obj._tags.push(...schema._tags); - obj._examples.push(...schema._examples); - obj._meta.push(...schema._meta); - - const inners = Object.keys(schema._inner); - const isObject = obj._type === 'object'; - for (let i = 0; i < inners.length; ++i) { - const key = inners[i]; - const source = schema._inner[key]; - if (source) { - const target = obj._inner[key]; - if (target) { - if (isObject && key === 'children') { - const keys = {}; - - for (let j = 0; j < target.length; ++j) { - keys[target[j].key] = j; - } - - for (let j = 0; j < source.length; ++j) { - const sourceKey = source[j].key; - if (keys[sourceKey] >= 0) { - target[keys[sourceKey]] = { - key: sourceKey, - schema: target[keys[sourceKey]].schema.concat(source[j].schema) - }; - } - else { - target.push(source[j]); - } - } - } - else { - obj._inner[key] = obj._inner[key].concat(source); - } - } - else { - obj._inner[key] = source.slice(); - } - } - } - - return obj; - } - - _test(name, arg, func, options) { - - const obj = this.clone(); - obj._tests.push({ func, name, arg, options }); - return obj; - } - - _testUnique(name, arg, func, options) { - - const obj = this.clone(); - obj._tests = obj._tests.filter((test) => test.name !== name); - obj._tests.push({ func, name, arg, options }); - return obj; - } - - options(options) { - - Hoek.assert(!options.context, 'Cannot override context'); - this.checkOptions(options); - - const obj = this.clone(); - obj._settings = Settings.concat(obj._settings, options); - return obj; - } - - strict(isStrict) { - - const obj = this.clone(); - - const convert = isStrict === undefined ? false : !isStrict; - obj._settings = Settings.concat(obj._settings, { convert }); - return obj; - } - - raw(isRaw) { - - const value = isRaw === undefined ? true : isRaw; - - if (this._flags.raw === value) { - return this; - } - - const obj = this.clone(); - obj._flags.raw = value; - return obj; - } - - error(err, options = { self: false }) { - - Hoek.assert(err && (err instanceof Error || typeof err === 'function'), 'Must provide a valid Error object or a function'); - - const unknownKeys = Object.keys(options).filter((k) => !['self'].includes(k)); - Hoek.assert(unknownKeys.length === 0, `Options ${unknownKeys} are unknown`); - - const obj = this.clone(); - obj._flags.error = err; - - if (options.self) { - obj._flags.selfError = true; - } - - return obj; - } - - allow(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); - obj._invalids.remove(value); - obj._valids.add(value, obj._refs); - } - - return obj; - } - - valid(...values) { - - const obj = this.allow(...values); - obj._flags.allowOnly = true; - return obj; - } - - invalid(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined'); - obj._valids.remove(value); - obj._invalids.add(value, obj._refs); - } - - return obj; - } - - required() { - - if (this._flags.presence === 'required') { - return this; - } - - const obj = this.clone(); - obj._flags.presence = 'required'; - return obj; - } - - optional() { - - if (this._flags.presence === 'optional') { - return this; - } - - const obj = this.clone(); - obj._flags.presence = 'optional'; - return obj; - } - - - forbidden() { - - if (this._flags.presence === 'forbidden') { - return this; - } - - const obj = this.clone(); - obj._flags.presence = 'forbidden'; - return obj; - } - - - strip() { - - if (this._flags.strip) { - return this; - } - - const obj = this.clone(); - obj._flags.strip = true; - return obj; - } - - applyFunctionToChildren(children, fn, args = [], root) { - - children = [].concat(children); - - if (children.length !== 1 || children[0] !== '') { - root = root ? (root + '.') : ''; - - const extraChildren = (children[0] === '' ? children.slice(1) : children).map((child) => { - - return root + child; - }); - - throw new Error('unknown key(s) ' + extraChildren.join(', ')); - } - - return this[fn](...args); - } - - default(value, description) { - - if (typeof value === 'function' && - !Ref.isRef(value)) { - - if (!value.description && - description) { - - value.description = description; - } - - if (!this._flags.func) { - Hoek.assert(typeof value.description === 'string' && value.description.length > 0, 'description must be provided when default value is a function'); - } - } - - const obj = this.clone(); - obj._flags.default = value; - Ref.push(obj._refs, value); - return obj; - } - - empty(schema) { - - const obj = this.clone(); - if (schema === undefined) { - delete obj._flags.empty; - } - else { - obj._flags.empty = Cast.schema(this._currentJoi, schema); - } - - return obj; - } - - when(condition, options) { - - Hoek.assert(options && typeof options === 'object', 'Invalid options'); - Hoek.assert(options.then !== undefined || options.otherwise !== undefined, 'options must have at least one of "then" or "otherwise"'); - - const then = options.hasOwnProperty('then') ? this.concat(Cast.schema(this._currentJoi, options.then)) : undefined; - const otherwise = options.hasOwnProperty('otherwise') ? this.concat(Cast.schema(this._currentJoi, options.otherwise)) : undefined; - - Alternatives = Alternatives || __nccwpck_require__(32797); - - const alternativeOptions = { then, otherwise }; - if (Object.prototype.hasOwnProperty.call(options, 'is')) { - alternativeOptions.is = options.is; - } - - const obj = Alternatives.when(condition, alternativeOptions); - obj._flags.presence = 'ignore'; - obj._baseType = this; - - return obj; - } - - description(desc) { - - Hoek.assert(desc && typeof desc === 'string', 'Description must be a non-empty string'); - - const obj = this.clone(); - obj._description = desc; - return obj; - } - - notes(notes) { - - Hoek.assert(notes && (typeof notes === 'string' || Array.isArray(notes)), 'Notes must be a non-empty string or array'); - - const obj = this.clone(); - obj._notes = obj._notes.concat(notes); - return obj; - } - - tags(tags) { - - Hoek.assert(tags && (typeof tags === 'string' || Array.isArray(tags)), 'Tags must be a non-empty string or array'); - - const obj = this.clone(); - obj._tags = obj._tags.concat(tags); - return obj; - } - - meta(meta) { - - Hoek.assert(meta !== undefined, 'Meta cannot be undefined'); - - const obj = this.clone(); - obj._meta = obj._meta.concat(meta); - return obj; - } - - example(...examples) { - - Hoek.assert(examples.length > 0, 'Missing examples'); - - const processed = []; - for (let i = 0; i < examples.length; ++i) { - const example = [].concat(examples[i]); - Hoek.assert(example.length <= 2, `Bad example format at index ${i}`); - - const value = example[0]; - let options = example[1]; - if (options !== undefined) { - Hoek.assert(options && typeof options === 'object', `Options for example at index ${i} must be an object`); - const unknownOptions = Object.keys(options).filter((option) => !['parent', 'context'].includes(option)); - Hoek.assert(unknownOptions.length === 0, `Unknown example options ${unknownOptions} at index ${i}`); - } - else { - options = {}; - } - - const localState = new State('', [], options.parent || null); - const result = this._validate(value, localState, Settings.concat(internals.defaults, options.context ? { context: options.context } : null)); - Hoek.assert(!result.errors, `Bad example at index ${i}:`, result.errors && Errors.process(result.errors, value)); - - const ex = { value }; - if (Object.keys(options).length) { - ex.options = options; - } - - processed.push(ex); - } - - const obj = this.clone(); - obj._examples = processed; - return obj; - } - - unit(name) { - - Hoek.assert(name && typeof name === 'string', 'Unit name must be a non-empty string'); - - const obj = this.clone(); - obj._unit = name; - return obj; - } - - _prepareEmptyValue(value) { - - if (typeof value === 'string' && this._flags.trim) { - return value.trim(); - } - - return value; - } - - _validate(value, state, options, reference) { - - const originalValue = value; - - // Setup state and settings - - state = state || new State('', [], null, reference); - - if (this._settings) { - const isDefaultOptions = options === internals.defaults; - if (isDefaultOptions && this._settings[Symbols.settingsCache]) { - options = this._settings[Symbols.settingsCache]; - } - else { - options = Settings.concat(this._language ? Settings.concat({ language: this._language }, options) : options, this._settings); - if (isDefaultOptions) { - this._settings[Symbols.settingsCache] = options; - } - } - } - else if (this._language) { - options = Settings.concat({ language: this._language }, options); - } - - let errors = []; - - if (this._coerce) { - const coerced = this._coerce(value, state, options); - if (coerced.errors) { - value = coerced.value; - errors = errors.concat(coerced.errors); - return this._finalizeValue(value, originalValue, errors, state, options); // Coerced error always aborts early - } - - value = coerced.value; - } - - if (this._flags.empty && !this._flags.empty._validate(this._prepareEmptyValue(value), null, internals.defaults).errors) { - value = undefined; - } - - // Check presence requirements - - const presence = this._flags.presence || options.presence; - if (presence === 'optional') { - if (value === undefined) { - const isDeepDefault = this._flags.hasOwnProperty('default') && this._flags.default === undefined; - if (isDeepDefault && this._type === 'object') { - value = {}; - } - else { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - } - else if (presence === 'required' && - value === undefined) { - - errors.push(this.createError('any.required', null, state, options)); - return this._finalizeValue(value, originalValue, errors, state, options); - } - else if (presence === 'forbidden') { - if (value === undefined) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - - errors.push(this.createError('any.unknown', null, state, options)); - return this._finalizeValue(value, originalValue, errors, state, options); - } - - // Check allowed and denied values using the original value - - let match = this._valids.get(value, state, options, this._flags.insensitive); - if (match) { - if (options.convert) { - value = match.value; - } - - return this._finalizeValue(value, originalValue, errors, state, options); - } - - if (this._invalids.has(value, state, options, this._flags.insensitive)) { - errors.push(this.createError(value === '' ? 'any.empty' : 'any.invalid', { value, invalids: this._invalids.values({ stripUndefined: true }) }, state, options)); - if (options.abortEarly) { - - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - - // Convert value and validate type - - if (this._base) { - const base = this._base(value, state, options); - if (base.errors) { - value = base.value; - errors = errors.concat(base.errors); - return this._finalizeValue(value, originalValue, errors, state, options); // Base error always aborts early - } - - if (base.value !== value) { - value = base.value; - - // Check allowed and denied values using the converted value - - match = this._valids.get(value, state, options, this._flags.insensitive); - if (match) { - value = match.value; - return this._finalizeValue(value, originalValue, errors, state, options); - } - - if (this._invalids.has(value, state, options, this._flags.insensitive)) { - errors.push(this.createError(value === '' ? 'any.empty' : 'any.invalid', { value, invalids: this._invalids.values({ stripUndefined: true }) }, state, options)); - if (options.abortEarly) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - } - } - - // Required values did not match - - if (this._flags.allowOnly) { - errors.push(this.createError('any.allowOnly', { value, valids: this._valids.values({ stripUndefined: true }) }, state, options)); - if (options.abortEarly) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - - // Validate tests - - for (let i = 0; i < this._tests.length; ++i) { - const test = this._tests[i]; - const ret = test.func.call(this, value, state, options); - if (ret instanceof Errors.Err) { - errors.push(ret); - if (options.abortEarly) { - return this._finalizeValue(value, originalValue, errors, state, options); - } - } - else { - value = ret; - } - } - - return this._finalizeValue(value, originalValue, errors, state, options); - } - - _finalizeValue(value, originalValue, errors, state, options) { - - let finalValue; - - if (value !== undefined) { - finalValue = this._flags.raw ? originalValue : value; - } - else if (options.noDefaults) { - finalValue = value; - } - else if (Ref.isRef(this._flags.default)) { - finalValue = this._flags.default(state.parent, options); - } - else if (typeof this._flags.default === 'function' && - !(this._flags.func && !this._flags.default.description)) { - - let args; - - if (state.parent !== null && - this._flags.default.length > 0) { - - args = [Hoek.clone(state.parent), options]; - } - - const defaultValue = internals._try(this._flags.default, args); - finalValue = defaultValue.value; - if (defaultValue.error) { - errors.push(this.createError('any.default', { error: defaultValue.error }, state, options)); - } - } - else { - finalValue = Hoek.clone(this._flags.default); - } - - if (errors.length && - typeof this._flags.error === 'function' && - ( - !this._flags.selfError || - errors.some((e) => state.path.length === e.path.length) - ) - ) { - const change = this._flags.error.call(this, errors); - - if (typeof change === 'string') { - errors = [this.createOverrideError('override', { reason: errors }, state, options, change)]; - } - else { - errors = [].concat(change) - .map((err) => { - - return err instanceof Error ? - err : - this.createOverrideError(err.type || 'override', err.context, state, options, err.message, err.template); - }); - } - } - - return { - value: this._flags.strip ? undefined : finalValue, - finalValue, - errors: errors.length ? errors : null - }; - } - - _validateWithOptions(value, options, callback) { - - if (options) { - this.checkOptions(options); - } - - const settings = Settings.concat(internals.defaults, options); - const result = this._validate(value, null, settings); - const errors = Errors.process(result.errors, value); - - if (callback) { - return callback(errors, result.value); - } - - return { - error: errors, - value: result.value, - then(resolve, reject) { - - if (errors) { - return Promise.reject(errors).catch(reject); - } - - return Promise.resolve(result.value).then(resolve); - }, - catch(reject) { - - if (errors) { - return Promise.reject(errors).catch(reject); - } - - return Promise.resolve(result.value); - } - }; - } - - validate(value, options, callback) { - - if (typeof options === 'function') { - return this._validateWithOptions(value, null, options); - } - - return this._validateWithOptions(value, options, callback); - } - - describe() { - - const description = { - type: this._type - }; - - const flags = Object.keys(this._flags); - if (flags.length) { - if (['empty', 'default', 'lazy', 'label'].some((flag) => this._flags.hasOwnProperty(flag))) { - description.flags = {}; - for (let i = 0; i < flags.length; ++i) { - const flag = flags[i]; - if (flag === 'empty') { - description.flags[flag] = this._flags[flag].describe(); - } - else if (flag === 'default') { - if (Ref.isRef(this._flags[flag])) { - description.flags[flag] = this._flags[flag].toString(); - } - else if (typeof this._flags[flag] === 'function') { - description.flags[flag] = { - description: this._flags[flag].description, - function : this._flags[flag] - }; - } - else { - description.flags[flag] = this._flags[flag]; - } - } - else if (flag === 'lazy' || flag === 'label') { - // We don't want it in the description - } - else { - description.flags[flag] = this._flags[flag]; - } - } - } - else { - description.flags = this._flags; - } - } - - if (this._settings) { - description.options = Hoek.clone(this._settings); - } - - if (this._baseType) { - description.base = this._baseType.describe(); - } - - if (this._description) { - description.description = this._description; - } - - if (this._notes.length) { - description.notes = this._notes; - } - - if (this._tags.length) { - description.tags = this._tags; - } - - if (this._meta.length) { - description.meta = this._meta; - } - - if (this._examples.length) { - description.examples = this._examples; - } - - if (this._unit) { - description.unit = this._unit; - } - - const valids = this._valids.values(); - if (valids.length) { - description.valids = valids.map((v) => { - - return Ref.isRef(v) ? v.toString() : v; - }); - } - - const invalids = this._invalids.values(); - if (invalids.length) { - description.invalids = invalids.map((v) => { - - return Ref.isRef(v) ? v.toString() : v; - }); - } - - description.rules = []; - - for (let i = 0; i < this._tests.length; ++i) { - const validator = this._tests[i]; - const item = { name: validator.name }; - - if (validator.arg !== void 0) { - item.arg = Ref.isRef(validator.arg) ? validator.arg.toString() : validator.arg; - } - - const options = validator.options; - if (options) { - if (options.hasRef) { - item.arg = {}; - const keys = Object.keys(validator.arg); - for (let j = 0; j < keys.length; ++j) { - const key = keys[j]; - const value = validator.arg[key]; - item.arg[key] = Ref.isRef(value) ? value.toString() : value; - } - } - - if (typeof options.description === 'string') { - item.description = options.description; - } - else if (typeof options.description === 'function') { - item.description = options.description(item.arg); - } - } - - description.rules.push(item); - } - - if (!description.rules.length) { - delete description.rules; - } - - const label = this._getLabel(); - if (label) { - description.label = label; - } - - return description; - } - - label(name) { - - Hoek.assert(name && typeof name === 'string', 'Label name must be a non-empty string'); - - const obj = this.clone(); - obj._flags.label = name; - return obj; - } - - _getLabel(def) { - - return this._flags.label || def; - } - -}; - - -internals.Any.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects - -// Aliases - -internals.Any.prototype.only = internals.Any.prototype.equal = internals.Any.prototype.valid; -internals.Any.prototype.disallow = internals.Any.prototype.not = internals.Any.prototype.invalid; -internals.Any.prototype.exist = internals.Any.prototype.required; - - -internals.Any.prototype[internals.symbol] = { - version: Pkg.version, - compile: Cast.schema, - root: '_currentJoi' -}; - - -internals._try = function (fn, args = []) { - - let err; - let result; - - try { - result = fn(...args); - } - catch (e) { - err = e; - } - - return { - value: result, - error: err - }; -}; - - -/***/ }), - -/***/ 29804: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Symbols = __nccwpck_require__(52252); - - -const internals = {}; - - -exports.concat = function (target, source) { - - if (!source) { - return target; - } - - const obj = Object.assign({}, target); - - const language = source.language; - - Object.assign(obj, source); - - if (language && target && target.language) { - obj.language = Hoek.applyToDefaults(target.language, language); - } - - if (obj[Symbols.settingsCache]) { - delete obj[Symbols.settingsCache]; - } - - return obj; -}; - - -/***/ }), - -/***/ 81500: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Bourne = __nccwpck_require__(97174); -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Cast = __nccwpck_require__(16415); -const Ref = __nccwpck_require__(71802); -const State = __nccwpck_require__(13538); - - -const internals = {}; - - -internals.fastSplice = function (arr, i) { - - let pos = i; - while (pos < arr.length) { - arr[pos++] = arr[pos]; - } - - --arr.length; -}; - - -internals.Array = class extends Any { - - constructor() { - - super(); - this._type = 'array'; - this._inner.items = []; - this._inner.ordereds = []; - this._inner.inclusions = []; - this._inner.exclusions = []; - this._inner.requireds = []; - this._flags.sparse = false; - } - - _base(value, state, options) { - - const result = { - value - }; - - if (typeof value === 'string' && - options.convert) { - - if (value.length > 1 && - (value[0] === '[' || /^\s*\[/.test(value))) { - - try { - result.value = Bourne.parse(value); - } - catch (e) { } - } - } - - let isArray = Array.isArray(result.value); - const wasArray = isArray; - if (options.convert && this._flags.single && !isArray) { - result.value = [result.value]; - isArray = true; - } - - if (!isArray) { - result.errors = this.createError('array.base', null, state, options); - return result; - } - - if (this._inner.inclusions.length || - this._inner.exclusions.length || - this._inner.requireds.length || - this._inner.ordereds.length || - !this._flags.sparse) { - - // Clone the array so that we don't modify the original - if (wasArray) { - result.value = result.value.slice(0); - } - - result.errors = this._checkItems(result.value, wasArray, state, options); - - if (result.errors && wasArray && options.convert && this._flags.single) { - - // Attempt a 2nd pass by putting the array inside one. - const previousErrors = result.errors; - - result.value = [result.value]; - result.errors = this._checkItems(result.value, wasArray, state, options); - - if (result.errors) { - - // Restore previous errors and value since this didn't validate either. - result.errors = previousErrors; - result.value = result.value[0]; - } - } - } - - return result; - } - - _checkItems(items, wasArray, state, options) { - - const errors = []; - let errored; - - const requireds = this._inner.requireds.slice(); - const ordereds = this._inner.ordereds.slice(); - const inclusions = [...this._inner.inclusions, ...requireds]; - - let il = items.length; - for (let i = 0; i < il; ++i) { - errored = false; - const item = items[i]; - let isValid = false; - const key = wasArray ? i : state.key; - const path = wasArray ? [...state.path, i] : state.path; - const localState = new State(key, path, state.parent, state.reference); - let res; - - // Sparse - - if (!this._flags.sparse && item === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - - if (options.abortEarly) { - return errors; - } - - ordereds.shift(); - - continue; - } - - // Exclusions - - for (let j = 0; j < this._inner.exclusions.length; ++j) { - res = this._inner.exclusions[j]._validate(item, localState, {}); // Not passing options to use defaults - - if (!res.errors) { - errors.push(this.createError(wasArray ? 'array.excludes' : 'array.excludesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options)); - errored = true; - - if (options.abortEarly) { - return errors; - } - - ordereds.shift(); - - break; - } - } - - if (errored) { - continue; - } - - // Ordered - if (this._inner.ordereds.length) { - if (ordereds.length > 0) { - const ordered = ordereds.shift(); - res = ordered._validate(item, localState, options); - if (!res.errors) { - if (ordered._flags.strip) { - internals.fastSplice(items, i); - --i; - --il; - } - else if (!this._flags.sparse && res.value === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - - if (options.abortEarly) { - return errors; - } - - continue; - } - else { - items[i] = res.value; - } - } - else { - errors.push(this.createError('array.ordered', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options)); - if (options.abortEarly) { - return errors; - } - } - - continue; - } - else if (!this._inner.items.length) { - errors.push(this.createError('array.orderedLength', { pos: i, limit: this._inner.ordereds.length }, { key: state.key, path: localState.path }, options)); - if (options.abortEarly) { - return errors; - } - - continue; - } - } - - // Requireds - - const requiredChecks = []; - let jl = requireds.length; - for (let j = 0; j < jl; ++j) { - res = requiredChecks[j] = requireds[j]._validate(item, localState, options); - if (!res.errors) { - items[i] = res.value; - isValid = true; - internals.fastSplice(requireds, j); - --j; - --jl; - - if (!this._flags.sparse && res.value === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - - if (options.abortEarly) { - return errors; - } - } - - break; - } - } - - if (isValid) { - continue; - } - - // Inclusions - - const stripUnknown = options.stripUnknown && !!options.stripUnknown.arrays || false; - - jl = inclusions.length; - for (let j = 0; j < jl; ++j) { - const inclusion = inclusions[j]; - - // Avoid re-running requireds that already didn't match in the previous loop - const previousCheck = requireds.indexOf(inclusion); - if (previousCheck !== -1) { - res = requiredChecks[previousCheck]; - } - else { - res = inclusion._validate(item, localState, options); - - if (!res.errors) { - if (inclusion._flags.strip) { - internals.fastSplice(items, i); - --i; - --il; - } - else if (!this._flags.sparse && res.value === undefined) { - errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options)); - errored = true; - } - else { - items[i] = res.value; - } - - isValid = true; - break; - } - } - - // Return the actual error if only one inclusion defined - if (jl === 1) { - if (stripUnknown) { - internals.fastSplice(items, i); - --i; - --il; - isValid = true; - break; - } - - errors.push(this.createError(wasArray ? 'array.includesOne' : 'array.includesOneSingle', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options)); - errored = true; - - if (options.abortEarly) { - return errors; - } - - break; - } - } - - if (errored) { - continue; - } - - if (this._inner.inclusions.length && !isValid) { - if (stripUnknown) { - internals.fastSplice(items, i); - --i; - --il; - continue; - } - - errors.push(this.createError(wasArray ? 'array.includes' : 'array.includesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options)); - - if (options.abortEarly) { - return errors; - } - } - } - - if (requireds.length) { - this._fillMissedErrors(errors, requireds, state, options); - } - - if (ordereds.length) { - this._fillOrderedErrors(errors, ordereds, state, options); - } - - return errors.length ? errors : null; - } - - describe() { - - const description = super.describe(); - - if (this._inner.ordereds.length) { - description.orderedItems = []; - - for (let i = 0; i < this._inner.ordereds.length; ++i) { - description.orderedItems.push(this._inner.ordereds[i].describe()); - } - } - - if (this._inner.items.length) { - description.items = []; - - for (let i = 0; i < this._inner.items.length; ++i) { - description.items.push(this._inner.items[i].describe()); - } - } - - if (description.rules) { - for (let i = 0; i < description.rules.length; ++i) { - const rule = description.rules[i]; - if (rule.name === 'has') { - rule.arg = rule.arg.describe(); - } - } - } - - return description; - } - - items(...schemas) { - - const obj = this.clone(); - - Hoek.flatten(schemas).forEach((type, index) => { - - try { - type = Cast.schema(this._currentJoi, type); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.path = index + '.' + castErr.path; - } - else { - castErr.path = index; - } - - castErr.message = `${castErr.message}(${castErr.path})`; - throw castErr; - } - - obj._inner.items.push(type); - - if (type._flags.presence === 'required') { - obj._inner.requireds.push(type); - } - else if (type._flags.presence === 'forbidden') { - obj._inner.exclusions.push(type.optional()); - } - else { - obj._inner.inclusions.push(type); - } - }); - - return obj; - } - - ordered(...schemas) { - - const obj = this.clone(); - - Hoek.flatten(schemas).forEach((type, index) => { - - try { - type = Cast.schema(this._currentJoi, type); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.path = index + '.' + castErr.path; - } - else { - castErr.path = index; - } - - castErr.message = `${castErr.message}(${castErr.path})`; - throw castErr; - } - - obj._inner.ordereds.push(type); - }); - - return obj; - } - - min(limit) { - - const isRef = Ref.isRef(limit); - - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - - return this._testUnique('min', limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) { - return this.createError('array.ref', { ref: limit, value: compareTo }, state, options); - } - } - else { - compareTo = limit; - } - - if (value.length >= compareTo) { - return value; - } - - return this.createError('array.min', { limit, value }, state, options); - }); - } - - max(limit) { - - const isRef = Ref.isRef(limit); - - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - - return this._testUnique('max', limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) { - return this.createError('array.ref', { ref: limit.key }, state, options); - } - } - else { - compareTo = limit; - } - - if (value.length <= compareTo) { - return value; - } - - return this.createError('array.max', { limit, value }, state, options); - }); - } - - length(limit) { - - const isRef = Ref.isRef(limit); - - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - - return this._testUnique('length', limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) { - return this.createError('array.ref', { ref: limit.key }, state, options); - } - } - else { - compareTo = limit; - } - - if (value.length === compareTo) { - return value; - } - - return this.createError('array.length', { limit, value }, state, options); - }); - } - - has(schema) { - - try { - schema = Cast.schema(this._currentJoi, schema); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.message = `${castErr.message}(${castErr.path})`; - } - - throw castErr; - } - - return this._test('has', schema, function (value, state, options) { - - const isValid = value.some((item, idx) => { - - const localState = new State(idx, [...state.path, idx], state.key, state.reference); - return !schema._validate(item, localState, options).errors; - }); - - if (isValid) { - return value; - } - - const patternLabel = schema._getLabel(); - if (patternLabel) { - return this.createError('array.hasKnown', { patternLabel }, state, options); - } - - return this.createError('array.hasUnknown', null, state, options); - }); - } - - unique(comparator, configs) { - - Hoek.assert(comparator === undefined || - typeof comparator === 'function' || - typeof comparator === 'string', 'comparator must be a function or a string'); - - Hoek.assert(configs === undefined || - typeof configs === 'object', 'configs must be an object'); - - const settings = { - ignoreUndefined: (configs && configs.ignoreUndefined) || false - }; - - - if (typeof comparator === 'string') { - settings.path = comparator; - } - else if (typeof comparator === 'function') { - settings.comparator = comparator; - } - - return this._test('unique', settings, function (value, state, options) { - - const found = { - string: Object.create(null), - number: Object.create(null), - undefined: Object.create(null), - boolean: Object.create(null), - object: new Map(), - function: new Map(), - custom: new Map() - }; - - const compare = settings.comparator || Hoek.deepEqual; - const ignoreUndefined = settings.ignoreUndefined; - - for (let i = 0; i < value.length; ++i) { - const item = settings.path ? Hoek.reach(value[i], settings.path) : value[i]; - const records = settings.comparator ? found.custom : found[typeof item]; - - // All available types are supported, so it's not possible to reach 100% coverage without ignoring this line. - // I still want to keep the test for future js versions with new types (eg. Symbol). - if (/* $lab:coverage:off$ */ records /* $lab:coverage:on$ */) { - if (records instanceof Map) { - const entries = records.entries(); - let current; - while (!(current = entries.next()).done) { - if (compare(current.value[0], item)) { - const localState = new State(state.key, [...state.path, i], state.parent, state.reference); - const context = { - pos: i, - value: value[i], - dupePos: current.value[1], - dupeValue: value[current.value[1]] - }; - - if (settings.path) { - context.path = settings.path; - } - - return this.createError('array.unique', context, localState, options); - } - } - - records.set(item, i); - } - else { - if ((!ignoreUndefined || item !== undefined) && records[item] !== undefined) { - const localState = new State(state.key, [...state.path, i], state.parent, state.reference); - - const context = { - pos: i, - value: value[i], - dupePos: records[item], - dupeValue: value[records[item]] - }; - - if (settings.path) { - context.path = settings.path; - } - - return this.createError('array.unique', context, localState, options); - } - - records[item] = i; - } - } - } - - return value; - }); - } - - sparse(enabled) { - - const value = enabled === undefined ? true : !!enabled; - - if (this._flags.sparse === value) { - return this; - } - - const obj = this.clone(); - obj._flags.sparse = value; - return obj; - } - - single(enabled) { - - const value = enabled === undefined ? true : !!enabled; - - if (this._flags.single === value) { - return this; - } - - const obj = this.clone(); - obj._flags.single = value; - return obj; - } - - _fillMissedErrors(errors, requireds, state, options) { - - const knownMisses = []; - let unknownMisses = 0; - for (let i = 0; i < requireds.length; ++i) { - const label = requireds[i]._getLabel(); - if (label) { - knownMisses.push(label); - } - else { - ++unknownMisses; - } - } - - if (knownMisses.length) { - if (unknownMisses) { - errors.push(this.createError('array.includesRequiredBoth', { knownMisses, unknownMisses }, { key: state.key, path: state.path }, options)); - } - else { - errors.push(this.createError('array.includesRequiredKnowns', { knownMisses }, { key: state.key, path: state.path }, options)); - } - } - else { - errors.push(this.createError('array.includesRequiredUnknowns', { unknownMisses }, { key: state.key, path: state.path }, options)); - } - } - - - _fillOrderedErrors(errors, ordereds, state, options) { - - const requiredOrdereds = []; - - for (let i = 0; i < ordereds.length; ++i) { - const presence = Hoek.reach(ordereds[i], '_flags.presence'); - if (presence === 'required') { - requiredOrdereds.push(ordereds[i]); - } - } - - if (requiredOrdereds.length) { - this._fillMissedErrors(errors, requiredOrdereds, state, options); - } - } - -}; - - -module.exports = new internals.Array(); - - -/***/ }), - -/***/ 2608: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); - - -const internals = {}; - - -internals.Binary = class extends Any { - - constructor() { - - super(); - this._type = 'binary'; - } - - _base(value, state, options) { - - const result = { - value - }; - - if (typeof value === 'string' && - options.convert) { - - try { - result.value = Buffer.from(value, this._flags.encoding); - } - catch (e) { } - } - - result.errors = Buffer.isBuffer(result.value) ? null : this.createError('binary.base', null, state, options); - return result; - } - - encoding(encoding) { - - Hoek.assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); - - if (this._flags.encoding === encoding) { - return this; - } - - const obj = this.clone(); - obj._flags.encoding = encoding; - return obj; - } - - min(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('min', limit, function (value, state, options) { - - if (value.length >= limit) { - return value; - } - - return this.createError('binary.min', { limit, value }, state, options); - }); - } - - max(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('max', limit, function (value, state, options) { - - if (value.length <= limit) { - return value; - } - - return this.createError('binary.max', { limit, value }, state, options); - }); - } - - length(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('length', limit, function (value, state, options) { - - if (value.length === limit) { - return value; - } - - return this.createError('binary.length', { limit, value }, state, options); - }); - } - -}; - - -module.exports = new internals.Binary(); - - -/***/ }), - -/***/ 78578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); - - -const internals = { - Set: __nccwpck_require__(39417) -}; - - -internals.Boolean = class extends Any { - constructor() { - - super(); - this._type = 'boolean'; - this._flags.insensitive = true; - this._inner.truthySet = new internals.Set(); - this._inner.falsySet = new internals.Set(); - } - - _base(value, state, options) { - - const result = { - value - }; - - if (typeof value === 'string' && - options.convert) { - - const normalized = this._flags.insensitive ? value.toLowerCase() : value; - result.value = (normalized === 'true' ? true - : (normalized === 'false' ? false : value)); - } - - if (typeof result.value !== 'boolean') { - result.value = (this._inner.truthySet.has(value, null, null, this._flags.insensitive) ? true - : (this._inner.falsySet.has(value, null, null, this._flags.insensitive) ? false : value)); - } - - result.errors = (typeof result.value === 'boolean') ? null : this.createError('boolean.base', { value }, state, options); - return result; - } - - truthy(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call truthy with undefined'); - obj._inner.truthySet.add(value); - } - - return obj; - } - - falsy(...values) { - - const obj = this.clone(); - values = Hoek.flatten(values); - for (let i = 0; i < values.length; ++i) { - const value = values[i]; - - Hoek.assert(value !== undefined, 'Cannot call falsy with undefined'); - obj._inner.falsySet.add(value); - } - - return obj; - } - - insensitive(enabled) { - - const insensitive = enabled === undefined ? true : !!enabled; - - if (this._flags.insensitive === insensitive) { - return this; - } - - const obj = this.clone(); - obj._flags.insensitive = insensitive; - return obj; - } - - describe() { - - const description = super.describe(); - description.truthy = [true, ...this._inner.truthySet.values()]; - description.falsy = [false, ...this._inner.falsySet.values()]; - return description; - } -}; - - -module.exports = new internals.Boolean(); - - -/***/ }), - -/***/ 46254: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - -internals.isoDate = /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/; -internals.invalidDate = new Date(''); -internals.isIsoDate = (() => { - - const isoString = internals.isoDate.toString(); - - return (date) => { - - return date && (date.toString() === isoString); - }; -})(); - -internals.Date = class extends Any { - - constructor() { - - super(); - this._type = 'date'; - } - - _base(value, state, options) { - - const result = { - value: (options.convert && internals.Date.toDate(value, this._flags.format, this._flags.timestamp, this._flags.multiplier)) || value - }; - - if (result.value instanceof Date && !isNaN(result.value.getTime())) { - result.errors = null; - } - else if (!options.convert) { - result.errors = this.createError('date.strict', { value }, state, options); - } - else { - let type; - if (internals.isIsoDate(this._flags.format)) { - type = 'isoDate'; - } - else if (this._flags.timestamp) { - type = `timestamp.${this._flags.timestamp}`; - } - else { - type = 'base'; - } - - result.errors = this.createError(`date.${type}`, { value }, state, options); - } - - return result; - } - - static toDate(value, format, timestamp, multiplier) { - - if (value instanceof Date) { - return value; - } - - if (typeof value === 'string' || - (typeof value === 'number' && !isNaN(value) && isFinite(value))) { - - const isIsoDate = format && internals.isIsoDate(format); - if (!isIsoDate && - typeof value === 'string' && - /^[+-]?\d+(\.\d+)?$/.test(value)) { - - value = parseFloat(value); - } - - let date; - if (isIsoDate) { - date = format.test(value) ? new Date(value.toString()) : internals.invalidDate; - } - else if (timestamp) { - date = /^\s*$/.test(value) ? internals.invalidDate : new Date(value * multiplier); - } - else { - date = new Date(value); - } - - if (!isNaN(date.getTime())) { - return date; - } - } - - return null; - } - - iso() { - - if (this._flags.format === internals.isoDate) { - return this; - } - - const obj = this.clone(); - obj._flags.format = internals.isoDate; - return obj; - } - - timestamp(type = 'javascript') { - - const allowed = ['javascript', 'unix']; - Hoek.assert(allowed.includes(type), '"type" must be one of "' + allowed.join('", "') + '"'); - - if (this._flags.timestamp === type) { - return this; - } - - const obj = this.clone(); - obj._flags.timestamp = type; - obj._flags.multiplier = type === 'unix' ? 1000 : 1; - return obj; - } - - _isIsoDate(value) { - - return internals.isoDate.test(value); - } - -}; - -internals.compare = function (type, compare) { - - return function (date) { - - const isNow = date === 'now'; - const isRef = Ref.isRef(date); - - if (!isNow && !isRef) { - date = internals.Date.toDate(date); - } - - Hoek.assert(date, 'Invalid date format'); - - return this._test(type, date, function (value, state, options) { - - let compareTo; - if (isNow) { - compareTo = Date.now(); - } - else if (isRef) { - const refValue = date(state.reference || state.parent, options); - compareTo = internals.Date.toDate(refValue); - - if (!compareTo) { - return this.createError('date.ref', { ref: date, value: refValue }, state, options); - } - - compareTo = compareTo.getTime(); - } - else { - compareTo = date.getTime(); - } - - if (compare(value.getTime(), compareTo)) { - return value; - } - - return this.createError('date.' + type, { limit: new Date(compareTo), value }, state, options); - }); - }; -}; - - -internals.Date.prototype.min = internals.compare('min', (value, date) => value >= date); -internals.Date.prototype.max = internals.compare('max', (value, date) => value <= date); -internals.Date.prototype.greater = internals.compare('greater', (value, date) => value > date); -internals.Date.prototype.less = internals.compare('less', (value, date) => value < date); - - -module.exports = new internals.Date(); - - -/***/ }), - -/***/ 28710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const ObjectType = __nccwpck_require__(38395); -const Ref = __nccwpck_require__(71802); - - -const internals = {}; - - -internals.Func = class extends ObjectType.constructor { - - constructor() { - - super(); - this._flags.func = true; - } - - arity(n) { - - Hoek.assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); - - return this._test('arity', n, function (value, state, options) { - - if (value.length === n) { - return value; - } - - return this.createError('function.arity', { n }, state, options); - }); - } - - minArity(n) { - - Hoek.assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer'); - - return this._test('minArity', n, function (value, state, options) { - - if (value.length >= n) { - return value; - } - - return this.createError('function.minArity', { n }, state, options); - }); - } - - maxArity(n) { - - Hoek.assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer'); - - return this._test('maxArity', n, function (value, state, options) { - - if (value.length <= n) { - return value; - } - - return this.createError('function.maxArity', { n }, state, options); - }); - } - - ref() { - - return this._test('ref', null, function (value, state, options) { - - if (Ref.isRef(value)) { - return value; - } - - return this.createError('function.ref', { value }, state, options); - }); - } - - class() { - - return this._test('class', null, function (value, state, options) { - - if ((/^\s*class\s/).test(value.toString())) { - return value; - } - - return this.createError('function.class', { value }, state, options); - }); - } -}; - -module.exports = new internals.Func(); - - -/***/ }), - -/***/ 92187: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); - - -const internals = {}; - - -internals.Lazy = class extends Any { - - constructor() { - - super(); - this._type = 'lazy'; - this._flags.once = true; - this._cache = null; - } - - _init(fn, options) { - - return this.set(fn, options); - } - - _base(value, state, options) { - - let schema; - if (this._cache) { - schema = this._cache; - } - else { - const result = { value }; - const lazy = this._flags.lazy; - - if (!lazy) { - result.errors = this.createError('lazy.base', null, state, options); - return result; - } - - schema = lazy(); - - if (!(schema instanceof Any)) { - result.errors = this.createError('lazy.schema', { schema }, state, options); - return result; - } - - if (this._flags.once) { - this._cache = schema; - } - } - - return schema._validate(value, state, options); - } - - set(fn, options) { - - Hoek.assert(typeof fn === 'function', 'You must provide a function as first argument'); - Hoek.assert(options === undefined || (options && typeof options === 'object' && !Array.isArray(options)), `Options must be an object`); - - if (options) { - const unknownOptions = Object.keys(options).filter((key) => !['once'].includes(key)); - Hoek.assert(unknownOptions.length === 0, `Options contain unknown keys: ${unknownOptions}`); - Hoek.assert(options.once === undefined || typeof options.once === 'boolean', 'Option "once" must be a boolean'); - } - - const obj = this.clone(); - obj._flags.lazy = fn; - - if (options && options.once !== obj._flags.once) { - obj._flags.once = options.once; - } - - return obj; - } - -}; - -module.exports = new internals.Lazy(); - - -/***/ }), - -/***/ 18668: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Ref = __nccwpck_require__(71802); - - -const internals = { - precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/, - normalizeExponent(str) { - - return str - .replace(/\.?0+e/, 'e') - .replace(/e\+/, 'e') - .replace(/^\+/, '') - .replace(/^(-?)0+([1-9])/, '$1$2'); - }, - normalizeDecimal(str) { - - str = str - .replace(/^\+/, '') - .replace(/\.0+$/, '') - .replace(/^(-?)0+([1-9])/, '$1$2'); - - if (str.includes('.') && str.endsWith('0')) { - str = str.replace(/0+$/, ''); - } - - return str; - } -}; - - -internals.Number = class extends Any { - - constructor() { - - super(); - this._type = 'number'; - this._flags.unsafe = false; - this._invalids.add(Infinity); - this._invalids.add(-Infinity); - } - - _base(value, state, options) { - - const result = { - errors: null, - value - }; - - if (typeof value === 'string' && - options.convert) { - - const matches = value.match(/^\s*[+-]?\d+(?:\.\d+)?(?:e([+-]?\d+))?\s*$/i); - if (matches) { - - value = value.trim(); - result.value = parseFloat(value); - - if (!this._flags.unsafe) { - if (value.includes('e')) { - if (internals.normalizeExponent(`${result.value / Math.pow(10, matches[1])}e${matches[1]}`) !== internals.normalizeExponent(value)) { - result.errors = this.createError('number.unsafe', { value }, state, options); - return result; - } - } - else { - if (result.value.toString() !== internals.normalizeDecimal(value)) { - result.errors = this.createError('number.unsafe', { value }, state, options); - return result; - } - } - } - } - } - - const isNumber = typeof result.value === 'number' && !isNaN(result.value); - - if (options.convert && 'precision' in this._flags && isNumber) { - - // This is conceptually equivalent to using toFixed but it should be much faster - const precision = Math.pow(10, this._flags.precision); - result.value = Math.round(result.value * precision) / precision; - } - - if (isNumber) { - if (!this._flags.unsafe && - (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER)) { - result.errors = this.createError('number.unsafe', { value }, state, options); - } - } - else { - result.errors = this.createError('number.base', { value }, state, options); - } - - return result; - } - - multiple(base) { - - const isRef = Ref.isRef(base); - - if (!isRef) { - Hoek.assert(typeof base === 'number' && isFinite(base), 'multiple must be a number'); - Hoek.assert(base > 0, 'multiple must be greater than 0'); - } - - return this._test('multiple', base, function (value, state, options) { - - const divisor = isRef ? base(state.reference || state.parent, options) : base; - - if (isRef && (typeof divisor !== 'number' || !isFinite(divisor))) { - return this.createError('number.ref', { ref: base.key }, state, options); - } - - if (value % divisor === 0) { - return value; - } - - return this.createError('number.multiple', { multiple: base, value }, state, options); - }); - } - - integer() { - - return this._test('integer', undefined, function (value, state, options) { - - return Math.trunc(value) - value === 0 ? value : this.createError('number.integer', { value }, state, options); - }); - } - - unsafe(enabled = true) { - - Hoek.assert(typeof enabled === 'boolean', 'enabled must be a boolean'); - - if (this._flags.unsafe === enabled) { - return this; - } - - const obj = this.clone(); - obj._flags.unsafe = enabled; - return obj; - } - - negative() { - - return this._test('negative', undefined, function (value, state, options) { - - if (value < 0) { - return value; - } - - return this.createError('number.negative', { value }, state, options); - }); - } - - positive() { - - return this._test('positive', undefined, function (value, state, options) { - - if (value > 0) { - return value; - } - - return this.createError('number.positive', { value }, state, options); - }); - } - - precision(limit) { - - Hoek.assert(Number.isSafeInteger(limit), 'limit must be an integer'); - Hoek.assert(!('precision' in this._flags), 'precision already set'); - - const obj = this._test('precision', limit, function (value, state, options) { - - const places = value.toString().match(internals.precisionRx); - const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0); - if (decimals <= limit) { - return value; - } - - return this.createError('number.precision', { limit, value }, state, options); - }); - - obj._flags.precision = limit; - return obj; - } - - port() { - - return this._test('port', undefined, function (value, state, options) { - - if (!Number.isSafeInteger(value) || value < 0 || value > 65535) { - return this.createError('number.port', { value }, state, options); - } - - return value; - }); - } - -}; - - -internals.compare = function (type, compare) { - - return function (limit) { - - const isRef = Ref.isRef(limit); - const isNumber = typeof limit === 'number' && !isNaN(limit); - - Hoek.assert(isNumber || isRef, 'limit must be a number or reference'); - - return this._test(type, limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!(typeof compareTo === 'number' && !isNaN(compareTo))) { - return this.createError('number.ref', { ref: limit.key }, state, options); - } - } - else { - compareTo = limit; - } - - if (compare(value, compareTo)) { - return value; - } - - return this.createError('number.' + type, { limit: compareTo, value }, state, options); - }); - }; -}; - - -internals.Number.prototype.min = internals.compare('min', (value, limit) => value >= limit); -internals.Number.prototype.max = internals.compare('max', (value, limit) => value <= limit); -internals.Number.prototype.greater = internals.compare('greater', (value, limit) => value > limit); -internals.Number.prototype.less = internals.compare('less', (value, limit) => value < limit); - - -module.exports = new internals.Number(); - - -/***/ }), - -/***/ 38395: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Bourne = __nccwpck_require__(97174); -const Hoek = __nccwpck_require__(10904); -const Topo = __nccwpck_require__(88392); - -const Any = __nccwpck_require__(77641); -const Errors = __nccwpck_require__(32150); -const Cast = __nccwpck_require__(16415); -const State = __nccwpck_require__(13538); - - -const internals = {}; - - -internals.Object = class extends Any { - - constructor() { - - super(); - this._type = 'object'; - this._inner.children = null; - this._inner.renames = []; - this._inner.dependencies = []; - this._inner.patterns = []; - } - - _init(...args) { - - return args.length ? this.keys(...args) : this; - } - - _base(value, state, options) { - - let target = value; - const errors = []; - const finish = () => { - - return { - value: target, - errors: errors.length ? errors : null - }; - }; - - if (typeof value === 'string' && - options.convert) { - - if (value.length > 1 && - (value[0] === '{' || /^\s*\{/.test(value))) { - - try { - value = Bourne.parse(value); - } - catch (e) { } - } - } - - const type = this._flags.func ? 'function' : 'object'; - if (!value || - typeof value !== type || - Array.isArray(value)) { - - errors.push(this.createError(type + '.base', { value }, state, options)); - return finish(); - } - - // Skip if there are no other rules to test - - if (!this._inner.renames.length && - !this._inner.dependencies.length && - !this._inner.children && // null allows any keys - !this._inner.patterns.length) { - - target = value; - return finish(); - } - - // Ensure target is a local copy (parsed) or shallow copy - - if (target === value) { - if (type === 'object') { - target = Object.create(Object.getPrototypeOf(value)); - } - else { - target = function (...args) { - - return value.apply(this, args); - }; - - target.prototype = Hoek.clone(value.prototype); - } - - const valueKeys = Object.keys(value); - for (let i = 0; i < valueKeys.length; ++i) { - target[valueKeys[i]] = value[valueKeys[i]]; - } - } - else { - target = value; - } - - // Rename keys - - const renamed = {}; - for (let i = 0; i < this._inner.renames.length; ++i) { - const rename = this._inner.renames[i]; - - if (rename.isRegExp) { - const targetKeys = Object.keys(target); - const matchedTargetKeys = []; - - for (let j = 0; j < targetKeys.length; ++j) { - if (rename.from.test(targetKeys[j])) { - matchedTargetKeys.push(targetKeys[j]); - } - } - - const allUndefined = matchedTargetKeys.every((key) => target[key] === undefined); - if (rename.options.ignoreUndefined && allUndefined) { - continue; - } - - if (!rename.options.multiple && - renamed[rename.to]) { - - errors.push(this.createError('object.rename.regex.multiple', { from: matchedTargetKeys, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (Object.prototype.hasOwnProperty.call(target, rename.to) && - !rename.options.override && - !renamed[rename.to]) { - - errors.push(this.createError('object.rename.regex.override', { from: matchedTargetKeys, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (allUndefined) { - delete target[rename.to]; - } - else { - target[rename.to] = target[matchedTargetKeys[matchedTargetKeys.length - 1]]; - } - - renamed[rename.to] = true; - - if (!rename.options.alias) { - for (let j = 0; j < matchedTargetKeys.length; ++j) { - delete target[matchedTargetKeys[j]]; - } - } - } - else { - if (rename.options.ignoreUndefined && target[rename.from] === undefined) { - continue; - } - - if (!rename.options.multiple && - renamed[rename.to]) { - - errors.push(this.createError('object.rename.multiple', { from: rename.from, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (Object.prototype.hasOwnProperty.call(target, rename.to) && - !rename.options.override && - !renamed[rename.to]) { - - errors.push(this.createError('object.rename.override', { from: rename.from, to: rename.to }, state, options)); - if (options.abortEarly) { - return finish(); - } - } - - if (target[rename.from] === undefined) { - delete target[rename.to]; - } - else { - target[rename.to] = target[rename.from]; - } - - renamed[rename.to] = true; - - if (!rename.options.alias) { - delete target[rename.from]; - } - } - } - - // Validate schema - - if (!this._inner.children && // null allows any keys - !this._inner.patterns.length && - !this._inner.dependencies.length) { - - return finish(); - } - - const unprocessed = new Set(Object.keys(target)); - - if (this._inner.children) { - const stripProps = []; - - for (let i = 0; i < this._inner.children.length; ++i) { - const child = this._inner.children[i]; - const key = child.key; - const item = target[key]; - - unprocessed.delete(key); - - const localState = new State(key, [...state.path, key], target, state.reference); - const result = child.schema._validate(item, localState, options); - if (result.errors) { - errors.push(this.createError('object.child', { key, child: child.schema._getLabel(key), reason: result.errors }, localState, options)); - - if (options.abortEarly) { - return finish(); - } - } - else { - if (child.schema._flags.strip || (result.value === undefined && result.value !== item)) { - stripProps.push(key); - target[key] = result.finalValue; - } - else if (result.value !== undefined) { - target[key] = result.value; - } - } - } - - for (let i = 0; i < stripProps.length; ++i) { - delete target[stripProps[i]]; - } - } - - // Unknown keys - - if (unprocessed.size && this._inner.patterns.length) { - - for (const key of unprocessed) { - const localState = new State(key, [...state.path, key], target, state.reference); - const item = target[key]; - - for (let i = 0; i < this._inner.patterns.length; ++i) { - const pattern = this._inner.patterns[i]; - - if (pattern.regex ? - pattern.regex.test(key) : - !pattern.schema._validate(key, state, { ...options, abortEarly:true }).errors) { - - unprocessed.delete(key); - - const result = pattern.rule._validate(item, localState, options); - if (result.errors) { - errors.push(this.createError('object.child', { - key, - child: pattern.rule._getLabel(key), - reason: result.errors - }, localState, options)); - - if (options.abortEarly) { - return finish(); - } - } - - target[key] = result.value; - } - } - } - } - - if (unprocessed.size && (this._inner.children || this._inner.patterns.length)) { - if ((options.stripUnknown && this._flags.allowUnknown !== true) || - options.skipFunctions) { - - const stripUnknown = options.stripUnknown - ? (options.stripUnknown === true ? true : !!options.stripUnknown.objects) - : false; - - - for (const key of unprocessed) { - if (stripUnknown) { - delete target[key]; - unprocessed.delete(key); - } - else if (typeof target[key] === 'function') { - unprocessed.delete(key); - } - } - } - - if ((this._flags.allowUnknown !== undefined ? !this._flags.allowUnknown : !options.allowUnknown)) { - - for (const unprocessedKey of unprocessed) { - errors.push(this.createError('object.allowUnknown', { child: unprocessedKey, value: target[unprocessedKey] }, { - key: unprocessedKey, - path: [...state.path, unprocessedKey] - }, options, {})); - } - } - } - - // Validate dependencies - - for (let i = 0; i < this._inner.dependencies.length; ++i) { - const dep = this._inner.dependencies[i]; - const hasKey = dep.key !== null; - const splitKey = hasKey && dep.key.split('.'); - const localState = hasKey ? new State(splitKey[splitKey.length - 1], [...state.path, ...splitKey]) : new State(null, state.path); - const err = internals[dep.type].call(this, dep.key, hasKey && Hoek.reach(target, dep.key, { functions: true }), dep.peers, target, localState, options); - if (err instanceof Errors.Err) { - errors.push(err); - if (options.abortEarly) { - return finish(); - } - } - } - - return finish(); - } - - keys(schema) { - - Hoek.assert(schema === null || schema === undefined || typeof schema === 'object', 'Object schema must be a valid object'); - Hoek.assert(!schema || !(schema instanceof Any), 'Object schema cannot be a joi schema'); - - const obj = this.clone(); - - if (!schema) { - obj._inner.children = null; - return obj; - } - - const children = Object.keys(schema); - - if (!children.length) { - obj._inner.children = []; - return obj; - } - - const topo = new Topo(); - if (obj._inner.children) { - for (let i = 0; i < obj._inner.children.length; ++i) { - const child = obj._inner.children[i]; - - // Only add the key if we are not going to replace it later - if (!children.includes(child.key)) { - topo.add(child, { after: child._refs, group: child.key }); - } - } - } - - for (let i = 0; i < children.length; ++i) { - const key = children[i]; - const child = schema[key]; - try { - const cast = Cast.schema(this._currentJoi, child); - topo.add({ key, schema: cast }, { after: cast._refs, group: key }); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.path = key + '.' + castErr.path; - } - else { - castErr.path = key; - } - - throw castErr; - } - } - - obj._inner.children = topo.nodes; - - return obj; - } - - append(schema) { - // Skip any changes - if (schema === null || schema === undefined || Object.keys(schema).length === 0) { - return this; - } - - return this.keys(schema); - } - - unknown(allow) { - - const value = allow !== false; - - if (this._flags.allowUnknown === value) { - return this; - } - - const obj = this.clone(); - obj._flags.allowUnknown = value; - return obj; - } - - length(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('length', limit, function (value, state, options) { - - if (Object.keys(value).length === limit) { - return value; - } - - return this.createError('object.length', { limit, value }, state, options); - }); - } - - min(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('min', limit, function (value, state, options) { - - if (Object.keys(value).length >= limit) { - return value; - } - - return this.createError('object.min', { limit, value }, state, options); - }); - } - - max(limit) { - - Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer'); - - return this._test('max', limit, function (value, state, options) { - - if (Object.keys(value).length <= limit) { - return value; - } - - return this.createError('object.max', { limit, value }, state, options); - }); - } - - pattern(pattern, schema) { - - const isRegExp = pattern instanceof RegExp; - Hoek.assert(isRegExp || pattern instanceof Any, 'pattern must be a regex or schema'); - Hoek.assert(schema !== undefined, 'Invalid rule'); - - if (isRegExp) { - Hoek.assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); - } - - try { - schema = Cast.schema(this._currentJoi, schema); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.message = `${castErr.message}(${castErr.path})`; - } - - throw castErr; - } - - const obj = this.clone(); - if (isRegExp) { - obj._inner.patterns.push({ regex: pattern, rule: schema }); - } - else { - obj._inner.patterns.push({ schema: pattern, rule: schema }); - } - - return obj; - } - - schema() { - - return this._test('schema', null, function (value, state, options) { - - if (value instanceof Any) { - return value; - } - - return this.createError('object.schema', null, state, options); - }); - } - - with(key, peers) { - - Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.'); - - return this._dependency('with', key, peers); - } - - without(key, peers) { - - Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.'); - - return this._dependency('without', key, peers); - } - - xor(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('xor', null, peers); - } - - oxor(...peers) { - - return this._dependency('oxor', null, peers); - } - - or(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('or', null, peers); - } - - and(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('and', null, peers); - } - - nand(...peers) { - - peers = Hoek.flatten(peers); - return this._dependency('nand', null, peers); - } - - requiredKeys(...children) { - - children = Hoek.flatten(children); - return this.applyFunctionToChildren(children, 'required'); - } - - optionalKeys(...children) { - - children = Hoek.flatten(children); - return this.applyFunctionToChildren(children, 'optional'); - } - - forbiddenKeys(...children) { - - children = Hoek.flatten(children); - return this.applyFunctionToChildren(children, 'forbidden'); - } - - rename(from, to, options) { - - Hoek.assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument'); - Hoek.assert(typeof to === 'string', 'Rename missing the to argument'); - Hoek.assert(to !== from, 'Cannot rename key to same name:', from); - - for (let i = 0; i < this._inner.renames.length; ++i) { - Hoek.assert(this._inner.renames[i].from !== from, 'Cannot rename the same key multiple times'); - } - - const obj = this.clone(); - - obj._inner.renames.push({ - from, - to, - options: Hoek.applyToDefaults(internals.renameDefaults, options || {}), - isRegExp: from instanceof RegExp - }); - - return obj; - } - - applyFunctionToChildren(children, fn, args = [], root) { - - children = [].concat(children); - Hoek.assert(children.length > 0, 'expected at least one children'); - - const groupedChildren = internals.groupChildren(children); - let obj; - - if ('' in groupedChildren) { - obj = this[fn](...args); - delete groupedChildren['']; - } - else { - obj = this.clone(); - } - - if (obj._inner.children) { - root = root ? (root + '.') : ''; - - for (let i = 0; i < obj._inner.children.length; ++i) { - const child = obj._inner.children[i]; - const group = groupedChildren[child.key]; - - if (group) { - obj._inner.children[i] = { - key: child.key, - _refs: child._refs, - schema: child.schema.applyFunctionToChildren(group, fn, args, root + child.key) - }; - - delete groupedChildren[child.key]; - } - } - } - - const remaining = Object.keys(groupedChildren); - Hoek.assert(remaining.length === 0, 'unknown key(s)', remaining.join(', ')); - - return obj; - } - - _dependency(type, key, peers) { - - peers = [].concat(peers); - for (let i = 0; i < peers.length; ++i) { - Hoek.assert(typeof peers[i] === 'string', type, 'peers must be a string or array of strings'); - } - - const obj = this.clone(); - obj._inner.dependencies.push({ type, key, peers }); - return obj; - } - - describe(shallow) { - - const description = super.describe(); - - if (description.rules) { - for (let i = 0; i < description.rules.length; ++i) { - const rule = description.rules[i]; - // Coverage off for future-proof descriptions, only object().assert() is use right now - if (/* $lab:coverage:off$ */rule.arg && - typeof rule.arg === 'object' && - rule.arg.schema && - rule.arg.ref /* $lab:coverage:on$ */) { - rule.arg = { - schema: rule.arg.schema.describe(), - ref: rule.arg.ref.toString() - }; - } - } - } - - if (this._inner.children && - !shallow) { - - description.children = {}; - for (let i = 0; i < this._inner.children.length; ++i) { - const child = this._inner.children[i]; - description.children[child.key] = child.schema.describe(); - } - } - - if (this._inner.dependencies.length) { - description.dependencies = Hoek.clone(this._inner.dependencies); - } - - if (this._inner.patterns.length) { - description.patterns = []; - - for (let i = 0; i < this._inner.patterns.length; ++i) { - const pattern = this._inner.patterns[i]; - if (pattern.regex) { - description.patterns.push({ regex: pattern.regex.toString(), rule: pattern.rule.describe() }); - } - else { - description.patterns.push({ schema: pattern.schema.describe(), rule: pattern.rule.describe() }); - } - } - } - - if (this._inner.renames.length > 0) { - description.renames = Hoek.clone(this._inner.renames); - } - - return description; - } - - assert(ref, schema, message) { - - ref = Cast.ref(ref); - Hoek.assert(ref.isContext || ref.depth > 1, 'Cannot use assertions for root level references - use direct key rules instead'); - message = message || 'pass the assertion test'; - Hoek.assert(typeof message === 'string', 'Message must be a string'); - - try { - schema = Cast.schema(this._currentJoi, schema); - } - catch (castErr) { - if (castErr.hasOwnProperty('path')) { - castErr.message = `${castErr.message}(${castErr.path})`; - } - - throw castErr; - } - - const key = ref.path[ref.path.length - 1]; - const path = ref.path.join('.'); - - return this._test('assert', { schema, ref }, function (value, state, options) { - - const result = schema._validate(ref(value), null, options, value); - if (!result.errors) { - return value; - } - - const localState = new State(key, ref.path, state.parent, state.reference); - return this.createError('object.assert', { ref: path, message }, localState, options); - }); - } - - type(constructor, name = constructor.name) { - - Hoek.assert(typeof constructor === 'function', 'type must be a constructor function'); - const typeData = { - name, - ctor: constructor - }; - - return this._test('type', typeData, function (value, state, options) { - - if (value instanceof constructor) { - return value; - } - - return this.createError('object.type', { type: typeData.name, value }, state, options); - }); - } -}; - - -internals.renameDefaults = { - alias: false, // Keep old value in place - multiple: false, // Allow renaming multiple keys into the same target - override: false // Overrides an existing key -}; - - -internals.groupChildren = function (children) { - - children.sort(); - - const grouped = {}; - - for (let i = 0; i < children.length; ++i) { - const child = children[i]; - Hoek.assert(typeof child === 'string', 'children must be strings'); - const group = child.split('.')[0]; - const childGroup = grouped[group] = (grouped[group] || []); - childGroup.push(child.substring(group.length + 1)); - } - - return grouped; -}; - - -internals.keysToLabels = function (schema, keys) { - - const children = schema._inner.children; - - if (!children) { - return keys; - } - - const findLabel = function (key) { - - const matchingChild = schema._currentJoi.reach(schema, key); - return matchingChild ? matchingChild._getLabel(key) : key; - }; - - if (Array.isArray(keys)) { - return keys.map(findLabel); - } - - return findLabel(keys); -}; - - -internals.with = function (key, value, peers, parent, state, options) { - - if (value === undefined) { - return; - } - - for (let i = 0; i < peers.length; ++i) { - - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist === undefined) { - - return this.createError('object.with', { - main: key, - mainWithLabel: internals.keysToLabels(this, key), - peer, - peerWithLabel: internals.keysToLabels(this, peer) - }, state, options); - } - } -}; - - -internals.without = function (key, value, peers, parent, state, options) { - - if (value === undefined) { - return; - } - - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - - return this.createError('object.without', { - main: key, - mainWithLabel: internals.keysToLabels(this, key), - peer, - peerWithLabel: internals.keysToLabels(this, peer) - }, state, options); - } - } -}; - - -internals.xor = function (key, value, peers, parent, state, options) { - - const present = []; - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - present.push(peer); - } - } - - if (present.length === 1) { - return; - } - - const context = { peers, peersWithLabels: internals.keysToLabels(this, peers) }; - - if (present.length === 0) { - return this.createError('object.missing', context, state, options); - } - - context.present = present; - context.presentWithLabels = internals.keysToLabels(this, present); - - return this.createError('object.xor', context, state, options); -}; - - -internals.oxor = function (key, value, peers, parent, state, options) { - - const present = []; - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - present.push(peer); - } - } - - if (!present.length || - present.length === 1) { - - return; - } - - const context = { peers, peersWithLabels: internals.keysToLabels(this, peers) }; - context.present = present; - context.presentWithLabels = internals.keysToLabels(this, present); - - return this.createError('object.oxor', context, state, options); -}; - - -internals.or = function (key, value, peers, parent, state, options) { - - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - return; - } - } - - return this.createError('object.missing', { - peers, - peersWithLabels: internals.keysToLabels(this, peers) - }, state, options); -}; - - -internals.and = function (key, value, peers, parent, state, options) { - - const missing = []; - const present = []; - const count = peers.length; - for (let i = 0; i < count; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist === undefined) { - - missing.push(peer); - } - else { - present.push(peer); - } - } - - const aon = (missing.length === count || present.length === count); - - if (!aon) { - - return this.createError('object.and', { - present, - presentWithLabels: internals.keysToLabels(this, present), - missing, - missingWithLabels: internals.keysToLabels(this, missing) - }, state, options); - } -}; - - -internals.nand = function (key, value, peers, parent, state, options) { - - const present = []; - for (let i = 0; i < peers.length; ++i) { - const peer = peers[i]; - const keysExist = Hoek.reach(parent, peer, { functions: true }); - if (keysExist !== undefined) { - - present.push(peer); - } - } - - const main = peers[0]; - const values = peers.slice(1); - const allPresent = (present.length === peers.length); - return allPresent ? this.createError('object.nand', { - main, - mainWithLabel: internals.keysToLabels(this, main), - peers: values, - peersWithLabels: internals.keysToLabels(this, values) - }, state, options) : null; -}; - - -module.exports = new internals.Object(); - - -/***/ }), - -/***/ 13538: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = class { - constructor(key, path, parent, reference) { - - this.key = key; - this.path = path; - this.parent = parent; - this.reference = reference; - } -}; - - -/***/ }), - -/***/ 67769: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Net = __nccwpck_require__(11631); - -const Address = __nccwpck_require__(9491); -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); -const Ref = __nccwpck_require__(71802); -const JoiDate = __nccwpck_require__(46254); - -const Uri = __nccwpck_require__(30018); -const Ip = __nccwpck_require__(8751); - - -const internals = { - uriRegex: Uri.createUriRegex(), - ipRegex: Ip.createIpRegex(['ipv4', 'ipv6', 'ipvfuture'], 'optional'), - guidBrackets: { - '{': '}', '[': ']', '(': ')', '': '' - }, - guidVersions: { - uuidv1: '1', - uuidv2: '2', - uuidv3: '3', - uuidv4: '4', - uuidv5: '5' - }, - cidrPresences: ['required', 'optional', 'forbidden'], - normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD'] -}; - - -internals.String = class extends Any { - - constructor() { - - super(); - this._type = 'string'; - this._invalids.add(''); - } - - _base(value, state, options) { - - if (typeof value === 'string' && - options.convert) { - - if (this._flags.normalize) { - value = value.normalize(this._flags.normalize); - } - - if (this._flags.case) { - value = (this._flags.case === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase()); - } - - if (this._flags.trim) { - value = value.trim(); - } - - if (this._inner.replacements) { - - for (let i = 0; i < this._inner.replacements.length; ++i) { - const replacement = this._inner.replacements[i]; - value = value.replace(replacement.pattern, replacement.replacement); - } - } - - if (this._flags.truncate) { - for (let i = 0; i < this._tests.length; ++i) { - const test = this._tests[i]; - if (test.name === 'max') { - value = value.slice(0, test.arg); - break; - } - } - } - - if (this._flags.byteAligned && value.length % 2 !== 0) { - value = `0${value}`; - } - } - - return { - value, - errors: (typeof value === 'string') ? null : this.createError('string.base', { value }, state, options) - }; - } - - insensitive() { - - if (this._flags.insensitive) { - return this; - } - - const obj = this.clone(); - obj._flags.insensitive = true; - return obj; - } - - creditCard() { - - return this._test('creditCard', undefined, function (value, state, options) { - - let i = value.length; - let sum = 0; - let mul = 1; - - while (i--) { - const char = value.charAt(i) * mul; - sum = sum + (char - (char > 9) * 9); - mul = mul ^ 3; - } - - const check = (sum % 10 === 0) && (sum > 0); - return check ? value : this.createError('string.creditCard', { value }, state, options); - }); - } - - regex(pattern, patternOptions) { - - Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp'); - Hoek.assert(!pattern.flags.includes('g') && !pattern.flags.includes('y'), 'pattern should not use global or sticky mode'); - - const patternObject = { pattern }; - - if (typeof patternOptions === 'string') { - patternObject.name = patternOptions; - } - else if (typeof patternOptions === 'object') { - patternObject.invert = !!patternOptions.invert; - - if (patternOptions.name) { - patternObject.name = patternOptions.name; - } - } - - const errorCode = ['string.regex', patternObject.invert ? '.invert' : '', patternObject.name ? '.name' : '.base'].join(''); - - return this._test('regex', patternObject, function (value, state, options) { - - const patternMatch = patternObject.pattern.test(value); - - if (patternMatch ^ patternObject.invert) { - return value; - } - - return this.createError(errorCode, { name: patternObject.name, pattern: patternObject.pattern, value }, state, options); - }); - } - - alphanum() { - - return this._test('alphanum', undefined, function (value, state, options) { - - if (/^[a-zA-Z0-9]+$/.test(value)) { - return value; - } - - return this.createError('string.alphanum', { value }, state, options); - }); - } - - token() { - - return this._test('token', undefined, function (value, state, options) { - - if (/^\w+$/.test(value)) { - return value; - } - - return this.createError('string.token', { value }, state, options); - }); - } - - email(validationOptions) { - - if (validationOptions) { - Hoek.assert(typeof validationOptions === 'object', 'email options must be an object'); - - // Migration validation for unsupported options - - Hoek.assert(validationOptions.checkDNS === undefined, 'checkDNS option is not supported'); - Hoek.assert(validationOptions.errorLevel === undefined, 'errorLevel option is not supported'); - Hoek.assert(validationOptions.minDomainAtoms === undefined, 'minDomainAtoms option is not supported, use minDomainSegments instead'); - Hoek.assert(validationOptions.tldBlacklist === undefined, 'tldBlacklist option is not supported, use tlds.deny instead'); - Hoek.assert(validationOptions.tldWhitelist === undefined, 'tldWhitelist option is not supported, use tlds.allow instead'); - - // Validate options - - if (validationOptions.tlds && - typeof validationOptions.tlds === 'object') { - - Hoek.assert(validationOptions.tlds.allow === undefined || - validationOptions.tlds.allow === false || - validationOptions.tlds.allow === true || - Array.isArray(validationOptions.tlds.allow) || - validationOptions.tlds.allow instanceof Set, 'tlds.allow must be an array, Set, or boolean'); - - Hoek.assert(validationOptions.tlds.deny === undefined || - Array.isArray(validationOptions.tlds.deny) || - validationOptions.tlds.deny instanceof Set, 'tlds.deny must be an array or Set'); - - const normalizeTable = (table) => { - - if (table === undefined || - typeof table === 'boolean' || - table instanceof Set) { - - return table; - } - - return new Set(table); - }; - - validationOptions = Object.assign({}, validationOptions); // Shallow cloned - validationOptions.tlds = { - allow: normalizeTable(validationOptions.tlds.allow), - deny: normalizeTable(validationOptions.tlds.deny) - }; - } - - Hoek.assert(validationOptions.minDomainSegments === undefined || - Number.isSafeInteger(validationOptions.minDomainSegments) && validationOptions.minDomainSegments > 0, 'minDomainSegments must be a positive integer'); - } - - return this._test('email', validationOptions, function (value, state, options) { - - if (Address.email.isValid(value, validationOptions)) { - return value; - } - - return this.createError('string.email', { value }, state, options); - }); - } - - ip(ipOptions = {}) { - - let regex = internals.ipRegex; - Hoek.assert(typeof ipOptions === 'object', 'options must be an object'); - - if (ipOptions.cidr) { - Hoek.assert(typeof ipOptions.cidr === 'string', 'cidr must be a string'); - ipOptions.cidr = ipOptions.cidr.toLowerCase(); - - Hoek.assert(Hoek.contain(internals.cidrPresences, ipOptions.cidr), 'cidr must be one of ' + internals.cidrPresences.join(', ')); - - // If we only received a `cidr` setting, create a regex for it. But we don't need to create one if `cidr` is "optional" since that is the default - if (!ipOptions.version && ipOptions.cidr !== 'optional') { - regex = Ip.createIpRegex(['ipv4', 'ipv6', 'ipvfuture'], ipOptions.cidr); - } - } - else { - - // Set our default cidr strategy - ipOptions.cidr = 'optional'; - } - - let versions; - if (ipOptions.version) { - if (!Array.isArray(ipOptions.version)) { - ipOptions.version = [ipOptions.version]; - } - - Hoek.assert(ipOptions.version.length >= 1, 'version must have at least 1 version specified'); - - versions = []; - for (let i = 0; i < ipOptions.version.length; ++i) { - let version = ipOptions.version[i]; - Hoek.assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); - version = version.toLowerCase(); - Hoek.assert(Ip.versions[version], 'version at position ' + i + ' must be one of ' + Object.keys(Ip.versions).join(', ')); - versions.push(version); - } - - // Make sure we have a set of versions - versions = Array.from(new Set(versions)); - - regex = Ip.createIpRegex(versions, ipOptions.cidr); - } - - return this._test('ip', ipOptions, function (value, state, options) { - - if (regex.test(value)) { - return value; - } - - if (versions) { - return this.createError('string.ipVersion', { value, cidr: ipOptions.cidr, version: versions }, state, options); - } - - return this.createError('string.ip', { value, cidr: ipOptions.cidr }, state, options); - }); - } - - uri(uriOptions) { - - let customScheme = ''; - let allowRelative = false; - let relativeOnly = false; - let allowQuerySquareBrackets = false; - let regex = internals.uriRegex; - - if (uriOptions) { - Hoek.assert(typeof uriOptions === 'object', 'options must be an object'); - - const unknownOptions = Object.keys(uriOptions).filter((key) => !['scheme', 'allowRelative', 'relativeOnly', 'allowQuerySquareBrackets'].includes(key)); - Hoek.assert(unknownOptions.length === 0, `options contain unknown keys: ${unknownOptions}`); - - if (uriOptions.scheme) { - Hoek.assert(uriOptions.scheme instanceof RegExp || typeof uriOptions.scheme === 'string' || Array.isArray(uriOptions.scheme), 'scheme must be a RegExp, String, or Array'); - - if (!Array.isArray(uriOptions.scheme)) { - uriOptions.scheme = [uriOptions.scheme]; - } - - Hoek.assert(uriOptions.scheme.length >= 1, 'scheme must have at least 1 scheme specified'); - - // Flatten the array into a string to be used to match the schemes. - for (let i = 0; i < uriOptions.scheme.length; ++i) { - const scheme = uriOptions.scheme[i]; - Hoek.assert(scheme instanceof RegExp || typeof scheme === 'string', 'scheme at position ' + i + ' must be a RegExp or String'); - - // Add OR separators if a value already exists - customScheme = customScheme + (customScheme ? '|' : ''); - - // If someone wants to match HTTP or HTTPS for example then we need to support both RegExp and String so we don't escape their pattern unknowingly. - if (scheme instanceof RegExp) { - customScheme = customScheme + scheme.source; - } - else { - Hoek.assert(/[a-zA-Z][a-zA-Z0-9+-\.]*/.test(scheme), 'scheme at position ' + i + ' must be a valid scheme'); - customScheme = customScheme + Hoek.escapeRegex(scheme); - } - } - } - - if (uriOptions.allowRelative) { - allowRelative = true; - } - - if (uriOptions.relativeOnly) { - relativeOnly = true; - } - - if (uriOptions.allowQuerySquareBrackets) { - allowQuerySquareBrackets = true; - } - } - - if (customScheme || allowRelative || relativeOnly || allowQuerySquareBrackets) { - regex = Uri.createUriRegex(customScheme, allowRelative, relativeOnly, allowQuerySquareBrackets); - } - - return this._test('uri', uriOptions, function (value, state, options) { - - if (regex.test(value)) { - return value; - } - - if (relativeOnly) { - return this.createError('string.uriRelativeOnly', { value }, state, options); - } - - if (customScheme) { - return this.createError('string.uriCustomScheme', { scheme: customScheme, value }, state, options); - } - - return this.createError('string.uri', { value }, state, options); - }); - } - - isoDate() { - - return this._test('isoDate', undefined, function (value, state, options) { - - if (JoiDate._isIsoDate(value)) { - if (!options.convert) { - return value; - } - - const d = new Date(value); - if (!isNaN(d.getTime())) { - return d.toISOString(); - } - } - - return this.createError('string.isoDate', { value }, state, options); - }); - } - - guid(guidOptions) { - - let versionNumbers = ''; - - if (guidOptions && guidOptions.version) { - if (!Array.isArray(guidOptions.version)) { - guidOptions.version = [guidOptions.version]; - } - - Hoek.assert(guidOptions.version.length >= 1, 'version must have at least 1 valid version specified'); - const versions = new Set(); - - for (let i = 0; i < guidOptions.version.length; ++i) { - let version = guidOptions.version[i]; - Hoek.assert(typeof version === 'string', 'version at position ' + i + ' must be a string'); - version = version.toLowerCase(); - const versionNumber = internals.guidVersions[version]; - Hoek.assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', ')); - Hoek.assert(!(versions.has(versionNumber)), 'version at position ' + i + ' must not be a duplicate.'); - - versionNumbers += versionNumber; - versions.add(versionNumber); - } - } - - const guidRegex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}([:-]?)[0-9A-F]{4}\\2?[${versionNumbers || '0-9A-F'}][0-9A-F]{3}\\2?[${versionNumbers ? '89AB' : '0-9A-F'}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`, 'i'); - - return this._test('guid', guidOptions, function (value, state, options) { - - const results = guidRegex.exec(value); - - if (!results) { - return this.createError('string.guid', { value }, state, options); - } - - // Matching braces - if (internals.guidBrackets[results[1]] !== results[results.length - 1]) { - return this.createError('string.guid', { value }, state, options); - } - - return value; - }); - } - - hex(hexOptions = {}) { - - Hoek.assert(typeof hexOptions === 'object', 'hex options must be an object'); - Hoek.assert(typeof hexOptions.byteAligned === 'undefined' || typeof hexOptions.byteAligned === 'boolean', - 'byteAligned must be boolean'); - - const byteAligned = hexOptions.byteAligned === true; - const regex = /^[a-f0-9]+$/i; - - const obj = this._test('hex', regex, function (value, state, options) { - - if (regex.test(value)) { - if (byteAligned && value.length % 2 !== 0) { - return this.createError('string.hexAlign', { value }, state, options); - } - - return value; - } - - return this.createError('string.hex', { value }, state, options); - }); - - if (byteAligned) { - obj._flags.byteAligned = true; - } - - return obj; - } - - base64(base64Options = {}) { - - // Validation. - Hoek.assert(typeof base64Options === 'object', 'base64 options must be an object'); - Hoek.assert(typeof base64Options.paddingRequired === 'undefined' || typeof base64Options.paddingRequired === 'boolean', - 'paddingRequired must be boolean'); - - // Determine if padding is required. - const paddingRequired = base64Options.paddingRequired === false ? - base64Options.paddingRequired - : base64Options.paddingRequired || true; - - // Set validation based on preference. - const regex = paddingRequired ? - // Padding is required. - /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ - // Padding is optional. - : /^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/; - - return this._test('base64', regex, function (value, state, options) { - - if (regex.test(value)) { - return value; - } - - return this.createError('string.base64', { value }, state, options); - }); - } - - dataUri(dataUriOptions = {}) { - - const regex = /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/; - - // Determine if padding is required. - const paddingRequired = dataUriOptions.paddingRequired === false ? - dataUriOptions.paddingRequired - : dataUriOptions.paddingRequired || true; - - const base64regex = paddingRequired ? - /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/ - : /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/; - - return this._test('dataUri', regex, function (value, state, options) { - - const matches = value.match(regex); - - if (matches) { - if (!matches[2]) { - return value; - } - - if (matches[2] !== 'base64') { - return value; - } - - if (base64regex.test(matches[3])) { - return value; - } - } - - return this.createError('string.dataUri', { value }, state, options); - }); - } - - hostname() { - - const regex = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; - - return this._test('hostname', undefined, function (value, state, options) { - - if ((value.length <= 255 && regex.test(value)) || - Net.isIPv6(value)) { - - return value; - } - - return this.createError('string.hostname', { value }, state, options); - }); - } - - normalize(form = 'NFC') { - - Hoek.assert(Hoek.contain(internals.normalizationForms, form), 'normalization form must be one of ' + internals.normalizationForms.join(', ')); - - const obj = this._test('normalize', form, function (value, state, options) { - - if (options.convert || - value === value.normalize(form)) { - - return value; - } - - return this.createError('string.normalize', { value, form }, state, options); - }); - - obj._flags.normalize = form; - return obj; - } - - lowercase() { - - const obj = this._test('lowercase', undefined, function (value, state, options) { - - if (options.convert || - value === value.toLocaleLowerCase()) { - - return value; - } - - return this.createError('string.lowercase', { value }, state, options); - }); - - obj._flags.case = 'lower'; - return obj; - } - - uppercase() { - - const obj = this._test('uppercase', undefined, function (value, state, options) { - - if (options.convert || - value === value.toLocaleUpperCase()) { - - return value; - } - - return this.createError('string.uppercase', { value }, state, options); - }); - - obj._flags.case = 'upper'; - return obj; - } - - trim(enabled = true) { - - Hoek.assert(typeof enabled === 'boolean', 'option must be a boolean'); - - if ((this._flags.trim && enabled) || (!this._flags.trim && !enabled)) { - return this; - } - - let obj; - if (enabled) { - obj = this._test('trim', undefined, function (value, state, options) { - - if (options.convert || - value === value.trim()) { - - return value; - } - - return this.createError('string.trim', { value }, state, options); - }); - } - else { - obj = this.clone(); - obj._tests = obj._tests.filter((test) => test.name !== 'trim'); - } - - obj._flags.trim = enabled; - return obj; - } - - replace(pattern, replacement) { - - if (typeof pattern === 'string') { - pattern = new RegExp(Hoek.escapeRegex(pattern), 'g'); - } - - Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp'); - Hoek.assert(typeof replacement === 'string', 'replacement must be a String'); - - // This can not be considere a test like trim, we can't "reject" - // anything from this rule, so just clone the current object - const obj = this.clone(); - - if (!obj._inner.replacements) { - obj._inner.replacements = []; - } - - obj._inner.replacements.push({ - pattern, - replacement - }); - - return obj; - } - - truncate(enabled) { - - const value = enabled === undefined ? true : !!enabled; - - if (this._flags.truncate === value) { - return this; - } - - const obj = this.clone(); - obj._flags.truncate = value; - return obj; - } - -}; - -internals.compare = function (type, compare) { - - return function (limit, encoding) { - - const isRef = Ref.isRef(limit); - - Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference'); - Hoek.assert(!encoding || Buffer.isEncoding(encoding), 'Invalid encoding:', encoding); - - return this._test(type, limit, function (value, state, options) { - - let compareTo; - if (isRef) { - compareTo = limit(state.reference || state.parent, options); - - if (!Number.isSafeInteger(compareTo)) { - return this.createError('string.ref', { ref: limit, value: compareTo }, state, options); - } - } - else { - compareTo = limit; - } - - if (compare(value, compareTo, encoding)) { - return value; - } - - return this.createError('string.' + type, { limit: compareTo, value, encoding }, state, options); - }); - }; -}; - - -internals.String.prototype.min = internals.compare('min', (value, limit, encoding) => { - - const length = encoding ? Buffer.byteLength(value, encoding) : value.length; - return length >= limit; -}); - - -internals.String.prototype.max = internals.compare('max', (value, limit, encoding) => { - - const length = encoding ? Buffer.byteLength(value, encoding) : value.length; - return length <= limit; -}); - - -internals.String.prototype.length = internals.compare('length', (value, limit, encoding) => { - - const length = encoding ? Buffer.byteLength(value, encoding) : value.length; - return length === limit; -}); - -// Aliases - -internals.String.prototype.uuid = internals.String.prototype.guid; - -module.exports = new internals.String(); - - -/***/ }), - -/***/ 8751: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const RFC3986 = __nccwpck_require__(49954); - - -const internals = { - Ip: { - cidrs: { - ipv4: { - required: '\\/(?:' + RFC3986.ipv4Cidr + ')', - optional: '(?:\\/(?:' + RFC3986.ipv4Cidr + '))?', - forbidden: '' - }, - ipv6: { - required: '\\/' + RFC3986.ipv6Cidr, - optional: '(?:\\/' + RFC3986.ipv6Cidr + ')?', - forbidden: '' - }, - ipvfuture: { - required: '\\/' + RFC3986.ipv6Cidr, - optional: '(?:\\/' + RFC3986.ipv6Cidr + ')?', - forbidden: '' - } - }, - versions: { - ipv4: RFC3986.IPv4address, - ipv6: RFC3986.IPv6address, - ipvfuture: RFC3986.IPvFuture - } - } -}; - - -internals.Ip.createIpRegex = function (versions, cidr) { - - let regex; - for (let i = 0; i < versions.length; ++i) { - const version = versions[i]; - if (!regex) { - regex = '^(?:' + internals.Ip.versions[version] + internals.Ip.cidrs[version][cidr]; - } - else { - regex += '|' + internals.Ip.versions[version] + internals.Ip.cidrs[version][cidr]; - } - } - - return new RegExp(regex + ')$'); -}; - -module.exports = internals.Ip; - - -/***/ }), - -/***/ 49954: -/***/ ((module) => { - -"use strict"; - - -const internals = { - rfc3986: {} -}; - - -internals.generate = function () { - - /** - * elements separated by forward slash ("/") are alternatives. - */ - const or = '|'; - - /** - * Rule to support zero-padded addresses. - */ - const zeroPad = '0?'; - - /** - * DIGIT = %x30-39 ; 0-9 - */ - const digit = '0-9'; - const digitOnly = '[' + digit + ']'; - - /** - * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z - */ - const alpha = 'a-zA-Z'; - const alphaOnly = '[' + alpha + ']'; - - /** - * IPv4 - * cidr = DIGIT ; 0-9 - * / %x31-32 DIGIT ; 10-29 - * / "3" %x30-32 ; 30-32 - */ - internals.rfc3986.ipv4Cidr = digitOnly + or + '[1-2]' + digitOnly + or + '3' + '[0-2]'; - - /** - * IPv6 - * cidr = DIGIT ; 0-9 - * / %x31-39 DIGIT ; 10-99 - * / "1" %x0-1 DIGIT ; 100-119 - * / "12" %x0-8 ; 120-128 - */ - internals.rfc3986.ipv6Cidr = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + '[01]' + digitOnly + or + '12[0-8])'; - - /** - * HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" - */ - const hexDigit = digit + 'A-Fa-f'; - const hexDigitOnly = '[' + hexDigit + ']'; - - /** - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - */ - const unreserved = alpha + digit + '-\\._~'; - - /** - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - */ - const subDelims = '!\\$&\'\\(\\)\\*\\+,;='; - - /** - * pct-encoded = "%" HEXDIG HEXDIG - */ - const pctEncoded = '%' + hexDigit; - - /** - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ - const pchar = unreserved + pctEncoded + subDelims + ':@'; - const pcharOnly = '[' + pchar + ']'; - - /** - * squareBrackets example: [] - */ - const squareBrackets = '\\[\\]'; - - /** - * dec-octet = DIGIT ; 0-9 - * / %x31-39 DIGIT ; 10-99 - * / "1" 2DIGIT ; 100-199 - * / "2" %x30-34 DIGIT ; 200-249 - * / "25" %x30-35 ; 250-255 - */ - const decOctect = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + digitOnly + digitOnly + or + '2' + '[0-4]' + digitOnly + or + '25' + '[0-5])'; - - /** - * IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet - */ - internals.rfc3986.IPv4address = '(?:' + decOctect + '\\.){3}' + decOctect; - - /** - * h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal - * ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address - * IPv6address = 6( h16 ":" ) ls32 - * / "::" 5( h16 ":" ) ls32 - * / [ h16 ] "::" 4( h16 ":" ) ls32 - * / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - * / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - * / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - * / [ *4( h16 ":" ) h16 ] "::" ls32 - * / [ *5( h16 ":" ) h16 ] "::" h16 - * / [ *6( h16 ":" ) h16 ] "::" - */ - const h16 = hexDigitOnly + '{1,4}'; - const ls32 = '(?:' + h16 + ':' + h16 + '|' + internals.rfc3986.IPv4address + ')'; - const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32; - const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32; - const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32; - const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32; - const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32; - const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32; - const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32; - const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16; - const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::'; - internals.rfc3986.IPv6address = '(?:' + IPv6SixHex + or + IPv6FiveHex + or + IPv6FourHex + or + IPv6ThreeHex + or + IPv6TwoHex + or + IPv6OneHex + or + IPv6NoneHex + or + IPv6NoneHex2 + or + IPv6NoneHex3 + ')'; - - /** - * IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) - */ - internals.rfc3986.IPvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+'; - - /** - * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) - */ - internals.rfc3986.scheme = alphaOnly + '[' + alpha + digit + '+-\\.]*'; - - /** - * userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) - */ - const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*'; - - /** - * IP-literal = "[" ( IPv6address / IPvFuture ) "]" - */ - const IPLiteral = '\\[(?:' + internals.rfc3986.IPv6address + or + internals.rfc3986.IPvFuture + ')\\]'; - - /** - * reg-name = *( unreserved / pct-encoded / sub-delims ) - */ - const regName = '[' + unreserved + pctEncoded + subDelims + ']{0,255}'; - - /** - * host = IP-literal / IPv4address / reg-name - */ - const host = '(?:' + IPLiteral + or + internals.rfc3986.IPv4address + or + regName + ')'; - - /** - * port = *DIGIT - */ - const port = digitOnly + '*'; - - /** - * authority = [ userinfo "@" ] host [ ":" port ] - */ - const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?'; - - /** - * segment = *pchar - * segment-nz = 1*pchar - * path = path-abempty ; begins with "/" or is empty - * / path-absolute ; begins with "/" but not "//" - * / path-noscheme ; begins with a non-colon segment - * / path-rootless ; begins with a segment - * / path-empty ; zero characters - * path-abempty = *( "/" segment ) - * path-absolute = "/" [ segment-nz *( "/" segment ) ] - * path-rootless = segment-nz *( "/" segment ) - */ - const segment = pcharOnly + '*'; - const segmentNz = pcharOnly + '+'; - const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+'; - const pathEmpty = ''; - const pathAbEmpty = '(?:\\/' + segment + ')*'; - const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?'; - const pathRootless = segmentNz + pathAbEmpty; - const pathNoScheme = segmentNzNc + pathAbEmpty; - - /** - * hier-part = "//" authority path - */ - internals.rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathRootless + ')'; - - /** - * relative-part = "//" authority path-abempty - * / path-absolute - * / path-noscheme - * / path-empty - */ - internals.rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathNoScheme + or + pathEmpty + ')'; - - /** - * query = *( pchar / "/" / "?" ) - */ - internals.rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line. - - /** - * query = *( pchar / "[" / "]" / "/" / "?" ) - */ - internals.rfc3986.queryWithSquareBrackets = '[' + pchar + squareBrackets + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line. - - /** - * fragment = *( pchar / "/" / "?" ) - */ - internals.rfc3986.fragment = '[' + pchar + '\\/\\?]*'; -}; - - -internals.generate(); - -module.exports = internals.rfc3986; - - -/***/ }), - -/***/ 30018: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const RFC3986 = __nccwpck_require__(49954); - - -const internals = { - Uri: { - createUriRegex: function (optionalScheme, allowRelative, relativeOnly, allowQuerySquareBrackets) { - - let scheme = RFC3986.scheme; - let prefix; - - if (relativeOnly) { - prefix = '(?:' + RFC3986.relativeRef + ')'; - } - else { - // If we were passed a scheme, use it instead of the generic one - if (optionalScheme) { - - // Have to put this in a non-capturing group to handle the OR statements - scheme = '(?:' + optionalScheme + ')'; - } - - const withScheme = '(?:' + scheme + ':' + RFC3986.hierPart + ')'; - - prefix = allowRelative ? '(?:' + withScheme + '|' + RFC3986.relativeRef + ')' : withScheme; - } - - /** - * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] - * - * OR - * - * relative-ref = relative-part [ "?" query ] [ "#" fragment ] - */ - return new RegExp('^' + prefix + '(?:\\?' + (allowQuerySquareBrackets ? RFC3986.queryWithSquareBrackets : RFC3986.query) + ')?' + '(?:#' + RFC3986.fragment + ')?$'); - } - } -}; - -module.exports = internals.Uri; - - -/***/ }), - -/***/ 62462: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Util = __nccwpck_require__(31669); - -const Hoek = __nccwpck_require__(10904); - -const Any = __nccwpck_require__(77641); - - -const internals = {}; - - -internals.Map = class extends Map { - - slice() { - - return new internals.Map(this); - } - - toString() { - - return Util.inspect(this); - } -}; - - -internals.Symbol = class extends Any { - - constructor() { - - super(); - this._type = 'symbol'; - this._inner.map = new internals.Map(); - } - - _base(value, state, options) { - - if (options.convert) { - const lookup = this._inner.map.get(value); - if (lookup) { - value = lookup; - } - - if (this._flags.allowOnly) { - return { - value, - errors: (typeof value === 'symbol') ? null : this.createError('symbol.map', { value, map: this._inner.map }, state, options) - }; - } - } - - return { - value, - errors: (typeof value === 'symbol') ? null : this.createError('symbol.base', { value }, state, options) - }; - } - - map(iterable) { - - if (iterable && !iterable[Symbol.iterator] && typeof iterable === 'object') { - iterable = Object.entries(iterable); - } - - Hoek.assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object'); - const obj = this.clone(); - - const symbols = []; - for (const entry of iterable) { - Hoek.assert(entry && entry[Symbol.iterator], 'Entry must be an iterable'); - const [key, value] = entry; - - Hoek.assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be an object, function, or Symbol'); - Hoek.assert(typeof value === 'symbol', 'Value must be a Symbol'); - obj._inner.map.set(key, value); - symbols.push(value); - } - - return obj.valid(...symbols); - } - - describe() { - - const description = super.describe(); - description.map = new Map(this._inner.map); - return description; - } -}; - - -module.exports = new internals.Symbol(); - - -/***/ }), - -/***/ 52252: -/***/ ((module) => { - -"use strict"; - - -const internals = {}; - - -module.exports = { - settingsCache: Symbol('settingsCache') -}; - - -/***/ }), - -/***/ 88392: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Assert = __nccwpck_require__(32718); - - -const internals = {}; - - -module.exports = class Topo { - - constructor() { - - this._items = []; - this.nodes = []; - } - - add(nodes, options) { - - options = options || {}; - - // Validate rules - - const before = [].concat(options.before || []); - const after = [].concat(options.after || []); - const group = options.group || '?'; - const sort = options.sort || 0; // Used for merging only - - Assert(!before.includes(group), `Item cannot come before itself: ${group}`); - Assert(!before.includes('?'), 'Item cannot come before unassociated items'); - Assert(!after.includes(group), `Item cannot come after itself: ${group}`); - Assert(!after.includes('?'), 'Item cannot come after unassociated items'); - - if (!Array.isArray(nodes)) { - nodes = [nodes]; - } - - for (const node of nodes) { - const item = { - seq: this._items.length, - sort, - before, - after, - group, - node - }; - - this._items.push(item); - } - - // Insert event - - const valid = this._sort(); - Assert(valid, 'item', group !== '?' ? `added into group ${group}` : '', 'created a dependencies error'); - - return this.nodes; - } - - merge(others) { - - if (!Array.isArray(others)) { - others = [others]; - } - - for (const other of others) { - if (other) { - for (const item of other._items) { - this._items.push(Object.assign({}, item)); // Shallow cloned - } - } - } - - // Sort items - - this._items.sort(internals.mergeSort); - for (let i = 0; i < this._items.length; ++i) { - this._items[i].seq = i; - } - - const valid = this._sort(); - Assert(valid, 'merge created a dependencies error'); - - return this.nodes; - } - - _sort() { - - // Construct graph - - const graph = {}; - const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives - const groups = Object.create(null); - - for (const item of this._items) { - const seq = item.seq; // Unique across all items - const group = item.group; - - // Determine Groups - - groups[group] = groups[group] || []; - groups[group].push(seq); - - // Build intermediary graph using 'before' - - graph[seq] = item.before; - - // Build second intermediary graph with 'after' - - for (const after of item.after) { - graphAfters[after] = graphAfters[after] || []; - graphAfters[after].push(seq); - } - } - - // Expand intermediary graph - - for (const node in graph) { - const expandedGroups = []; - - for (const graphNodeItem in graph[node]) { - const group = graph[node][graphNodeItem]; - groups[group] = groups[group] || []; - expandedGroups.push(...groups[group]); - } - - graph[node] = expandedGroups; - } - - // Merge intermediary graph using graphAfters into final graph - - for (const group in graphAfters) { - if (groups[group]) { - for (const node of groups[group]) { - graph[node].push(...graphAfters[group]); - } - } - } - - // Compile ancestors - - const ancestors = {}; - for (const node in graph) { - const children = graph[node]; - for (const child of children) { - ancestors[child] = ancestors[child] || []; - ancestors[child].push(node); - } - } - - // Topo sort - - const visited = {}; - const sorted = []; - - for (let i = 0; i < this._items.length; ++i) { // Looping through item.seq values out of order - let next = i; - - if (ancestors[i]) { - next = null; - for (let j = 0; j < this._items.length; ++j) { // As above, these are item.seq values - if (visited[j] === true) { - continue; - } - - if (!ancestors[j]) { - ancestors[j] = []; - } - - const shouldSeeCount = ancestors[j].length; - let seenCount = 0; - for (let k = 0; k < shouldSeeCount; ++k) { - if (visited[ancestors[j][k]]) { - ++seenCount; - } - } - - if (seenCount === shouldSeeCount) { - next = j; - break; - } - } - } - - if (next !== null) { - visited[next] = true; - sorted.push(next); - } - } - - if (sorted.length !== this._items.length) { - return false; - } - - const seqIndex = {}; - for (const item of this._items) { - seqIndex[item.seq] = item; - } - - this._items = []; - this.nodes = []; - - for (const value of sorted) { - const sortedItem = seqIndex[value]; - this.nodes.push(sortedItem.node); - this._items.push(sortedItem); - } - - return true; - } -}; - - -internals.mergeSort = (a, b) => { - - return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1); -}; - - -/***/ }), - -/***/ 47541: -/***/ ((__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 universalUserAgent = __nccwpck_require__(45030); -var request = __nccwpck_require__(36234); -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; -} - -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 _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; -} - -// https://github.com/isaacs/node-lru-cache#readme -function getCache() { - return new LRU({ - // cache max. 15000 tokens, that will use less than 10mb memory - max: 15000, - // Cache for 1 minute less than GitHub expiry - maxAge: 1000 * 60 * 59 - }); -} -async function get(cache, options) { - const cacheKey = optionsToCacheKey(options); - const result = await cache.get(cacheKey); - - if (!result) { - return; - } - - const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|"); - const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => { - if (/!$/.test(string)) { - permissions[string.slice(0, -1)] = "write"; - } else { - permissions[string] = "read"; - } - - return permissions; - }, {}); - return { - token, - createdAt, - expiresAt, - permissions, - repositoryIds: options.repositoryIds, - singleFileName, - repositorySelection: repositorySelection - }; -} -async function set(cache, options, data) { - const key = optionsToCacheKey(options); - const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(","); - const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|"); - await cache.set(key, value); -} - -function optionsToCacheKey({ - installationId, - permissions = {}, - repositoryIds = [] -}) { - 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("|"); -} - -function toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - singleFileName -}) { - return Object.assign({ - type: "token", - tokenType: "installation", - token, - installationId, - permissions, - createdAt, - expiresAt, - repositorySelection - }, repositoryIds ? { - repositoryIds - } : null, singleFileName ? { - singleFileName - } : null); -} - -async function getInstallationAuthentication(state, options, customRequest) { - const installationId = Number(options.installationId || state.installationId); - - if (!installationId) { - throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); - } - - if (options.factory) { - const { - type, - factory - } = options, - factoryAuthOptions = _objectWithoutProperties(options, ["type", "factory"]); // @ts-ignore if `options.factory` is set, the return type for `auth()` should be `Promise>` - - - return factory(Object.assign({}, state, factoryAuthOptions)); - } - - const optionsWithInstallationTokenFromState = Object.assign({ - installationId - }, options); - - if (!options.refresh) { - const result = await get(state.cache, optionsWithInstallationTokenFromState); - - if (result) { - const { - token, - createdAt, - expiresAt, - permissions, - repositoryIds, - singleFileName, - repositorySelection - } = result; - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - permissions, - repositorySelection, - repositoryIds, - singleFileName - }); - } - } - - const appAuthentication = await getAppAuthentication(state); - const request = customRequest || state.request; - const { - data: { - token, - expires_at: expiresAt, - repositories, - permissions, - // @ts-ignore - repository_selection: repositorySelection, - // @ts-ignore - single_file: singleFileName - } - } = await request("POST /app/installations/{installation_id}/access_tokens", { - installation_id: installationId, - repository_ids: options.repositoryIds, - permissions: options.permissions, - mediaType: { - previews: ["machine-man"] - }, - headers: { - authorization: `bearer ${appAuthentication.token}` - } - }); - const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; - const createdAt = new Date().toISOString(); - await set(state.cache, optionsWithInstallationTokenFromState, { - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - singleFileName - }); - return toTokenAuthentication({ - installationId, - token, - createdAt, - expiresAt, - repositorySelection, - permissions, - repositoryIds, - 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. - - 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); - - 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) - }); - } - - const { - data: { - access_token: token, - scope - } - } = response; - return { - type: "token", - tokenType: "oauth", - token, - scopes: scope.split(/,\s*/).filter(Boolean) - }; -} - -async function auth(state, options) { - if (options.type === "app") { - return getAppAuthentication(state); - } - - if (options.type === "installation") { - return getInstallationAuthentication(state, options); - } - - 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) -// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js - -function routeMatcher(paths) { - // EXAMPLE. For the following paths: - - /* [ - "/orgs/{org}/invitations", - "/repos/{owner}/{repo}/collaborators/{username}" - ] */ - const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - - /* [ - '/orgs/(?:.+?)/invitations', - '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' - ] */ - - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: - - /* - ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ - It may look scary, but paste it into https://www.debuggex.com/ - and it will make a lot more sense! - */ - - return new RegExp(regex, "i"); -} - -const REGEX = routeMatcher(PATHS); -function requiresAppAuth(url) { - return !!url && REGEX.test(url); -} - -const FIVE_SECONDS_IN_MS = 5 * 1000; - -function isNotTimeSkewError(error) { - return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/)); -} - -async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); - - if (requiresAppAuth(endpoint.url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { - const { - token - } = await getAppAuthentication(state); - endpoint.headers.authorization = `bearer ${token}`; - let response; - - try { - response = await request(endpoint); - } catch (error) { - // If there's an issue with the expiration, regenerate the token and try again. - // Otherwise rethrow the error for upstream handling. - if (isNotTimeSkewError(error)) { - throw error; - } // If the date header is missing, we can't correct the system time skew. - // Throw the error to be handled upstream. - - - if (typeof error.headers.date === "undefined") { - throw error; - } - - const diff = Math.floor((Date.parse(error.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 { - token - } = await getAppAuthentication(_objectSpread2(_objectSpread2({}, state), {}, { - timeDifference: diff - })); - endpoint.headers.authorization = `bearer ${token}`; - return request(endpoint); - } - - return response; - } - - const { - token, - createdAt - } = await getInstallationAuthentication(state, {}, request); - endpoint.headers.authorization = `token ${token}`; - return sendRequestWithRetries(state, request, endpoint, createdAt); -} -/** - * Newly created tokens might not be accessible immediately after creation. - * In case of a 401 response, we retry with an exponential delay until more - * than five seconds pass since the creation of the token. - * - * @see https://github.com/octokit/auth-app.js/issues/65 - */ - -async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { - const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); - - try { - return await request(options); - } catch (error) { - if (error.status !== 401) { - throw error; - } - - if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) { - if (retries > 0) { - error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; - } - - throw error; - } - - ++retries; - const awaitTime = retries * 1000; - state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`); - await new Promise(resolve => setTimeout(resolve, awaitTime)); - return sendRequestWithRetries(state, request, options, createdAt, retries); - } -} - -const VERSION = "2.10.5"; - -const createAppAuth = function createAppAuth(options) { - const log = Object.assign({ - warn: console.warn.bind(console) - }, options.log); - - if ("id" in options) { - log.warn(new deprecation.Deprecation('[@octokit/auth-app] "createAppAuth({ id })" is deprecated, use "createAppAuth({ appId })" instead')); - } - - const state = Object.assign({ - request: request.request.defaults({ - headers: { - "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }), - cache: getCache() - }, options, { - appId: Number("appId" in options ? options.appId : options.id) - }, options.installationId ? { - installationId: Number(options.installationId) - } : {}, { - log - }); - 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"); - } - - 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 - - -/***/ }), - -/***/ 79567: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -async function auth(reason) { - return { - type: "unauthenticated", - reason - }; -} - -function isRateLimitError(error) { - if (error.status !== 403) { - return false; - } - /* istanbul ignore if */ - - - if (!error.headers) { - return false; - } - - return error.headers["x-ratelimit-remaining"] === "0"; -} - -const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; -function isAbuseLimitError(error) { - if (error.status !== 403) { - return false; - } - - return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); -} - -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; - } - - if (error.status >= 400 && error.status < 500) { - error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); - } - - throw error; - }); -} - -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 - - -/***/ }), - -/***/ 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); - -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; -} - -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: "" - } - }; // 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; - } - - 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 ¯\_(ツ)_/¯ - - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, ["authStrategy"]); - - 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; - } - -} -Octokit.VERSION = VERSION; -Octokit.plugins = []; - -exports.Octokit = Octokit; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 59440: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var isPlainObject = __nccwpck_require__(70558); -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)); - } - - 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(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } 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.10"; - -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 - - -/***/ }), - -/***/ 70558: -/***/ ((__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; - - -/***/ }), - -/***/ 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.5.8"; - -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 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; - } - - 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 - - -/***/ }), - -/***/ 25823: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var requestError = __nccwpck_require__(10537); - -const VERSION = "1.2.8"; - -function isIssueLabelsUpdateOrReplace({ - method, - url -}) { - if (!["POST", "PUT"].includes(method)) { - return false; - } - - if (!/\/repos\/[^/]+\/[^/]+\/issues\/[^/]+\/labels/.test(url)) { - return false; - } - - return true; -} - -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 */ - - if (options.request.validate) { - delete options.request.validate.labels; - } - - return 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.headers || !error.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.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; - - 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 - }; - 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 - }; - } - - }) - }; -} - -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 -}); - -/** - * @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.paginateRest = paginateRest; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 83044: -/***/ ((__unused_webpack_module, exports) => { - -"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"] - } - }], - 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"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"], - removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits"] - }, - issues: { - addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", { - mediaType: { - previews: ["mockingbird"] - } - }], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], - removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: ["POST /markdown/raw", { - headers: { - "content-type": "text/plain; charset=utf-8" - } - }] - }, - meta: { - get: ["GET /meta"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], - deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], - getImportStatus: ["GET /repos/{owner}/{repo}/import"], - getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - listForAuthenticatedUser: ["GET /user/migrations", { - mediaType: { - previews: ["wyandotte"] - } - }], - listForOrg: ["GET /orgs/{org}/migrations", { - mediaType: { - previews: ["wyandotte"] - } - }], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] - } - }], - listReposForUser: ["GET /user/migrations/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] - } - }], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], - unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] - } - }], - unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] - } - }], - updateImport: ["PATCH /repos/{owner}/{repo}/import"] - }, - orgs: { - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], - createInvitation: ["POST /orgs/{org}/invitations"], - createWebhook: ["POST /orgs/{org}/hooks"], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - get: ["GET /orgs/{org}"], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], - removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - createCard: ["POST /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - createColumn: ["POST /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - createForAuthenticatedUser: ["POST /user/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForOrg: ["POST /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForRepo: ["POST /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - delete: ["DELETE /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteCard: ["DELETE /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteColumn: ["DELETE /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - get: ["GET /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getCard: ["GET /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getColumn: ["GET /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", { - mediaType: { - previews: ["inertia"] - } - }], - listCards: ["GET /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - listCollaborators: ["GET /projects/{project_id}/collaborators", { - mediaType: { - previews: ["inertia"] - } - }], - listColumns: ["GET /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - listForOrg: ["GET /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForRepo: ["GET /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForUser: ["GET /users/{username}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - moveCard: ["POST /projects/columns/cards/{card_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - moveColumn: ["POST /projects/columns/{column_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - update: ["PATCH /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateCard: ["PATCH /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateColumn: ["PATCH /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch", { - mediaType: { - previews: ["lydian"] - } - }], - updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] - }, - rateLimit: { - get: ["GET /rate_limit"] - }, - reactions: { - createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteLegacy: ["DELETE /reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }, { - deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://docs.github.com/v3/reactions/#delete-a-reaction-legacy" - }], - listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }] - }, - repos: { - acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}"], - addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", { - mediaType: { - previews: ["baptiste"] - } - }], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}"], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - 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", { - mediaType: { - previews: ["zzzax"] - } - }], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], - deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, { - renamed: ["repos", "downloadZipballArchive"] - }], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], - getAllTopics: ["GET /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - 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}"], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - 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"], - 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}"], - getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", { - mediaType: { - previews: ["groot"] - } - }], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", { - mediaType: { - previews: ["groot"] - } - }], - listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], - removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], - updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], - updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "updateStatusCheckProtection"] - }], - updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"], - uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { - baseUrl: "https://uploads.github.com" - }] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits", { - mediaType: { - previews: ["cloak"] - } - }], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics", { - mediaType: { - previews: ["mercy"] - } - }], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"] - }, - teams: { - addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], - addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], - removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: ["POST /user/emails"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: ["POST /user/keys"], - deleteEmailForAuthenticated: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"], - list: ["GET /users"], - listBlockedByAuthenticated: ["GET /user/blocks"], - listEmailsForAuthenticated: ["GET /user/emails"], - listFollowedByAuthenticated: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: ["GET /user/keys"], - setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; - -const VERSION = "4.4.1"; - -function endpointsToMethods(octokit, endpointsMap) { - const newMethods = {}; - - for (const [scope, endpoints] of Object.entries(endpointsMap)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign({ - method, - url - }, defaults); - - if (!newMethods[scope]) { - newMethods[scope] = {}; - } - - const scopeMethods = newMethods[scope]; - - if (decorations) { - scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); - continue; - } - - scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); - } - } - - return newMethods; -} - -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - /* istanbul ignore next */ - - function withDecorations(...args) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` - - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: undefined - }); - return requestWithDefaults(options); - } - - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); - } - - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - - if (decorations.renamedParameters) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - const options = requestWithDefaults.endpoint.merge(...args); - - for (const [name, alias] of Object.entries(decorations.renamedParameters)) { - if (name in options) { - octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); - - if (!(alias in options)) { - options[alias] = options[name]; - } - - delete options[name]; - } - } - - return requestWithDefaults(options); - } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - - - return requestWithDefaults(...args); - } - - 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); -} -restEndpointMethods.VERSION = VERSION; - -exports.restEndpointMethods = restEndpointMethods; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 86298: -/***/ ((__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 Bottleneck = _interopDefault(__nccwpck_require__(11174)); - -// @ts-ignore -async function errorRequest(octokit, state, error, options) { - if (!error.request || !error.request.request) { - // address https://github.com/octokit/plugin-retry.js/issues/8 - throw error; - } // retry all >= 400 && not doNotRetry - - - if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { - const retries = options.request.retries != null ? options.request.retries : state.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error, retries, retryAfter); - } // Maybe eventually there will be more cases here - - - throw error; -} - -// @ts-ignore - -async function wrapRequest(state, request, options) { - const limiter = new Bottleneck(); // @ts-ignore - - limiter.on("failed", function (error, info) { - const maxRetries = ~~error.request.request.retries; - const after = ~~error.request.request.retryAfter; - options.request.retryCount = info.retryCount + 1; - - if (maxRetries > info.retryCount) { - // Returning a number instructs the limiter to retry - // the request after that number of milliseconds have passed - return after * state.retryAfterBaseValue; - } - }); - return limiter.schedule(request, options); -} - -const VERSION = "3.0.6"; -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; - } - - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); -} -retry.VERSION = VERSION; - -exports.VERSION = VERSION; -exports.retry = retry; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 9968: -/***/ ((__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 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; - }); - 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 VERSION = "3.3.4"; - -const noop = () => Promise.resolve(); // @ts-ignore - - -function wrapRequest(state, request, options) { - return state.retryLimiter.schedule(doRequest, state, request, options); -} // @ts-ignore - -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 retryCount = ~~options.request.retryCount; - const jobOptions = retryCount > 0 ? { - priority: 0, - weight: 0 - } : {}; - - if (state.clustering) { - // Remove a job from Redis if it has not completed or failed within 60s - // Examples: Node process terminated, client disconnected, etc. - // @ts-ignore - jobOptions.expiration = 1000 * 60; - } // Guarantee at least 1000ms between writes - // GraphQL can also trigger writes - - - if (isWrite || isGraphQL) { - await state.write.key(state.id).schedule(jobOptions, noop); - } // Guarantee at least 3000ms between requests that trigger notifications - - - if (isWrite && state.triggersNotification(options.url)) { - await state.notifications.key(state.id).schedule(jobOptions, noop); - } // Guarantee at least 2000ms between search requests - - - if (isSearch) { - await state.search.key(state.id).schedule(jobOptions, noop); - } - - const req = state.global.key(state.id).schedule(jobOptions, request, options); - - if (isGraphQL) { - const res = await req; - - 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, - data: res.data - }); - throw error; - } - } - - 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"]; - -// @ts-ignore -function routeMatcher(paths) { - // EXAMPLE. For the following paths: - - /* [ - "/orgs/:org/invitations", - "/repos/:owner/:repo/collaborators/:username" - ] */ - // @ts-ignore - const regexes = paths.map(path => path.split("/") // @ts-ignore - .map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - - /* [ - '/orgs/(?:.+?)/invitations', - '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' - ] */ - // @ts-ignore - - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: - - /* - ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ - It may look scary, but paste it into https://www.debuggex.com/ - and it will make a lot more sense! - */ - - return new RegExp(regex, "i"); -} - -const regex = routeMatcher(triggersNotificationPaths); -const triggersNotification = regex.test.bind(regex); -const groups = {}; // @ts-ignore - -const createGroups = function (Bottleneck, common) { - // @ts-ignore - groups.global = new Bottleneck.Group(_objectSpread2({ - id: "octokit-global", - maxConcurrent: 10 - }, common)); // @ts-ignore - - groups.search = new Bottleneck.Group(_objectSpread2({ - id: "octokit-search", - maxConcurrent: 1, - minTime: 2000 - }, common)); // @ts-ignore - - groups.write = new Bottleneck.Group(_objectSpread2({ - id: "octokit-write", - maxConcurrent: 1, - minTime: 1000 - }, common)); // @ts-ignore - - groups.notifications = new Bottleneck.Group(_objectSpread2({ - id: "octokit-notifications", - maxConcurrent: 1, - minTime: 3000 - }, common)); -}; - -function throttling(octokit, octokitOptions = {}) { - const { - enabled = true, - Bottleneck = BottleneckLight, - id = "no-id", - timeout = 1000 * 60 * 2, - // Redis TTL: 2 minutes - connection - } = octokitOptions.throttle || {}; - - if (!enabled) { - return; - } - - const common = { - connection, - timeout - }; // @ts-ignore - - if (groups.global == null) { - createGroups(Bottleneck, common); - } - - const state = Object.assign(_objectSpread2({ - clustering: connection != null, - triggersNotification, - minimumAbuseRetryAfter: 5, - retryAfterBaseValue: 1000, - retryLimiter: new Bottleneck(), - id - }, groups), // @ts-ignore - octokitOptions.throttle); - - if (typeof state.onAbuseLimit !== "function" || typeof state.onRateLimit !== "function") { - throw new Error(`octokit/plugin-throttling error: - You must pass the onAbuseLimit and onRateLimit error handlers. - See https://github.com/octokit/rest.js#throttling - - const octokit = new Octokit({ - throttle: { - onAbuseLimit: (retryAfter, options) => {/* ... */}, - onRateLimit: (retryAfter, options) => {/* ... */} - } - }) - `); - } - - const events = {}; - const emitter = new Bottleneck.Events(events); // @ts-ignore - - events.on("abuse-limit", state.onAbuseLimit); // @ts-ignore - - events.on("rate-limit", state.onRateLimit); // @ts-ignore - - events.on("error", e => console.warn("Error in throttling-plugin limit handler", e)); // @ts-ignore - - 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; - - if (!(shouldRetryGraphQL || error.status === 403)) { - return; - } - - const retryCount = ~~options.request.retryCount; - options.request.retryCount = retryCount; - const { - wantRetry, - retryAfter - } = await async function () { - if (/\babuse\b/i.test(error.message)) { - // The user has hit the abuse rate limit. (REST and GraphQL) - // 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 wantRetry = await emitter.trigger("abuse-limit", retryAfter, options, octokit); - return { - wantRetry, - retryAfter - }; - } - - if (error.headers != null && error.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 retryAfter = Math.max(Math.ceil((rateLimitReset - Date.now()) / 1000), 0); - const wantRetry = await emitter.trigger("rate-limit", retryAfter, options, octokit); - return { - wantRetry, - retryAfter - }; - } - - return {}; - }(); - - if (wantRetry) { - options.request.retryCount++; // @ts-ignore - - return retryAfter * state.retryAfterBaseValue; - } - }); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); -} -throttling.VERSION = VERSION; -throttling.triggersNotification = triggersNotification; - -exports.throttling = throttling; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 10537: -/***/ ((__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 deprecation = __nccwpck_require__(58932); -var once = _interopDefault(__nccwpck_require__(1223)); - -const logOnce = once(deprecation => console.warn(deprecation)); -/** - * Error with extra properties to help with debugging - */ - -class RequestError extends Error { - constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = "HttpError"; - this.status = statusCode; - Object.defineProperty(this, "code", { - get() { - logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - } - - }); - this.headers = options.headers || {}; // redact request credentials without mutating original request options - - const requestCopy = Object.assign({}, options.request); - - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") - }); - } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; - } - -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 36234: -/***/ ((__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 endpoint = __nccwpck_require__(59440); -var universalUserAgent = __nccwpck_require__(45030); -var isPlainObject = __nccwpck_require__(49062); -var nodeFetch = _interopDefault(__nccwpck_require__(80467)); -var requestError = __nccwpck_require__(10537); - -const VERSION = "5.4.12"; - -function getBufferResponse(response) { - return response.arrayBuffer(); -} - -function fetchWrapper(requestOptions) { - if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - - let headers = {}; - let status; - let url; - const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; - return fetch(requestOptions.url, Object.assign({ - method: requestOptions.method, - body: requestOptions.body, - headers: requestOptions.headers, - redirect: requestOptions.redirect - }, requestOptions.request)).then(response => { - url = response.url; - status = response.status; - - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - - if (status === 204 || status === 205) { - return; - } // GitHub API returns 200 for HEAD requests - - - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - - throw new requestError.RequestError(response.statusText, status, { - headers, - request: requestOptions - }); - } - - if (status === 304) { - throw new requestError.RequestError("Not modified", status, { - headers, - request: requestOptions - }); - } - - if (status >= 400) { - return response.text().then(message => { - const error = new requestError.RequestError(message, 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; - }); - } - - 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); - }).then(data => { - return { - status, - url, - headers, - data - }; - }).catch(error => { - if (error instanceof requestError.RequestError) { - throw error; - } - - throw new requestError.RequestError(error.message, 500, { - headers, - request: requestOptions - }); - }); -} - -function withDefaults(oldEndpoint, newDefaults) { - const endpoint = oldEndpoint.defaults(newDefaults); - - const newApi = function (route, parameters) { - const endpointOptions = endpoint.merge(route, parameters); - - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint.parse(endpointOptions)); - } - - const request = (route, parameters) => { - return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); - }; - - Object.assign(request, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); - return endpointOptions.request.hook(request, endpointOptions); - }; - - return Object.assign(newApi, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); -} - -const request = withDefaults(endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } -}); - -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: -/***/ ((__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 AggregateError = _interopDefault(__nccwpck_require__(61231)); -var crypto = __nccwpck_require__(76417); -var buffer = __nccwpck_require__(64293); -var debug = __nccwpck_require__(38237); - -// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY -// make edits in scripts/update-known-events.js -const webhookNames = ["*", "check_run", "check_run.completed", "check_run.created", "check_run.requested_action", "check_run.rerequested", "check_suite", "check_suite.completed", "check_suite.requested", "check_suite.rerequested", "code_scanning_alert", "code_scanning_alert.appeared_in_branch", "code_scanning_alert.closed_by_user", "code_scanning_alert.created", "code_scanning_alert.fixed", "code_scanning_alert.reopened", "code_scanning_alert.reopened_by_user", "commit_comment", "commit_comment.created", "content_reference", "content_reference.created", "create", "delete", "deploy_key", "deploy_key.created", "deploy_key.deleted", "deployment", "deployment.created", "deployment_status", "deployment_status.created", "error", "fork", "github_app_authorization", "github_app_authorization.revoked", "gollum", "installation", "installation.created", "installation.deleted", "installation.new_permissions_accepted", "installation.suspend", "installation.unsuspend", "installation_repositories", "installation_repositories.added", "installation_repositories.removed", "issue_comment", "issue_comment.created", "issue_comment.deleted", "issue_comment.edited", "issues", "issues.assigned", "issues.closed", "issues.deleted", "issues.demilestoned", "issues.edited", "issues.labeled", "issues.locked", "issues.milestoned", "issues.opened", "issues.pinned", "issues.reopened", "issues.transferred", "issues.unassigned", "issues.unlabeled", "issues.unlocked", "issues.unpinned", "label", "label.created", "label.deleted", "label.edited", "marketplace_purchase", "marketplace_purchase.cancelled", "marketplace_purchase.changed", "marketplace_purchase.pending_change", "marketplace_purchase.pending_change_cancelled", "marketplace_purchase.purchased", "member", "member.added", "member.edited", "member.removed", "membership", "membership.added", "membership.removed", "meta", "meta.deleted", "milestone", "milestone.closed", "milestone.created", "milestone.deleted", "milestone.edited", "milestone.opened", "org_block", "org_block.blocked", "org_block.unblocked", "organization", "organization.deleted", "organization.member_added", "organization.member_invited", "organization.member_removed", "organization.renamed", "package", "package.published", "package.updated", "page_build", "ping", "project", "project.closed", "project.created", "project.deleted", "project.edited", "project.reopened", "project_card", "project_card.converted", "project_card.created", "project_card.deleted", "project_card.edited", "project_card.moved", "project_column", "project_column.created", "project_column.deleted", "project_column.edited", "project_column.moved", "public", "pull_request", "pull_request.assigned", "pull_request.closed", "pull_request.edited", "pull_request.labeled", "pull_request.locked", "pull_request.merged", "pull_request.opened", "pull_request.ready_for_review", "pull_request.reopened", "pull_request.review_request_removed", "pull_request.review_requested", "pull_request.synchronize", "pull_request.unassigned", "pull_request.unlabeled", "pull_request.unlocked", "pull_request_review", "pull_request_review.dismissed", "pull_request_review.edited", "pull_request_review.submitted", "pull_request_review_comment", "pull_request_review_comment.created", "pull_request_review_comment.deleted", "pull_request_review_comment.edited", "push", "release", "release.created", "release.deleted", "release.edited", "release.prereleased", "release.published", "release.released", "release.unpublished", "repository", "repository.archived", "repository.created", "repository.deleted", "repository.edited", "repository.privatized", "repository.publicized", "repository.renamed", "repository.transferred", "repository.unarchived", "repository_dispatch", "repository_dispatch.on-demand-test", "repository_import", "repository_vulnerability_alert", "repository_vulnerability_alert.create", "repository_vulnerability_alert.dismiss", "repository_vulnerability_alert.resolve", "secret_scanning_alert", "secret_scanning_alert.created", "secret_scanning_alert.reopened", "secret_scanning_alert.resolved", "security_advisory", "security_advisory.performed", "security_advisory.published", "security_advisory.updated", "sponsorship", "sponsorship.cancelled", "sponsorship.created", "sponsorship.edited", "sponsorship.pending_cancellation", "sponsorship.pending_tier_change", "sponsorship.tier_changed", "star", "star.created", "star.deleted", "status", "team", "team.added_to_repository", "team.created", "team.deleted", "team.edited", "team.removed_from_repository", "team_add", "watch", "watch.started", "workflow_dispatch", "workflow_run", "workflow_run.action", "workflow_run.completed", "workflow_run.requested"]; - -function handleEventHandlers(state, webhookName, handler) { - if (!state.hooks[webhookName]) { - state.hooks[webhookName] = []; - } - - state.hooks[webhookName].push(handler); -} - -function receiverOn(state, webhookNameOrNames, handler) { - if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler)); - return; - } - - if (webhookNames.indexOf(webhookNameOrNames) === -1) { - console.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`); - } - - if (webhookNameOrNames === "*" || webhookNameOrNames === "error") { - const webhookName = webhookNameOrNames === "*" ? "any" : webhookNameOrNames; - console.warn(`Using the "${webhookNameOrNames}" event with the regular Webhooks.on() function is deprecated. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`); - } - - handleEventHandlers(state, webhookNameOrNames, handler); -} -function receiverOnAny(state, handler) { - handleEventHandlers(state, "*", handler); -} -function receiverOnError(state, handler) { - handleEventHandlers(state, "error", handler); -} - -// Errors thrown or rejected Promises in "error" event handlers are not handled -// as they are in the webhook event handlers. If errors occur, we log a -// "Fatal: Error occured" message to stdout -function wrapErrorHandler(handler, error) { - let returnValue; - - try { - returnValue = handler(error); - } catch (error) { - console.log('FATAL: Error occured in "error" event handler'); - console.log(error); - } - - if (returnValue && returnValue.catch) { - returnValue.catch(error => { - console.log('FATAL: Error occured in "error" event handler'); - console.log(error); - }); - } -} - -// @ts-ignore to address #245 - -function getHooks(state, eventPayloadAction, eventName) { - const hooks = [state.hooks[`${eventName}.${eventPayloadAction}`]]; - hooks.push(state.hooks[eventName]); - hooks.push(state.hooks["*"]); - return [].concat(...hooks.filter(Boolean)); -} // main handler function - - -function receiverHandle(state, event) { - const errorHandlers = state.hooks.error || []; - - if (event instanceof Error) { - const error = Object.assign(new AggregateError([event]), { - event, - errors: [event] - }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); - return Promise.reject(error); - } - - if (!event || !event.name) { - throw new AggregateError(["Event name not passed"]); - } - - if (!event.payload) { - throw new AggregateError(["Event payload not passed"]); - } // flatten arrays of event listeners and remove undefined values - - - const hooks = getHooks(state, event.payload.action, event.name); - - if (hooks.length === 0) { - return Promise.resolve(); - } - - const errors = []; - const promises = hooks.map(handler => { - let promise = Promise.resolve(event); - - if (state.transform) { - promise = promise.then(state.transform); - } - - return promise.then(event => { - return handler(event); - }).catch(error => errors.push(Object.assign(error, { - event - }))); - }); - return Promise.all(promises).then(() => { - if (errors.length === 0) { - return; - } - - const error = new AggregateError(errors); - Object.assign(error, { - event, - errors - }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); - throw error; - }); -} - -function removeListener(state, webhookNameOrNames, handler) { - if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => removeListener(state, webhookName, handler)); - return; - } - - if (!state.hooks[webhookNameOrNames]) { - return; - } // remove last hook that has been added, that way - // it behaves the same as removeListener - - - for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) { - if (state.hooks[webhookNameOrNames][i] === handler) { - state.hooks[webhookNameOrNames].splice(i, 1); - return; - } - } -} - -function createEventHandler(options) { - const state = { - hooks: {} - }; - - if (options && options.transform) { - state.transform = options.transform; - } - - return { - on: receiverOn.bind(null, state), - onAny: receiverOnAny.bind(null, state), - onError: receiverOnError.bind(null, state), - removeListener: removeListener.bind(null, state), - receive: receiverHandle.bind(null, state) - }; -} - -function isntWebhook(request, options) { - // GitHub sends all events as POST requests - if (request.method !== "POST") { - return true; - } // We must match the configured path to allow custom POST routes which include - // the webhook route. For example if the webhook route is / then it would be - // impossible to define a `POST /my/custom/app` route as the `POST /`. - - - if (typeof request.url !== "string" || request.url.split("?")[0] !== options.path) { - return true; - } - - return false; -} - -const WEBHOOK_HEADERS = ["x-github-event", "x-hub-signature", "x-github-delivery"]; // https://developer.github.com/webhooks/#delivery-headers - -function getMissingHeaders(request) { - return WEBHOOK_HEADERS.filter(header => !(header in request.headers)); -} - -// @ts-ignore to address #245 -function getPayload(request) { - // If request.body already exists we can stop here - // See https://github.com/octokit/webhooks.js/pull/23 - // @ts-expect-error - if (request.body) return Promise.resolve(request.body); - return new Promise((resolve, reject) => { - let data = ""; - request.setEncoding("utf8"); - request.on("error", error => reject(new AggregateError([error]))); - request.on("data", chunk => data += chunk); - request.on("end", () => { - try { - resolve(JSON.parse(data)); - } catch (error) { - error.message = "Invalid JSON"; - error.status = 400; - reject(new AggregateError([error])); - } - }); - }); -} - -var Algorithm; - -(function (Algorithm) { - Algorithm["SHA1"] = "sha1"; - Algorithm["SHA256"] = "sha256"; -})(Algorithm || (Algorithm = {})); - -function sign(options, payload) { - const { - secret, - algorithm - } = typeof options === "string" ? { - secret: options, - algorithm: Algorithm.SHA1 - } : { - secret: options.secret, - algorithm: options.algorithm || Algorithm.SHA1 - }; - - if (!secret || !payload) { - throw new TypeError("[@octokit/webhooks] secret & payload required"); - } - - if (!Object.values(Algorithm).includes(algorithm)) { - throw new TypeError(`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`); - } - - payload = typeof payload === "string" ? payload : toNormalizedJsonString(payload); - return `${algorithm}=${crypto.createHmac(algorithm, secret).update(payload).digest("hex")}`; -} - -function toNormalizedJsonString(payload) { - return JSON.stringify(payload).replace(/[^\\]\\u[\da-f]{4}/g, s => { - return s.substr(0, 3) + s.substr(3).toUpperCase(); - }); -} - -const getAlgorithm = signature => { - return signature.startsWith("sha256=") ? "sha256" : "sha1"; -}; - -function verify(secret, eventPayload, signature) { - if (!secret || !eventPayload || !signature) { - throw new TypeError("[@octokit/webhooks] secret, eventPayload & signature required"); - } - - const signatureBuffer = buffer.Buffer.from(signature); - const algorithm = getAlgorithm(signature); - const verificationBuffer = buffer.Buffer.from(sign({ - secret, - algorithm - }, eventPayload)); - - if (signatureBuffer.length !== verificationBuffer.length) { - return false; - } - - return crypto.timingSafeEqual(signatureBuffer, verificationBuffer); -} - -function verifyAndReceive(state, event) { - // verify will validate that the secret is not undefined - const matchesSignature = verify(state.secret, event.payload, event.signature); - - if (!matchesSignature) { - const error = new Error("[@octokit/webhooks] signature does not match event payload and secret"); - return state.eventHandler.receive(Object.assign(error, { - event, - status: 400 - })); - } - - return state.eventHandler.receive({ - id: event.id, - name: event.name, - payload: event.payload - }); -} - -const debugWebhooks = debug.debug("webhooks:receiver"); -function middleware(state, request, response, next) { - if (isntWebhook(request, { - path: state.path - })) { - // the next callback is set when used as an express middleware. That allows - // it to define custom routes like /my/custom/page while the webhooks are - // expected to be sent to the / root path. Otherwise the root path would - // match all requests and would make it impossible to define custom rooutes - if (next) { - next(); - return; - } - - debugWebhooks(`ignored: ${request.method} ${request.url}`); - response.statusCode = 404; - response.end("Not found"); - return; - } - - const missingHeaders = getMissingHeaders(request).join(", "); - - if (missingHeaders) { - const error = new Error(`[@octokit/webhooks] Required headers missing: ${missingHeaders}`); - return state.eventHandler.receive(error).catch(() => { - response.statusCode = 400; - response.end(error.message); - }); - } - - const eventName = request.headers["x-github-event"]; - const signatureSHA1 = request.headers["x-hub-signature"]; - const signatureSHA256 = request.headers["x-hub-signature-256"]; - const id = request.headers["x-github-delivery"]; - debugWebhooks(`${eventName} event received (id: ${id})`); // GitHub will abort the request if it does not receive a response within 10s - // See https://github.com/octokit/webhooks.js/issues/185 - - let didTimeout = false; - const timeout = setTimeout(() => { - didTimeout = true; - response.statusCode = 202; - response.end("still processing\n"); - }, 9000).unref(); - return getPayload(request).then(payload => { - return verifyAndReceive(state, { - id: id, - name: eventName, - payload, - signature: signatureSHA256 || signatureSHA1 - }); - }).then(() => { - clearTimeout(timeout); - if (didTimeout) return; - response.end("ok\n"); - }).catch(error => { - clearTimeout(timeout); - if (didTimeout) return; - const statusCode = Array.from(error)[0].status; - response.statusCode = statusCode || 500; - response.end(error.toString()); - }); -} - -function createMiddleware(options) { - if (!options || !options.secret) { - throw new Error("[@octokit/webhooks] options.secret required"); - } - - const state = { - eventHandler: createEventHandler(options), - path: options.path || "/", - secret: options.secret, - hooks: {} - }; - const api = middleware.bind(null, state); - api.on = state.eventHandler.on; - api.removeListener = state.eventHandler.removeListener; - return api; -} - -class Webhooks { - constructor(options) { - if (!options || !options.secret) { - throw new Error("[@octokit/webhooks] options.secret required"); - } - - const state = { - eventHandler: createEventHandler(options), - path: options.path || "/", - secret: options.secret, - hooks: {} - }; - this.sign = sign.bind(null, options.secret); - this.verify = verify.bind(null, options.secret); - this.on = state.eventHandler.on; - this.onAny = state.eventHandler.onAny; - this.onError = state.eventHandler.onError; - this.removeListener = state.eventHandler.removeListener; - this.receive = state.eventHandler.receive; - this.middleware = middleware.bind(null, state); - this.verifyAndReceive = verifyAndReceive.bind(null, state); - } - -} - -const createWebhooksApi = Webhooks.prototype.constructor; - -exports.Webhooks = Webhooks; -exports.createEventHandler = createEventHandler; -exports.createMiddleware = createMiddleware; -exports.createWebhooksApi = createWebhooksApi; -exports.sign = sign; -exports.verify = verify; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 93159: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const ProbotExports = __nccwpck_require__(58930); -const pino = __nccwpck_require__(79608); - -const { transport } = __nccwpck_require__(96645); - -module.exports = { ...ProbotExports, run }; - -async function run(app) { - const log = pino({}, transport); - - const githubToken = - process.env.GITHUB_TOKEN || - process.env.INPUT_GITHUB_TOKEN || - process.env.INPUT_TOKEN; - - if (!githubToken) { - log.error( - "[probot/adapter-github-actions] a token must be passed as `env.GITHUB_TOKEN` or `with.GITHUB_TOKEN` or `with.token`, see https://github.com/probot/adapter-github-actions#usage" - ); - return; - } - - const envVariablesMissing = [ - "GITHUB_RUN_ID", - "GITHUB_EVENT_NAME", - "GITHUB_EVENT_PATH", - ].filter((name) => !process.env[name]); - - if (envVariablesMissing.length) { - log.error( - `[probot/adapter-github-actions] GitHub Action default environment variables missing: ${envVariablesMissing.join( - ", " - )}. See https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables` - ); - return; - } - - const probot = ProbotExports.createProbot({ - overrides: { - githubToken, - log, - }, - }); - - await probot.load(app); - - return probot - .receive({ - id: process.env.GITHUB_RUN_ID, - name: process.env.GITHUB_EVENT_NAME, - payload: require(process.env.GITHUB_EVENT_PATH), - }) - .catch((error) => { - probot.log.error(error); - }); -} - - -/***/ }), - -/***/ 96645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inspect } = __nccwpck_require__(31669); - -const through = __nccwpck_require__(18180); -const core = __nccwpck_require__(42186); -const pino = __nccwpck_require__(79608); - -const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = { - trace: "debug", - debug: "debug", - info: "info", - warn: "warning", - error: "error", - fatal: "error", -}; - -const transport = through.obj(function (chunk, enc, cb) { - const { level, hostname, pid, msg, time, ...meta } = JSON.parse(chunk); - const levelLabel = pino.levels.labels[level] || level; - const logMethodName = LEVEL_TO_ACTIONS_CORE_LOG_METHOD[levelLabel]; - - const output = [ - msg, - Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "", - ] - .join("\n") - .trim(); - - if (logMethodName in core) { - core[logMethodName](output); - } else { - core.error(`"${level}" is not a known log level - ${output}`); - } - - cb(); -}); - -module.exports = { transport }; - - -/***/ }), - -/***/ 97743: -/***/ ((__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 path = __nccwpck_require__(85622); -var fs = __nccwpck_require__(35747); -var isBase64 = _interopDefault(__nccwpck_require__(31310)); - -const VERSION = "0.0.0-development"; - -function getPrivateKey(options = {}) { - const env = options.env || process.env; - const cwd = options.cwd || process.cwd(); - - if (options.filepath) { - return fs.readFileSync(path.resolve(cwd, options.filepath), "utf-8"); - } - - if (env.PRIVATE_KEY) { - let privateKey = env.PRIVATE_KEY; - - if (isBase64(privateKey)) { - // Decode base64-encoded certificate - 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"); - } - - 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.`); - } - - if (env.PRIVATE_KEY_PATH) { - const filepath = path.resolve(cwd, env.PRIVATE_KEY_PATH); - - if (fs.existsSync(filepath)) { - return fs.readFileSync(filepath, "utf-8"); - } else { - throw new Error(`[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.`); - } - } - - const pemFiles = fs.readdirSync(cwd).filter(path => path.endsWith(".pem")); - - if (pemFiles.length > 1) { - const paths = pemFiles.join(", "); - throw new Error(`[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH`); - } else if (pemFiles[0]) { - return getPrivateKey({ - filepath: pemFiles[0], - cwd - }); - } - - return null; -} -getPrivateKey.VERSION = VERSION; - -exports.getPrivateKey = getPrivateKey; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 59326: -/***/ ((__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 yaml = _interopDefault(__nccwpck_require__(21917)); - -const VERSION = "1.0.1"; - -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 SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"]; -/** - * Load configuration from a given repository and path. - * - * @param octokit Octokit instance - * @param options - */ - -async function getConfigFile(octokit, { - owner, - repo, - path, - ref -}) { - const fileExtension = path.split(".").pop().toLowerCase(); - - if (!SUPPORTED_FILE_EXTENSIONS.includes(fileExtension)) { - throw new Error(`[@probot/octokit-plugin-config] .${fileExtension} extension is not support for configuration (path: "${path}")`); - } // https://docs.github.com/en/rest/reference/repos#get-repository-content - - - const requestOptions = await octokit.request.endpoint("GET /repos/{owner}/{repo}/contents/{path}", _objectSpread2({ - owner, - repo, - path, - mediaType: { - format: "raw" - } - }, ref ? { - ref - } : {})); - const emptyConfigResult = { - owner, - repo, - path, - url: requestOptions.url, - config: null - }; - - try { - const { - data, - headers - } = await octokit.request(requestOptions); // 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 - // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-directory - // - // symlinks just return the content of the linked file when requesting the raw formt, - // 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.`); - } - - if (fileExtension === "json") { - if (typeof data === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (invalid JSON)`); - } - - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { - config: data - }); - } - - const config = yaml.safeLoad(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)`); - } - - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { - config - }); - } catch (error) { - if (error.status === 404) { - return emptyConfigResult; - } - - 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 error; - } -} - -const EXTENDS_REGEX = new RegExp("^" + "(?:([a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38})/)?" + // org -"([-_.\\w\\d]+)" + // project -"(?::([-_./\\w\\d]+\\.ya?ml))?" + // filename -"$", "i"); -/** - * Computes parameters to retrieve the configuration file specified in _extends - * - * Base can either be the name of a repository in the same organization or - * a full slug "organization/repo". - * - * @param options - * @return The params needed to retrieve a configuration file - */ - -function extendsToGetContentParams({ - owner, - path, - url, - extendsValue -}) { - if (typeof extendsValue !== "string") { - throw new Error(`[@probot/octokit-plugin-config] Invalid value ${JSON.stringify(extendsValue)} for _extends in ${url}`); - } - - const match = extendsValue.match(EXTENDS_REGEX); - - if (match === null) { - throw new Error(`[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}`); - } - - return { - owner: match[1] || owner, - repo: match[2], - path: match[3] || path - }; -} - -/** - * Load configuration from selected repository file. If the file does not exist - * it loads configuration from the owners `.github` repository. - * - * If the repository file configuration includes an `_extends` key, that file - * is loaded. Same with the target file until no `_extends` key is present. - * - * @param octokit Octokit instance - * @param options - */ - -async function getConfigFiles(octokit, { - owner, - repo, - path, - branch -}) { - const requestedRepoFile = await getConfigFile(octokit, { - owner, - repo, - path, - ref: branch - }); // if no configuration file present in selected repository, - // try to load it from the `.github` repository - - 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 - -/***/ }), - -/***/ 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); -/** - * 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); - * } - * - * // ... - * } - */ -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 - -/***/ }), - -/***/ 79212: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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__) => { - -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; -} -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); - }); - 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 = FunctionToString.id; - } - /** - * @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 - -/***/ }), - -/***/ 54838: -/***/ ((__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); -// "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; - } - /** - * @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 - -/***/ }), - -/***/ 96727: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 - -/***/ }), - -/***/ 1553: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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(), - }; -} -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; -} -exports.eventToSentryRequest = eventToSentryRequest; -//# sourceMappingURL=request.js.map - -/***/ }), - -/***/ 46406: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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(); - } - var hub = hub_1.getCurrentHub(); - 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 - */ - 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 - -/***/ }), - -/***/ 53536: -/***/ ((__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 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); - } - 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; -} -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; -} -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()); - } - // 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.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; -} -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); - } - catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); - } -} -/** - * 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 - */ -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 - -/***/ }), - -/***/ 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 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 - -/***/ }), - -/***/ 4213: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 = {}; - } - /** - * 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 (this._level) { - event.level = this._level; - } - if (this._transactionName) { - event.transaction = this._transactionName; - } - // 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); - } - } - 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; - } - }; - /** - * 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 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); -} -exports.addGlobalEventProcessor = addGlobalEventProcessor; -//# sourceMappingURL=scope.js.map - -/***/ }), - -/***/ 12474: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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); - } - } - /** 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(); - } - }; - /** 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 - -/***/ }), - -/***/ 88455: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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]; - } - 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."); -} -/** - * 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'); - } - catch (exception) { - syntheticException = exception; - } - return callOnHub('captureException', exception, { - captureContext: captureContext, - originalException: exception, - syntheticException: syntheticException, - }); -} -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); - } - catch (exception) { - syntheticException = exception; - } - // 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); -} -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); -} -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]; - } - 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); -} -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); -/** - * 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 - -/***/ }), - -/***/ 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 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; - } - /** - * @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 - -/***/ }), - -/***/ 45400: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 || ''); - } - 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; -} -/** - * 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 (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); - } - if (options.serverName && !event.server_name) { - event.server_name = global.process.env.SENTRY_NAME || os.hostname(); - } - 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); - } - } - // 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 }); - } - } - if (options.transaction && !event.transaction) { - event.transaction = extractTransaction(req, options.transaction); - } - 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); - }; -} -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; - } - 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 - -/***/ }), - -/***/ 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.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 - -/***/ }), - -/***/ 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; - 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); - }; - }; -} -//# sourceMappingURL=console.js.map - -/***/ }), - -/***/ 76280: -/***/ ((__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 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; - } - /** - * @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); - } - }; - /** - * @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 - -/***/ }), - -/***/ 72310: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 - -/***/ }), - -/***/ 70208: -/***/ ((__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 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); - } - 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); - } - 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 - -/***/ }), - -/***/ 90046: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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; -} -/** 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 - -/***/ }), - -/***/ 50443: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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(); - } - /** - * @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 - -/***/ }), - -/***/ 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 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; - } - /** - * @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 }); - }); - /* 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 if (this._options.mode === 'strict') { - utils_1.consoleSandbox(function () { - console.warn(rejectionWarning); - }); - handlers_1.logAndExitProcess(reason); - } - /* eslint-enable no-console */ - }; - /** - * @inheritDoc - */ - OnUnhandledRejection.id = 'OnUnhandledRejection'; - return OnUnhandledRejection; -}()); -exports.OnUnhandledRejection = OnUnhandledRejection; -//# sourceMappingURL=onunhandledrejection.js.map - -/***/ }), - -/***/ 84103: -/***/ ((__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 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; - } - // 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); - } - // 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.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 (url.username || url.password) { - options.auth = url.username + ":" + url.password; - } - return options; -} -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(); - } - // 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 - -/***/ }), - -/***/ 19090: -/***/ ((__unused_webpack_module, 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 ''; - } -} -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; -} -/** - * 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); - } - }); -} -/** - * @hidden - */ -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 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); - } - try { - return addPrePostContext(filesToRead, frames, linesOfContext); - } - 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); - } -} -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); - }); - }); -} -/** - * @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); - }); - }); -} -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], - }, - }); - }); - }); -} -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); - } - // The frame where the crash happened, should be the last entry in the array - return localStack.reverse(); -} -exports.prepareFramesForEvent = prepareFramesForEvent; -//# sourceMappingURL=parsers.js.map - -/***/ }), - -/***/ 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 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; - } - // 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()); - } - core_1.initAndBind(client_1.NodeClient, options); -} -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(); -} -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)]; - }); - }); -} -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)]; - }); - }); -} -exports.close = close; -//# sourceMappingURL=sdk.js.map - -/***/ }), - -/***/ 46276: -/***/ ((__unused_webpack_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 - */ -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 - -/***/ }), - -/***/ 43240: -/***/ ((__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 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 - -/***/ }), - -/***/ 84490: -/***/ ((__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 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 - -/***/ }), - -/***/ 68621: -/***/ ((__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 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; - } - /** - * @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 - -/***/ }), - -/***/ 21437: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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 - -/***/ }), - -/***/ 31271: -/***/ ((__unused_webpack_module, exports) => { - -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__) => { - -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.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; -} -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 - -/***/ }), - -/***/ 71425: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var browsertracing_1 = __nccwpck_require__(33577); -exports.BrowserTracing = browsertracing_1.BrowserTracing; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 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 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 ('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(transaction, entry, event, timeOrigin, eventEnd) { - var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; - var start = entry[event + "Start"]; - if (!start || !end) { - return; - } - _startChild(transaction, { - description: event, - endTimestamp: timeOrigin + utils_2.msToSec(end), - op: 'browser', - startTimestamp: timeOrigin + utils_2.msToSec(start), - }); -} -/** 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), - }); -} -/** - * 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)); -} -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 - -/***/ }), - -/***/ 27854: -/***/ ((__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 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', - }); - } -} -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; - } -} -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. - } - } - } -} -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 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', - }); - } -} -exports.defaultRoutingInstrumentation = defaultRoutingInstrumentation; -//# 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) { - 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__) => { - -/* - * 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 - -/***/ }), - -/***/ 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 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__) => { - -/* - * 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); - } - } - 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 - -/***/ }), - -/***/ 54592: -/***/ ((__unused_webpack_module, exports) => { - -/* - * 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) => { - -/* - * 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__) => { - -/* - * 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); - } - return { - get timeStamp() { - return firstHiddenTime; - }, - }; -}; -//# sourceMappingURL=getFirstHidden.js.map - -/***/ }), - -/***/ 45300: -/***/ ((__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 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) => { - -/* - * 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)) { - 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 - -/***/ }), - -/***/ 9658: -/***/ ((__unused_webpack_module, exports) => { - -/* - * 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 }); - } - }, { capture: true, once: once }); -}; -//# sourceMappingURL=onHidden.js.map - -/***/ }), - -/***/ 45181: -/***/ ((__unused_webpack_module, exports) => { - -/* - * 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, - }); - }); - }); - } - return inputPromise; -}; -//# sourceMappingURL=whenInput.js.map - -/***/ }), - -/***/ 47906: -/***/ ((__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; -/** - * 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 - -/***/ }), - -/***/ 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 {}; -} -/** - * 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 - */ -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) - * - * @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); - } - } - } - // 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); - } - } - 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 (!carrier.__SENTRY__.extensions.traceHeaders) { - carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; - } - } -} -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 - */ - 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; -/** - * 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); }); - } - 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; - }); - // 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'); - } - 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) { - this._initTimeout = setTimeout(function () { - if (!_this._finished) { - _this.finish(); - } - }, this._idleTimeout); - 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 - -/***/ }), - -/***/ 64358: -/***/ ((__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; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 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); -/** - * Express integration - * - * Provides an request and error handler for Express framework as well as tracing capabilities - */ -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'); - } - /** - * @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); - } - } -} -/** - * 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 - -/***/ }), - -/***/ 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 - -/***/ }), - -/***/ 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 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 = {}; } - /** - * @inheritDoc - */ - this.name = Mongo.id; - this._operations = Array.isArray(options.operations) - ? options.operations - : OPERATIONS; - this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; - } - /** - * @inheritDoc - */ - Mongo.prototype.setupOnce = function (_, getCurrentHub) { - var collection; - try { - var mongodbModule = utils_1.dynamicRequire(module, 'mongodb'); - collection = mongodbModule.Collection; - } - catch (e) { - utils_1.logger.error('Mongo Integration was unable to require `mongodb` package.'); - return; - } - this._instrumentOperations(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; - 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); - }])); - }; - }); - }; - /** - * 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 - -/***/ }), - -/***/ 67082: -/***/ ((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; - } - /** - * @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); - }; - }); - }; - /** - * @inheritDoc - */ - Mysql.id = 'Mysql'; - return Mysql; -}()); -exports.Mysql = Mysql; -//# sourceMappingURL=mysql.js.map - -/***/ }), - -/***/ 31931: -/***/ ((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-postgres package */ -var Postgres = /** @class */ (function () { - function Postgres() { - /** - * @inheritDoc - */ - this.name = Postgres.id; - } - /** - * @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; - }); - }; - }); - }; - /** - * @inheritDoc - */ - Postgres.id = 'Postgres'; - return Postgres; -}()); -exports.Postgres = Postgres; -//# sourceMappingURL=postgres.js.map - -/***/ }), - -/***/ 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); -/** - * Keeps track of finished spans for a given transaction - * @internal - * @hideconstructor - * @hidden - */ -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; -/** - * 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 - */ - 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.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 - -/***/ }), - -/***/ 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}. - */ - 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 - -/***/ }), - -/***/ 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 ? transactionContext.name : ''; - _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); - }; - /** - * @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); - }; - 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 - */ - 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) { - /** - * 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 - -/***/ }), - -/***/ 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 })); -/** - * 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) { - promise.then(null, function (e) { - // TODO: Use a better logging mechanism - // eslint-disable-next-line no-console - console.error(e); - }); -} -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); -/** - * 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) { - // 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); - } - catch (_oO) { - return ''; - } -} -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) { - 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]); - } - } - 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 + "\"]"); - } - } - return out.join(''); -} -//# sourceMappingURL=browser.js.map - -/***/ }), - -/***/ 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, user = _a.user; - return (protocol + "://" + user + (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], 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(); - } - 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, user: user }); - }; - /** 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; - }; - /** 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); - } - 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 - -/***/ }), - -/***/ 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); - } - } - } - 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) { - 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]; - } - 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); -} -/** 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; - } - lastCapturedEvent = event; - if (debounceTimer) { - clearTimeout(debounceTimer); - } - if (debounce) { - debounceTimer = setTimeout(function () { - handler({ event: event, name: name }); - }); - } - else { - handler({ event: event, name: name }); - } - }; -} -/** - * 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; - } - catch (e) { - // just accessing event properties can throw an exception in some rare circumstances - // see: https://github.com/getsentry/raven-js/issues/838 - return; - } - 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; - } - // record first keypress in a series, but ignore subsequent - // keypresses until debounce clears - if (!keypressTimeout) { - domEventHandler('input', handler)(event); - } - clearTimeout(keypressTimeout); - keypressTimeout = setTimeout(function () { - keypressTimeout = undefined; - }, debounceDuration); - }; -} -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 - -/***/ }), - -/***/ 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; -/** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; -} -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. - */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } - catch (_e) { - return false; - } -} -exports.isInstanceOf = isInstanceOf; -//# sourceMappingURL=is.js.map - -/***/ }), - -/***/ 15577: -/***/ ((__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; - } - /** 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 */ -/** - * 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 - -/***/ }), - -/***/ 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 = {}; -/** - * Safely get global scope object - * - * @returns Global scope object - */ -function getGlobalObject() { - return (node_1.isNodeEnv() - ? global - : typeof window !== 'undefined' - ? window - : typeof self !== 'undefined' - ? self - : fallbackGlobalObject); -} -exports.getGlobalObject = getGlobalObject; -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -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])); - } - // 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 {}; - } - 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(); - } - // 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; -/** - * 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 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'; -} -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; -/** - * A safe form of location.href - */ -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-]+)*))?$/; -/** - * Parses input into a SemVer interface - * @param input string representation of a semver version - */ -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 -/** - * 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 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; - } - return defaultRetryAfter; -} -exports.parseRetryAfterHeader = parseRetryAfterHeader; -/** - * This function adds context (pre/post/line) lines to the provided frame - * - * @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 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; -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} -exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; -//# sourceMappingURL=misc.js.map - -/***/ }), - -/***/ 16411: -/***/ ((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); -/** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question - */ -function isNodeEnv() { - return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; -} -exports.isNodeEnv = isNodeEnv; -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// 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); -} -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']; -/** - * Normalizes data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not - * provided. - * @returns An object containing normalized request data - */ -function extractNodeRequestData(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 - // koa: req.header - var headers = (req.headers || req.header || {}); - // method: - // node, express, koa: req.method - var method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node: req.headers.host - var host = req.hostname || req.host || headers.host || ''; - // protocol: - // node: - // 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 - var originalUrl = (req.originalUrl || req.url || ''); - // absolute url - var absoluteUrl = protocol + "://" + host + originalUrl; - keys.forEach(function (key) { - switch (key) { - case 'headers': - requestData.headers = headers; - break; - case 'method': - requestData.method = method; - break; - case 'url': - requestData.url = absoluteUrl; - break; - case 'cookies': - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware): req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = req.cookies || dynamicRequire(module, 'cookie').parse(headers.cookie || ''); - break; - case 'query_string': - // query string: - // node: req.url (raw) - // express, koa: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = dynamicRequire(module, 'url').parse(originalUrl || '', false).query; - break; - case 'data': - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // node, express, koa: req.body - if (req.body !== undefined) { - requestData.data = is_1.isString(req.body) ? req.body : JSON.stringify(object_1.normalize(req.body)); - } - break; - default: - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = req[key]; - } - } - }); - 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); -/** - * Wrap a given object method with a higher-order function - * - * @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 - */ -function fill(source, name, replacement) { - if (!(name in source)) { - return; - } - 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 - } - } - 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 (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; - } - } - 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; - } - // 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**'; - } -} -exports.normalize = normalize; -/** - * 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; - } - return string_1.truncate(serialized, maxLength); - } - return ''; -} -exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; -/** - * Given any object, return the new object with removed keys that value was `undefined`. - * Works recursively on objects and arrays. - */ -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 - -/***/ }), - -/***/ 39188: -/***/ ((__unused_webpack_module, exports) => { - -// 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 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; - } - } - 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; -} -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 - -/***/ }), - -/***/ 1243: -/***/ ((__unused_webpack_module, exports) => { - -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 - -/***/ }), - -/***/ 31811: -/***/ ((__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 = []; - } - /** - * 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 to the queue. - * - * @param task Can be any PromiseLike - * @returns The original promise. - */ - PromiseBuffer.prototype.add = function (task) { - 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); - } - 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 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. - */ - PromiseBuffer.prototype.drain = function (timeout) { - 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); - }) - .then(null, function () { - resolve(true); - }); - }); - }; - return PromiseBuffer; -}()); -exports.PromiseBuffer = PromiseBuffer; -//# sourceMappingURL=promisebuffer.js.map - -/***/ }), - -/***/ 5986: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var defaultFunctionName = ''; -/** - * Safely extract function name from itself - */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } - catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } -} -exports.getFunctionName = getFunctionName; -//# sourceMappingURL=stacktrace.js.map - -/***/ }), - -/***/ 66538: -/***/ ((__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}'; - } - 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 ''; - } - 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); -} -exports.safeJoin = safeJoin; -/** - * 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 - */ -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 - -/***/ }), - -/***/ 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); -/** - * Tells whether current environment supports ErrorEvent objects - * {@link supportsErrorEvent}. - * - * @returns Answer to the given question. - */ -function supportsErrorEvent() { - try { - new ErrorEvent(''); - return true; - } - catch (e) { - return false; - } -} -exports.supportsErrorEvent = supportsErrorEvent; -/** - * Tells whether current environment supports DOMError objects - * {@link supportsDOMError}. - * - * @returns Answer to the given question. - */ -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; -/** - * Tells whether current environment supports DOMException objects - * {@link supportsDOMException}. - * - * @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}. - * - * @returns Answer to the given question. - */ -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; -/** - * 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()); -} -/** - * Tells whether current environment supports Fetch API natively - * {@link supportsNativeFetch}. - * - * @returns true if `window.fetch` is natively implemented, false otherwise - */ -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; -/** - * Tells whether current environment supports ReportingObserver API - * {@link supportsReportingObserver}. - * - * @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}. - * - * @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}. - * - * @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 - */ -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 - -/***/ }), - -/***/ 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); -/** - * 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". - */ -var dateTimestampSource = { - nowSeconds: function () { return Date.now() / 1000; }, -}; -/** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. - */ -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, - }; -} -/** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. - */ -function getNodePerformance() { - try { - var perfHooks = node_1.dynamicRequire(module, 'perf_hooks'); - return perfHooks.performance; - } - catch (_) { - return undefined; - } -} -/** - * 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. - */ -exports.dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); -/** - * 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. - */ -exports.timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); -// Re-exported with an old name for backwards-compatibility. -exports.timestampWithMs = exports.timestampInSeconds; -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -exports.usingPerformanceAPI = platformPerformance !== undefined; -/** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. - */ -exports.browserPerformanceTimeOrigin = (function () { - var performance = misc_1.getGlobalObject().performance; - if (!performance) { - return undefined; - } - if (performance.timeOrigin) { - return performance.timeOrigin; - } - // 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 - -/***/ }), - -/***/ 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 - -/** - * Create a new Accepts object for the given req. - * - * @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". - * - * 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 - */ - -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] - } - } - - // 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 -} - -/** - * 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 - */ - -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 -} - -/** - * 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 - */ - -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 -} - -/** - * 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 - */ - -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 -} - -/** - * Convert extnames to mime. - * - * @param {String} type - * @return {String} - * @private - */ - -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type -} - -/** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private - */ - -function validMime (type) { - return typeof type === 'string' -} - - -/***/ }), - -/***/ 2122: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -/** - * Module exports. - */ - -module.exports = __nccwpck_require__(12016) - - -/***/ }), - -/***/ 66918: -/***/ ((__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} - */ - -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()] - - if (mime && mime.charset) { - return mime.charset - } - - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } - - return false -} - -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ - -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 - - if (!mime) { - return false - } - - // 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 -} - -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] - - if (!exts || !exts.length) { - return false - } - - return exts[0] -} - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ - -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) - - if (!extension) { - return false - } - - return exports.types[extension] || false -} - -/** - * Populate the extensions and types maps. - * @private - */ - -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] - - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions - - 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 - } - }) -} - - -/***/ }), - -/***/ 49690: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - -"use strict"; - -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; - } - 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); - } - } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug('Destroying agent %o', this.constructor.name); - } - } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 66570: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -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.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; - - -/***/ }), - -/***/ 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('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; - - -/***/ }), - -/***/ 52068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* module decorator */ module = __nccwpck_require__.nmd(module); - - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -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 - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @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` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - 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)); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - - -/***/ }), - -/***/ 62003: -/***/ ((module) => { - -"use strict"; - - -/** - * Expose `arrayFlatten`. - */ -module.exports = arrayFlatten - -/** - * 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] - - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) - } - } - - return result -} - -/** - * 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] - - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) - } - } - - return result -} - -/** - * 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, []) - } - - return flattenWithDepth(array, [], depth) -} - - -/***/ }), - -/***/ 14812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = -{ - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) -}; - - -/***/ }), - -/***/ 1700: -/***/ ((module) => { - -// API -module.exports = abort; - -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); - - // reset leftover jobs - state.jobs = {}; -} - -/** - * 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](); - } -} - - -/***/ }), - -/***/ 72794: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var defer = __nccwpck_require__(15295); - -// API -module.exports = async; - -/** - * 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; - - // check if async happened - defer(function() { isAsync = true; }); - - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; -} - - -/***/ }), - -/***/ 15295: -/***/ ((module) => { - -module.exports = defer; - -/** - * Runs provided function on next iteration of the event loop - * - * @param {function} fn - function to run - */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); - - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } -} - - -/***/ }), - -/***/ 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 - */ -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); - }); -} - -/** - * 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; -} - - -/***/ }), - -/***/ 42474: -/***/ ((module) => { - -// 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 - } - ; - - 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; -} - - -/***/ }), - -/***/ 37942: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) - ; - -// API -module.exports = terminator; - -/** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination - */ -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; - -/** - * 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 (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; +const Endpoints = { + actions: { + addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"], + 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"], + downloadWorkflowRunAttemptLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/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}"], + getWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"], + 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"], + listJobsForWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/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"], + 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}", {}, { + renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] + }], + addRepoToInstallationForAuthenticatedUser: ["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"] } - }); - - state.index++; - } - - return terminator.bind(state, callback); -} - - -/***/ }), - -/***/ 50445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var serialOrdered = __nccwpck_require__(3578); - -// Public API -module.exports = serial; - -/** - * 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); -} - - -/***/ }), - -/***/ 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; - -/** - * 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); - - 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; - } - - // done here - callback(null, state.results); - }); - - return terminator.bind(state, callback); -} - -/* - * -- Sort methods - */ - -/** - * 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; -} - -/** - * 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); -} - - -/***/ }), - -/***/ 86950: -/***/ ((module) => { - -"use strict"; - - -/* global SharedArrayBuffer, Atomics */ - -if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { - const nil = new Int32Array(new SharedArrayBuffer(4)) - - 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') + }], + createContentAttachmentForRepo: ["POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments", { + mediaType: { + previews: ["corsair"] } - 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 { - - 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') + }], + 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"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + 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"], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"], + removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, { + renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] + }], + removeRepoFromInstallationForAuthenticatedUser: ["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"], + rerequestRun: ["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"], + 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" } - 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 = sleep - -} - - -/***/ }), - -/***/ 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) - -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef - - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} - -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} - -function HookCollection () { - var state = { - registry: {} - } - - var hook = register.bind(null, state) - bindApi(hook, state) - - return hook -} - -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() -} - -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 - - -/***/ }), - -/***/ 5549: -/***/ ((module) => { - -module.exports = addHook - -function addHook (state, kind, name, hook) { - var orig = hook - if (!state.registry[name]) { - state.registry[name] = [] - } - - if (kind === 'before') { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)) - } - } - - if (kind === 'after') { - hook = function (method, options) { - var result - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_ - return orig(result, options) - }) - .then(function () { - return result - }) - } - } - - if (kind === 'error') { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options) - }) - } - } - - state.registry[name].push({ - hook: hook, - orig: orig - }) -} - - -/***/ }), - -/***/ 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) + }], + getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, { + renamed: ["codeScanning", "listAlertInstances"] + }], + 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"], + getConductCode: ["GET /codes_of_conduct/{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"] + }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + 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", {}, { + 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", {}, { + 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", {}, { + renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] + }] + }, + issues: { + addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], + removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: ["POST /markdown/raw", { + headers: { + "content-type": "text/plain; charset=utf-8" } - - return (state.registry[name]).reduce(function (method, registered) { - return registered.hook.bind(null, method, options) - }, method)() - }) -} - - -/***/ }), - -/***/ 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) -} - - -/***/ }), - -/***/ 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 - */ - -Object.defineProperty(exports, "json", ({ - configurable: true, - enumerable: true, - get: createParserGetter('json') -})) - -/** - * Raw parser. - * @public - */ - -Object.defineProperty(exports, "raw", ({ - configurable: true, - enumerable: true, - get: createParserGetter('raw') -})) - -/** - * Text parser. - * @public - */ - -Object.defineProperty(exports, "text", ({ - configurable: true, - enumerable: true, - get: createParserGetter('text') -})) - -/** - * URL-encoded parser. - * @public - */ - -Object.defineProperty(exports, "urlencoded", ({ - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -})) - -/** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public - */ - -function bodyParser (options) { - var opts = {} - - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] + }] + }, + meta: { + get: ["GET /meta"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + cancelImport: ["DELETE /repos/{owner}/{repo}/import"], + deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"], + deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"], + downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"], + getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"], + getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], + getImportStatus: ["GET /repos/{owner}/{repo}/import"], + getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: ["GET /user/migrations/{migration_id}/repositories"], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {}, { + renamed: ["migrations", "listReposForAuthenticatedUser"] + }], + mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], + setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: ["PUT /repos/{owner}/{repo}/import"], + unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"], + unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"], + updateImport: ["PATCH /repos/{owner}/{repo}/import"] + }, + 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}"], + convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], + createInvitation: ["POST /orgs/{org}/invitations"], + createWebhook: ["POST /orgs/{org}/hooks"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + get: ["GET /orgs/{org}"], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"], + 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"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], + removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], + 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}"], + deletePackageForUser: ["DELETE /users/{username}/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}"], + deletePackageVersionForUser: ["DELETE /users/{username}/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}"], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"], + restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"], + restorePackageForUser: ["POST /users/{username}/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"], + restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"], + updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] + }, + rateLimit: { + get: ["GET /rate_limit"] + }, + reactions: { + createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"], + createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], + createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], + createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"], + createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], + createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"], + deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"], + deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"], + deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"], + deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"], + deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"], + deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"], + listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], + listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], + listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], + listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"] + }, + repos: { + acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}", {}, { + renamed: ["repos", "acceptInvitationForAuthenticatedUser"] + }], + acceptInvitationForAuthenticatedUser: ["PATCH /user/repository_invitations/{invitation_id}"], + addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + 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"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate"], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}", {}, { + renamed: ["repos", "declineInvitationForAuthenticatedUser"] + }], + declineInvitationForAuthenticatedUser: ["DELETE /user/repository_invitations/{invitation_id}"], + 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}"], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + 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"], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"], + disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"], + disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"], + downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, { + renamed: ["repos", "downloadZipballArchive"] + }], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"], + enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"], + enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"], + generateReleaseNotes: ["POST /repos/{owner}/{repo}/releases/generate-notes"], + 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: { + previews: ["mercy"] } - } - } - - 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) - }) - } -} - -/** - * Create a getter for loading a parser. - * @private - */ - -function createParserGetter (name) { - return function get () { - return loadParser(name) - } -} - -/** - * Load a parser module. - * @private - */ - -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) -} - - -/***/ }), - -/***/ 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 - -/** - * 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 - */ - -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) + }], + getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + 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"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + 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}"], + getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"], + getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"], + listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], + removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], + removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + 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"] } - - // 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 + }], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], + updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], + updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "updateStatusCheckProtection"] + }], + updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"], + uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { + baseUrl: "https://uploads.github.com" + }] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics", { + mediaType: { + previews: ["mercy"] } - } - - // 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() - }) -} - -/** - * Get the content stream of the request. - * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private - */ - -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' - }) + }], + users: ["GET /search/users"] + }, + secretScanning: { + getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"] + }, + teams: { + addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], + addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], + removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: ["POST /user/emails", {}, { + renamed: ["users", "addEmailForAuthenticatedUser"] + }], + addEmailForAuthenticatedUser: ["POST /user/emails"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: ["POST /user/gpg_keys", {}, { + renamed: ["users", "createGpgKeyForAuthenticatedUser"] + }], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: ["POST /user/keys", {}, { + renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] + }], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + deleteEmailForAuthenticated: ["DELETE /user/emails", {}, { + renamed: ["users", "deleteEmailForAuthenticatedUser"] + }], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] + }], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}", {}, { + renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] + }], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "getGpgKeyForAuthenticatedUser"] + }], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}", {}, { + renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] + }], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + list: ["GET /users"], + listBlockedByAuthenticated: ["GET /user/blocks", {}, { + renamed: ["users", "listBlockedByAuthenticatedUser"] + }], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: ["GET /user/emails", {}, { + renamed: ["users", "listEmailsForAuthenticatedUser"] + }], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: ["GET /user/following", {}, { + renamed: ["users", "listFollowedByAuthenticatedUser"] + }], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: ["GET /user/gpg_keys", {}, { + renamed: ["users", "listGpgKeysForAuthenticatedUser"] + }], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: ["GET /user/public_emails", {}, { + renamed: ["users", "listPublicEmailsForAuthenticatedUser"] + }], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: ["GET /user/keys", {}, { + renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] + }], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility", {}, { + renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] + }], + setPrimaryEmailVisibilityForAuthenticatedUser: ["PATCH /user/email/visibility"], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] } +}; - return stream -} - - -/***/ }), - -/***/ 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 - */ - - - -/** - * Module dependencies. - * @private - */ - -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) - -/** - * Module exports. - */ - -module.exports = json - -/** - * 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 - */ - -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex - -/** - * Create a middleware to parse JSON bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ - -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 +const VERSION = "5.13.0"; - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } +function endpointsToMethods(octokit, endpointsMap) { + const newMethods = {}; - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type + for (const [scope, endpoints] of Object.entries(endpointsMap)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign({ + method, + url + }, defaults); - 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 (!newMethods[scope]) { + newMethods[scope] = {}; + } - if (strict) { - var first = firstchar(body) + const scopeMethods = newMethods[scope]; - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) + if (decorations) { + scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); + continue; } - } - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) + scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); } } - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} + return newMethods; +} - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + /* istanbul ignore next */ - debug('content-type %j', req.headers['content-type']) + function withDecorations(...args) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: undefined + }); + return requestWithDefaults(options); } - // 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 + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); } - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Create strict violation syntax error matching native error. - * - * @param {string} str - * @param {string} char - * @return {Error} - * @private - */ - -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 - }) - } -} + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } -/** - * Get the first non-whitespace character in a string. - * - * @param {string} str - * @return {function} - * @private - */ + if (decorations.renamedParameters) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + const options = requestWithDefaults.endpoint.merge(...args); -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] -} + for (const [name, alias] of Object.entries(decorations.renamedParameters)) { + if (name in options) { + octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ + if (!(alias in options)) { + options[alias] = options[name]; + } -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} + delete options[name]; + } + } -/** - * Normalize a SyntaxError for JSON.parse. - * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} - */ + return requestWithDefaults(options); + } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 -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] - } + return requestWithDefaults(...args); } - // 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 + return Object.assign(withDecorations, requestWithDefaults); } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit, Endpoints); + return { + rest: api + }; } - - -/***/ }), - -/***/ 49609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - */ - -var bytes = __nccwpck_require__(86966) -var debug = __nccwpck_require__(7471)('body-parser:raw') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) - -/** - * Module exports. - */ - -module.exports = raw - -/** - * 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') - } - - // 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 - } - - 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 - } - - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) - } +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit, Endpoints); + return _objectSpread2(_objectSpread2({}, api), {}, { + rest: api + }); } +legacyRestEndpointMethods.VERSION = VERSION; -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} +exports.legacyRestEndpointMethods = legacyRestEndpointMethods; +exports.restEndpointMethods = restEndpointMethods; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 26382: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - */ +/***/ 86298: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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) -/** - * Module exports. - */ -module.exports = text +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Create a middleware to parse text bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -function text (options) { - var opts = options || {} +var Bottleneck = _interopDefault(__nccwpck_require__(11174)); - 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 +// @ts-ignore +async function errorRequest(octokit, state, error, options) { + if (!error.request || !error.request.request) { + // address https://github.com/octokit/plugin-retry.js/issues/8 + throw error; + } // retry all >= 400 && not doNotRetry - 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 + if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { + const retries = options.request.retries != null ? options.request.retries : state.retries; + const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); + throw octokit.retry.retryRequest(error, retries, retryAfter); + } // Maybe eventually there will be more cases here - function parse (buf) { - return buf - } - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } + throw error; +} - req.body = req.body || {} +// @ts-ignore - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +async function wrapRequest(state, request, options) { + const limiter = new Bottleneck(); // @ts-ignore - debug('content-type %j', req.headers['content-type']) + limiter.on("failed", function (error, info) { + const maxRetries = ~~error.request.request.retries; + const after = ~~error.request.request.retryAfter; + options.request.retryCount = info.retryCount + 1; - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + if (maxRetries > info.retryCount) { + // Returning a number instructs the limiter to retry + // the request after that number of milliseconds have passed + return after * state.retryAfterBaseValue; } - - // get charset - var charset = getCharset(req) || defaultCharset - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } + }); + return limiter.schedule(request, options); } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ +const VERSION = "3.0.6"; +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; + } + }; -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) + if (!state.enabled) { + return; } -} - -/***/ }), + octokit.hook.error("request", errorRequest.bind(null, octokit, state)); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); +} +retry.VERSION = VERSION; -/***/ 76100: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.VERSION = VERSION; +exports.retry = retry; +//# sourceMappingURL=index.js.map -"use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ }), +/***/ 9968: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Module dependencies. - * @private - */ -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) -/** - * Module exports. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -module.exports = urlencoded +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -/** - * Cache of parser modules. - */ +var BottleneckLight = _interopDefault(__nccwpck_require__(11174)); -var parsers = Object.create(null) +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; + } -/** - * Create a middleware to parse urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ + return obj; +} -function urlencoded (options) { - var opts = options || {} +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - // notice because option default will flip in next major - if (opts.extended === undefined) { - deprecate('undefined extended: provide extended option') + 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); } - 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 + return keys; +} - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') +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)); + }); + } } - // create the appropriate query parser - var queryparse = extended - ? extendedparser(opts) - : simpleparser(opts) + return target; +} - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type +const VERSION = "3.3.4"; - function parse (body) { - return body.length - ? queryparse(body) - : {} - } +const noop = () => Promise.resolve(); // @ts-ignore - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - req.body = req.body || {} +function wrapRequest(state, request, options) { + return state.retryLimiter.schedule(doRequest, state, request, options); +} // @ts-ignore - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +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 retryCount = ~~options.request.retryCount; + const jobOptions = retryCount > 0 ? { + priority: 0, + weight: 0 + } : {}; - debug('content-type %j', req.headers['content-type']) + if (state.clustering) { + // Remove a job from Redis if it has not completed or failed within 60s + // Examples: Node process terminated, client disconnected, etc. + // @ts-ignore + jobOptions.expiration = 1000 * 60; + } // Guarantee at least 1000ms between writes + // GraphQL can also trigger writes - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - // 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 (isWrite || isGraphQL) { + await state.write.key(state.id).schedule(jobOptions, noop); + } // Guarantee at least 3000ms between requests that trigger notifications - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} -/** - * Get the extended query parser. - * - * @param {object} options - */ + if (isWrite && state.triggersNotification(options.url)) { + await state.notifications.key(state.id).schedule(jobOptions, noop); + } // Guarantee at least 2000ms between search requests -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 (isSearch) { + await state.search.key(state.id).schedule(jobOptions, noop); } - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } + const req = state.global.key(state.id).schedule(jobOptions, request, options); - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) + if (isGraphQL) { + const res = await req; - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) + 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, + data: res.data + }); + throw error; } - - var arrayLimit = Math.max(100, paramCount) - - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) } -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } + return req; } -/** - * Count the number of parameters, stopping once limit reached - * - * @param {string} body - * @param {number} limit - * @api private - */ - -function parameterCount (body, limit) { - var count = 0 - var index = 0 +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"]; - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ +// @ts-ignore +function routeMatcher(paths) { + // EXAMPLE. For the following paths: - if (count === limit) { - return undefined - } - } + /* [ + "/orgs/:org/invitations", + "/repos/:owner/:repo/collaborators/:username" + ] */ + // @ts-ignore + const regexes = paths.map(path => path.split("/") // @ts-ignore + .map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - return count -} + /* [ + '/orgs/(?:.+?)/invitations', + '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' + ] */ + // @ts-ignore -/** - * Get parser for module name dynamically. - * - * @param {string} name - * @return {function} - * @api private - */ + const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: -function parser (name) { - var mod = parsers[name] + /* + ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ + It may look scary, but paste it into https://www.debuggex.com/ + and it will make a lot more sense! + */ - if (mod !== undefined) { - return mod.parse - } + return new RegExp(regex, "i"); +} - // this uses a switch for static require analysis - switch (name) { - case 'qs': - mod = __nccwpck_require__(22760) - break - case 'querystring': - mod = __nccwpck_require__(71191) - break - } +const regex = routeMatcher(triggersNotificationPaths); +const triggersNotification = regex.test.bind(regex); +const groups = {}; // @ts-ignore - // store to prevent invoking require() - parsers[name] = mod +const createGroups = function (Bottleneck, common) { + // @ts-ignore + groups.global = new Bottleneck.Group(_objectSpread2({ + id: "octokit-global", + maxConcurrent: 10 + }, common)); // @ts-ignore - return mod.parse -} + groups.search = new Bottleneck.Group(_objectSpread2({ + id: "octokit-search", + maxConcurrent: 1, + minTime: 2000 + }, common)); // @ts-ignore -/** - * Get the simple query parser. - * - * @param {object} options - */ + groups.write = new Bottleneck.Group(_objectSpread2({ + id: "octokit-write", + maxConcurrent: 1, + minTime: 1000 + }, common)); // @ts-ignore -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') + groups.notifications = new Bottleneck.Group(_objectSpread2({ + id: "octokit-notifications", + maxConcurrent: 1, + minTime: 3000 + }, common)); +}; - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } +function throttling(octokit, octokitOptions = {}) { + const { + enabled = true, + Bottleneck = BottleneckLight, + id = "no-id", + timeout = 1000 * 60 * 2, + // Redis TTL: 2 minutes + connection + } = octokitOptions.throttle || {}; - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 + if (!enabled) { + return; } - 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' - }) - } + const common = { + connection, + timeout + }; // @ts-ignore - debug('parse urlencoding') - return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + if (groups.global == null) { + createGroups(Bottleneck, common); } -} -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ + const state = Object.assign(_objectSpread2({ + clustering: connection != null, + triggersNotification, + minimumAbuseRetryAfter: 5, + retryAfterBaseValue: 1000, + retryLimiter: new Bottleneck(), + id + }, groups), // @ts-ignore + octokitOptions.throttle); -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) + if (typeof state.onAbuseLimit !== "function" || typeof state.onRateLimit !== "function") { + throw new Error(`octokit/plugin-throttling error: + You must pass the onAbuseLimit and onRateLimit error handlers. + See https://github.com/octokit/rest.js#throttling + + const octokit = new Octokit({ + throttle: { + onAbuseLimit: (retryAfter, options) => {/* ... */}, + onRateLimit: (retryAfter, options) => {/* ... */} + } + }) + `); } -} + const events = {}; + const emitter = new Bottleneck.Events(events); // @ts-ignore -/***/ }), + events.on("abuse-limit", state.onAbuseLimit); // @ts-ignore -/***/ 15377: -/***/ ((module, exports, __nccwpck_require__) => { + events.on("rate-limit", state.onRateLimit); // @ts-ignore -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + events.on("error", e => console.warn("Error in throttling-plugin limit handler", e)); // @ts-ignore -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(); + 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; -/** - * Colors. - */ + if (!(shouldRetryGraphQL || error.status === 403)) { + return; + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + const retryCount = ~~options.request.retryCount; + options.request.retryCount = retryCount; + const { + wantRetry, + retryAfter + } = await async function () { + if (/\babuse\b/i.test(error.message)) { + // The user has hit the abuse rate limit. (REST and GraphQL) + // 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 wantRetry = await emitter.trigger("abuse-limit", retryAfter, options, octokit); + return { + wantRetry, + retryAfter + }; + } -/** - * 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 - */ + if (error.headers != null && error.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 retryAfter = Math.max(Math.ceil((rateLimitReset - Date.now()) / 1000), 0); + const wantRetry = await emitter.trigger("rate-limit", retryAfter, options, octokit); + return { + wantRetry, + retryAfter + }; + } -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; - } + return {}; + }(); - // 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+)/)); -} + if (wantRetry) { + options.request.retryCount++; // @ts-ignore -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + return retryAfter * state.retryAfterBaseValue; + } + }); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); +} +throttling.VERSION = VERSION; +throttling.triggersNotification = triggersNotification; -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; +exports.throttling = throttling; +//# sourceMappingURL=index.js.map -/** - * Colorize log arguments if enabled. - * - * @api public - */ +/***/ }), -function formatArgs(args) { - var useColors = this.useColors; +/***/ 10537: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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') +Object.defineProperty(exports, "__esModule", ({ value: true })); - // 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; - } - }); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - args.splice(lastC, 0, c); -} +var deprecation = __nccwpck_require__(58932); +var once = _interopDefault(__nccwpck_require__(1223)); +const logOnce = once(deprecation => console.warn(deprecation)); /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public + * Error with extra properties to help with debugging */ -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); -} +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + /* istanbul ignore next */ -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } - } catch(e) {} -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + 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; + } -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options - // 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; + const requestCopy = Object.assign({}, options.request); + + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; } - return r; } -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map -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) {} -} +/***/ 36234: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), -/***/ 22552: -/***/ ((module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ +var endpoint = __nccwpck_require__(59440); +var universalUserAgent = __nccwpck_require__(45030); +var isPlainObject = __nccwpck_require__(63287); +var nodeFetch = _interopDefault(__nccwpck_require__(81768)); +var requestError = __nccwpck_require__(10537); -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); +const VERSION = "5.4.12"; -/** - * The currently active debug mode names, and names to skip. - */ +function getBufferResponse(response) { + return response.arrayBuffer(); +} -exports.names = []; -exports.skips = []; +function fetchWrapper(requestOptions) { + if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } -/** - * 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". - */ + let headers = {}; + let status; + let url; + const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; + return fetch(requestOptions.url, Object.assign({ + method: requestOptions.method, + body: requestOptions.body, + headers: requestOptions.headers, + redirect: requestOptions.redirect + }, requestOptions.request)).then(response => { + url = response.url; + status = response.status; -exports.formatters = {}; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } -/** - * Previous log timestamp. - */ + if (status === 204 || status === 205) { + return; + } // GitHub API returns 200 for HEAD requests -var prevTime; -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } -function selectColor(namespace) { - var hash = 0, i; + throw new requestError.RequestError(response.statusText, status, { + headers, + request: requestOptions + }); + } - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (status === 304) { + throw new requestError.RequestError("Not modified", status, { + headers, + request: requestOptions + }); + } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + if (status >= 400) { + return response.text().then(message => { + const error = new requestError.RequestError(message, status, { + headers, + request: requestOptions + }); -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ + try { + let responseBody = JSON.parse(error.message); + Object.assign(error, responseBody); + let errors = responseBody.errors; // Assumption `errors` would always be in Array format -function createDebug(namespace) { + error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); + } catch (e) {// ignore, see octokit/rest.js#684 + } - function debug() { - // disabled? - if (!debug.enabled) return; + throw error; + }); + } - var self = debug; + const contentType = response.headers.get("content-type"); - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + if (/application\/json/.test(contentType)) { + return response.json(); + } - // 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]; + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); } - args[0] = exports.coerce(args[0]); + return getBufferResponse(response); + }).then(data => { + return { + status, + url, + headers, + data + }; + }).catch(error => { + if (error instanceof requestError.RequestError) { + throw error; + } - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + throw new requestError.RequestError(error.message, 500, { + headers, + request: requestOptions + }); + }); +} + +function withDefaults(oldEndpoint, newDefaults) { + const endpoint = oldEndpoint.defaults(newDefaults); + + const newApi = function (route, parameters) { + const endpointOptions = endpoint.merge(route, parameters); + + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint.parse(endpointOptions)); } - // 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); + const request = (route, parameters) => { + return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); + }; - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; + Object.assign(request, { + endpoint, + defaults: withDefaults.bind(null, endpoint) }); + return endpointOptions.request.hook(request, endpointOptions); + }; - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + return Object.assign(newApi, { + endpoint, + defaults: withDefaults.bind(null, endpoint) + }); +} - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); +const request = withDefaults(endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` } +}); - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +exports.request = request; +//# sourceMappingURL=index.js.map - // 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 - */ +/***/ 81768: +/***/ ((module, exports, __nccwpck_require__) => { -function enable(namespaces) { - exports.save(namespaces); - exports.names = []; - exports.skips = []; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +Object.defineProperty(exports, "__esModule", ({ value: true })); - 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 + '$')); - } - } +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(__nccwpck_require__(12781)); +var http = _interopDefault(__nccwpck_require__(13685)); +var Url = _interopDefault(__nccwpck_require__(57310)); +var https = _interopDefault(__nccwpck_require__(95687)); +var zlib = _interopDefault(__nccwpck_require__(59796)); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } } -/** - * Disable debug output. - * - * @api public - */ +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); -function disable() { - exports.enable(''); -} +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); /** - * Returns true if the given mode name is enabled, false otherwise. + * fetch-error.js * - * @param {String} name - * @return {Boolean} - * @api public + * FetchError interface for operational errors */ -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`. + * Create FetchError instance * - * @param {Mixed} val - * @return {Mixed} - * @api private + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError */ +function FetchError(message, type, systemError) { + Error.call(this, message); -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); } +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; -/***/ }), +let convert; +try { + convert = (__nccwpck_require__(22877).convert); +} catch (e) {} -/***/ 7471: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; /** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void */ +function Body(body) { + var _this = this; -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(15377); -} else { - module.exports = __nccwpck_require__(74117); -} + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; -/***/ }), + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; -/***/ 74117: -/***/ ((module, exports, __nccwpck_require__) => { + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} -/** - * Module dependencies. - */ +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); + get bodyUsed() { + return this[INTERNALS].disturbed; + }, -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, -exports = module.exports = __nccwpck_require__(22552); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, -/** - * Colors. - */ + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; -exports.colors = [6, 2, 3, 4, 5, 1]; + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, -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() }); + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, - // 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); + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; - obj[prop] = val; - return obj; -}, {}); + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * Consume and convert an entire Body to a Buffer. * - * $ DEBUG_FD=3 node script.js 3>debug.log + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise */ +function consumeBody() { + var _this4 = this; -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)')() -} + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + this[INTERNALS].disturbed = true; -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} + let body = this.body; -/** - * Map %o to `util.inspect()`, all on a single line. - */ + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } -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(' '); -}; + // body is blob + if (isBlob(body)) { + body = body.stream(); + } -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + return new Body.Promise(function (resolve, reject) { + let resTimeout; - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } - 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]; - } -} + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + accumBytes += chunk.length; + accum.push(chunk); + }); -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; - } -} + body.on('end', function () { + if (abort) { + return; + } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + clearTimeout(resTimeout); -function load() { - return process.env.DEBUG; + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); } /** - * Copied from `node/src/node.js`. + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding * - * 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 Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } -function 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'; + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; - // 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; + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } - case 'FILE': - var fs = __nccwpck_require__(35747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(11631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + // html5 + if (!res && str) { + res = / { + return body; +} /** - * Helpers. + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param Mixed instance Any options.body input */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +function extractContentType(body) { + if (body === null) { + // body is null + return null; + } else if (typeof body === 'string') { + // body is string + return 'text/plain;charset=UTF-8'; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isBlob(body)) { + // body is blob + return body.type || null; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return null; + } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + return null; + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + return null; + } else if (typeof body.getBoundary === 'function') { + // detect form data input from form-data module + return `multipart/form-data;boundary=${body.getBoundary()}`; + } else if (body instanceof Stream) { + // body is stream + // can't really do much about this + return null; + } else { + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; + } +} /** - * Parse or format the given `val`. - * - * Options: + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. * - * - `long` verbose formatting [false] + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes * - * @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 Body instance Instance of Body + * @return Number? Number of bytes, or null if not possible */ +function getTotalBytes(instance) { + const body = instance.body; -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) - ); -}; + + if (body === null) { + // body is null + return 0; + } else if (isBlob(body)) { + return body.size; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + return null; + } +} /** - * Parse the given `str` and return milliseconds. + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. * - * @param {String} str - * @return {Number} - * @api private + * @param Body instance Instance of Body + * @return Void */ +function writeToStream(dest, instance) { + const body = instance.body; -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; - } + + if (body === null) { + // body is null + dest.end(); + } else if (isBlob(body)) { + body.stream().pipe(dest); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } } +// expose Promise +Body.Promise = global.Promise; + /** - * Short format for `ms`. + * headers.js * - * @param {Number} ms - * @return {String} - * @api private + * Headers class offers convenient helpers */ -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'; +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; + +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } +} + +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } } /** - * Long format for `ms`. + * Find the key in the map object given a header name. * - * @param {Number} ms - * @return {String} - * @api private + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; } -/** - * Pluralization helper. - */ +const MAP = Symbol('map'); +class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; -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'; -} + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } -/***/ }), + return; + } -/***/ 85442: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } -"use strict"; + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } -var Batcher, Events, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } -Batcher = function () { - class Batcher { - constructor(options = {}) { - this.options = options; - parser.load(this.options, this.defaults, this); - this.Events = new Events(this); - this._arr = []; + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - this._resetPromise(); +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); - this._lastFlush = Date.now(); - } +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} - this._resolve(); +const INTERNAL = Symbol('internal'); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} - add(data) { - var ret; +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } - this._arr.push(data); + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; - ret = this._promise; + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } - 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); - } + this[INTERNAL].index = index + 1; - return ret; - } + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - } +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); - ; - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; - return Batcher; -}.call(void 0); +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); -module.exports = Batcher; + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } -/***/ }), + return obj; +} -/***/ 83911: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} -"use strict"; +const INTERNALS$1 = Symbol('Response internals'); +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -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; } + Body.call(this, body, opts); -function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } + const status = opts.status || 200; + const headers = new Headers(opts.headers); -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } -function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + get url() { + return this[INTERNALS$1].url || ''; + } -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 status() { + return this[INTERNALS$1].status; + } -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); }); }; } + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } -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); + get redirected() { + return this[INTERNALS$1].counter > 0; + } -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); + get statusText() { + return this[INTERNALS$1].statusText; + } - this._validateOptions(options, invalid); + get headers() { + return this[INTERNALS$1].headers; + } - 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, {}); + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} - 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); +Body.mixIn(Response.prototype); - this._queues.on("leftzero", () => { - var base; - return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; - }); +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); - this._queues.on("zero", () => { - var base; - return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; - }); - } +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); - _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."); - } - } +const INTERNALS$2 = Symbol('Request internals'); - ready() { - return this._store.ready; - } +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; - clients() { - return this._store.clients; - } +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - channel() { - return `b_${this.id}`; - } +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} - publish(message) { - return this._store.__publish__(message); - } +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } + let parsedURL; - chain(_limiter) { - this._limiter = _limiter; - return this; - } + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } - queued(priority) { - return this._queues.queued(priority); - } + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); - clusterQueued() { - return this._store.__queued__(); - } + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - running() { - return this._store.__running__(); - } + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); - done() { - return this._store.__done__(); - } + const headers = new Headers(init.headers || input.headers || {}); - jobStatus(id) { - return this._states.jobStatus(id); - } + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } - jobs(status) { - return this._states.statusJobs(status); - } + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; - counts() { - return this._states.statusCounts(); - } + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } - _randomIndex() { - return Math.random().toString(36).slice(2); - } + get method() { + return this[INTERNALS$2].method; + } - check(weight = 1) { - return this._store.__check__(weight); - } + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } - _run(next, wait, index, retryCount) { - var _this = this; + get headers() { + return this[INTERNALS$2].headers; + } - var completed, done; - this.Events.trigger("debug", `Scheduling ${next.options.id}`, { - args: next.args, - options: next.options - }); - done = false; + get redirect() { + return this[INTERNALS$2].redirect; + } - completed = - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (...args) { - var e, error, eventInfo, retry, retryAfter, running; + get signal() { + return this[INTERNALS$2].signal; + } - if (!done) { - try { - done = true; - clearTimeout(_this._scheduled[index].expiration); - delete _this._scheduled[index]; - eventInfo = { - args: next.args, - options: next.options, - retryCount - }; + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} - if ((error = args[0]) != null) { - retry = yield _this.Events.trigger("failed", error, eventInfo); +Body.mixIn(Request.prototype); - if (retry != null) { - retryAfter = ~~retry; +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); - _this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); - return _this._run(next, retryAfter, index, retryCount + 1); - } - } +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); - _this._states.next(next.options.id); // DONE + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } - _this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } - _this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } - var _ref2 = yield _this._store.__free__(index, next.options.weight); + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } - running = _ref2.running; + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } - _this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } - if (running === 0 && _this.empty()) { - _this.Events.trigger("idle"); - } + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } - return typeof next.cb === "function" ? next.cb(...args) : void 0; - } catch (error1) { - e = error1; - return _this.Events.trigger("error", e); - } - } - }); + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } - return function completed() { - return _ref.apply(this, arguments); - }; - }(); + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js - if (retryCount === 0) { - // RUNNING - this._states.next(next.options.id); - } + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} - return this._scheduled[index] = { - timeout: setTimeout(() => { - this.Events.trigger("debug", `Executing ${next.options.id}`, { - args: next.args, - options: next.options - }); +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ - if (retryCount === 0) { - // EXECUTING - this._states.next(next.options.id); - } +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); - 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 - }; - } + this.type = 'aborted'; + this.message = message; - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} - if (this.queued() === 0) { - return this.Promise.resolve(null); - } +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; - queue = this._queues.getFirst(); +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; +const resolve_url = Url.resolve; - var _next2 = next = queue.first(); +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { - options = _next2.options; - args = _next2.args; + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } - if (capacity != null && options.weight > capacity) { - return this.Promise.resolve(null); - } + Body.Promise = fetch.Promise; - 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 - }); + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); - if (success) { - queue.shift(); - empty = this.empty(); + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; - if (empty) { - this.Events.trigger("empty"); - } + let response = null; - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; - this._run(next, wait, index, 0); + if (signal && signal.aborted) { + abort(); + return; + } - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then(drained => { - var newCapacity; + // send request + const req = send(options); + let reqTimeout; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch(e => { - return this.Events.trigger("error", e); - }); - } + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } - _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)); - } - } + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } - return this.Events.trigger("dropped", job); - } - } + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } - _dropAllQueued(message) { - return this._queues.shiftAll(job => { - return this._drop(job, message); - }); - } + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); - stop(options = {}) { - var done, waitForExecuting; - options = parser.load(options, this.stopDefaults); + req.on('response', function (res) { + clearTimeout(reqTimeout); - waitForExecuting = at => { - var finished; + const headers = createHeadersLenient(res.headers); - finished = () => { - var counts; - counts = this._states.counts; - return counts[0] + counts[1] + counts[2] + counts[3] === at; - }; + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); - 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; + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } - for (k in ref) { - v = ref[k]; + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; - this._drop(v.job, options.dropErrorMessage); - } - } + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } - this._dropAllQueued(options.dropErrorMessage); + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } - this.submit = (...args) => { - var _ref3, _ref4, _splice$call, _splice$call2; + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); - 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; - }; + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); - return done; - } + // HTTP-network fetch step 12.1.1.4: handle content codings - submit(...args) { - var _this2 = this; + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } - var cb, job, options, ref, ref1, task; + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; - if (typeof args[0] === "function") { - var _ref5, _ref6, _splice$call3, _splice$call4; + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } - 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; + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); - 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); - } + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; - job = { - options, - task, - args, - cb - }; - options.priority = this._sanitizePriority(options.priority); +// expose Promise +fetch.Promise = global.Promise; - if (options.id === this.jobDefaults.id) { - options.id = `${options.id}-${this._randomIndex()}`; - } +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; - 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 +/***/ 49768: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.Events.trigger("debug", `Queueing ${options.id}`, { - args, - options - }); - return this._submitLock.schedule( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var blocked, e, reachedHWM, shifted, strategy; - try { - var _ref10 = yield _this2._store.__submit__(_this2.queued(), options.weight); +Object.defineProperty(exports, "__esModule", ({ value: true })); - reachedHWM = _ref10.reachedHWM; - blocked = _ref10.blocked; - strategy = _ref10.strategy; +var crypto = __nccwpck_require__(6113); +var buffer = __nccwpck_require__(14300); - _this2.Events.trigger("debug", `Queued ${options.id}`, { - args, - options, - reachedHWM, - blocked - }); - } catch (error1) { - e = error1; +const VERSION = "2.0.0"; - _this2._states.remove(options.id); +var Algorithm; - _this2.Events.trigger("debug", `Could not queue ${options.id}`, { - args, - options, - error: e - }); +(function (Algorithm) { + Algorithm["SHA1"] = "sha1"; + Algorithm["SHA256"] = "sha256"; +})(Algorithm || (Algorithm = {})); - if (typeof job.cb === "function") { - job.cb(e); - } +async function sign(options, payload) { + const { + secret, + algorithm + } = typeof options === "object" ? { + secret: options.secret, + algorithm: options.algorithm || Algorithm.SHA256 + } : { + secret: options, + algorithm: Algorithm.SHA256 + }; - return false; - } + if (!secret || !payload) { + throw new TypeError("[@octokit/webhooks-methods] secret & payload required for sign()"); + } - if (blocked) { - _this2._drop(job); + if (!Object.values(Algorithm).includes(algorithm)) { + throw new TypeError(`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`); + } - 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; + return `${algorithm}=${crypto.createHmac(algorithm, secret).update(payload).digest("hex")}`; +} +sign.VERSION = VERSION; - if (shifted != null) { - _this2._drop(shifted); - } +const getAlgorithm = signature => { + return signature.startsWith("sha256=") ? "sha256" : "sha1"; +}; - if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - _this2._drop(job); - } +async function verify(secret, eventPayload, signature) { + if (!secret || !eventPayload || !signature) { + throw new TypeError("[@octokit/webhooks-methods] secret, eventPayload & signature required"); + } - return reachedHWM; - } - } + const signatureBuffer = buffer.Buffer.from(signature); + const algorithm = getAlgorithm(signature); + const verificationBuffer = buffer.Buffer.from(await sign({ + secret, + algorithm + }, eventPayload)); - _this2._states.next(job.options.id); // QUEUED + if (signatureBuffer.length !== verificationBuffer.length) { + return false; + } // constant time comparison to prevent timing attachs + // https://stackoverflow.com/a/31096242/206879 + // https://en.wikipedia.org/wiki/Timing_attack - _this2._queues.push(options.priority, job); + return crypto.timingSafeEqual(signatureBuffer, verificationBuffer); +} +verify.VERSION = VERSION; - yield _this2._drainAll(); - return reachedHWM; - })); - } +exports.sign = sign; +exports.verify = verify; +//# sourceMappingURL=index.js.map - schedule(...args) { - var options, task, wrapped; - if (typeof args[0] === "function") { - var _args = args; +/***/ }), - var _args2 = _toArray(_args); +/***/ 18513: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - wrapped = (...args) => { - var _ref11, _ref12, _splice$call7, _splice$call8; +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - 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); +var AggregateError = _interopDefault(__nccwpck_require__(61231)); +var webhooksMethods = __nccwpck_require__(49768); - returned = function () { - try { - return task(...args); - } catch (error1) { - e = error1; - return this.Promise.reject(e); - } - }.call(this); +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - 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); - }); - }; + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); - 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); - }); + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } - 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); - }; - - return wrapped; - } + keys.push.apply(keys, symbols); + } - updateSettings(options = {}) { - var _this3 = this; + return keys; +} - return _asyncToGenerator(function* () { - yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); - parser.overwrite(options, _this3.instanceDefaults, _this3); - return _this3; - })(); - } +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - currentReservoir() { - return this._store.__currentReservoir__(); + 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)); + }); } + } - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } + 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; } - ; - 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; + return obj; +} -/***/ }), +const createLogger = logger => _objectSpread2({ + debug: () => {}, + info: () => {}, + warn: console.warn.bind(console), + error: console.error.bind(console) +}, logger); -/***/ 93529: -/***/ ((module) => { +// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY +// make edits in scripts/generate-types.ts +const emitterEventNames = ["branch_protection_rule", "branch_protection_rule.created", "branch_protection_rule.deleted", "branch_protection_rule.edited", "check_run", "check_run.completed", "check_run.created", "check_run.requested_action", "check_run.rerequested", "check_suite", "check_suite.completed", "check_suite.requested", "check_suite.rerequested", "code_scanning_alert", "code_scanning_alert.appeared_in_branch", "code_scanning_alert.closed_by_user", "code_scanning_alert.created", "code_scanning_alert.fixed", "code_scanning_alert.reopened", "code_scanning_alert.reopened_by_user", "commit_comment", "commit_comment.created", "create", "delete", "deploy_key", "deploy_key.created", "deploy_key.deleted", "deployment", "deployment.created", "deployment_status", "deployment_status.created", "discussion", "discussion.answered", "discussion.category_changed", "discussion.created", "discussion.deleted", "discussion.edited", "discussion.labeled", "discussion.locked", "discussion.pinned", "discussion.transferred", "discussion.unanswered", "discussion.unlabeled", "discussion.unlocked", "discussion.unpinned", "discussion_comment", "discussion_comment.created", "discussion_comment.deleted", "discussion_comment.edited", "fork", "github_app_authorization", "github_app_authorization.revoked", "gollum", "installation", "installation.created", "installation.deleted", "installation.new_permissions_accepted", "installation.suspend", "installation.unsuspend", "installation_repositories", "installation_repositories.added", "installation_repositories.removed", "issue_comment", "issue_comment.created", "issue_comment.deleted", "issue_comment.edited", "issues", "issues.assigned", "issues.closed", "issues.deleted", "issues.demilestoned", "issues.edited", "issues.labeled", "issues.locked", "issues.milestoned", "issues.opened", "issues.pinned", "issues.reopened", "issues.transferred", "issues.unassigned", "issues.unlabeled", "issues.unlocked", "issues.unpinned", "label", "label.created", "label.deleted", "label.edited", "marketplace_purchase", "marketplace_purchase.cancelled", "marketplace_purchase.changed", "marketplace_purchase.pending_change", "marketplace_purchase.pending_change_cancelled", "marketplace_purchase.purchased", "member", "member.added", "member.edited", "member.removed", "membership", "membership.added", "membership.removed", "meta", "meta.deleted", "milestone", "milestone.closed", "milestone.created", "milestone.deleted", "milestone.edited", "milestone.opened", "org_block", "org_block.blocked", "org_block.unblocked", "organization", "organization.deleted", "organization.member_added", "organization.member_invited", "organization.member_removed", "organization.renamed", "package", "package.published", "package.updated", "page_build", "ping", "project", "project.closed", "project.created", "project.deleted", "project.edited", "project.reopened", "project_card", "project_card.converted", "project_card.created", "project_card.deleted", "project_card.edited", "project_card.moved", "project_column", "project_column.created", "project_column.deleted", "project_column.edited", "project_column.moved", "public", "pull_request", "pull_request.assigned", "pull_request.auto_merge_disabled", "pull_request.auto_merge_enabled", "pull_request.closed", "pull_request.converted_to_draft", "pull_request.edited", "pull_request.labeled", "pull_request.locked", "pull_request.opened", "pull_request.ready_for_review", "pull_request.reopened", "pull_request.review_request_removed", "pull_request.review_requested", "pull_request.synchronize", "pull_request.unassigned", "pull_request.unlabeled", "pull_request.unlocked", "pull_request_review", "pull_request_review.dismissed", "pull_request_review.edited", "pull_request_review.submitted", "pull_request_review_comment", "pull_request_review_comment.created", "pull_request_review_comment.deleted", "pull_request_review_comment.edited", "pull_request_review_thread", "pull_request_review_thread.resolved", "pull_request_review_thread.unresolved", "push", "release", "release.created", "release.deleted", "release.edited", "release.prereleased", "release.published", "release.released", "release.unpublished", "repository", "repository.archived", "repository.created", "repository.deleted", "repository.edited", "repository.privatized", "repository.publicized", "repository.renamed", "repository.transferred", "repository.unarchived", "repository_dispatch", "repository_import", "repository_vulnerability_alert", "repository_vulnerability_alert.create", "repository_vulnerability_alert.dismiss", "repository_vulnerability_alert.resolve", "secret_scanning_alert", "secret_scanning_alert.created", "secret_scanning_alert.reopened", "secret_scanning_alert.resolved", "security_advisory", "security_advisory.performed", "security_advisory.published", "security_advisory.updated", "security_advisory.withdrawn", "sponsorship", "sponsorship.cancelled", "sponsorship.created", "sponsorship.edited", "sponsorship.pending_cancellation", "sponsorship.pending_tier_change", "sponsorship.tier_changed", "star", "star.created", "star.deleted", "status", "team", "team.added_to_repository", "team.created", "team.deleted", "team.edited", "team.removed_from_repository", "team_add", "watch", "watch.started", "workflow_dispatch", "workflow_job", "workflow_job.completed", "workflow_job.in_progress", "workflow_job.queued", "workflow_job.started", "workflow_run", "workflow_run.completed", "workflow_run.requested"]; -"use strict"; +function handleEventHandlers(state, webhookName, handler) { + if (!state.hooks[webhookName]) { + state.hooks[webhookName] = []; + } + state.hooks[webhookName].push(handler); +} -var BottleneckError; -BottleneckError = class BottleneckError extends Error {}; -module.exports = BottleneckError; +function receiverOn(state, webhookNameOrNames, handler) { + if (Array.isArray(webhookNameOrNames)) { + webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler)); + return; + } -/***/ }), + if (["*", "error"].includes(webhookNameOrNames)) { + const webhookName = webhookNameOrNames === "*" ? "any" : webhookNameOrNames; + const message = `Using the "${webhookNameOrNames}" event with the regular Webhooks.on() function is not supported. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`; + throw new Error(message); + } -/***/ 38579: -/***/ ((module) => { + if (!emitterEventNames.includes(webhookNameOrNames)) { + state.log.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`); + } -"use strict"; + handleEventHandlers(state, webhookNameOrNames, handler); +} +function receiverOnAny(state, handler) { + handleEventHandlers(state, "*", handler); +} +function receiverOnError(state, handler) { + handleEventHandlers(state, "error", handler); +} +// Errors thrown or rejected Promises in "error" event handlers are not handled +// as they are in the webhook event handlers. If errors occur, we log a +// "Fatal: Error occurred" message to stdout +function wrapErrorHandler(handler, error) { + let returnValue; -var DLList; -DLList = class DLList { - constructor(_queues) { - this._queues = _queues; - this._first = null; - this._last = null; - this.length = 0; + try { + returnValue = handler(error); + } catch (error) { + console.log('FATAL: Error occurred in "error" event handler'); + console.log(error); } - push(value) { - var node, ref1; - this.length++; - - if ((ref1 = this._queues) != null) { - ref1.incr(); - } + if (returnValue && returnValue.catch) { + returnValue.catch(error => { + console.log('FATAL: Error occurred in "error" event handler'); + console.log(error); + }); + } +} - node = { - value, - next: null - }; +// @ts-ignore to address #245 - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } +function getHooks(state, eventPayloadAction, eventName) { + const hooks = [state.hooks[eventName], state.hooks["*"]]; - return void 0; + if (eventPayloadAction) { + hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]); } - shift() { - var ref1, ref2, value; + return [].concat(...hooks.filter(Boolean)); +} // main handler function - if (this._first == null) { - return void 0; - } else { - this.length--; - if ((ref1 = this._queues) != null) { - ref1.decr(); - } - } +function receiverHandle(state, event) { + const errorHandlers = state.hooks.error || []; - value = this._first.value; - this._first = (ref2 = this._first.next) != null ? ref2 : this._last = null; - return value; + if (event instanceof Error) { + const error = Object.assign(new AggregateError([event]), { + event, + errors: [event] + }); + errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); + return Promise.reject(error); } - first() { - if (this._first != null) { - return this._first.value; - } + if (!event || !event.name) { + throw new AggregateError(["Event name not passed"]); } - getArray() { - var node, ref, results; - node = this._first; - results = []; + if (!event.payload) { + throw new AggregateError(["Event payload not passed"]); + } // flatten arrays of event listeners and remove undefined values - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; + const hooks = getHooks(state, "action" in event.payload ? event.payload.action : null, event.name); + + if (hooks.length === 0) { + return Promise.resolve(); } - forEachShift(cb) { - var node; - node = this.shift(); + const errors = []; + const promises = hooks.map(handler => { + let promise = Promise.resolve(event); - while (node != null) { - cb(node), node = this.shift(); + if (state.transform) { + promise = promise.then(state.transform); } - return void 0; - } + return promise.then(event => { + return handler(event); + }).catch(error => errors.push(Object.assign(error, { + event + }))); + }); + return Promise.all(promises).then(() => { + if (errors.length === 0) { + return; + } -}; -module.exports = DLList; + const error = new AggregateError(errors); + Object.assign(error, { + event, + errors + }); + errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); + throw error; + }); +} -/***/ }), +function removeListener(state, webhookNameOrNames, handler) { + if (Array.isArray(webhookNameOrNames)) { + webhookNameOrNames.forEach(webhookName => removeListener(state, webhookName, handler)); + return; + } -/***/ 107: -/***/ ((module) => { + if (!state.hooks[webhookNameOrNames]) { + return; + } // remove last hook that has been added, that way + // it behaves the same as removeListener -"use strict"; + for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) { + if (state.hooks[webhookNameOrNames][i] === handler) { + state.hooks[webhookNameOrNames].splice(i, 1); + return; + } + } +} -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 createEventHandler(options) { + const state = { + hooks: {}, + log: createLogger(options && options.log) + }; -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); }); }; } + if (options && options.transform) { + state.transform = options.transform; + } -var Events; -Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; + return { + on: receiverOn.bind(null, state), + onAny: receiverOnAny.bind(null, state), + onError: receiverOnError.bind(null, state), + removeListener: removeListener.bind(null, state), + receive: receiverHandle.bind(null, state) + }; +} + +/** + * GitHub sends its JSON with an indentation of 2 spaces and a line break at the end + */ +function toNormalizedJsonString(payload) { + const payloadString = JSON.stringify(payload); + return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, s => { + return s.substr(0, 3) + s.substr(3).toUpperCase(); + }); +} - if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { - throw new Error("An Emitter already exists for this object"); - } +async function sign(secret, payload) { + return webhooksMethods.sign(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload)); +} - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; +async function verify(secret, payload, signature) { + return webhooksMethods.verify(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload), signature); +} - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; +async function verifyAndReceive(state, event) { + // verify will validate that the secret is not undefined + const matchesSignature = await webhooksMethods.verify(state.secret, typeof event.payload === "object" ? toNormalizedJsonString(event.payload) : event.payload, event.signature); - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; + if (!matchesSignature) { + const error = new Error("[@octokit/webhooks] signature does not match event payload and secret"); + return state.eventHandler.receive(Object.assign(error, { + event, + status: 400 + })); } - _addListener(name, status, cb) { - var base; + return state.eventHandler.receive({ + id: event.id, + name: event.name, + payload: typeof event.payload === "string" ? JSON.parse(event.payload) : event.payload + }); +} - if ((base = this._events)[name] == null) { - base[name] = []; - } +const WEBHOOK_HEADERS = ["x-github-event", "x-hub-signature-256", "x-github-delivery"]; // https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers - this._events[name].push({ - cb, - status +function getMissingHeaders(request) { + return WEBHOOK_HEADERS.filter(header => !(header in request.headers)); +} + +// @ts-ignore to address #245 +function getPayload(request) { + // If request.body already exists we can stop here + // See https://github.com/octokit/webhooks.js/pull/23 + if (request.body) return Promise.resolve(request.body); + return new Promise((resolve, reject) => { + let data = ""; + request.setEncoding("utf8"); // istanbul ignore next + + request.on("error", error => reject(new AggregateError([error]))); + request.on("data", chunk => data += chunk); + request.on("end", () => { + try { + resolve(JSON.parse(data)); + } catch (error) { + error.message = "Invalid JSON"; + error.status = 400; + reject(new AggregateError([error])); + } }); + }); +} - return this.instance; +async function middleware(webhooks, options, request, response, next) { + let pathname; + + try { + pathname = new URL(request.url, "http://localhost").pathname; + } catch (error) { + response.writeHead(422, { + "content-type": "application/json" + }); + response.end(JSON.stringify({ + error: `Request URL could not be parsed: ${request.url}` + })); + return; } - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; + const isUnknownRoute = request.method !== "POST" || pathname !== options.path; + const isExpressMiddleware = typeof next === "function"; + + if (isUnknownRoute) { + if (isExpressMiddleware) { + return next(); } else { - return 0; + return options.onUnhandledRequest(request, response); } } - trigger(name, ...args) { - var _this = this; + const missingHeaders = getMissingHeaders(request).join(", "); - return _asyncToGenerator(function* () { - var e, promises; + if (missingHeaders) { + response.writeHead(400, { + "content-type": "application/json" + }); + response.end(JSON.stringify({ + error: `Required headers missing: ${missingHeaders}` + })); + return; + } - try { - if (name !== "debug") { - _this.trigger("debug", `Event triggered: ${name}`, args); - } + const eventName = request.headers["x-github-event"]; + const signatureSHA256 = request.headers["x-hub-signature-256"]; + const id = request.headers["x-github-delivery"]; + options.log.debug(`${eventName} event received (id: ${id})`); // GitHub will abort the request if it does not receive a response within 10s + // See https://github.com/octokit/webhooks.js/issues/185 - if (_this._events[name] == null) { - return; - } + let didTimeout = false; + const timeout = setTimeout(() => { + didTimeout = true; + response.statusCode = 202; + response.end("still processing\n"); + }, 9000).unref(); - _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; + try { + const payload = await getPayload(request); + await webhooks.verifyAndReceive({ + id: id, + name: eventName, + payload: payload, + signature: signatureSHA256 + }); + clearTimeout(timeout); + if (didTimeout) return; + response.end("ok\n"); + } catch (error) { + clearTimeout(timeout); + if (didTimeout) return; + const statusCode = Array.from(error)[0].status; + response.statusCode = typeof statusCode !== "undefined" ? statusCode : 500; + response.end(String(error)); + } +} - if (listener.status === "none") { - return; - } +function onUnhandledRequestDefault(request, response) { + response.writeHead(404, { + "content-type": "application/json" + }); + response.end(JSON.stringify({ + error: `Unknown route: ${request.method} ${request.url}` + })); +} - if (listener.status === "once") { - listener.status = "none"; - } +function createNodeMiddleware(webhooks, { + path = "/api/github/webhooks", + onUnhandledRequest = onUnhandledRequestDefault, + log = createLogger() +} = {}) { + return middleware.bind(null, webhooks, { + path, + onUnhandledRequest, + log + }); +} - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; +class Webhooks { + constructor(options) { + if (!options || !options.secret) { + throw new Error("[@octokit/webhooks] options.secret required"); + } - if (typeof (returned != null ? returned.then : void 0) === "function") { - return yield returned; - } else { - return returned; - } - } catch (error) { - e = error; + const state = { + eventHandler: createEventHandler(options), + secret: options.secret, + hooks: {}, + log: createLogger(options.log) + }; + this.sign = sign.bind(null, options.secret); + this.verify = verify.bind(null, options.secret); + this.on = state.eventHandler.on; + this.onAny = state.eventHandler.onAny; + this.onError = state.eventHandler.onError; + this.removeListener = state.eventHandler.removeListener; + this.receive = state.eventHandler.receive; + this.verifyAndReceive = verifyAndReceive.bind(null, state); + } - if (true) { - _this.trigger("error", e); - } +} - return null; - } - }); +exports.Webhooks = Webhooks; +exports.createEventHandler = createEventHandler; +exports.createNodeMiddleware = createNodeMiddleware; +exports.emitterEventNames = emitterEventNames; +//# sourceMappingURL=index.js.map - 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); - } +/***/ }), - return null; - } - })(); - } +/***/ 93159: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -}; -module.exports = Events; +const ProbotExports = __nccwpck_require__(93181); +const pino = __nccwpck_require__(79608); -/***/ }), +const { transport } = __nccwpck_require__(96645); -/***/ 53068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = { ...ProbotExports, run }; -"use strict"; +async function run(app) { + const log = pino({}, transport); + const githubToken = + process.env.GITHUB_TOKEN || + process.env.INPUT_GITHUB_TOKEN || + process.env.INPUT_TOKEN; -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + if (!githubToken) { + log.error( + "[probot/adapter-github-actions] a token must be passed as `env.GITHUB_TOKEN` or `with.GITHUB_TOKEN` or `with.token`, see https://github.com/probot/adapter-github-actions#usage" + ); + return; + } -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + const envVariablesMissing = [ + "GITHUB_RUN_ID", + "GITHUB_EVENT_NAME", + "GITHUB_EVENT_PATH", + ].filter((name) => !process.env[name]); -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; } + if (envVariablesMissing.length) { + log.error( + `[probot/adapter-github-actions] GitHub Action default environment variables missing: ${envVariablesMissing.join( + ", " + )}. See https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables` + ); + return; + } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + const probot = ProbotExports.createProbot({ + overrides: { + githubToken, + log, + }, + }); -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); } } + await probot.load(app); -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 probot + .receive({ + id: process.env.GITHUB_RUN_ID, + name: process.env.GITHUB_EVENT_NAME, + payload: require(process.env.GITHUB_EVENT_PATH), + }) + .catch((error) => { + probot.log.error(error); + }); +} -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); -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); +/***/ }), - this._startAutoCleanup(); +/***/ 18915: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - 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 - })); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(53322); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; } - } + this.command = command; + this.properties = properties; + this.message = message; } - - 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; - })(); + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; } +} +function escapeData(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map - deleteKey(key = "") { - var _this = this; +/***/ }), - return _asyncToGenerator(function* () { - var deleted, instance; - instance = _this.instances[key]; +/***/ 68648: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (_this.connection) { - deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); + +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 __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(18915); +const file_command_1 = __nccwpck_require__(20); +const utils_1 = __nccwpck_require__(53322); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + const delimiter = '_GitHubActionsFileCommandDelimeter_'; + const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; + file_command_1.issueCommand('ENV', commandValue); + } + else { + command_1.issueCommand('set-env', { name }, convertedVal); + } +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueCommand('PATH', inputPath); + } + else { + command_1.issueCommand('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + command_1.issueCommand('set-output', { name }, value); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + */ +function error(message) { + command_1.issue('error', message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ +function warning(message) { + command_1.issue('warning', message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); } - - if (instance != null) { - delete _this.instances[key]; - yield instance.disconnect(); + finally { + endGroup(); } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +//# sourceMappingURL=core.js.map - return instance != null || deleted > 0; - })(); - } - - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; +/***/ }), - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } +/***/ 20: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return results; - } - keys() { - return Object.keys(this.instances); +// For internal use, subject to change. +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(53322); +function issueCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); } - - clusterKeys() { - var _this2 = this; - - return _asyncToGenerator(function* () { - var cursor, end, found, i, k, keys, len, next, start; - - if (_this2.connection == null) { - return _this2.Promise.resolve(_this2.keys()); - } - - keys = []; - cursor = null; - start = `b_${_this2.id}-`.length; - end = "_settings".length; - - while (cursor !== 0) { - var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); - - var _ref2 = _slicedToArray(_ref, 2); - - 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; - })(); + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); } + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueCommand = issueCommand; +//# sourceMappingURL=file-command.js.map - _startAutoCleanup() { - var _this3 = this; - - 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 = []; - - for (k in ref) { - v = ref[k]; - - 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)); - } - } +/***/ }), - return results; - }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; - } +/***/ 53322: +/***/ ((__unused_webpack_module, exports) => { - updateSettings(options = {}) { - parser.overwrite(options, this.defaults, this); - parser.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; } - - disconnect(flush = true) { - var ref; - - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } + else if (typeof input === 'string' || input instanceof String) { + return input; } - - } - - ; - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; - return Group; -}.call(void 0); - -module.exports = Group; + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 47710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -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 Events, IORedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); - -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 - - parser.load(options, this.defaults, this); - - if (this.Events == null) { - this.Events = new Events(this); - } +/***/ 36267: +/***/ ((module, exports, __nccwpck_require__) => { - this.terminated = false; +/** + * Module dependencies. + */ - 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); - } +const EventEmitter = (__nccwpck_require__(82361).EventEmitter); +const spawn = (__nccwpck_require__(32081).spawn); +const path = __nccwpck_require__(71017); +const fs = __nccwpck_require__(57147); - this.subscriber = this.client.duplicate(); - } +// @ts-check - this.limiters = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - this._loadScripts(); +class Option { + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} description + * @api public + */ - return { - client: this.client, - subscriber: this.subscriber - }; - }); + 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; + } - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); - - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } - - if (client.status === "ready") { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); - } + /** + * Return option name. + * + * @return {string} + * @api private + */ - _loadScripts() { - return Scripts.names.forEach(name => { - return this.client.defineCommand(name, { - lua: Scripts.payload(name) - }); - }); + name() { + if (this.long) { + return this.long.replace(/^--/, ''); } + return this.short.replace(/^-/, ''); + }; - __runCommand__(cmd) { - var _this = this; - - return _asyncToGenerator(function* () { - var _, deleted; - - yield _this.ready; + /** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {string} + * @api private + */ - var _ref = yield _this.client.pipeline([cmd]).exec(); + attributeName() { + return camelcase(this.name().replace(/^no-/, '')); + }; - var _ref2 = _slicedToArray(_ref, 1); + /** + * Check if `arg` matches the short or long flag. + * + * @param {string} arg + * @return {boolean} + * @api private + */ - var _ref2$ = _slicedToArray(_ref2[0], 2); + is(arg) { + return this.short === arg || this.long === arg; + }; +} - _ = _ref2$[0]; - deleted = _ref2$[1]; - return deleted; - })(); - } +/** + * 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; + } +} - __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(); - }); - }); - })); - } +class Command extends EventEmitter { + /** + * Initialize a new `Command`. + * + * @param {string} [name] + * @api public + */ - __removeLimiter__(instance) { - var _this2 = this; + 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; - return [instance.channel(), instance.channel_client()].forEach( - /*#__PURE__*/ - function () { - var _ref3 = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield _this2.subscriber.unsubscribe(channel); - } + 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'; + } - return delete _this2.limiters[channel]; - }); + /** + * 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 + */ - return function (_x) { - return _ref3.apply(this, arguments); - }; - }()); + 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()); - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [keys.length].concat(keys, args, cb); + if (desc) { + cmd.description(desc); + cmd._executableHandler = true; } + if (opts.isDefault) this._defaultCommandName = cmd._name; - __scriptFn__(name) { - return this.client[name].bind(this.client); - } + 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; - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); + 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; - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); - } + if (desc) return this; + return cmd; + }; - this.limiters = {}; - this.terminated = true; + /** + * 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 + */ - if (flush) { - return this.Promise.all([this.client.quit(), this.subscriber.quit()]); - } else { - this.client.disconnect(); - this.subscriber.disconnect(); - return this.Promise.resolve(); - } + createCommand(name) { + return new Command(name); + }; + + /** + * 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 + */ + + addCommand(cmd, opts) { + if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); + + // 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); - } + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation - ; - IORedisConnection.prototype.datastore = "ioredis"; - IORedisConnection.prototype.defaults = { - clientOptions: {}, - clusterNodes: null, - client: null, - Promise: Promise, - Events: null + this.commands.push(cmd); + cmd.parent = this; + return this; }; - return IORedisConnection; -}.call(void 0); -module.exports = IORedisConnection; + /** + * Define argument syntax for the command. + * + * @api public + */ -/***/ }), + arguments(desc) { + return this._parseExpectedArgs(desc.split(/ +/)); + }; -/***/ 38979: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * 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 + */ -"use strict"; + 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; + }; + /** + * @return {boolean} + * @api private + */ -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); } } + _lazyHasImplicitHelpCommand() { + if (this._hasImplicitHelpCommand === undefined) { + this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); + } + return this._hasImplicitHelpCommand; + }; -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); }); }; } + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} `this` command for chaining + * @api private + */ -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 = {}; + _parseExpectedArgs(args) { + if (!args.length) return; + args.forEach((arg) => { + const argDetails = { + required: false, + name: '', + variadic: false + }; - this._startHeartbeat(); - } + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } - _startHeartbeat() { - var base; + 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; + }; - if (this.heartbeat == null && this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null) { - return typeof (base = this.heartbeat = setInterval(() => { - var now; - now = Date.now(); + /** + * 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 + */ - 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; + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; } else { - return clearInterval(this.heartbeat); + this._exitCallback = (err) => { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; } - } - - __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 this; + }; - return _asyncToGenerator(function* () { - yield _this2.yieldLoop(); - clearInterval(_this2.heartbeat); - return _this2.Promise.resolve(); - })(); - } + /** + * 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 + */ - yieldLoop(t = 0) { - return new this.Promise(function (resolve, reject) { - return setTimeout(resolve, t); - }); - } + _exit(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. + } + process.exit(exitCode); + }; - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; - } + /** + * 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 + */ - __updateSettings__(options) { - var _this3 = this; + 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)); + } - return _asyncToGenerator(function* () { - yield _this3.yieldLoop(); - parser.overwrite(options, options, _this3.storeOptions); + 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; + }; - _this3._startHeartbeat(); + /** + * Internal routine to check whether there is a clash storing option value with a Command property. + * + * @param {Option} option + * @api private + */ - _this3.instance._drainAll(_this3.computeCapacity()); + _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; + } - return true; - })(); - } + const commandProperty = this._getOptionValue(option.attributeName()); + if (commandProperty === undefined) { + // no clash + return; + } - __running__() { - var _this4 = this; + 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); + } - return _asyncToGenerator(function* () { - yield _this4.yieldLoop(); - return _this4._running; - })(); - } + 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 - __queued__() { - var _this5 = this; +Read more on https://git.io/JJc0W`); + } + }; - return _asyncToGenerator(function* () { - yield _this5.yieldLoop(); - return _this5.instance.queued(); - })(); - } + /** + * 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 + */ - __done__() { - var _this6 = this; + _optionEx(config, flags, description, fn, defaultValue) { + const option = new Option(flags, description); + const oname = option.name(); + const name = option.attributeName(); + option.mandatory = !!config.mandatory; - return _asyncToGenerator(function* () { - yield _this6.yieldLoop(); - return _this6._done; - })(); - } + this._checkForOptionNameClash(option); - __groupCheck__(time) { - var _this7 = this; + // 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; + } + } - return _asyncToGenerator(function* () { - yield _this7.yieldLoop(); - return _this7._nextRequest + _this7.timeout < time; - })(); - } + // 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; + } + } - computeCapacity() { - var maxConcurrent, reservoir; - var _this$storeOptions = this.storeOptions; - maxConcurrent = _this$storeOptions.maxConcurrent; - reservoir = _this$storeOptions.reservoir; + // register the option + this.options.push(option); - 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; - } - } + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, (val) => { + const oldValue = this._getOptionValue(name); - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return capacity == null || weight <= capacity; - } + // 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); + } + } - __incrementReservoir__(incr) { - var _this8 = this; + // 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); + } + }); - return _asyncToGenerator(function* () { - var reservoir; - yield _this8.yieldLoop(); - reservoir = _this8.storeOptions.reservoir += incr; + return this; + }; - _this8.instance._drainAll(_this8.computeCapacity()); + /** + * 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 + */ - return reservoir; - })(); - } + option(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); + }; - __currentReservoir__() { - var _this9 = this; + /** + * 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 + */ - return _asyncToGenerator(function* () { - yield _this9.yieldLoop(); - return _this9.storeOptions.reservoir; - })(); - } + requiredOption(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); + }; - isBlocked(now) { - return this._unblockTime >= now; - } + /** + * 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; + }; - check(weight, now) { - return this.conditionsCheck(weight) && this._nextRequest - now <= 0; - } + /** + * 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; + }; - __check__(weight) { - var _this10 = 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 + */ - return _asyncToGenerator(function* () { - var now; - yield _this10.yieldLoop(); - now = Date.now(); - return _this10.check(weight, now); - })(); - } + storeOptionsAsProperties(value) { + this._storeOptionsAsPropertiesCalled = true; + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + throw new Error('call .storeOptionsAsProperties() before adding options'); + } + return this; + }; - __register__(index, weight, expiration) { - var _this11 = this; + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ - return _asyncToGenerator(function* () { - var now, wait; - yield _this11.yieldLoop(); - now = Date.now(); + passCommandToAction(value) { + this._passCommandToAction = (value === undefined) || value; + return this; + }; - if (_this11.conditionsCheck(weight)) { - _this11._running += weight; + /** + * Store option value + * + * @param {string} key + * @param {Object} value + * @api private + */ - if (_this11.storeOptions.reservoir != null) { - _this11.storeOptions.reservoir -= weight; - } + _setOptionValue(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } + }; - 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 - }; - } - })(); - } + /** + * Retrieve option value + * + * @param {string} key + * @return {Object} value + * @api private + */ - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } + _getOptionValue(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; + }; - __submit__(queueLength, weight) { - var _this12 = this; + /** + * 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 + */ - return _asyncToGenerator(function* () { - var blocked, now, reachedHWM; - yield _this12.yieldLoop(); + parse(argv, parseOptions) { + if (argv !== undefined && !Array.isArray(argv)) { + throw new Error('first parameter to parse must be array or undefined'); + } + parseOptions = parseOptions || {}; - 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}`); + // 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(); - 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; + // 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; + } - _this12.instance._dropAllQueued(); - } + // Guess name, used in usage in help. + this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); - return { - reachedHWM, - blocked, - strategy: _this12.storeOptions.strategy - }; - })(); - } + // Let's go! + this._parseCommand([], userArgs); - __free__(index, weight) { - var _this13 = this; + return this; + }; - return _asyncToGenerator(function* () { - yield _this13.yieldLoop(); - _this13._running -= weight; - _this13._done += weight; + /** + * 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 + */ - _this13.instance._drainAll(_this13.computeCapacity()); + parseAsync(argv, parseOptions) { + this.parse(argv, parseOptions); + return Promise.all(this._actionResults).then(() => this); + }; - return { - running: _this13._running - }; - })(); - } + /** + * Execute a sub-command executable. + * + * @api private + */ -}; -module.exports = LocalDatastore; + _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']; -/***/ }), + // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. + this._checkForMissingMandatoryOptions(); -/***/ 65893: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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; + } -"use strict"; + let baseDir; + try { + const resolvedLink = fs.realpathSync(scriptPath); + baseDir = path.dirname(resolvedLink); + } catch (e) { + baseDir = '.'; // dummy, probably not going to find executable! + } + // name of the subcommand, like `pm-install` + let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; + if (subcommand._executableFile) { + bin = subcommand._executableFile; + } -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; + 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}`; + } + }); + } + launchWithNode = sourceExt.includes(path.extname(bin)); - this._lists = function () { - var j, ref, results; - results = []; + let proc; + if (process.platform !== 'win32') { + if (launchWithNode) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); - for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { - results.push(new DLList(this)); + 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' }); + } - return results; - }.call(this); - } + 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); + } + }); + }); - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); + // 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)')); + }); } - } + 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); + } + }); - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } + // Store the reference to the child process + this.runningCommand = proc; + }; - push(priority, job) { - return this._lists[priority].push(job); - } + /** + * @api private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this._helpAndError(); - queued(priority) { - if (priority != null) { - return this._lists[priority].length; + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); } else { - return this._length; + subCommand._parseCommand(operands, unknown); } - } + }; - shiftAll(fn) { - return this._lists.forEach(function (list) { - return list.forEachShift(fn); - }); - } + /** + * 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 { + this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); + } + } 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(); + } - getFirst(arr = this._lists) { - var j, len, list; + outputHelpIfRequested(this, parsed.unknown); + this._checkForMissingMandatoryOptions(); + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); + } - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; + 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); + } + }); - if (list.length > 0) { - return list; + 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() } } + }; - return []; - } + /** + * Find matching command. + * + * @api private + */ + _findCommand(name) { + if (!name) return undefined; + return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); + }; - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @api private + */ -}; -module.exports = Queues; + _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 + */ -/***/ 29992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _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); + } + }); + } + }; -"use strict"; + /** + * 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 + */ + 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(); -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 maybeOption(arg) { + return arg.length > 1 && arg[0] === '-'; + } -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); }); }; } + // parse options + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); -var Events, RedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); + // literal + if (arg === '--') { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } -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 + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; - parser.load(options, this.defaults, this); + 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; + } + } - if (this.Events == null) { - this.Events = new Events(this); + // 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; + } } - this.terminated = false; + // 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; + } + } - if (this.client == null) { - this.client = Redis.createClient(this.clientOptions); + // looks like an option but unknown, unknowns from here + if (arg.length > 1 && arg[0] === '-') { + dest = unknown; } - 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 - }; - }); + // add arg + dest.push(arg); } - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); + return { operands, unknown }; + }; - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } + /** + * 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; - if (client.ready) { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); + for (let i = 0; i < len; i++) { + const key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; } - _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); - } + return this._optionValues; + }; - this.shas[name] = replies[0]; - return resolve(replies[0]); - }); - }); - } + /** + * Argument `name` is missing. + * + * @param {string} name + * @api private + */ - _loadScripts() { - return this.Promise.all(Scripts.names.map(k => { - return this._loadScript(k); - })); - } + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); + }; - __runCommand__(cmd) { - var _this = this; + /** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {string} [flag] + * @api private + */ - 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]); - } - }); - }); - })(); + 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); + }; - __addLimiter__(instance) { - return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { - return new this.Promise((resolve, reject) => { - var handler; + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ - handler = chan => { - if (chan === channel) { - this.subscriber.removeListener("subscribe", handler); - this.limiters[channel] = instance; - return resolve(); - } - }; + missingMandatoryOptionValue(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); + }; - this.subscriber.on("subscribe", handler); - return this.subscriber.subscribe(channel); - }); - })); + /** + * Unknown option `flag`. + * + * @param {string} flag + * @api private + */ + + unknownOption(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); + }; + + /** + * Unknown command. + * + * @api private + */ + + 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); + }; - __removeLimiter__(instance) { - var _this2 = this; + /** + * 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 + */ - 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); - } + 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; + }; - if (chan === channel) { - return resolve(); - } - }); - }); - } + /** + * Set the description to `str`. + * + * @param {string} str + * @param {Object} [argsDescription] + * @return {string|Command} + * @api public + */ - return delete _this2.limiters[channel]; - }); + description(str, argsDescription) { + if (str === undefined && argsDescription === undefined) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; + }; - return function (_x) { - return _ref.apply(this, arguments); - }; - }())); - } + /** + * 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 + */ - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [this.shas[name], keys.length].concat(keys, args, cb); - } + alias(alias) { + if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility - __scriptFn__(name) { - return this.client.evalsha.bind(this.client); + 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]; } - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); - } + command._aliases.push(alias); + return this; + }; - this.limiters = {}; - this.terminated = true; - this.client.end(flush); - this.subscriber.end(flush); - return this.Promise.resolve(); + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {string[]|Command} + * @api public + */ + + 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; + + aliases.forEach((alias) => this.alias(alias)); + return this; + }; + + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ + + usage(str) { + if (str === undefined) { + if (this._usage) return this._usage; + + 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(' '); } - } + this._usage = str; + return this; + }; - ; - RedisConnection.prototype.datastore = "redis"; - RedisConnection.prototype.defaults = { - clientOptions: {}, - client: null, - Promise: Promise, - Events: null + /** + * Get or set the name of the command + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ + + name(str) { + if (str === undefined) return this._name; + this._name = str; + return this; }; - return RedisConnection; -}.call(void 0); -module.exports = RedisConnection; + /** + * 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(' '); -/***/ 4946: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return [ + cmd._name + + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); -"use strict"; + if (this._lazyHasImplicitHelpCommand()) { + commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); + } + return commandDetails; + }; + /** + * Return the largest command length. + * + * @return {number} + * @api private + */ -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + largestCommandLength() { + const commands = this.prepareCommands(); + return commands.reduce((max, command) => { + return Math.max(max, command[0].length); + }, 0); + }; -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + /** + * Return the largest option length. + * + * @return {number} + * @api private + */ -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; } + largestOptionLength() { + const options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + return options.reduce((max, option) => { + return Math.max(max, option.flags.length); + }, 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); } } + /** + * Return the largest arg length. + * + * @return {number} + * @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); }); }; } + largestArgLength() { + return this._args.reduce((max, arg) => { + return Math.max(max, arg.name.length); + }, 0); + }; -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; + /** + * Return the pad width. + * + * @return {number} + * @api private + */ - 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; + padWidth() { + let width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } } - 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(); + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); } + } - return this.clients; - }); - } - - __publish__(message) { - var _this = this; + return width; + }; - return _asyncToGenerator(function* () { - var client; + /** + * Return help for options. + * + * @return {string} + * @api private + */ - var _ref = yield _this.ready; + 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); + }; - client = _ref.client; - return client.publish(_this.instance.channel(), `message:${message.toString()}`); - })(); - } + // 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); + }); - onMessage(channel, message) { - var _this2 = this; + // 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)); + } - return _asyncToGenerator(function* () { - var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; + return help.join('\n'); + }; - try { - pos = message.indexOf(":"); - var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; - type = _ref2[0]; - data = _ref2[1]; + /** + * Return command help documentation. + * + * @return {string} + * @api private + */ - if (type === "capacity") { - return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); - } else if (type === "capacity-priority") { - var _data$split = data.split(":"); + commandHelp() { + if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; - var _data$split2 = _slicedToArray(_data$split, 3); + const commands = this.prepareCommands(); + const width = this.padWidth(); - rawCapacity = _data$split2[0]; - priorityClient = _data$split2[1]; - counter = _data$split2[2]; - capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; - 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; + 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'); + }; - 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); - } - })(); - } + /** + * Return program help documentation. + * + * @return {string} + * @api public + */ - __disconnect__(flush) { - clearInterval(this.heartbeat); + helpInformation() { + let desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; - if (this.sharedConnection) { - return this.connection.__removeLimiter__(this.instance); - } else { - return this.connection.disconnect(flush); + 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(''); + } } - } - runScript(name, args) { - var _this3 = this; + 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(), + '' + ]; - return _asyncToGenerator(function* () { - if (!(name === "init" || name === "register_client")) { - yield _this3.ready; - } + let cmds = []; + const commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; - return new _this3.Promise((resolve, reject) => { - var all_args, arr; - all_args = [Date.now(), _this3.clientId].concat(args); + let options = []; + if (this._hasHelpOption || this.options.length > 0) { + options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + } - _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); + }; - arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { - if (err != null) { - return reject(err); - } + /** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public + */ - 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); - } - }); - })(); - } + 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); + }; - prepareArray(arr) { - var i, len, results, x; - results = []; + /** + * 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 + */ - for (i = 0, len = arr.length; i < len; i++) { - x = arr[i]; - results.push(x != null ? x.toString() : ""); + helpOption(flags, description) { + if (typeof flags === 'boolean') { + this._hasHelpOption = flags; + return this; } + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; - return results; - } + const helpFlags = _parseOptionFlags(this._helpFlags); + this._helpShortFlag = helpFlags.shortFlag; + this._helpLongFlag = helpFlags.longFlag; - prepareObject(obj) { - var arr, k, v; - arr = []; + return this; + }; - for (k in obj) { - v = obj[k]; - arr.push(k, v != null ? v.toString() : ""); - } + /** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ - return arr; - } + 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)'); + }; - 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; - } + /** + * Output help information and exit. Display for error situations. + * + * @api private + */ - convertBool(b) { - return !!b; - } + _helpAndError() { + this.outputHelp(); + // message: do not have all displayed text available so only passing placeholder. + this._exit(1, 'commander.help', '(outputHelp)'); + }; +}; - __updateSettings__(options) { - var _this4 = this; +/** + * Expose the root command. + */ - return _asyncToGenerator(function* () { - yield _this4.runScript("update_settings", _this4.prepareObject(options)); - return parser.overwrite(options, options, _this4.storeOptions); - })(); - } +exports = module.exports = new Command(); +exports.program = exports; // More explicit access to global command. - __running__() { - return this.runScript("running", []); - } +/** + * Expose classes + */ - __queued__() { - return this.runScript("queued", []); - } +exports.Command = Command; +exports.Option = Option; +exports.CommanderError = CommanderError; - __done__() { - return this.runScript("done", []); - } +/** + * Camel-case the given `flag` + * + * @param {string} flag + * @return {string} + * @api private + */ - __groupCheck__() { - var _this5 = this; +function camelcase(flag) { + return flag.split('-').reduce((str, word) => { + return str + word[0].toUpperCase() + word.slice(1); + }); +} - return _asyncToGenerator(function* () { - return _this5.convertBool((yield _this5.runScript("group_check", []))); - })(); - } +/** + * Pad `str` to `width`. + * + * @param {string} str + * @param {number} width + * @return {string} + * @api private + */ + +function pad(str, width) { + const len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} - __incrementReservoir__(incr) { - return this.runScript("increment_reservoir", [incr]); - } +/** + * 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 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'); +} - __currentReservoir__() { - return this.runScript("current_reservoir", []); - } +/** + * 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; - __check__(weight) { - var _this6 = this; + return wrap(str, width, indent); +} - return _asyncToGenerator(function* () { - return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); - })(); +/** + * 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 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)'); } +} - __register__(index, weight, expiration) { - var _this7 = this; +/** + * Takes an argument and returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {string} + * @api private + */ - return _asyncToGenerator(function* () { - var reservoir, success, wait; +function humanReadableArgName(arg) { + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); - var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; +} - var _ref5 = _slicedToArray(_ref4, 3); +/** + * Parse the short and long flag out of something like '-m,--mixed ' + * + * @api private + */ - success = _ref5[0]; - wait = _ref5[1]; - reservoir = _ref5[2]; - return { - success: _this7.convertBool(success), - wait, - reservoir - }; - })(); +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; } + return { shortFlag, longFlag }; +} - __submit__(queueLength, weight) { - var _this8 = this; +/** + * 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 + */ - return _asyncToGenerator(function* () { - var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; +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]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; + } - try { - var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); + if (debugOption && debugPort !== '0') { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + return arg; + }); +} - 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; +/***/ }), - if (e.message.indexOf("OVERWEIGHT") === 0) { - var _e$message$split = e.message.split(":"); +/***/ 3598: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - var _e$message$split2 = _slicedToArray(_e$message$split, 3); - 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; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultApp = void 0; +const path_1 = __importDefault(__nccwpck_require__(71017)); +function defaultApp(app, { getRouter }) { + if (!getRouter) { + throw new Error("getRouter() is required for defaultApp"); + } + const router = getRouter(); + router.get("/probot", (req, res) => { + let pkg; + try { + pkg = require(path_1.default.join(process.cwd(), "package.json")); } - } - })(); - } + catch (e) { + pkg = {}; + } + res.render("probot.hbs", pkg); + }); + router.get("/", (req, res, next) => res.redirect("/probot")); +} +exports.defaultApp = defaultApp; +//# sourceMappingURL=default.js.map - __free__(index, weight) { - var _this9 = this; +/***/ }), + +/***/ 36769: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return _asyncToGenerator(function* () { - var running; - running = yield _this9.runScript("free", _this9.prepareArray([index])); - return { - running - }; - })(); - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; -module.exports = RedisDatastore; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.setupAppFactory = void 0; +const body_parser_1 = __importDefault(__nccwpck_require__(97076)); +const child_process_1 = __nccwpck_require__(32081); +const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); +const manifest_creation_1 = __nccwpck_require__(18785); +const logging_middleware_1 = __nccwpck_require__(24631); +const is_production_1 = __nccwpck_require__(75381); +const setupAppFactory = (host, port) => async function setupApp(app, { getRouter }) { + const setup = new manifest_creation_1.ManifestCreation(); + // If not on Glitch or Production, create a smee URL + if (!is_production_1.isProduction() && + !(process.env.PROJECT_DOMAIN || + process.env.WEBHOOK_PROXY_URL || + process.env.NO_SMEE_SETUP === "true")) { + await setup.createWebhookChannel(); + } + if (!getRouter) { + throw new Error("getRouter is required to use the setup app"); + } + const route = getRouter(); + route.use(logging_middleware_1.getLoggingMiddleware(app.log)); + printWelcomeMessage(app, host, port); + route.get("/probot", async (req, res) => { + const baseUrl = getBaseUrl(req); + const pkg = setup.pkg; + const manifest = setup.getManifest(pkg, baseUrl); + const createAppUrl = setup.createAppUrl; + // Pass the manifest to be POST'd + res.render("setup.hbs", { pkg, createAppUrl, manifest }); + }); + route.get("/probot/setup", async (req, res) => { + const { code } = req.query; + const response = await setup.createAppFromCode(code); + // If using glitch, restart the app + if (process.env.PROJECT_DOMAIN) { + child_process_1.exec("refresh", (error) => { + if (error) { + app.log.error(error); + } + }); + } + else { + printRestartMessage(app); + } + res.redirect(`${response}/installations/new`); + }); + route.get("/probot/import", async (_req, res) => { + const { WEBHOOK_PROXY_URL, GHE_HOST } = process.env; + const GH_HOST = `https://${GHE_HOST !== null && GHE_HOST !== void 0 ? GHE_HOST : "github.com"}`; + res.render("import.hbs", { WEBHOOK_PROXY_URL, GH_HOST }); + }); + route.post("/probot/import", body_parser_1.default.json(), async (req, res) => { + const { appId, pem, webhook_secret } = req.body; + if (!appId || !pem || !webhook_secret) { + res.status(400).send("appId and/or pem and/or webhook_secret missing"); + return; + } + update_dotenv_1.default({ + APP_ID: appId, + PRIVATE_KEY: `"${pem}"`, + WEBHOOK_SECRET: webhook_secret, + }); + res.end(); + printRestartMessage(app); + }); + route.get("/probot/success", async (req, res) => { + res.render("success.hbs"); + }); + route.get("/", (req, res, next) => res.redirect("/probot")); +}; +exports.setupAppFactory = setupAppFactory; +function printWelcomeMessage(app, host, port) { + // use glitch env to get correct domain welcome message + // https://glitch.com/help/project/ + const domain = process.env.PROJECT_DOMAIN || + `http://${host !== null && host !== void 0 ? host : "localhost"}:${port || 3000}`; + [ + ``, + `Welcome to Probot!`, + `Probot is in setup mode, webhooks cannot be received and`, + `custom routes will not work until APP_ID and PRIVATE_KEY`, + `are configured in .env.`, + `Please follow the instructions at ${domain} to configure .env.`, + `Once you are done, restart the server.`, + ``, + ].forEach((line) => { + app.log.info(line); + }); +} +function printRestartMessage(app) { + app.log.info(""); + app.log.info("Probot has been set up, please restart the server!"); + app.log.info(""); +} +function getBaseUrl(req) { + const protocols = req.headers["x-forwarded-proto"] || req.protocol; + const protocol = typeof protocols === "string" ? protocols.split(",")[0] : protocols[0]; + const host = req.headers["x-forwarded-host"] || req.get("host"); + const baseUrl = `${protocol}://${host}`; + return baseUrl; +} +//# sourceMappingURL=setup.js.map /***/ }), -/***/ 4169: +/***/ 81084: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - -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"] -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.auth = void 0; +const get_authenticated_octokit_1 = __nccwpck_require__(53535); +/** + * Authenticate and get a GitHub client that can be used to make API calls. + * + * You'll probably want to use `context.octokit` instead. + * + * **Note**: `app.auth` is asynchronous, so it needs to be prefixed with a + * [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) + * to wait for the magic to happen. + * + * ```js + * module.exports = (app) => { + * app.on('issues.opened', async context => { + * const octokit = await app.auth(); + * }); + * }; + * ``` + * + * @param id - ID of the installation, which can be extracted from + * `context.payload.installation.id`. If called without this parameter, the + * client wil authenticate [as the app](https://docs.github.com/en/developers/apps/authenticating-with-github-apps#authenticating-as-a-github-app) + * instead of as a specific installation, which means it can only be used for + * [app APIs](https://docs.github.com/apps/). + * + * @returns An authenticated GitHub API client + */ +async function auth(state, installationId, log) { + return get_authenticated_octokit_1.getAuthenticatedOctokit(Object.assign({}, state, log ? { log } : null), installationId); +} +exports.auth = auth; +//# sourceMappingURL=auth.js.map -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`]; -}; +/***/ }), -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); +/***/ 57767: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -exports.keys = function (name, id) { - return templates[name].keys(id); -}; -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"); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readCliOptions = void 0; +const commander_1 = __importDefault(__nccwpck_require__(36267)); +const get_private_key_1 = __nccwpck_require__(97743); +function readCliOptions(argv) { + commander_1.default + .usage("[options] ") + .option("-p, --port ", "Port to start the server on", String(process.env.PORT || 3000)) + .option("-H --host ", "Host to start the server on", process.env.HOST) + .option("-W, --webhook-proxy ", "URL of the webhook proxy service.`", process.env.WEBHOOK_PROXY_URL) + .option("-w, --webhook-path ", "URL path which receives webhooks. Ex: `/webhook`", process.env.WEBHOOK_PATH) + .option("-a, --app ", "ID of the GitHub App", process.env.APP_ID) + .option("-s, --secret ", "Webhook secret of the GitHub App", process.env.WEBHOOK_SECRET) + .option("-P, --private-key ", "Path to private key file (.pem) for the GitHub App", process.env.PRIVATE_KEY_PATH) + .option("-L, --log-level ", 'One of: "trace" | "debug" | "info" | "warn" | "error" | "fatal"', process.env.LOG_LEVEL || "info") + .option("--log-format ", 'One of: "pretty", "json"', process.env.LOG_FORMAT) + .option("--log-level-in-string", "Set to log levels (trace, debug, info, ...) as words instead of numbers (10, 20, 30, ...)", process.env.LOG_LEVEL_IN_STRING === "true") + .option("--sentry-dsn ", 'Set to your Sentry DSN, e.g. "https://1234abcd@sentry.io/12345"', process.env.SENTRY_DSN) + .option("--redis-url ", 'Set to a "redis://" url in order to enable cluster support for request throttling. Example: "redis://:secret@redis-123.redislabs.com:12345/0"', process.env.REDIS_URL) + .option("--base-url ", 'GitHub API base URL. If you use GitHub Enterprise Server, and your hostname is "https://github.acme-inc.com", then the root URL is "https://github.acme-inc.com/api/v3"', process.env.GHE_HOST + ? `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3` + : "https://api.github.com") + .parse(argv); + const { app: appId, privateKey: privateKeyPath, redisUrl, ...options } = commander_1.default; + return { + privateKey: get_private_key_1.getPrivateKey({ filepath: privateKeyPath }) || undefined, + appId, + redisConfig: redisUrl, + ...options, + }; +} +exports.readCliOptions = readCliOptions; +//# sourceMappingURL=read-cli-options.js.map /***/ }), -/***/ 2527: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 74420: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readEnvOptions = void 0; +const get_private_key_1 = __nccwpck_require__(97743); +function readEnvOptions(env = process.env) { + const privateKey = get_private_key_1.getPrivateKey({ env }); + const logFormat = env.LOG_FORMAT || (env.NODE_ENV === "production" ? "json" : "pretty"); + return { + args: [], + privateKey: (privateKey && privateKey.toString()) || undefined, + appId: Number(env.APP_ID), + port: Number(env.PORT) || 3000, + host: env.HOST, + secret: env.WEBHOOK_SECRET, + webhookPath: env.WEBHOOK_PATH, + webhookProxy: env.WEBHOOK_PROXY_URL, + logLevel: env.LOG_LEVEL, + logFormat: logFormat, + logLevelInString: env.LOG_LEVEL_IN_STRING === "true", + logMessageKey: env.LOG_MESSAGE_KEY, + sentryDsn: env.SENTRY_DSN, + redisConfig: env.REDIS_URL, + baseUrl: env.GHE_HOST + ? `${env.GHE_PROTOCOL || "https"}://${env.GHE_HOST}/api/v3` + : "https://api.github.com", + }; +} +exports.readEnvOptions = readEnvOptions; +//# sourceMappingURL=read-env-options.js.map -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; - }); - } +/***/ }), - next(id) { - var current, next; - current = this.jobs[id]; - next = current + 1; +/***/ 45006: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - 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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const path_1 = __importDefault(__nccwpck_require__(71017)); +const deepmerge_1 = __importDefault(__nccwpck_require__(56323)); +const alias_log_1 = __nccwpck_require__(19752); +/** + * The context of the event that was triggered, including the payload and + * helpers for extracting information can be passed to GitHub API calls. + * + * ```js + * module.exports = app => { + * app.on('push', context => { + * context.log.info('Code was pushed to the repo, what should we do with it?'); + * }); + * }; + * ``` + * + * @property {octokit} octokit - An Octokit instance + * @property {payload} payload - The webhook event payload + * @property {log} log - A pino instance + */ +class Context { + constructor(event, octokit, log) { + this.name = event.name; + this.id = event.id; + this.payload = event.payload; + this.octokit = octokit; + this.log = alias_log_1.aliasLog(log); } - } + /** + * Return the `owner` and `repo` params for making API requests against a + * repository. + * + * ```js + * const params = context.repo({path: '.github/config.yml'}) + * // Returns: {owner: 'username', repo: 'reponame', path: '.github/config.yml'} + * ``` + * + * @param object - Params to be merged with the repo params. + * + */ + repo(object) { + // @ts-ignore `repository` is not always present in this.payload + const repo = this.payload.repository; + if (!repo) { + throw new Error("context.repo() is not supported for this webhook event."); + } + return Object.assign({ + owner: repo.owner.login, + repo: repo.name, + }, object); + } + /** + * Return the `owner`, `repo`, and `issue_number` params for making API requests + * against an issue. The object passed in will be merged with the repo params. + * + * + * ```js + * const params = context.issue({body: 'Hello World!'}) + * // Returns: {owner: 'username', repo: 'reponame', issue_number: 123, body: 'Hello World!'} + * ``` + * + * @param object - Params to be merged with the issue params. + */ + issue(object) { + return Object.assign({ + issue_number: + // @ts-ignore - this.payload may not have `issue` or `pull_request` keys + (this.payload.issue || this.payload.pull_request || this.payload) + .number, + }, this.repo(object)); + } + /** + * Return the `owner`, `repo`, and `pull_number` params for making API requests + * against a pull request. The object passed in will be merged with the repo params. + * + * + * ```js + * const params = context.pullRequest({body: 'Hello World!'}) + * // Returns: {owner: 'username', repo: 'reponame', pull_number: 123, body: 'Hello World!'} + * ``` + * + * @param object - Params to be merged with the pull request params. + */ + pullRequest(object) { + const payload = this.payload; + return Object.assign({ + // @ts-ignore - this.payload may not have `issue` or `pull_request` keys + pull_number: (payload.issue || payload.pull_request || payload).number, + }, this.repo(object)); + } + /** + * Returns a boolean if the actor on the event was a bot. + * @type {boolean} + */ + get isBot() { + // @ts-expect-error - `sender` key is currently not present in all events + // see https://github.com/octokit/webhooks/issues/510 + return this.payload.sender.type === "Bot"; + } + /** + * Reads the app configuration from the given YAML file in the `.github` + * directory of the repository. + * + * For example, given a file named `.github/config.yml`: + * + * ```yml + * close: true + * comment: Check the specs on the rotary girder. + * ``` + * + * Your app can read that file from the target repository: + * + * ```js + * // Load config from .github/config.yml in the repository + * const config = await context.config('config.yml') + * + * if (config.close) { + * context.octokit.issues.comment(context.issue({body: config.comment})) + * context.octokit.issues.edit(context.issue({state: 'closed'})) + * } + * ``` + * + * You can also use a `defaultConfig` object: + * + * ```js + * // Load config from .github/config.yml in the repository and combine with default config + * const config = await context.config('config.yml', {comment: 'Make sure to check all the specs.'}) + * + * if (config.close) { + * context.octokit.issues.comment(context.issue({body: config.comment})); + * context.octokit.issues.edit(context.issue({state: 'closed'})) + * } + * ``` + * + * Config files can also specify a base that they extend. `deepMergeOptions` can be used + * to configure how the target config, extended base, and default configs are merged. + * + * For security reasons, configuration is only loaded from the repository's default branch, + * changes made in pull requests from different branches or forks are ignored. + * + * If you need more lower-level control over reading and merging configuration files, + * you can `context.octokit.config.get(options)`, see https://github.com/probot/octokit-plugin-config. + * + * @param fileName - Name of the YAML file in the `.github` directory + * @param defaultConfig - An object of default config options + * @param deepMergeOptions - Controls merging configs (from the [deepmerge](https://github.com/TehShrike/deepmerge) module) + * @return Configuration object read from the file + */ + async config(fileName, defaultConfig, deepMergeOptions) { + const params = this.repo({ + path: path_1.default.posix.join(".github", fileName), + defaults(configs) { + const result = deepmerge_1.default.all([defaultConfig || {}, ...configs], deepMergeOptions); + return result; + }, + }); + // @ts-ignore + const { config, files } = await this.octokit.config.get(params); + // if no default config is set, and no config files are found, return null + if (!defaultConfig && !files.find((file) => file.config !== null)) { + return null; + } + return config; + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map - start(id) { - var initial; - initial = 0; - this.jobs[id] = initial; - return this.counts[initial]++; - } +/***/ }), - remove(id) { - var current; - current = this.jobs[id]; +/***/ 44488: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (current != null) { - this.counts[current]--; - delete this.jobs[id]; - } - return current != null; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createNodeMiddleware = void 0; +const webhooks_1 = __nccwpck_require__(18513); +function createNodeMiddleware(appFn, { probot, webhooksPath }) { + probot.load(appFn); + return webhooks_1.createNodeMiddleware(probot.webhooks, { + path: webhooksPath || "/", + }); +} +exports.createNodeMiddleware = createNodeMiddleware; +//# sourceMappingURL=create-node-middleware.js.map - jobStatus(id) { - var ref; - return (ref = this.status[this.jobs[id]]) != null ? ref : null; - } +/***/ }), - statusJobs(status) { - var k, pos, ref, results, v; +/***/ 52728: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createProbot = void 0; +const get_private_key_1 = __nccwpck_require__(97743); +const get_log_1 = __nccwpck_require__(90751); +const probot_1 = __nccwpck_require__(22357); +const DEFAULTS = { + APP_ID: "", + WEBHOOK_SECRET: "", + GHE_HOST: "", + GHE_PROTOCOL: "", + LOG_FORMAT: "", + LOG_LEVEL: "warn", + LOG_LEVEL_IN_STRING: "", + LOG_MESSAGE_KEY: "msg", + REDIS_URL: "", + SENTRY_DSN: "", +}; +/** + * Merges configuration from defaults/environment variables/overrides and returns + * a Probot instance. Finds private key using [`@probot/get-private-key`](https://github.com/probot/get-private-key). + * + * @see https://probot.github.io/docs/configuration/ + * @param defaults default Options, will be overwritten if according environment variable is set + * @param overrides overwrites defaults and according environment variables + * @param env defaults to process.env + */ +function createProbot({ overrides = {}, defaults = {}, env = process.env, } = {}) { + const privateKey = get_private_key_1.getPrivateKey({ env }); + const envWithDefaults = { ...DEFAULTS, ...env }; + const envOptions = { + logLevel: envWithDefaults.LOG_LEVEL, + appId: Number(envWithDefaults.APP_ID), + privateKey: (privateKey && privateKey.toString()) || undefined, + secret: envWithDefaults.WEBHOOK_SECRET, + redisConfig: envWithDefaults.REDIS_URL, + baseUrl: envWithDefaults.GHE_HOST + ? `${envWithDefaults.GHE_PROTOCOL || "https"}://${envWithDefaults.GHE_HOST}/api/v3` + : "https://api.github.com", + }; + const probotOptions = { + ...defaults, + ...envOptions, + ...overrides, + }; + const logOptions = { + level: probotOptions.logLevel, + logFormat: envWithDefaults.LOG_FORMAT, + logLevelInString: envWithDefaults.LOG_LEVEL_IN_STRING === "true", + logMessageKey: envWithDefaults.LOG_MESSAGE_KEY, + sentryDsn: envWithDefaults.SENTRY_DSN, + }; + const log = get_log_1.getLog(logOptions).child({ name: "server" }); + return new probot_1.Probot({ + log: log.child({ name: "probot" }), + ...probotOptions, + }); +} +exports.createProbot = createProbot; +//# sourceMappingURL=create-probot.js.map - ref = this.jobs; - results = []; +/***/ }), - for (k in ref) { - v = ref[k]; +/***/ 19752: +/***/ ((__unused_webpack_module, exports) => { - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this.jobs); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.aliasLog = void 0; +/** + * `probot.log()`, `app.log()` and `context.log()` are aliasing `.log.info()`. + * We will probably remove the aliasing in future. + */ +function aliasLog(log) { + function logInfo() { + // @ts-ignore + log.info(...arguments); } - } - - statusCounts() { - return this.counts.reduce((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }, {}); - } - -}; -module.exports = States; + for (const key in log) { + // @ts-ignore + logInfo[key] = + typeof log[key] === "function" ? log[key].bind(log) : log[key]; + } + // @ts-ignore + return logInfo; +} +exports.aliasLog = aliasLog; +//# sourceMappingURL=alias-log.js.map /***/ }), -/***/ 56029: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 5789: +/***/ ((__unused_webpack_module, exports) => { -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getErrorHandler = void 0; +function getErrorHandler(log) { + return (error) => { + const errors = (error.name === "AggregateError" ? error : [error]); + const event = error.event; + for (const error of errors) { + const errMessage = (error.message || "").toLowerCase(); + if (errMessage.includes("x-hub-signature-256")) { + log.error(error, "Go to https://github.com/settings/apps/YOUR_APP and verify that the Webhook secret matches the value of the WEBHOOK_SECRET environment variable."); + continue; + } + if (errMessage.includes("pem") || errMessage.includes("json web token")) { + log.error(error, "Your private key (a .pem file or PRIVATE_KEY environment variable) or APP_ID is incorrect. Go to https://github.com/settings/apps/YOUR_APP, verify that APP_ID is set correctly, and generate a new PEM file if necessary."); + continue; + } + log + .child({ + name: "event", + id: event ? event.id : undefined, + }) + .error(error); + } + }; +} +exports.getErrorHandler = getErrorHandler; +//# sourceMappingURL=get-error-handler.js.map -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(); } +/***/ 90751: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -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); } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getLog = void 0; +/** + * A logger backed by [pino](https://getpino.io/) + * + * The default log level is `info`, but you can change it passing a level + * string set to one of: `"trace"`, `"debug"`, `"info"`, `"warn"`, + * `"error"`, or `"fatal"`. + * + * ```js + * app.log.debug("…so is this"); + * app.log.trace("Now we're talking"); + * app.log.info("I thought you should know…"); + * app.log.warn("Woah there"); + * app.log.error("ETOOMANYLOGS"); + * app.log.fatal("Goodbye, cruel world!"); + * ``` + */ +const pino_1 = __importDefault(__nccwpck_require__(79608)); +const pino_2 = __nccwpck_require__(39662); +function getLog(options = {}) { + const { level, logMessageKey, ...getTransformStreamOptions } = options; + const pinoOptions = { + level: level || "info", + name: "probot", + messageKey: logMessageKey || "msg", + }; + const transform = pino_2.getTransformStream(getTransformStreamOptions); + // @ts-ignore TODO: check out what's wrong here + transform.pipe(pino_1.default.destination(1)); + const log = pino_1.default(pinoOptions, transform); + return log; +} +exports.getLog = getLog; +//# sourceMappingURL=get-log.js.map -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +/***/ }), -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(); - } +/***/ 75381: +/***/ ((__unused_webpack_module, exports) => { - isEmpty() { - return this._queue.length === 0; - } - _tryToRun() { - var next; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isProduction = void 0; +function isProduction() { + return process.env.NODE_ENV === "production"; +} +exports.isProduction = isProduction; +//# sourceMappingURL=is-production.js.map - if (this._running < 1 && this._queue.length > 0) { - this._running++; - next = this._queue.shift(); - return next.task(...next.args, (...args) => { - this._running--; +/***/ }), - this._tryToRun(); +/***/ 33208: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return typeof next.cb === "function" ? next.cb(...args) : void 0; - }); - } - } - submit(task, ...args) { - var _ref, _ref2, _splice$call, _splice$call2; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveAppFunction = void 0; +const resolve_1 = __nccwpck_require__(39283); +const defaultOptions = {}; +const resolveAppFunction = async (appFnId, opts) => { + opts = opts || defaultOptions; + // These are mostly to ease testing + const basedir = opts.basedir || process.cwd(); + const resolver = opts.resolver || resolve_1.sync; + const appFnPath = resolver(appFnId, { basedir }); + const mod = await Promise.resolve().then(() => __importStar(require(appFnPath))); + // Note: This needs "esModuleInterop" to be set to "true" in "tsconfig.json" + return mod.default; +}; +exports.resolveAppFunction = resolveAppFunction; +//# sourceMappingURL=resolve-app-function.js.map - 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); +/***/ }), - this._queue.push({ - task, - args, - cb - }); +/***/ 66217: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this._tryToRun(); - } - schedule(task, ...args) { - var wrapped; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createWebhookProxy = void 0; +const createWebhookProxy = (opts) => { + try { + const SmeeClient = __nccwpck_require__(22854); + const smee = new SmeeClient({ + logger: opts.logger, + source: opts.url, + target: `http://localhost:${opts.port}${opts.path}`, + }); + return smee.start(); + } + catch (error) { + opts.logger.warn("Run `npm install --save-dev smee-client` to proxy webhooks to localhost."); + return; + } +}; +exports.createWebhookProxy = createWebhookProxy; +//# sourceMappingURL=webhook-proxy.js.map - wrapped = function wrapped(...args) { - var _ref3, _ref4, _splice$call3, _splice$call4; +/***/ }), - 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); - }); - }; +/***/ 93181: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return new this.Promise((resolve, reject) => { - return this.submit(wrapped, ...args, function (...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }); - }); - } -}; -module.exports = Sync; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createProbot = exports.createNodeMiddleware = exports.Server = exports.Probot = exports.run = exports.ProbotOctokit = exports.Context = void 0; +const context_1 = __nccwpck_require__(45006); +Object.defineProperty(exports, "Context", ({ enumerable: true, get: function () { return context_1.Context; } })); +const probot_1 = __nccwpck_require__(22357); +Object.defineProperty(exports, "Probot", ({ enumerable: true, get: function () { return probot_1.Probot; } })); +const server_1 = __nccwpck_require__(83148); +Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); +const probot_octokit_1 = __nccwpck_require__(97268); +Object.defineProperty(exports, "ProbotOctokit", ({ enumerable: true, get: function () { return probot_octokit_1.ProbotOctokit; } })); +const run_1 = __nccwpck_require__(57124); +Object.defineProperty(exports, "run", ({ enumerable: true, get: function () { return run_1.run; } })); +const create_node_middleware_1 = __nccwpck_require__(44488); +Object.defineProperty(exports, "createNodeMiddleware", ({ enumerable: true, get: function () { return create_node_middleware_1.createNodeMiddleware; } })); +const create_probot_1 = __nccwpck_require__(52728); +Object.defineProperty(exports, "createProbot", ({ enumerable: true, get: function () { return create_probot_1.createProbot; } })); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 27356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 18785: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -module.exports = __nccwpck_require__(83911); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ManifestCreation = void 0; +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const js_yaml_1 = __importDefault(__nccwpck_require__(21917)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const update_dotenv_1 = __importDefault(__nccwpck_require__(51023)); +const probot_octokit_1 = __nccwpck_require__(97268); +class ManifestCreation { + get pkg() { + let pkg; + try { + pkg = require(path_1.default.join(process.cwd(), "package.json")); + } + catch (e) { + pkg = {}; + } + return pkg; + } + async createWebhookChannel() { + try { + // tslint:disable:no-var-requires + const SmeeClient = __nccwpck_require__(22854); + await this.updateEnv({ + WEBHOOK_PROXY_URL: await SmeeClient.createChannel(), + }); + } + catch (error) { + // Smee is not available, so we'll just move on + // tslint:disable:no-console + console.warn("Unable to connect to smee.io, try restarting your server."); + } + } + getManifest(pkg, baseUrl) { + let manifest = {}; + try { + const file = fs_1.default.readFileSync(path_1.default.join(process.cwd(), "app.yml"), "utf8"); + manifest = js_yaml_1.default.safeLoad(file); + } + catch (error) { + // App config does not exist, which is ok. + if (error.code !== "ENOENT") { + throw error; + } + } + const generatedManifest = JSON.stringify(Object.assign({ + description: manifest.description || pkg.description, + hook_attributes: { + url: process.env.WEBHOOK_PROXY_URL || `${baseUrl}/`, + }, + name: process.env.PROJECT_DOMAIN || manifest.name || pkg.name, + public: manifest.public || true, + redirect_url: `${baseUrl}/probot/setup`, + // TODO: add setup url + // setup_url:`${baseUrl}/probot/success`, + url: manifest.url || pkg.homepage || pkg.repository, + version: "v1", + }, manifest)); + return generatedManifest; + } + async createAppFromCode(code) { + const octokit = new probot_octokit_1.ProbotOctokit(); + const options = { + code, + mediaType: { + previews: ["fury"], // needed for GHES 2.20 and older + }, + ...(process.env.GHE_HOST && { + baseUrl: `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3`, + }), + }; + const response = await octokit.request("POST /app-manifests/:code/conversions", options); + const { id, client_id, client_secret, webhook_secret, pem } = response.data; + await this.updateEnv({ + APP_ID: id.toString(), + PRIVATE_KEY: `"${pem}"`, + WEBHOOK_SECRET: webhook_secret, + GITHUB_CLIENT_ID: client_id, + GITHUB_CLIENT_SECRET: client_secret, + }); + return response.data.html_url; + } + async updateEnv(env) { + // Needs to be public due to tests + return update_dotenv_1.default(env); + } + get createAppUrl() { + const githubHost = process.env.GHE_HOST || `github.com`; + return `${process.env.GHE_PROTOCOL || "https"}://${githubHost}/settings/apps/new`; + } +} +exports.ManifestCreation = ManifestCreation; +//# sourceMappingURL=manifest-creation.js.map /***/ }), -/***/ 67823: +/***/ 53535: /***/ ((__unused_webpack_module, exports) => { -"use strict"; - - -exports.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; -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAuthenticatedOctokit = void 0; +async function getAuthenticatedOctokit(state, installationId) { + const { log, octokit } = state; + if (!installationId) + return octokit; + return octokit.auth({ + type: "installation", + installationId, + factory: ({ octokit, octokitOptions, ...otherOptions }) => { + const pinoLog = log.child({ name: "github" }); + const options = { + ...octokitOptions, + log: { + fatal: pinoLog.fatal.bind(pinoLog), + error: pinoLog.error.bind(pinoLog), + warn: pinoLog.warn.bind(pinoLog), + info: pinoLog.info.bind(pinoLog), + debug: pinoLog.debug.bind(pinoLog), + trace: pinoLog.trace.bind(pinoLog), + }, + throttle: { + ...octokitOptions.throttle, + id: installationId, + }, + auth: { + ...octokitOptions.auth, + otherOptions, + installationId, + }, + }; + const Octokit = octokit.constructor; + return new Octokit(options); + }, + }); +} +exports.getAuthenticatedOctokit = getAuthenticatedOctokit; +//# sourceMappingURL=get-authenticated-octokit.js.map -exports.overwrite = function (received, defaults, onto = {}) { - var k, v; +/***/ }), - for (k in received) { - v = received[k]; +/***/ 51729: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitThrottleOptions = void 0; +const bottleneck_1 = __importDefault(__nccwpck_require__(27356)); +const ioredis_1 = __importDefault(__nccwpck_require__(45069)); +function getOctokitThrottleOptions(options) { + let { log, redisConfig } = options; + if (!redisConfig) + return; + const connection = new bottleneck_1.default.IORedisConnection({ + client: getRedisClient(options), + }); + connection.on("error", (error) => { + log.error(Object.assign(error, { source: "bottleneck" })); + }); + return { + Bottleneck: bottleneck_1.default, + connection, + }; +} +exports.getOctokitThrottleOptions = getOctokitThrottleOptions; +function getRedisClient({ log, redisConfig }) { + if (redisConfig) + return new ioredis_1.default(redisConfig); +} +//# sourceMappingURL=get-octokit-throttle-options.js.map /***/ }), -/***/ 11174: -/***/ (function(module) { +/***/ 1330: +/***/ ((__unused_webpack_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'; - var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getProbotOctokitWithDefaults = void 0; +const get_octokit_throttle_options_1 = __nccwpck_require__(51729); +/** + * Returns an Octokit instance with default settings for authentication. If + * a `githubToken` is passed explicitly, the Octokit instance will be + * pre-authenticated with that token when instantiated. Otherwise Octokit's + * app authentication strategy is used, and `options.auth` options are merged + * deeply when instantiated. + * + * Besides the authentication, the Octokit's baseUrl is set as well when run + * against a GitHub Enterprise Server with a custom domain. + */ +function getProbotOctokitWithDefaults(options) { + const authOptions = options.githubToken + ? { + token: options.githubToken, + } + : { + cache: options.cache, + appId: options.appId, + privateKey: options.privateKey, + }; + const octokitThrottleOptions = get_octokit_throttle_options_1.getOctokitThrottleOptions({ + log: options.log, + redisConfig: options.redisConfig, + }); + let defaultOptions = { + auth: authOptions, + }; + if (options.baseUrl) { + defaultOptions.baseUrl = options.baseUrl; + } + if (octokitThrottleOptions) { + defaultOptions.throttle = octokitThrottleOptions; + } + return options.Octokit.defaults((instanceOptions) => { + const options = Object.assign({}, defaultOptions, instanceOptions, { + auth: instanceOptions.auth + ? Object.assign({}, defaultOptions.auth, instanceOptions.auth) + : defaultOptions.auth, + }); + if (instanceOptions.throttle) { + options.throttle = Object.assign({}, defaultOptions.throttle, instanceOptions.throttle); + } + return options; + }); +} +exports.getProbotOctokitWithDefaults = getProbotOctokitWithDefaults; +//# sourceMappingURL=get-probot-octokit-with-defaults.js.map - function getCjsExportFromNamespace (n) { - return n && n.default || n; - } +/***/ }), - 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; - }; +/***/ 879: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; - var parser = { - load: load, - overwrite: overwrite - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getWebhooks = void 0; +const webhooks_1 = __nccwpck_require__(18513); +const get_error_handler_1 = __nccwpck_require__(5789); +const octokit_webhooks_transform_1 = __nccwpck_require__(16973); +// import { Context } from "../context"; +function getWebhooks(state) { + // TODO: This should be webhooks = new Webhooks({...}) but fails with + // > The context of the event that was triggered, including the payload and + // helpers for extracting information can be passed to GitHub API calls + const webhooks = new webhooks_1.Webhooks({ + secret: state.webhooks.secret, + transform: octokit_webhooks_transform_1.webhookTransform.bind(null, state), + }); + webhooks.onError(get_error_handler_1.getErrorHandler(state.log)); + return webhooks; +} +exports.getWebhooks = getWebhooks; +//# sourceMappingURL=get-webhooks.js.map - var DLList; +/***/ }), - DLList = class DLList { - constructor(_queues) { - this._queues = _queues; - this._first = null; - this._last = null; - this.length = 0; - } +/***/ 7828: +/***/ ((__unused_webpack_module, exports) => { - 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; - } - 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; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.probotRequestLogging = void 0; +function probotRequestLogging(octokit) { + octokit.hook.error("request", (error, options) => { + if ("status" in error) { + const { method, url, request, ...params } = octokit.request.endpoint.parse(options); + const msg = `GitHub request: ${method} ${url} - ${error.status}`; + // @ts-expect-error log.debug is a pino log method and accepts a fields object + octokit.log.debug(params.body || {}, msg); + } + throw error; + }); + octokit.hook.after("request", (result, options) => { + const { method, url, request, ...params } = octokit.request.endpoint.parse(options); + const msg = `GitHub request: ${method} ${url} - ${result.status}`; + // @ts-ignore log.debug is a pino log method and accepts a fields object + octokit.log.debug(params.body || {}, msg); + }); +} +exports.probotRequestLogging = probotRequestLogging; +//# sourceMappingURL=octokit-plugin-probot-request-logging.js.map - first() { - if (this._first != null) { - return this._first.value; - } - } +/***/ }), - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } +/***/ 16973: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.webhookTransform = void 0; +const context_1 = __nccwpck_require__(45006); +/** + * Probot's transform option, which extends the `event` object that is passed + * to webhook event handlers by `@octokit/webhooks` + * @see https://github.com/octokit/webhooks.js/#constructor + */ +async function webhookTransform(state, event) { + const log = state.log.child({ name: "event", id: event.id }); + const octokit = (await state.octokit.auth({ + type: "event-octokit", + event, + })); + return new context_1.Context(event, octokit, log); +} +exports.webhookTransform = webhookTransform; +//# sourceMappingURL=octokit-webhooks-transform.js.map - var DLList_1 = DLList; +/***/ }), - var Events; +/***/ 97268: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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 = {}; - } - }; - } - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProbotOctokit = void 0; +const core_1 = __nccwpck_require__(76762); +const plugin_enterprise_compatibility_1 = __nccwpck_require__(25823); +const plugin_paginate_rest_1 = __nccwpck_require__(64193); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); +const plugin_retry_1 = __nccwpck_require__(86298); +const plugin_throttling_1 = __nccwpck_require__(9968); +const octokit_plugin_config_1 = __nccwpck_require__(59326); +const octokit_auth_probot_1 = __nccwpck_require__(80536); +const octokit_plugin_probot_request_logging_1 = __nccwpck_require__(7828); +const version_1 = __nccwpck_require__(1403); +const defaultOptions = { + authStrategy: octokit_auth_probot_1.createProbotAuth, + throttle: { + onAbuseLimit: (retryAfter, options, octokit) => { + octokit.log.warn(`Abuse limit hit with "${options.method} ${options.url}", retrying in ${retryAfter} seconds.`); + return true; + }, + onRateLimit: (retryAfter, options, octokit) => { + octokit.log.warn(`Rate limit hit with "${options.method} ${options.url}", retrying in ${retryAfter} seconds.`); + return true; + }, + }, + userAgent: `probot/${version_1.VERSION}`, +}; +exports.ProbotOctokit = core_1.Octokit.plugin(plugin_throttling_1.throttling, plugin_retry_1.retry, plugin_paginate_rest_1.paginateRest, plugin_rest_endpoint_methods_1.legacyRestEndpointMethods, plugin_enterprise_compatibility_1.enterpriseCompatibility, octokit_plugin_probot_request_logging_1.probotRequestLogging, octokit_plugin_config_1.config).defaults((instanceOptions) => { + // merge throttle options deeply + const options = Object.assign({}, defaultOptions, instanceOptions, { + throttle: instanceOptions.throttle + ? Object.assign({}, defaultOptions.throttle, instanceOptions.throttle) + : defaultOptions.throttle, + }); + return options; +}); +//# sourceMappingURL=probot-octokit.js.map - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } +/***/ }), - 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; - } - } +/***/ 22357: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - }; - var Events_1 = Events; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Probot = void 0; +const lru_cache_1 = __importDefault(__nccwpck_require__(7129)); +const alias_log_1 = __nccwpck_require__(19752); +const auth_1 = __nccwpck_require__(81084); +const get_log_1 = __nccwpck_require__(90751); +const get_probot_octokit_with_defaults_1 = __nccwpck_require__(1330); +const get_webhooks_1 = __nccwpck_require__(879); +const probot_octokit_1 = __nccwpck_require__(97268); +const version_1 = __nccwpck_require__(1403); +class Probot { + constructor(options = {}) { + options.secret = options.secret || "development"; + let level = options.logLevel; + const logMessageKey = options.logMessageKey; + this.log = alias_log_1.aliasLog(options.log || get_log_1.getLog({ level, logMessageKey })); + // TODO: support redis backend for access token cache if `options.redisConfig` + const cache = new lru_cache_1.default({ + // cache max. 15000 tokens, that will use less than 10mb memory + max: 15000, + // Cache for 1 minute less than GitHub expiry + maxAge: 1000 * 60 * 59, + }); + const Octokit = get_probot_octokit_with_defaults_1.getProbotOctokitWithDefaults({ + githubToken: options.githubToken, + Octokit: options.Octokit || probot_octokit_1.ProbotOctokit, + appId: Number(options.appId), + privateKey: options.privateKey, + cache, + log: this.log, + redisConfig: options.redisConfig, + baseUrl: options.baseUrl, + }); + const octokit = new Octokit(); + this.state = { + cache, + githubToken: options.githubToken, + log: this.log, + Octokit, + octokit, + webhooks: { + secret: options.secret, + }, + appId: Number(options.appId), + privateKey: options.privateKey, + host: options.host, + port: options.port, + }; + this.auth = auth_1.auth.bind(null, this.state); + this.webhooks = get_webhooks_1.getWebhooks(this.state); + this.on = this.webhooks.on; + this.onAny = this.webhooks.onAny; + this.onError = this.webhooks.onError; + this.version = version_1.VERSION; + } + static defaults(defaults) { + const ProbotWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + super(Object.assign({}, defaults, options)); + } + }; + return ProbotWithDefaults; + } + receive(event) { + this.log.debug({ event }, "Webhook received"); + return this.webhooks.receive(event); + } + async load(appFn) { + if (Array.isArray(appFn)) { + for (const fn of appFn) { + await this.load(fn); + } + return; + } + return appFn(this, {}); + } +} +exports.Probot = Probot; +Probot.version = version_1.VERSION; +//# sourceMappingURL=probot.js.map - var DLList$1, Events$1, Queues; +/***/ }), - DLList$1 = DLList_1; +/***/ 57124: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - Events$1 = Events_1; - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1(this)); - } - return results; - }).call(this); - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.run = void 0; +const pkg_conf_1 = __importDefault(__nccwpck_require__(51235)); +const index_1 = __nccwpck_require__(93181); +const setup_1 = __nccwpck_require__(36769); +const get_log_1 = __nccwpck_require__(90751); +const read_cli_options_1 = __nccwpck_require__(57767); +const read_env_options_1 = __nccwpck_require__(74420); +const server_1 = __nccwpck_require__(83148); +const default_1 = __nccwpck_require__(3598); +const resolve_app_function_1 = __nccwpck_require__(33208); +const is_production_1 = __nccwpck_require__(75381); +/** + * + * @param appFnOrArgv set to either a probot application function: `(app) => { ... }` or to process.argv + */ +async function run(appFnOrArgv, additionalOptions) { + (__nccwpck_require__(12437).config)(); + const envOptions = read_env_options_1.readEnvOptions(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.env); + const cliOptions = Array.isArray(appFnOrArgv) + ? read_cli_options_1.readCliOptions(appFnOrArgv) + : {}; + const { + // log options + logLevel: level, logFormat, logLevelInString, logMessageKey, sentryDsn, + // server options + host, port, webhookPath, webhookProxy, + // probot options + appId, privateKey, redisConfig, secret, baseUrl, + // others + args, } = { ...envOptions, ...cliOptions }; + const logOptions = { + level, + logFormat, + logLevelInString, + logMessageKey, + sentryDsn, + }; + const log = get_log_1.getLog(logOptions); + const probotOptions = { + appId, + privateKey, + redisConfig, + secret, + baseUrl, + log: log.child({ name: "probot" }), + }; + const serverOptions = { + host, + port, + webhookPath, + webhookProxy, + log: log.child({ name: "server" }), + Probot: index_1.Probot.defaults(probotOptions), + }; + let server; + if (!appId || !privateKey) { + if (is_production_1.isProduction()) { + if (!appId) { + throw new Error("App ID is missing, and is required to run in production mode. " + + "To resolve, ensure the APP_ID environment variable is set."); + } + else if (!privateKey) { + throw new Error("Certificate is missing, and is required to run in production mode. " + + "To resolve, ensure either the PRIVATE_KEY or PRIVATE_KEY_PATH environment variable is set and contains a valid certificate"); + } + } + // Workaround for setup (#1512) + // When probot is started for the first time, it gets into a setup mode + // where `appId` and `privateKey` are not present. The setup mode gets + // these credentials. In order to not throw an error, we set the values + // to anything, as the Probot instance is not used in setup it makes no + // difference anyway. + server = new server_1.Server({ + ...serverOptions, + Probot: index_1.Probot.defaults({ + ...probotOptions, + appId: 1, + privateKey: "dummy value for setup, see #1512", + }), + }); + await server.load(setup_1.setupAppFactory(host, port)); + await server.start(); + return server; + } + if (Array.isArray(appFnOrArgv)) { + const pkg = await pkg_conf_1.default("probot"); + const combinedApps = async (app) => { + await server.load(default_1.defaultApp); + if (Array.isArray(pkg.apps)) { + for (const appPath of pkg.apps) { + const appFn = await resolve_app_function_1.resolveAppFunction(appPath); + await server.load(appFn); + } + } + const [appPath] = args; + const appFn = await resolve_app_function_1.resolveAppFunction(appPath); + await server.load(appFn); + }; + server = new server_1.Server(serverOptions); + await server.load(combinedApps); + await server.start(); + return server; + } + server = new server_1.Server(serverOptions); + await server.load(appFnOrArgv); + await server.start(); + return server; +} +exports.run = run; +//# sourceMappingURL=run.js.map - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } +/***/ }), - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } +/***/ 24631: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - push(priority, job) { - return this._lists[priority].push(job); - } - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getLoggingMiddleware = void 0; +const pino_http_1 = __importDefault(__nccwpck_require__(31778)); +const uuid_1 = __nccwpck_require__(75840); +function getLoggingMiddleware(logger) { + return pino_http_1.default({ + logger: logger.child({ name: "http" }), + customSuccessMessage(res) { + const responseTime = Date.now() - res[pino_http_1.default.startTime]; + // @ts-ignore + return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`; + }, + customErrorMessage(err, res) { + const responseTime = Date.now() - res[pino_http_1.default.startTime]; + // @ts-ignore + return `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`; + }, + genReqId: (req) => req.headers["x-request-id"] || + req.headers["x-github-delivery"] || + uuid_1.v4(), + }); +} +exports.getLoggingMiddleware = getLoggingMiddleware; +//# sourceMappingURL=logging-middleware.js.map - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } +/***/ }), - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } +/***/ 83148: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } - }; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Server = void 0; +const express_1 = __importStar(__nccwpck_require__(71204)); +const path_1 = __nccwpck_require__(71017); +const webhooks_1 = __nccwpck_require__(18513); +const get_log_1 = __nccwpck_require__(90751); +const logging_middleware_1 = __nccwpck_require__(24631); +const webhook_proxy_1 = __nccwpck_require__(66217); +const version_1 = __nccwpck_require__(1403); +class Server { + constructor(options = {}) { + this.version = version_1.VERSION; + this.expressApp = express_1.default(); + this.log = options.log || get_log_1.getLog().child({ name: "server" }); + this.probotApp = new options.Probot(); + this.state = { + port: options.port, + host: options.host, + webhookPath: options.webhookPath || "/", + webhookProxy: options.webhookProxy, + }; + this.expressApp.use(logging_middleware_1.getLoggingMiddleware(this.log)); + this.expressApp.use("/probot/static/", express_1.default.static(__nccwpck_require__.ab + "static")); + this.expressApp.use(this.state.webhookPath, webhooks_1.createNodeMiddleware(this.probotApp.webhooks, { + path: "/", + })); + this.expressApp.set("view engine", "hbs"); + this.expressApp.set("views", __nccwpck_require__.ab + "views"); + this.expressApp.get("/ping", (req, res) => res.end("PONG")); + } + async load(appFn) { + await appFn(this.probotApp, { + getRouter: (path) => this.router(path), + }); + } + async start() { + this.log.info(`Running Probot v${this.version} (Node.js: ${process.version})`); + const port = this.state.port || 3000; + const { host, webhookPath, webhookProxy } = this.state; + const printableHost = host !== null && host !== void 0 ? host : "localhost"; + this.state.httpServer = (await new Promise((resolve, reject) => { + const server = this.expressApp.listen(port, ...(host ? [host] : []), () => { + if (webhookProxy) { + this.state.eventSource = webhook_proxy_1.createWebhookProxy({ + logger: this.log, + path: webhookPath, + port: port, + url: webhookProxy, + }); + } + this.log.info(`Listening on http://${printableHost}:${port}`); + resolve(server); + }); + server.on("error", (error) => { + if (error.code === "EADDRINUSE") { + error = Object.assign(error, { + message: `Port ${port} is already in use. You can define the PORT environment variable to use a different port.`, + }); + } + this.log.error(error); + reject(error); + }); + })); + return this.state.httpServer; + } + async stop() { + if (this.state.eventSource) + this.state.eventSource.close(); + if (!this.state.httpServer) + return; + const server = this.state.httpServer; + return new Promise((resolve) => server.close(resolve)); + } + router(path = "/") { + const newRouter = express_1.Router(); + this.expressApp.use(path, newRouter); + return newRouter; + } +} +exports.Server = Server; +Server.version = version_1.VERSION; +//# sourceMappingURL=server.js.map - var Queues_1 = Queues; +/***/ }), - var BottleneckError; +/***/ 1403: +/***/ ((__unused_webpack_module, exports) => { - BottleneckError = class BottleneckError extends Error {}; - var BottleneckError_1 = BottleneckError; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VERSION = void 0; +// The version is set automatically before publish to npm +exports.VERSION = "12.1.4"; +//# sourceMappingURL=version.js.map - var BottleneckError$1, LocalDatastore, parser$1; +/***/ }), - parser$1 = parser; +/***/ 96645: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - BottleneckError$1 = BottleneckError_1; +const { inspect } = __nccwpck_require__(73837); - 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(); - } +const through = __nccwpck_require__(18180); +const core = __nccwpck_require__(68648); +const pino = __nccwpck_require__(79608); - _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); - } - } +const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = { + trace: "debug", + debug: "debug", + info: "info", + warn: "warning", + error: "error", + fatal: "error", +}; - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } +const transport = through.obj(function (chunk, enc, cb) { + const { level, hostname, pid, msg, time, ...meta } = JSON.parse(chunk); + const levelLabel = pino.levels.labels[level] || level; + const logMethodName = LEVEL_TO_ACTIONS_CORE_LOG_METHOD[levelLabel]; - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } + const output = [ + msg, + Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "", + ] + .join("\n") + .trim(); - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } + if (logMethodName in core) { + core[logMethodName](output); + } else { + core.error(`"${level}" is not a known log level - ${output}`); + } - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } + cb(); +}); - async __updateSettings__(options) { - await this.yieldLoop(); - parser$1.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } +module.exports = { transport }; - async __running__() { - await this.yieldLoop(); - return this._running; - } - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } +/***/ }), + +/***/ 97743: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - async __done__() { - await this.yieldLoop(); - return this._done; - } - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } - 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; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); +var isBase64 = _interopDefault(__nccwpck_require__(31310)); - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } +const VERSION = "0.0.0-development"; - isBlocked(now) { - return this._unblockTime >= now; - } +function getPrivateKey(options = {}) { + const env = options.env || process.env; + const cwd = options.cwd || process.cwd(); - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } + if (options.filepath) { + return fs.readFileSync(path.resolve(cwd, options.filepath), "utf-8"); + } - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } + if (env.PRIVATE_KEY) { + let privateKey = env.PRIVATE_KEY; - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } + if (isBase64(privateKey)) { + // Decode base64-encoded certificate + privateKey = Buffer.from(privateKey, "base64").toString(); + } - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } + const begin = "-----BEGIN RSA PRIVATE KEY-----"; + const end = "-----END RSA PRIVATE KEY-----"; - 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 - }; - } + if (privateKey.includes(begin) && privateKey.includes(end)) { + // Full key with new lines + return privateKey.replace(/\\n/g, "\n"); + } - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } + 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.`); + } - }; + if (env.PRIVATE_KEY_PATH) { + const filepath = path.resolve(cwd, env.PRIVATE_KEY_PATH); - var LocalDatastore_1 = LocalDatastore; + if (fs.existsSync(filepath)) { + return fs.readFileSync(filepath, "utf-8"); + } else { + throw new Error(`[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.`); + } + } - var BottleneckError$2, States; + const pemFiles = fs.readdirSync(cwd).filter(path => path.endsWith(".pem")); - BottleneckError$2 = BottleneckError_1; + if (pemFiles.length > 1) { + const paths = pemFiles.join(", "); + throw new Error(`[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH`); + } else if (pemFiles[0]) { + return getPrivateKey({ + filepath: pemFiles[0], + cwd + }); + } - States = class States { - constructor(status1) { - this.status = status1; - this.jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } + return null; +} +getPrivateKey.VERSION = VERSION; - 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]; - } - } +exports.getPrivateKey = getPrivateKey; +//# sourceMappingURL=index.js.map - start(id) { - var initial; - initial = 0; - this.jobs[id] = initial; - return this.counts[initial]++; - } - remove(id) { - var current; - current = this.jobs[id]; - if (current != null) { - this.counts[current]--; - delete this.jobs[id]; - } - return current != null; - } +/***/ }), - jobStatus(id) { - var ref; - return (ref = this.status[this.jobs[id]]) != null ? ref : null; - } +/***/ 59326: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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); - } - } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - var States_1 = States; +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var DLList$2, Sync, - splice = [].splice; +var yaml = _interopDefault(__nccwpck_require__(21917)); - DLList$2 = DLList_1; +const VERSION = "1.0.1"; - 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(); - } +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; + } - isEmpty() { - return this._queue.length === 0; - } + return obj; +} - _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; - }); - } - } +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - submit(task, ...args) { - var cb, ref; - ref = args, [...args] = ref, [cb] = splice.call(args, -1); - this._queue.push({task, args, cb}); - return this._tryToRun(); - } + 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); + } - 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); - }); - }); - } + return keys; +} - }; +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - var Sync_1 = Sync; + 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)); + }); + } + } - var version = "2.17.1"; - var version$1 = { - version: version - }; + return target; +} - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); +const SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"]; +/** + * Load configuration from a given repository and path. + * + * @param octokit Octokit instance + * @param options + */ - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +async function getConfigFile(octokit, { + owner, + repo, + path, + ref +}) { + const fileExtension = path.split(".").pop().toLowerCase(); - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + if (!SUPPORTED_FILE_EXTENSIONS.includes(fileExtension)) { + throw new Error(`[@probot/octokit-plugin-config] .${fileExtension} extension is not support for configuration (path: "${path}")`); + } // https://docs.github.com/en/rest/reference/repos#get-repository-content - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$2; + const requestOptions = await octokit.request.endpoint("GET /repos/{owner}/{repo}/contents/{path}", _objectSpread2({ + owner, + repo, + path, + mediaType: { + format: "raw" + } + }, ref ? { + ref + } : {})); + const emptyConfigResult = { + owner, + repo, + path, + url: requestOptions.url, + config: null + }; - parser$2 = parser; + try { + const { + data, + headers + } = await octokit.request(requestOptions); // 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 + // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-directory + // + // symlinks just return the content of the linked file when requesting the raw formt, + // so we are fine - Events$2 = Events_1; + 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.`); + } - RedisConnection$1 = require$$2; + if (fileExtension === "json") { + if (typeof data === "string") { + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (invalid JSON)`); + } - IORedisConnection$1 = require$$3; + return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { + config: data + }); + } - Scripts$1 = require$$4; + const config = yaml.safeLoad(data) || {}; - 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})); - } - } - } + if (typeof config === "string") { + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (YAML is not an object)`); + } - 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 _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { + config + }); + } catch (error) { + if (error.status === 404) { + return emptyConfigResult; + } - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } + if (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})`); + } - 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; - } + throw error; + } +} - keys() { - return Object.keys(this.instances); - } +const EXTENDS_REGEX = new RegExp("^" + "(?:([a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38})/)?" + // org +"([-_.\\w\\d]+)" + // project +"(?::([-_./\\w\\d]+\\.ya?ml))?" + // filename +"$", "i"); +/** + * Computes parameters to retrieve the configuration file specified in _extends + * + * Base can either be the name of a repository in the same organization or + * a full slug "organization/repo". + * + * @param options + * @return The params needed to retrieve a configuration file + */ - 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; - } +function extendsToGetContentParams({ + owner, + path, + url, + extendsValue +}) { + if (typeof extendsValue !== "string") { + throw new Error(`[@probot/octokit-plugin-config] Invalid value ${JSON.stringify(extendsValue)} for _extends in ${url}`); + } - _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; - } + const match = extendsValue.match(EXTENDS_REGEX); - updateSettings(options = {}) { - parser$2.overwrite(options, this.defaults, this); - parser$2.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } + if (match === null) { + throw new Error(`[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}`); + } - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } + return { + owner: match[1] || owner, + repo: match[2], + path: match[3] || path + }; +} - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; +/** + * Load configuration from selected repository file. If the file does not exist + * it loads configuration from the owners `.github` repository. + * + * If the repository file configuration includes an `_extends` key, that file + * is loaded. Same with the target file until no `_extends` key is present. + * + * @param octokit Octokit instance + * @param options + */ - return Group; +async function getConfigFiles(octokit, { + owner, + repo, + path, + branch +}) { + const requestedRepoFile = await getConfigFile(octokit, { + owner, + repo, + path, + ref: branch + }); // if no configuration file present in selected repository, + // try to load it from the `.github` repository - }).call(commonjsGlobal); + if (!requestedRepoFile.config) { + if (repo === ".github") { + return [requestedRepoFile]; + } - var Group_1 = Group; + const defaultRepoConfig = await getConfigFile(octokit, { + owner, + repo: ".github", + path + }); + return [requestedRepoFile, defaultRepoConfig]; + } // if the configuration has no `_extends` key, we are done here. - var Batcher, Events$3, parser$3; - parser$3 = parser; + if (!requestedRepoFile.config._extends) { + return [requestedRepoFile]; + } // parse the value of `_extends` into request parameters to + // retrieve the new configuration file - Events$3 = Events_1; - 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(); - } + let extendConfigOptions = extendsToGetContentParams({ + owner, + path, + url: requestedRepoFile.url, + extendsValue: requestedRepoFile.config._extends + }); // remove the `_extends` key from the configuration that is returned - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } + 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 - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } + do { + const extendRepoConfig = await getConfigFile(octokit, extendConfigOptions); + files.push(extendRepoConfig); - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } + if (!extendRepoConfig.config || !extendRepoConfig.config._extends) { + return files; + } - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; + extendConfigOptions = extendsToGetContentParams({ + owner, + path, + url: extendRepoConfig.url, + extendsValue: extendRepoConfig.config._extends + }); + delete extendRepoConfig.config._extends; // Avoid loops - return Batcher; + const alreadyLoaded = files.find(file => file.owner === extendConfigOptions.owner && file.repo === extendConfigOptions.repo && file.path === extendConfigOptions.path); - }).call(commonjsGlobal); + 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); +} - var Batcher_1 = Batcher; +/** + * 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 require$$3$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +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) + }; +} - var require$$7 = getCjsExportFromNamespace(version$2); +/** + * @param octokit Octokit instance + */ - var Bottleneck, DEFAULT_PRIORITY, Events$4, LocalDatastore$1, NUM_PRIORITIES, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$4, - splice$1 = [].splice; +function config(octokit) { + return { + config: { + async get(options) { + return composeConfigGet(octokit, options); + } - NUM_PRIORITIES = 10; + } + }; +} +config.VERSION = VERSION; - DEFAULT_PRIORITY = 5; +exports.composeConfigGet = composeConfigGet; +exports.config = config; +//# sourceMappingURL=index.js.map - parser$4 = parser; - Queues$1 = Queues_1; +/***/ }), - LocalDatastore$1 = LocalDatastore_1; +/***/ 39662: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - RedisDatastore$1 = require$$3$1; +module.exports = { getTransformStream }; - Events$4 = Events_1; +const { Transform } = __nccwpck_require__(51642); - States$1 = States_1; +const prettyFactory = __nccwpck_require__(31691); +const Sentry = __nccwpck_require__(22783); - Sync$1 = Sync_1; +const LEVEL_MAP = { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal", +}; - 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; - }); - } +/** + * 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; - _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."); - } - } + 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, + }); + } - ready() { - return this._store.ready; - } + 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(","), + }); - clients() { - return this._store.clients; - } + return new Transform({ + objectMode: true, + transform(chunk, enc, cb) { + const line = chunk.toString().trim(); - channel() { - return `b_${this.id}`; - } + /* istanbul ignore if */ + if (line === undefined) return cb(); - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } + const data = sentryEnabled ? JSON.parse(line) : null; - publish(message) { - return this._store.__publish__(message); - } + if (sentryEnabled && data.level >= 50) { + Sentry.withScope(function (scope) { + const sentryLevelName = + data.level === 50 ? Sentry.Severity.Error : Sentry.Severity.Fatal; + scope.setLevel(sentryLevelName); - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } + for (const extra of ["event", "headers", "request", "status"]) { + if (!data[extra]) continue; - chain(_limiter) { - this._limiter = _limiter; - return this; - } + scope.setExtra(extra, data[extra]); + } - queued(priority) { - return this._queues.queued(priority); - } + // 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 } = {} } = {}, - clusterQueued() { - return this._store.__queued__(); - } + // When the repository belongs to an organization + organization: { login: organization } = {}, + // When the repository belongs to a user + repository: { owner: { login: owner } = {} } = {}, + } = data.event.payload; - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } + scope.setUser({ + id: id, + username: account || organization || owner, + }); + } - running() { - return this._store.__running__(); - } + Sentry.captureException(toSentryError(data)); + }); + } - done() { - return this._store.__done__(); - } + if (formattingEnabled) { + return cb(null, pretty(data || line)); + } - jobStatus(id) { - return this._states.jobStatus(id); - } + if (levelAsString) { + return cb(null, stringifyLogLevel(data || JSON.parse(line))); + } - jobs(status) { - return this._states.statusJobs(status); - } + cb(null, line + "\n"); + }, + }); +} - counts() { - return this._states.statusCounts(); - } +function stringifyLogLevel(data) { + data.level = LEVEL_MAP[data.level]; + return JSON.stringify(data) + "\n"; +} - _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; - } - } +function toSentryError(data) { + const error = new Error(data.msg); + error.name = data.type; + error.stack = data.stack; + return error; +} - _randomIndex() { - return Math.random().toString(36).slice(2); - } - check(weight = 1) { - return this._store.__check__(weight); - } +/***/ }), - _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 - }; - } +/***/ 90785: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _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); - } - }); - }); - } +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 - _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)); - } - } - return this.Events.trigger("dropped", job); - } - } +/***/ 25886: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _dropAllQueued(message) { - return this._queues.shiftAll((job) => { - return this._drop(job, message); - }); - } +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 - 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; - } +/***/ }), - 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; - }); - } +/***/ 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); +/** + * 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); + * } + * + * // ... + * } + */ +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 - 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); - }); - }); - } +/***/ }), - 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; - } +/***/ 79212: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$4.overwrite(options, this.storeDefaults)); - parser$4.overwrite(options, this.instanceDefaults, this); - return this; - } +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 - currentReservoir() { - return this._store.__currentReservoir__(); - } +/***/ }), - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +/***/ 58500: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } - Bottleneck.default = Bottleneck; +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; +} +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); + }); + return integrations; +} +exports.setupIntegrations = setupIntegrations; +//# sourceMappingURL=integration.js.map - Bottleneck.Events = Events$4; +/***/ }), - Bottleneck.version = Bottleneck.prototype.version = require$$7.version; +/***/ 87349: +/***/ ((__unused_webpack_module, exports) => { - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; +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; + } + /** + * @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 - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; +/***/ }), - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; +/***/ 54838: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; +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; + } + /** + * @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 - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; +/***/ }), - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; +/***/ 96727: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY, - weight: 1, - expiration: null, - id: "" - }; +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 - 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 - }; +/***/ 1553: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; +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(), + }; +} +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; +} +exports.eventToSentryRequest = eventToSentryRequest; +//# sourceMappingURL=request.js.map - 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." - }; +/***/ 46406: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return Bottleneck; +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(); + } + var hub = hub_1.getCurrentHub(); + var client = new clientClass(options); + hub.bindClient(client); +} +exports.initAndBind = initAndBind; +//# sourceMappingURL=sdk.js.map - }).call(commonjsGlobal); +/***/ }), - var Bottleneck_1 = Bottleneck; +/***/ 68641: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var lib = Bottleneck_1; +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 - return lib; +/***/ }), -}))); +/***/ 53536: +/***/ ((__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 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); + } + 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; +} +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; +} +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()); + } + // 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.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; +} +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); + } + catch (_Oo) { + // Return hub that lives on a global object + return getHubFromCarrier(registry); + } +} +/** + * 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 + */ +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 /***/ }), -/***/ 9239: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*jshint node:true */ - -var Buffer = __nccwpck_require__(64293).Buffer; // browserify -var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; - -module.exports = bufferEq; +/***/ 6393: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function bufferEq(a, b) { +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 - // 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; - } +/***/ 4213: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; +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 = {}; + } + /** + * 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 (this._level) { + event.level = this._level; + } + if (this._transactionName) { + event.transaction = this._transactionName; + } + // 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); + } + } + 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; + } + }; + /** + * 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 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); +} +exports.addGlobalEventProcessor = addGlobalEventProcessor; +//# sourceMappingURL=scope.js.map -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; +/***/ }), -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; +/***/ 12474: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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); + } + } + /** 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(); + } + }; + /** 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 /***/ }), -/***/ 86966: -/***/ ((module) => { +/***/ 88455: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed +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]; + } + 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."); +} +/** + * 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'); + } + catch (exception) { + syntheticException = exception; + } + return callOnHub('captureException', exception, { + captureContext: captureContext, + originalException: exception, + syntheticException: syntheticException, + }); +} +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); + } + catch (exception) { + syntheticException = exception; + } + // 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; /** - * Module exports. - * @public + * Set an object that will be merged sent as extra data with the event. + * @param extras Extras object to merge into current context. */ - -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; - +function setExtras(extras) { + callOnHub('setExtras', extras); +} +exports.setExtras = setExtras; /** - * Module variables. - * @private + * Set an object that will be merged sent as tags data with the event. + * @param tags Tags context object to merge into current context. */ - -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; - -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; - +function setTags(tags) { + callOnHub('setTags', tags); +} +exports.setTags = setTags; /** - * 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} + * 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 bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } - - if (typeof value === 'number') { - return format(value, options); - } - - return null; +function setExtra(key, extra) { + callOnHub('setExtra', key, extra); } - +exports.setExtra = setExtra; /** - * Format the given value in bytes into a string. + * Set key:value that will be sent as tags data with the event. * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. + * Can also be used to unset a tag, by passing `undefined`. * - * @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=] + * @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. * - * @returns {string|null} - * @public + * @param user User context object to be set in the current context. Pass `null` to unset the user. */ - -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } - - 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 (!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'; - } - } - - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } - - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } - - return str + unitSeparator + unit; +function setUser(user) { + callOnHub('setUser', user); } - +exports.setUser = setUser; /** - * Parse the string value into an integer in bytes. + * Creates a new scope with and executes the given operation within. + * The scope is automatically removed once the operation + * finishes or throws. * - * If no unit is given, it is assumed the value is in bytes. + * This is essentially a convenience function for: * - * @param {number|string} val + * pushScope(); + * callback(); + * popScope(); * - * @returns {number|null} - * @public + * @param callback that will be enclosed into push/popScope. */ - -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } - - if (typeof val !== 'string') { - return null; - } - - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - 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 Math.floor(map[unit] * floatValue); -} - - -/***/ }), - -/***/ 78818: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"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); - -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'); - } - - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; - -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} - -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; - - chalk.template.Instance = ChalkClass; - - return chalk.template; -}; - -function Chalk(options) { - return chalkFactory(options); -} - -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; - } - }; -} - -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } -}; - -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; - -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); - }; - } - }; -} - -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); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); - -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 { - open, - close, - openAll, - closeAll, - parent - }; -}; - -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); - - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; - - return builder; -}; - -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } - - let styler = self._styler; - - if (styler === undefined) { - return string; - } - - 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); - - styler = styler.parent; - } - } - - // 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); - } - - return openAll + string + closeAll; -}; - -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; - - 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(' '); - } - - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; - - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); - } - - if (template === undefined) { - template = __nccwpck_require__(20500); - } - - return template(chalk, parts.join('')); -}; - -Object.defineProperties(Chalk.prototype, styles); - -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; - -module.exports = chalk; - - -/***/ }), - -/***/ 20500: -/***/ ((module) => { - -"use strict"; - -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; - -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); - -function unescape(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; - - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } - - return ESCAPES.get(c) || c; -} - -function parseArguments(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; - - 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}')`); - } - } - - return results; +function withScope(callback) { + callOnHub('withScope', callback); } - -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; - - const results = []; - let matches; - - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; - - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; +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]; + } + callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); } - -function buildStyle(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } - - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } - - return current; +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); } +exports.startTransaction = startTransaction; +//# sourceMappingURL=index.js.map -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); - } - }); - - chunks.push(chunk.join('')); - - 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(''); -}; +/***/ 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); +/** + * 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 /***/ }), -/***/ 82415: -/***/ ((module) => { +/***/ 86147: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +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; + } + /** + * @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 +/***/ }), -const stringReplaceAll = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } +/***/ 45400: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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); +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__(13639); +var os = __nccwpck_require__(22037); +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 || ''); + } + 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; +} +/** + * 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 (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); + } + if (options.serverName && !event.server_name) { + event.server_name = global.process.env.SENTRY_NAME || os.hostname(); + } + 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); + } + } + // 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 }); + } + } + if (options.transaction && !event.transaction) { + event.transaction = extractTransaction(req, options.transaction); + } + 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); + }; +} +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; + } + 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 - returnValue += string.substr(endIndex); - return returnValue; -}; +/***/ }), -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); +/***/ 22783: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - returnValue += string.substr(endIndex); - return returnValue; -}; +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__(13639); +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 -module.exports = { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -}; +/***/ }), +/***/ 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__(73837); +/** Console module integration */ +var Console = /** @class */ (function () { + function Console() { + /** + * @inheritDoc + */ + this.name = Console.id; + } + /** + * @inheritDoc + */ + Console.prototype.setupOnce = function () { + var e_1, _a; + var consoleModule = __nccwpck_require__(96206); + 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); + }; + }; +} +//# sourceMappingURL=console.js.map /***/ }), -/***/ 27972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 76280: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +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; + } + /** + * @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__(13685); + 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__(95687); + utils_1.fill(httpsModule, 'get', wrappedHandlerMaker); + utils_1.fill(httpsModule, 'request', wrappedHandlerMaker); + } + }; + /** + * @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 -const os = __nccwpck_require__(12087); +/***/ }), -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(); +/***/ 72310: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); +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 - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } +/***/ }), - const match = pathMatches[1]; +/***/ 70208: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - 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 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); + } + 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); + } + 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 - 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, '~'))); - } +/***/ }), - return line; - }) - .join('\n'); -}; +/***/ 90046: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var fs_1 = __nccwpck_require__(57147); +var path_1 = __nccwpck_require__(71017); +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; +} +/** 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 /***/ }), -/***/ 2101: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 50443: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(16136); +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(); + } + /** + * @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 /***/ }), -/***/ 66168: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const utils = __nccwpck_require__(98911); - -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); +/***/ 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 handlers_1 = __nccwpck_require__(45400); +/** Global Promise Rejection handler */ +var OnUnhandledRejection = /** @class */ (function () { /** - * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to - * `init` being called; - * @type {Number} + * @inheritDoc */ - this.x = null; - this.y = null; - } - - 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); + function OnUnhandledRejection(_options) { + if (_options === void 0) { _options = { mode: 'warn' }; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = OnUnhandledRejection.id; } - this.colSpan = options.colSpan || 1; - this.rowSpan = options.rowSpan || 1; - } - - mergeTableOptions(tableOptions, cells) { - this.cells = cells; - - let optionsChars = this.options.chars || {}; - let tableChars = tableOptions.chars; - let chars = (this.chars = {}); - CHAR_NAMES.forEach(function (name) { - setOption(optionsChars, tableChars, name, chars); - }); - - this.truncate = this.options.truncate || tableOptions.truncate; - - 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; - - 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++; + /** + * @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; } - } - 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); + /* 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 if (this._options.mode === 'strict') { + utils_1.consoleSandbox(function () { + console.warn(rejectionWarning); + }); + handlers_1.logAndExitProcess(reason); + } + /* eslint-enable no-console */ + }; + /** + * @inheritDoc + */ + OnUnhandledRejection.id = 'OnUnhandledRejection'; + return OnUnhandledRejection; +}()); +exports.OnUnhandledRejection = OnUnhandledRejection; +//# sourceMappingURL=onunhandledrejection.js.map - this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; - this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; +/***/ }), - this.drawRight = x + this.colSpan == tableOptions.colWidths.length; - } +/***/ 84103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * 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; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var url_1 = __nccwpck_require__(57310); +/** + * 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; } - if (lineNum < padTop || lineNum >= padTop + this.lines.length) { - return this.drawEmpty(this.drawRight, spanningCell); + // 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); } - let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height; - return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell); - } - - /** - * 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)); + // 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 (drawRight) { - content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']); + 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); } - 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'; - } - } - } - } + if (url.username || url.password) { + options.auth = url.username + ":" + url.password; } - return this.chars[leftChar]; - } - - 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; + return options; +} +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(); } - } - - /** - * 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']; - } + // create a RequestOptions object of whatever's at index 0 + if (typeof requestArgs[0] === 'string') { + requestOptions = urlToOptions(new url_1.URL(requestArgs[0])); } - 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); + else if (requestArgs[0] instanceof url_1.URL) { + requestOptions = urlToOptions(requestArgs[0]); } - return left + content + right; - } - - /** - * 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); - } - - /** - * 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']; - } + 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]; } - let right = drawRight ? this.chars['right'] : ''; - let content = utils.repeat(' ', this.width); - return this.stylizeLine(left, content, right); - } } +exports.normalizeRequestArgs = normalizeRequestArgs; +//# sourceMappingURL=http.js.map -class ColSpanCell { - /** - * A Cell that doesn't do anything. It just draws empty lines. - * Used as a placeholder in column spanning. - * @constructor - */ - constructor() {} - - draw() { - return ''; - } +/***/ }), - init() {} +/***/ 19090: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - mergeTableOptions() {} +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var fs_1 = __nccwpck_require__(57147); +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(); } - -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; - } - - init(tableOptions) { - let y = this.y; - let originalY = this.originalCell.y; - this.cellOffset = y - originalY; - this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); - } - - draw(lineNum) { - if (lineNum == 'top') { - return this.originalCell.draw(this.offset, this.cellOffset); +exports.resetFileContentCache = resetFileContentCache; +/** JSDoc */ +function getFunction(frame) { + try { + return frame.functionName || frame.typeName + "." + (frame.methodName || ''); } - if (lineNum == 'bottom') { - return this.originalCell.draw('bottom'); + catch (e) { + // This seems to happen sometimes when using 'use strict', + // stemming from `getTypeName`. + // [TypeError: Cannot read property 'constructor' of undefined] + return ''; } - return this.originalCell.draw(this.offset + 1 + lineNum); - } - - mergeTableOptions() {} -} - -// 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]; - } -} - -function findDimension(dimensionTable, startingIndex, span) { - let ret = dimensionTable[startingIndex]; - for (let i = 1; i < span; i++) { - ret += 1 + dimensionTable[startingIndex + i]; - } - return ret; } - -function sumPlusOne(a, b) { - return a + b + 1; -} - -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; - - -/***/ }), - -/***/ 93875: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const objectAssign = __nccwpck_require__(17426); -const Cell = __nccwpck_require__(66168); -const { ColSpanCell, RowSpanCell } = Cell; - -(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 maxWidth(table) { - let mw = 0; - table.forEach(function (row) { - row.forEach(function (cell) { - mw = Math.max(mw, cell.x + (cell.colSpan || 1)); - }); - }); - return mw; - } - - function maxHeight(table) { - return table.length; - } - - 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); - - 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 yConflict && xConflict; - } - - 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; +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 false; - } - - function allBlank(rows, y, xMin, xMax) { - for (let x = xMin; x < xMax; x++) { - if (conflictExists(rows, x, y)) { - return false; - } + return file; +} +/** + * 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 true; - } - - 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]); + 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 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); +} +/** + * @hidden + */ +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 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); } - } - - function insertCell(cell, row) { - let x = 0; - while (x < row.length && row[x].x < cell.x) { - x++; + try { + return addPrePostContext(filesToRead, frames, linesOfContext); } - row.splice(x, 0, cell); - } - - 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]); - } - } + 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); } - } - - 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); - }); +} +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 makeTableLayout(rows) { - let cellRows = generateCells(rows); - layoutTable(cellRows); - fillInTable(cellRows); - addRowSpanCells(cellRows); - addColSpanCells(cellRows); - return cellRows; - } - - module.exports = { - makeTableLayout: makeTableLayout, - layoutTable: layoutTable, - addRowSpanCells: addRowSpanCells, - maxWidth: maxWidth, - fillInTable: fillInTable, - computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), - computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), - }; -})(); - -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); - } - }); +} +/** + * @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); + }); }); - - vals.forEach(function (val, index) { - if (typeof val === 'number') { - result[index] = val; - } +} +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], + }, + }); + }); }); - - //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++; - } - } +} +exports.parseError = parseError; +/** + * @hidden + */ +function prepareFramesForEvent(stack) { + if (!stack || !stack.length) { + return []; } - - objectAssign(vals, result); - for (let j = 0; j < vals.length; j++) { - vals[j] = Math.max(forcedMin, vals[j] || 0); + var localStack = stack; + var firstFrameFunction = localStack[0].function || ''; + if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { + localStack = localStack.slice(1); } - }; + // The frame where the crash happened, should be the last entry in the array + return localStack.reverse(); } - +exports.prepareFramesForEvent = prepareFramesForEvent; +//# sourceMappingURL=parsers.js.map /***/ }), -/***/ 16136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const utils = __nccwpck_require__(98911); -const tableLayout = __nccwpck_require__(93875); - -class Table extends Array { - constructor(options) { - super(); - - this.options = utils.mergeOptions(options); - } +/***/ 38836: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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 = []; +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__(13639); +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; } - - let cells = tableLayout.makeTableLayout(array); - - 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); - - let result = []; - - 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); - } - - if (rowIndex + 1 == cells.length) { - doDraw(row, 'bottom', result); - } + if (options.dsn === undefined && process.env.SENTRY_DSN) { + options.dsn = process.env.SENTRY_DSN; } - - return result.join('\n'); - } - - get width() { - let str = this.toString().split('\n'); - return str[0].length; - } -} - -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; - - -/***/ }), - -/***/ 98911: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const objectAssign = __nccwpck_require__(17426); -const stringWidth = __nccwpck_require__(42577); - -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; - } + 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; + } } - } - return str; + if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { + options.environment = process.env.SENTRY_ENVIRONMENT; + } + // 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()); + } + core_1.initAndBind(client_1.NodeClient, options); } - -let codeCache = {}; - -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 }; +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(); } - -//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); - -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]; - } - } - return; - } - let info = codeCache[controlChars[0]]; - if (info) { - state[info.set] = info.to; - } +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)]; + }); + }); } - -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; +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)]; + }); + }); } +exports.close = close; +//# sourceMappingURL=sdk.js.map -function unwindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; +/***/ }), - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; +/***/ 46276: +/***/ ((__unused_webpack_module, exports) => { - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret += codeCache[key].off; +/** + * 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 []; } - }); - - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret += '\u001b[49m'; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret += '\u001b[39m'; - } - - return ret; + 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 -function rewindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; +/***/ }), - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; +/***/ 43240: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret = codeCache[key].on + ret; +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__(57147); +var url = __nccwpck_require__(57310); +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); } - }); - - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret = lastBackgroundAdded + ret; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret = lastForegroundAdded + ret; - } - - return ret; -} - -function truncateWidth(str, desiredLength) { - if (str.length === strlen(str)) { - return str.substr(0, desiredLength); - } - - while (strlen(str) > desiredLength) { - str = str.slice(0, -1); - } - - return str; -} + /** + * @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 -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 = {}; +/***/ }), - 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); +/***/ 84490: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (retLen < desiredLength) { - if (!myArray) { - break; - } // full-width chars may cause a whitespace which cannot be filled - ret += myArray[0]; - updateState(state, myArray); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var http = __nccwpck_require__(13685); +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; } - } - - 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); - - return ret + truncateChar; -} + /** + * @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 -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 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; -} +/***/ 68621: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var https = __nccwpck_require__(95687); +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; } - 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 output; -} + /** + * @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 -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; -} +/***/ }), -module.exports = { - strlen: strlen, - repeat: repeat, - pad: pad, - truncate: truncate, - mergeOptions: mergeOptions, - wordWrap: multiLineWordWrap, - colorizeLines: colorizeLines, -}; +/***/ 21437: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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 /***/ }), -/***/ 48481: -/***/ ((module) => { +/***/ 31271: +/***/ ((__unused_webpack_module, exports) => { -/* - * 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. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SDK_NAME = 'sentry.javascript.node'; +exports.SDK_VERSION = '5.29.2'; +//# sourceMappingURL=version.js.map -/* 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 - */ +/***/ }), -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 -]; +/***/ 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(); /** - * Convert a string to a UTF8 array - faster than via buffer - * @param str - * @returns {Array} + * Add a listener that cancels and finishes a transaction when the global + * document is hidden. */ -var toUTF8Array = function toUTF8Array(str) { - var char; - var i = 0; - var p = 0; - var utf8 = []; - var len = str.length; - - 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; +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 - return utf8; -}; +/***/ }), + +/***/ 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.defaultRoutingInstrumentation, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true }, request_1.defaultRequestInstrumentationOptions); /** - * Convert a string into a redis slot hash. - * @param str - * @returns {number} + * 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 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; - - 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; +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 }); } - - result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); - } - - return result & 0x3FFF; -}; - + /** + * @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; /** - * 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} + * 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 */ -module.exports.generateMulti = function generateMulti(keys) { - var i = 1; - var len = keys.length; - var base = generate(keys[0]); +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 - while (i < len) { - if (generate(keys[i++]) !== base) return -1; - } +/***/ }), - return base; -}; +/***/ 71425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var browsertracing_1 = __nccwpck_require__(33577); +exports.BrowserTracing = browsertracing_1.BrowserTracing; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 97391: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* 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.) +/***/ 68451: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const reverseKeywords = {}; -for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; +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); } - -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); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - 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}); +/** 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(transaction, entry, event, timeOrigin, eventEnd) { + var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; + var start = entry[event + "Start"]; + if (!start || !end) { + return; + } + _startChild(transaction, { + description: event, + endTimestamp: timeOrigin + utils_2.msToSec(end), + op: 'browser', + startTimestamp: timeOrigin + utils_2.msToSec(start), + }); +} +/** 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), + }); +} +/** + * 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)); +} +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 -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; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - const l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; -}; - -convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - - 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; - }; - - 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; - } - - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; -}; - -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)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; -}; - -convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; +/***/ }), - 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; +/***/ 27854: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [c * 100, m * 100, y * 100, k * 100]; +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, }; - -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) - ); +/** 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', + }); + } } +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; + } +} +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. + } + } + } +} +exports.xhrCallback = xhrCallback; +//# sourceMappingURL=request.js.map -convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - - let currentClosestDistance = Infinity; - let currentClosestKeyword; - - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; - - // Compute comparative distance - const distance = comparativeDistance(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - - return currentClosestKeyword; -}; +/***/ }), -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; -}; +/***/ 40348: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; +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', + }); + } +} +exports.defaultRoutingInstrumentation = defaultRoutingInstrumentation; +//# sourceMappingURL=router.js.map - // 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); +/***/ }), - 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); +/***/ 56982: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [x * 100, y * 100, z * 100]; +/* + * 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 -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; - - 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); +/***/ }), - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); +/***/ 82496: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [l, a, b]; +/* + * 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 -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; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - const t1 = 2 * l - t2; +/***/ }), - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } +/***/ 99382: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (t3 > 1) { - t3--; - } +/* + * 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 - 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; - } +/***/ }), - rgb[i] = val * 255; - } +/***/ 55909: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return rgb; +/* + * 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); + } + } + 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 -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); +/***/ 54592: +/***/ ((__unused_webpack_module, exports) => { - return [h, sv * 100, v * 100]; +/* + * 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 -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; +/***/ 70093: +/***/ ((__unused_webpack_module, exports) => { - 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]; - } +/* + * 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 -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; +/***/ 88493: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [h, sl * 100, l * 100]; +/* + * 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); + } + return { + get timeStamp() { + return firstHiddenTime; + }, + }; }; +//# sourceMappingURL=getFirstHidden.js.map -// 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; - } +/***/ }), - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; +/***/ 45300: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ((i & 0x01) !== 0) { - f = 1 - f; - } +/* + * 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 - const n = wh + f * (v - wh); // Linear interpolation +/***/ }), - 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 */ +/***/ 17984: +/***/ ((__unused_webpack_module, exports) => { - return [r * 255, g * 255, b * 255]; +/* + * 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)) { + 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 -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); +/***/ 9658: +/***/ ((__unused_webpack_module, exports) => { - return [r * 255, g * 255, b * 255]; +/* + * 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 }); + } + }, { capture: true, once: once }); +}; +//# sourceMappingURL=onHidden.js.map -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); +/***/ }), - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; +/***/ 45181: +/***/ ((__unused_webpack_module, exports) => { - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; +/* + * 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, + }); + }); + }); + } + return inputPromise; +}; +//# sourceMappingURL=whenInput.js.map - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; +/***/ }), - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); +/***/ 47906: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [r * 255, g * 255, b * 255]; -}; +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; +/** + * 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 -convert.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; +/***/ }), - x /= 95.047; - y /= 100; - z /= 108.883; +/***/ 31409: +/***/ ((module, 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); +/* 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 {}; +} +/** + * 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 + */ +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) + * + * @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); + } + } + } + // 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); + } + } + 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 (!carrier.__SENTRY__.extensions.traceHeaders) { + carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; + } + } +} +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 - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); +/***/ }), - return [l, a, b]; -}; +/***/ 2171: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -convert.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; +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 + */ + 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; +/** + * 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); }); + } + 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; + }); + // 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'); + } + 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) { + this._initTimeout = setTimeout(function () { + if (!_this._finished) { + _this.finish(); + } + }, this._idleTimeout); + 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 - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; +/***/ }), - 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; +/***/ 64358: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - x *= 95.047; - y *= 100; - z *= 108.883; +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; +//# sourceMappingURL=index.js.map - return [x, y, z]; -}; +/***/ }), -convert.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; +/***/ 96221: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +/** + * Express integration + * + * Provides an request and error handler for Express framework as well as tracing capabilities + */ +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'); + } + /** + * @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); + } + } +} +/** + * 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 - if (h < 0) { - h += 360; - } +/***/ }), - const c = Math.sqrt(a * a + b * b); +/***/ 28502: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [l, c, h]; -}; +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 -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); +/***/ 22606: +/***/ ((module, exports, __nccwpck_require__) => { - return [l, a, b]; +/* module decorator */ module = __nccwpck_require__.nmd(module); +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', + '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 = {}; } + /** + * @inheritDoc + */ + this.name = Mongo.id; + this._operations = Array.isArray(options.operations) + ? options.operations + : OPERATIONS; + this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; + } + /** + * @inheritDoc + */ + Mongo.prototype.setupOnce = function (_, getCurrentHub) { + var collection; + try { + var mongodbModule = utils_1.dynamicRequire(module, 'mongodb'); + collection = mongodbModule.Collection; + } + catch (e) { + utils_1.logger.error('Mongo Integration was unable to require `mongodb` package.'); + return; + } + this._instrumentOperations(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; + 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); + }])); + }; + }); + }; + /** + * 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 -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); +/***/ }), - if (value === 0) { - return 30; - } +/***/ 67082: +/***/ ((module, exports, __nccwpck_require__) => { - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); +/* 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; + } + /** + * @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); + }; + }); + }; + /** + * @inheritDoc + */ + Mysql.id = 'Mysql'; + return Mysql; +}()); +exports.Mysql = Mysql; +//# sourceMappingURL=mysql.js.map - if (value === 2) { - ansi += 60; - } +/***/ }), - return ansi; -}; +/***/ 31931: +/***/ ((module, exports, __nccwpck_require__) => { -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]); -}; +/* module decorator */ module = __nccwpck_require__.nmd(module); +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 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; + }); + }; + }); + }; + /** + * @inheritDoc + */ + Postgres.id = 'Postgres'; + return Postgres; +}()); +exports.Postgres = Postgres; +//# sourceMappingURL=postgres.js.map -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; - } +/***/ 64655: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (r > 248) { - return 231; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); +/** + * Keeps track of finished spans for a given transaction + * @internal + * @hideconstructor + * @hidden + */ +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; +/** + * 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 + */ + 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.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 - return Math.round(((r - 8) / 247) * 24) + 232; - } +/***/ }), - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); +/***/ 58522: +/***/ ((__unused_webpack_module, exports) => { - return ansi; -}; +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 -convert.ansi16.rgb = function (args) { - let color = args % 10; +/***/ }), - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } +/***/ 8186: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - color = color / 10.5 * 255; +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 ? transactionContext.name : ''; + _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); + }; + /** + * @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); + }; + return Transaction; +}(span_1.Span)); +exports.Transaction = Transaction; +//# sourceMappingURL=transaction.js.map - return [color, color, color]; - } +/***/ }), - 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; +/***/ 31386: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [r, g, b]; -}; +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 -convert.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } +/***/ }), - args -= 16; +/***/ 83789: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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; +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 - return [r, g, b]; -}; +/***/ }), -convert.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); +/***/ 6853: +/***/ ((__unused_webpack_module, exports) => { - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; +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 -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]; - } +/***/ }), - let colorString = match[0]; +/***/ 84954: +/***/ ((__unused_webpack_module, exports) => { - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } +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 - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; +/***/ }), - return [r, g, b]; -}; +/***/ 94124: +/***/ ((__unused_webpack_module, exports) => { -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; +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 - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } +/***/ }), - 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; - } +/***/ 61277: +/***/ ((__unused_webpack_module, exports) => { - hue /= 6; - hue %= 1; +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 - return [hue * 360, chroma * 100, grayscale * 100]; -}; +/***/ }), -convert.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; +/***/ 47540: +/***/ ((__unused_webpack_module, exports) => { - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); +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 - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } +/***/ }), - return [hsl[0], c * 100, f * 100]; -}; +/***/ 58343: +/***/ ((__unused_webpack_module, exports) => { -convert.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; +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) { + promise.then(null, function (e) { + // TODO: Use a better logging mechanism + // eslint-disable-next-line no-console + console.error(e); + }); +} +exports.forget = forget; +//# sourceMappingURL=async.js.map - const c = s * v; - let f = 0; +/***/ }), - if (c < 1.0) { - f = (v - c) / (1 - c); - } +/***/ 30597: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [hsv[0], c * 100, f * 100]; -}; +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) { + // 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); + } + catch (_oO) { + return ''; + } +} +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) { + 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]); + } + } + 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 + "\"]"); + } + } + return out.join(''); +} +//# sourceMappingURL=browser.js.map -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]; - } +/***/ 3275: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; +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, user = _a.user; + return (protocol + "://" + user + (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], 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(); + } + 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, user: user }); + }; + /** 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; + }; + /** 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); + } + 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 - /* 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 */ +/***/ }), - mg = (1.0 - c) * g; +/***/ 66238: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; +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 -convert.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; +/***/ }), - const v = c + g * (1.0 - c); - let f = 0; +/***/ 1620: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (v > 0.0) { - f = c / v; - } +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 - return [hcg[0], f * 100, v * 100]; -}; +/***/ }), -convert.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; +/***/ 65474: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; +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); + } + } + } + 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) { + 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]; + } + 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); +} +/** 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; + } + lastCapturedEvent = event; + if (debounceTimer) { + clearTimeout(debounceTimer); + } + if (debounce) { + debounceTimer = setTimeout(function () { + handler({ event: event, name: name }); + }); + } + else { + handler({ event: event, name: name }); + } + }; +} +/** + * 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; + } + catch (e) { + // just accessing event properties can throw an exception in some rare circumstances + // see: https://github.com/getsentry/raven-js/issues/838 + return; + } + 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; + } + // record first keypress in a series, but ignore subsequent + // keypresses until debounce clears + if (!keypressTimeout) { + domEventHandler('input', handler)(event); + } + clearTimeout(keypressTimeout); + keypressTimeout = setTimeout(function () { + keypressTimeout = undefined; + }, debounceDuration); + }; +} +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 - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } +/***/ }), - return [hcg[0], s * 100, l * 100]; -}; +/***/ 92757: +/***/ ((__unused_webpack_module, exports) => { -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]; -}; +/* 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; +/** + * Checks whether given value's type is a SyntheticEvent + * {@link isSyntheticEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isSyntheticEvent(wat) { + return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; +} +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. + */ +function isInstanceOf(wat, base) { + try { + return wat instanceof base; + } + catch (_e) { + return false; + } +} +exports.isInstanceOf = isInstanceOf; +//# sourceMappingURL=is.js.map -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; +/***/ }), - if (c < 1) { - g = (v - c) / (1 - c); - } +/***/ 15577: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [hwb[0], c * 100, g * 100]; -}; +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 -convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; +/***/ }), -convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; +/***/ 49515: +/***/ ((__unused_webpack_module, exports) => { -convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; +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 */ +/** + * 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 -convert.gray.hsl = function (args) { - return [0, 0, args[0]]; -}; +/***/ }), -convert.gray.hsv = convert.gray.hsl; +/***/ 32154: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var node_1 = __nccwpck_require__(16411); +var string_1 = __nccwpck_require__(66538); +var fallbackGlobalObject = {}; +/** + * Safely get global scope object + * + * @returns Global scope object + */ +function getGlobalObject() { + return (node_1.isNodeEnv() + ? global + : typeof window !== 'undefined' + ? window + : typeof self !== 'undefined' + ? self + : fallbackGlobalObject); +} +exports.getGlobalObject = getGlobalObject; +/** + * UUID4 generator + * + * @returns string Generated UUID4. + */ +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])); + } + // 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 {}; + } + 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(); + } + // 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; +/** + * 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 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'; +} +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; +/** + * A safe form of location.href + */ +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-]+)*))?$/; +/** + * Parses input into a SemVer interface + * @param input string representation of a semver version + */ +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 +/** + * 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 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; + } + return defaultRetryAfter; +} +exports.parseRetryAfterHeader = parseRetryAfterHeader; +/** + * This function adds context (pre/post/line) lines to the provided frame + * + * @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 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; +/** + * Strip the query string and fragment off of a given URL or path (if present) + * + * @param urlPath Full URL or path, including possible query string and/or fragment + * @returns URL or path without query string or fragment + */ +function stripUrlQueryAndFragment(urlPath) { + // eslint-disable-next-line no-useless-escape + return urlPath.split(/[\?#]/, 1)[0]; +} +exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; +//# sourceMappingURL=misc.js.map -convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; +/***/ }), -convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; +/***/ 16411: +/***/ ((module, exports, __nccwpck_require__) => { -convert.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; +/* 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); +/** + * Checks whether we're in the Node.js or Browser environment + * + * @returns Answer to given question + */ +function isNodeEnv() { + return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; +} +exports.isNodeEnv = isNodeEnv; +/** + * Requires a module which is protected against bundler minification. + * + * @param request The module path to resolve + */ +// 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); +} +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']; +/** + * Normalizes data from the request object, accounting for framework differences. + * + * @param req The request object from which to extract data + * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not + * provided. + * @returns An object containing normalized request data + */ +function extractNodeRequestData(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 + // koa: req.header + var headers = (req.headers || req.header || {}); + // method: + // node, express, koa: req.method + var method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node: req.headers.host + var host = req.hostname || req.host || headers.host || ''; + // protocol: + // node: + // 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 + var originalUrl = (req.originalUrl || req.url || ''); + // absolute url + var absoluteUrl = protocol + "://" + host + originalUrl; + keys.forEach(function (key) { + switch (key) { + case 'headers': + requestData.headers = headers; + break; + case 'method': + requestData.method = method; + break; + case 'url': + requestData.url = absoluteUrl; + break; + case 'cookies': + // cookies: + // node, express, koa: req.headers.cookie + // vercel, sails.js, express (w/ cookie middleware): req.cookies + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = req.cookies || dynamicRequire(module, 'cookie').parse(headers.cookie || ''); + break; + case 'query_string': + // query string: + // node: req.url (raw) + // express, koa: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = dynamicRequire(module, 'url').parse(originalUrl || '', false).query; + break; + case 'data': + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // node, express, koa: req.body + if (req.body !== undefined) { + requestData.data = is_1.isString(req.body) ? req.body : JSON.stringify(object_1.normalize(req.body)); + } + break; + default: + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = req[key]; + } + } + }); + return requestData; +} +exports.extractNodeRequestData = extractNodeRequestData; +//# sourceMappingURL=node.js.map - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; +/***/ }), -convert.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; +/***/ 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); +/** + * Wrap a given object method with a higher-order function + * + * @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 + */ +function fill(source, name, replacement) { + if (!(name in source)) { + return; + } + 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 + } + } + 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 (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; + } + } + 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; + } + // 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**'; + } +} +exports.normalize = normalize; +/** + * 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; + } + return string_1.truncate(serialized, maxLength); + } + return ''; +} +exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; +/** + * Given any object, return the new object with removed keys that value was `undefined`. + * Works recursively on objects and arrays. + */ +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 /***/ }), -/***/ 86931: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const conversions = __nccwpck_require__(97391); -const route = __nccwpck_require__(30880); - -const convert = {}; - -const models = Object.keys(conversions); - -function wrapRaw(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - return fn(args); - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } +/***/ 39188: +/***/ ((__unused_webpack_module, exports) => { - return wrappedFn; +// 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; } - -function wrapRounded(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - const result = fn(args); - - // 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]); - } - } - - return result; - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; +// 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) : []; } - -models.forEach(fromModel => { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - const routes = route(fromModel); - const routeModels = Object.keys(routes); - - routeModels.forEach(toModel => { - const fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); - -module.exports = convert; - +// 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; + } + } + 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; +} +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 /***/ }), -/***/ 30880: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const conversions = __nccwpck_require__(97391); - -/* - This function routes a model to all other models. - - 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). - - conversions that are not possible simply are not included. -*/ - -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 - }; - } +/***/ 1243: +/***/ ((__unused_webpack_module, exports) => { - return graph; +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 -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; // Unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); +/***/ }), - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; +/***/ 31811: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } +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 to the queue. + * + * @param task Can be any PromiseLike + * @returns The original promise. + */ + PromiseBuffer.prototype.add = function (task) { + 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); + } + 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 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. + */ + PromiseBuffer.prototype.drain = function (timeout) { + 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); + }) + .then(null, function () { + resolve(true); + }); + }); + }; + return PromiseBuffer; +}()); +exports.PromiseBuffer = PromiseBuffer; +//# sourceMappingURL=promisebuffer.js.map - return graph; -} +/***/ }), -function link(from, to) { - return function (args) { - return to(from(args)); - }; +/***/ 5986: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var defaultFunctionName = ''; +/** + * Safely extract function name from itself + */ +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== 'function') { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; + } + catch (e) { + // Just accessing custom props in some Selenium environments + // can cause a "Permission denied" exception (see raven-js#495). + return defaultFunctionName; + } } +exports.getFunctionName = getFunctionName; +//# sourceMappingURL=stacktrace.js.map -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; - } +/***/ 66538: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - fn.conversion = path; - return fn; +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}'; + } + 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 ''; + } + 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); +} +exports.safeJoin = safeJoin; +/** + * 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 + */ +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 -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; - } +/***/ 88714: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - conversion[toModel] = wrapConversion(toModel, graph); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var logger_1 = __nccwpck_require__(15577); +var misc_1 = __nccwpck_require__(32154); +/** + * Tells whether current environment supports ErrorEvent objects + * {@link supportsErrorEvent}. + * + * @returns Answer to the given question. + */ +function supportsErrorEvent() { + try { + new ErrorEvent(''); + return true; + } + catch (e) { + return false; + } +} +exports.supportsErrorEvent = supportsErrorEvent; +/** + * Tells whether current environment supports DOMError objects + * {@link supportsDOMError}. + * + * @returns Answer to the given question. + */ +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; +/** + * Tells whether current environment supports DOMException objects + * {@link supportsDOMException}. + * + * @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}. + * + * @returns Answer to the given question. + */ +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; +/** + * 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()); +} +/** + * Tells whether current environment supports Fetch API natively + * {@link supportsNativeFetch}. + * + * @returns true if `window.fetch` is natively implemented, false otherwise + */ +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; +/** + * Tells whether current environment supports ReportingObserver API + * {@link supportsReportingObserver}. + * + * @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}. + * + * @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}. + * + * @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 - return conversion; -}; +/***/ }), +/***/ 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 + */ +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 /***/ }), -/***/ 78510: -/***/ ((module) => { - -"use strict"; - +/***/ 1735: +/***/ ((module, exports, __nccwpck_require__) => { -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] +/* 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); +/** + * 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". + */ +var dateTimestampSource = { + nowSeconds: function () { return Date.now() / 1000; }, }; - +/** + * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not + * support the API. + * + * Wrapping the native API works around differences in behavior from different browsers. + */ +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, + }; +} +/** + * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't + * implement the API. + */ +function getNodePerformance() { + try { + var perfHooks = node_1.dynamicRequire(module, 'perf_hooks'); + return perfHooks.performance; + } + catch (_) { + return undefined; + } +} +/** + * 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. + */ +exports.dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); +/** + * 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. + */ +exports.timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); +// Re-exported with an old name for backwards-compatibility. +exports.timestampWithMs = exports.timestampInSeconds; +/** + * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. + */ +exports.usingPerformanceAPI = platformPerformance !== undefined; +/** + * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the + * performance API is available. + */ +exports.browserPerformanceTimeOrigin = (function () { + var performance = misc_1.getGlobalObject().performance; + if (!performance) { + return undefined; + } + if (performance.timeOrigin) { + return performance.timeOrigin; + } + // 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 /***/ }), -/***/ 43595: +/***/ 83633: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -The MIT License (MIT) -Original Library - - Copyright (c) Marak Squires -Additional functionality - - Copyright (c) Sindre Sorhus (sindresorhus.com) +/** + * Module dependencies. + * @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: +var Negotiator = __nccwpck_require__(95385) +var mime = __nccwpck_require__(66918) -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 = Accepts -*/ +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } -var colors = {}; -module['exports'] = colors; + this.headers = req.headers + this.negotiator = new Negotiator(req) +} -colors.themes = {}; +/** + * 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 util = __nccwpck_require__(31669); -var ansiStyles = colors.styles = __nccwpck_require__(73104); -var defineProps = Object.defineProperties; -var newLineRegex = new RegExp(/[\r\n]+/g); +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ -colors.supportsColor = __nccwpck_require__(10662).supportsColor; + // 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 (typeof colors.enabled === 'undefined') { - colors.enabled = colors.supportsColor() !== false; -} + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } -colors.enable = function() { - colors.enabled = true; -}; + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } -colors.disable = function() { - colors.enabled = false; -}; + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] -colors.stripColors = colors.strip = function(str) { - return ('' + str).replace(/\x1B\[\d+m/g, ''); -}; + return first + ? types[mimes.indexOf(first)] + : false +} -// eslint-disable-next-line no-unused-vars -var stylize = colors.stylize = function stylize(str, style) { - if (!colors.enabled) { - return str+''; - } +/** + * 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 + */ - var styleMap = ansiStyles[style]; +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ - // 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); + // 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] + } } - return styleMap.open + str + styleMap.close; -}; - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var escapeStringRegexp = function(str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() } - return str.replace(matchOperatorsRe, '\\$&'); -}; -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; -} - -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; -})(); + return this.negotiator.encodings(encodings)[0] || false +} -var proto = defineProps(function colors() {}, styles); +/** + * 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 + */ -function applyStyle() { - var args = Array.prototype.slice.call(arguments); +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ - 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); + // 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] } - }).join(' '); + } - if (!colors.enabled || !str) { - return str; + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() } - var newLinesPresent = str.indexOf('\n') != -1; + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * 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 + */ - var nestedStyles = this._styles; +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ - 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; - }); + // 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] } } - 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 colors[theme[style]](str); - }; - })(style); + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() } -}; -function init() { - var ret = {}; - Object.keys(styles).forEach(function(name) { - ret[name] = { - get: function() { - return build([name]); - }, - }; - }); - return ret; + return this.negotiator.languages(languages)[0] || false } -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); - -// 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); +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ -for (var map in colors.maps) { - (function(map) { - colors[map] = function(str) { - return sequencer(colors.maps[map], str); - }; - })(map); +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type } -defineProps(colors, init()); - - -/***/ }), - -/***/ 31302: -/***/ ((module) => { +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ -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; -}; +function validMime (type) { + return typeof type === 'string' +} /***/ }), -/***/ 45610: -/***/ ((module) => { - -// 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); - - 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; - } - +/***/ 2122: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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; - } +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ - 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); -}; +/** + * Module exports. + */ +module.exports = __nccwpck_require__(58376) /***/ }), -/***/ 76936: -/***/ ((module) => { - -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); - } - }; -}; - +/***/ 66918: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ 75210: -/***/ ((module) => { -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); - } - }; -}; +/** + * Module dependencies. + * @private + */ +var db = __nccwpck_require__(2122) +var extname = (__nccwpck_require__(71017).extname) -/***/ }), +/** + * Module variables. + * @private + */ -/***/ 13441: -/***/ ((module) => { +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i -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); - }; -}; +/** + * 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) -/***/ 12989: -/***/ ((module) => { +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -module['exports'] = function(colors) { - return function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; -}; +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()] -/***/ }), + if (mime && mime.charset) { + return mime.charset + } -/***/ 73104: -/***/ ((module) => { + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } -/* -The MIT License (MIT) + return false +} -Copyright (c) Sindre Sorhus (sindresorhus.com) +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ -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 contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str -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 (!mime) { + return false + } -*/ + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } -var styles = {}; -module['exports'] = styles; - -var codes = { - reset: [0, 0], - - 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], - - 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], - - bgBrightRed: [101, 49], - bgBrightGreen: [102, 49], - bgBrightYellow: [103, 49], - bgBrightBlue: [104, 49], - bgBrightMagenta: [105, 49], - bgBrightCyan: [106, 49], - bgBrightWhite: [107, 49], - - // 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], - -}; - -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'; -}); + return mime +} +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -/***/ }), +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } -/***/ 10223: -/***/ ((module) => { + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) -"use strict"; -/* -MIT License + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] -Copyright (c) Sindre Sorhus (sindresorhus.com) + if (!exts || !exts.length) { + return false + } -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: + return exts[0] +} -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ -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 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) + if (!extension) { + return false + } -module.exports = function(flag, argv) { - argv = argv || process.argv; + return exports.types[extension] || false +} - var terminatorPos = argv.indexOf('--'); - var prefix = /^-{1,2}/.test(flag) ? '' : '--'; - var pos = argv.indexOf(prefix + flag); +/** + * Populate the extensions and types maps. + * @private + */ - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; +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 + } -/***/ 10662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // mime -> extensions + extensions[type] = exts -"use strict"; -/* -The MIT License (MIT) + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] -Copyright (c) Sindre Sorhus (sindresorhus.com) + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) -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: + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + // set the extension -> mime + types[extension] = type + } + }) +} -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. -*/ +/***/ }), +/***/ 49690: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { -var os = __nccwpck_require__(12087); -var hasFlag = __nccwpck_require__(10223); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = __nccwpck_require__(82361); +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; + } + 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); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map -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; -} +/***/ 66570: +/***/ ((__unused_webpack_module, exports) => { -function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level: level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, - }; +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["default"] = promisify; +//# sourceMappingURL=promisify.js.map -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } - - if (hasFlag('color=16m') || hasFlag('color=full') - || hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } - - var min = forceColor ? 1 : 0; - - 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 1; - } +/***/ 61231: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { - return sign in env; - }) || env.CI_NAME === 'codeship') { - return 1; - } - return min; - } +const indentString = __nccwpck_require__(98043); +const cleanStack = __nccwpck_require__(27972); - if ('TEAMCITY_VERSION' in env) { - return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 - ); - } +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - if ('TERM_PROGRAM' in env) { - var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Hyper': - return 3; - case 'Apple_Terminal': - return 2; - // No default - } - } + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } + 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); + } - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } + return new Error(error); + }); - if ('COLORTERM' in env) { - return 1; - } + 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 (env.TERM === 'dumb') { - return min; - } + this.name = 'AggregateError'; - return min; -} + Object.defineProperty(this, '_errors', {value: errors}); + } -function getSupportLevel(stream) { - var level = supportsColor(stream); - return translateLevel(level); + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } } -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr), -}; +module.exports = AggregateError; /***/ }), -/***/ 41997: +/***/ 52068: /***/ ((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; +/* module decorator */ module = __nccwpck_require__.nmd(module); -/***/ }), +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; -/***/ 89296: -/***/ (function(module) { +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; -/* 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 () { +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; - var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; - function indexOrEnd(str, q) { - return str.indexOf(q) === -1 ? str.length : str.indexOf(q); - } +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); - 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; - } + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); - function tryParse(v) { - return isNaN(Number(v)) ? v : Number(v); - } + return value; + }, + enumerable: true, + configurable: true + }); +}; - 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)'); - } - } +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = __nccwpck_require__(86931); + } - function compareVersions(v1, v2) { - [v1, v2].forEach(validate); + const offset = isBackground ? 10 : 0; + const styles = {}; - var s1 = split(v1); - var s2 = split(v2); + 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); + } + } - 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 styles; +}; - if (n1 > n2) return 1; - if (n2 > n1) return -1; - } +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], - var sp1 = s1[s1.length - 1]; - var sp2 = s2[s2.length - 1]; + // 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], - if (sp1 && sp2) { - var p1 = sp1.split('.').map(tryParse); - var p2 = sp2.split('.').map(tryParse); + // 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] + } + }; - 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; + // 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; - if (p1[i] > p2[i]) return 1; - if (p2[i] > p1[i]) return -1; - } - } else if (sp1 || sp2) { - return sp1 ? -1 : 1; - } + 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` + }; - return 0; - }; + group[styleName] = styles[styleName]; - var allowedOperators = [ - '>', - '>=', - '=', - '<', - '<=' - ]; + codes.set(style[0], style[1]); + } - var operatorResMap = { - '>': [1], - '>=': [0, 1], - '=': [0], - '<=': [-1, 0], - '<': [-1] - }; + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } - 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('|')); - } - } + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); - compareVersions.validate = function(version) { - return typeof version === 'string' && semver.test(version); - } + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; - compareVersions.compare = function (v1, v2, operator) { - // Validate operator - validateOperator(operator); + 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)); - // 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; - } + return styles; +} - return compareVersions; -})); +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); /***/ }), -/***/ 53921: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ 62003: +/***/ ((module) => { /** - * Module exports. - * @public + * Expose `arrayFlatten`. */ - -module.exports = contentDisposition -module.exports.parse = parse +module.exports = arrayFlatten /** - * Module dependencies. - * @private + * 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] -var basename = __nccwpck_require__(85622).basename -var Buffer = __nccwpck_require__(21867).Buffer - -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private - */ + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + return result +} /** - * RegExp to match percent encoding escape. - * @private + * 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] -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g - -/** - * RegExp to match non-latin1 characters. - * @private - */ + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + return result +} /** - * RegExp to match quoted-pair in RFC 2616 + * Flatten an array, with the ability to define a depth. * - * quoted-pair = "\" CHAR - * CHAR = - * @private + * @param {Array} array + * @param {Number} depth + * @return {Array} */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + return flattenWithDepth(array, [], depth) +} -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ -var QUOTE_REGEXP = /([\\"])/g +/***/ }), -/** - * 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 - */ +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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 = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) +}; -/** - * 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 - */ -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!#$&+.^_`|~-])+)$/ +/***/ }), -/** - * 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 - */ +/***/ 1700: +/***/ ((module) => { -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex +// API +module.exports = abort; /** - * Create an attachment Content-Disposition header. + * Aborts leftover active jobs * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public + * @param {object} state - current state object */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); -function contentDisposition (filename, options) { - var opts = options || {} - - // get type - var type = opts.type || 'attachment' - - // get parameters - var params = createparams(filename, opts.fallback) - - // format into string - return format(new ContentDisposition(type, params)) + // reset leftover jobs + state.jobs = {}; } /** - * Create parameters object from filename and fallback. + * Cleans up leftover job by invoking abort function for the provided job id * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private + * @this state + * @param {string|number} key - job id to abort */ - -function createparams (filename, fallback) { - if (filename === undefined) { - return - } - - var params = {} - - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } - - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } - - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } - - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') - } - - // restrict to file base name - var name = basename(filename) - - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) - - // 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 - } - - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); } - - return params } -/** - * 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 +/***/ }), - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') - } +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // start with normalized type - var string = String(type).toLowerCase() +var defer = __nccwpck_require__(15295); - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() +// API +module.exports = async; - for (var i = 0; i < params.length; i++) { - param = params[i] +/** + * 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; - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) + // check if async happened + defer(function() { isAsync = true; }); - string += '; ' + param + '=' + val + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); } - } - - return string + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; } + +/***/ }), + +/***/ 15295: +/***/ ((module) => { + +module.exports = defer; + /** - * Decode a RFC 6987 field value (gracefully). + * Runs provided function on next iteration of the event loop * - * @param {string} str - * @return {string} - * @private + * @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 + ); -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) - - if (!match) { - throw new TypeError('invalid extended field value') + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); } +} - var charset = match[1].toLowerCase() - var encoded = match[2] - var value - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) +/***/ }), - 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') - } +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return value -} +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) + ; + +// API +module.exports = iterate; /** - * Get ISO-8859-1 version of string. + * Iterates over each job object * - * @param {string} val - * @return {string} - * @private + * @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; -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') + 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); + }); } /** - * Parse Content-Disposition header string. + * Runs iterator over provided job element * - * @param {string} string - * @return {object} - * @public + * @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; -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); } - - var match = DISPOSITION_TYPE_REGEXP.exec(string) - - if (!match) { - throw new TypeError('invalid type format') + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); } - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() + return aborter; +} - var key - var names = [] - var params = {} - var value - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index +/***/ }), - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } +/***/ 42474: +/***/ ((module) => { - index += match[0].length - key = match[1].toLowerCase() - value = match[2] +// API +module.exports = state; - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') +/** + * 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 } + ; - names.push(key) - - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) + 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]); + }); + } - // overwrite existing value - params[key] = value - continue - } + return initState; +} - if (typeof params[key] === 'string') { - continue - } - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } +/***/ }), - params[key] = value - } +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; - return new ContentDisposition(type, params) -} +// API +module.exports = terminator; /** - * Percent decode a single character. + * Terminates jobs in the attached state context * - * @param {string} str - * @param {string} hex - * @return {string} - * @private + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} + // fast forward iteration index + this.index = this.size; -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ + // abort jobs + abort(this); -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() + // send back results we have so far + async(callback)(null, this.results); } -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ -function qstring (val) { - var str = String(val) +/***/ }), - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} +/***/ 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; /** - * Encode a Unicode string for HTTP (RFC 5987). + * Runs iterator over provided array elements in parallel * - * @param {string} val - * @return {string} - * @private + * @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); -function ustring (val) { - var str = String(val) + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); - return 'UTF-8\'\'' + encoded + state.index++; + } + + return terminator.bind(state, callback); } + +/***/ }), + +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var serialOrdered = __nccwpck_require__(3578); + +// Public API +module.exports = serial; + /** - * Class for parsed Content-Disposition header for v8 optimization + * Runs iterator over provided array elements in series * - * @public - * @param {string} type - * @param {object} parameters - * @constructor + * @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 ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); } /***/ }), -/***/ 99915: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ 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; /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * Runs iterator over provided sorted array elements in series * - * 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 ) + * @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 */ -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-]+$/ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); -/** - * 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 + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } -/** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g + state.index++; -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- Sort methods */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** - * Module exports. - * @public + * 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 */ - -exports.format = format -exports.parse = parse +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} /** - * Format object to media type. + * sort helper to sort array elements in descending order * - * @param {object} obj - * @return {string} - * @public + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - var parameters = obj.parameters - var type = obj.type +/***/ }), - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') - } +/***/ 86950: +/***/ ((module) => { - var string = type - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - for (var i = 0; i < params.length; i++) { - param = params[i] +/* global SharedArrayBuffer, Atomics */ - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') +if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { + const nil = new Int32Array(new SharedArrayBuffer(4)) + + 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') + } - string += '; ' + param + '=' + qstring(parameters[param]) + 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()){} } - return string + module.exports = sleep + } -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } +/***/ }), - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string +/***/ 83682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') +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 bindApi (hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) + hook.api = { remove: removeHookRef } + hook.remove = removeHookRef + + ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind] + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) + }) +} + +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} } + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook +} - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() +function HookCollection () { + var state = { + registry: {} + } - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') + var hook = register.bind(null, state) + bindApi(hook, state) + + return hook +} + +var collectionHookDeprecationMessageDisplayed = false +function Hook () { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') + collectionHookDeprecationMessageDisplayed = true } + return HookCollection() +} - var obj = new ContentType(type.toLowerCase()) +Hook.Singular = HookSingular.bind() +Hook.Collection = HookCollection.bind() - // parse parameters - if (index !== -1) { - var key - var match - var value +module.exports = Hook +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook +module.exports.Singular = Hook.Singular +module.exports.Collection = Hook.Collection - 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] +/***/ 5549: +/***/ ((module) => { - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } +module.exports = addHook - obj.parameters[key] = value +function addHook (state, kind, name, hook) { + var orig = hook + if (!state.registry[name]) { + state.registry[name] = [] + } + + if (kind === 'before') { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)) } + } - if (index !== header.length) { - throw new TypeError('invalid parameter format') + 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 obj + if (kind === 'error') { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options) + }) + } + } + + state.registry[name].push({ + hook: hook, + orig: orig + }) } -/** - * 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'] +/***/ 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 (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') + if (!options) { + options = {} } - return header + 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)() + }) } -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @private - */ -function qstring (val) { - var str = String(val) +/***/ }), - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } +/***/ 6819: +/***/ ((module) => { - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') +module.exports = removeHook + +function removeHook (state, name, method) { + if (!state.registry[name]) { + return } - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} + var index = state.registry[name] + .map(function (registered) { return registered.orig }) + .indexOf(method) -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type + if (index === -1) { + return + } + + state.registry[name].splice(index, 1) } /***/ }), -/***/ 61579: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 97076: +/***/ ((module, exports, __nccwpck_require__) => { -/** - * Module dependencies. +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -var crypto = __nccwpck_require__(76417); + /** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private + * Module dependencies. + * @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(/\=+$/, ''); -}; +var deprecate = __nccwpck_require__(18883)('body-parser') /** - * 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 + * Cache of loaded parsers. + * @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; -}; +var parsers = Object.create(null) /** - * Private + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded */ -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} - - -/***/ }), +/** + * Module exports. + * @type {Parsers} + */ -/***/ 93658: -/***/ ((__unused_webpack_module, exports) => { +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed +/** + * JSON parser. + * @public */ - +Object.defineProperty(exports, "json", ({ + configurable: true, + enumerable: true, + get: createParserGetter('json') +})) /** - * Module exports. + * Raw parser. * @public */ -exports.parse = parse; -exports.serialize = serialize; +Object.defineProperty(exports, "raw", ({ + configurable: true, + enumerable: true, + get: createParserGetter('raw') +})) /** - * Module variables. - * @private + * Text parser. + * @public */ -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; +Object.defineProperty(exports, "text", ({ + configurable: true, + enumerable: true, + get: createParserGetter('text') +})) /** - * 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 + * URL-encoded parser. + * @public */ -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; +Object.defineProperty(exports, "urlencoded", ({ + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +})) /** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values + * Create a middleware to parse json and urlencoded bodies. * - * @param {string} str * @param {object} [options] - * @return {object} + * @return {function} + * @deprecated * @public */ -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); +function bodyParser (options) { + var opts = {} + + // exclude type option + if (options) { + for (var prop in options) { + if (prop !== 'type') { + opts[prop] = options[prop] + } + } } - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; - } +/** + * Create a getter for loading a parser. + * @private + */ - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } +/** + * Load a parser module. + * @private + */ - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); - } +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser } - return obj; + // 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) } -/** - * 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 + +/***/ }), + +/***/ 88862: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -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'); - } +/** + * Module dependencies. + * @private + */ - var value = enc(val); +var createError = __nccwpck_require__(95193) +var getBody = __nccwpck_require__(47742) +var iconv = __nccwpck_require__(19032) +var onFinished = __nccwpck_require__(92098) +var zlib = __nccwpck_require__(59796) - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } +/** + * Module exports. + */ - var str = name + '=' + value; +module.exports = read - 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); - } +/** + * 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 + */ - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream - str += '; Domain=' + opt.domain; - } + // flag as parsed + req._body = true - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify - str += '; Path=' + opt.path; + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) } - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); - } + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding - str += '; Expires=' + opt.expires.toUTCString(); + // 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' + })) } - if (opt.httpOnly) { - str += '; HttpOnly'; - } + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error - if (opt.secure) { - str += '; Secure'; - } + 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) + } - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; + // read off entire request + stream.resume() + onFinished(req, function onfinished () { + next(createError(400, _error)) + }) + return + } - 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'); + // 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 + } } - } - return str; + // 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() + }) } /** - * Try decoding a string using a decoding function. + * Get the content stream of the request. * - * @param {string} str - * @param {function} decode - * @private + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private */ -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} +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' + }) + } -/***/ 65507: -/***/ ((__unused_webpack_module, exports) => { + 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' + }) + } -/* jshint node: true */ -(function () { - "use strict"; + return stream +} - 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("; "); - }; +/***/ 20859: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Cookie.prototype.toValueString = function toValueString() { - return this.name + "=" + this.value; - }; +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * 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 dependencies. + * @private + */ - this.name = key; - this.value = value; +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) - 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. + */ - if (!this.explicit_path) { - this.path = request_path || "/"; - } - if (!this.explicit_domain) { - this.domain = request_domain; - } +module.exports = json - return this; - } - return new Cookie().parse(str, request_domain, request_path); - }; +/** + * 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 + */ - 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; - }; +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex - 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; - }; +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ - function CookieJar() { - var cookies, cookies_list, collidable_cookie; - if (this instanceof CookieJar) { - cookies = Object.create(null); //name: [Cookie] +function json (options) { + var opts = options || {} - 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; - } + 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 (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 (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - return this; - } - return new CookieJar(); + // 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 {} } - 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 successful; - }; -}()); + 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 + }) + } + } -/***/ 51512: -/***/ (function(module) { + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } -/* - * 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. - */ + req.body = req.body || {} -(function(global) { - 'use strict'; + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - 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); - }); - }; - })(); + debug('content-type %j', req.headers['content-type']) - 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' - }; + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } - // Internationalization strings - 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' - ] - }; + // 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 + } -function pad(val, len) { - val = String(val); - len = len || 2; - while (val.length < len) { - val = '0' + val; + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) } - 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 + * Create strict violation syntax error matching native error. * - * @param {Object} `date` - * @return {Number} + * @param {string} str + * @param {string} char + * @return {Error} + * @private */ -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); - // Take January 4th as it is always in week 1 (see ISO 8601) - var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = str.substring(0, index) + '#' - // Change date to Thursday same week - firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); + 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 + }) + } +} - // Check if daylight-saving-time-switch occurred and correct for it - var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); - targetThursday.setHours(targetThursday.getHours() - ds); +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ - // Number of weeks between target Thursday and first Thursday - var weekDiff = (targetThursday - firstThursday) / (86400000*7); - return 1 + Math.floor(weekDiff); +function firstchar (str) { + return FIRST_CHAR_REGEXP.exec(str)[1] } /** - * Get ISO-8601 numeric representation of the day of the week - * 1 (for Monday) through 7 (for Sunday) - * - * @param {Object} `date` - * @return {Number} + * Get the charset of a request. + * + * @param {object} req + * @api private */ -function getDayOfWeek(date) { - var dow = date.getDay(); - if(dow === 0) { - dow = 7; + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined } - return dow; } /** - * kind-of shortcut - * @param {*} val - * @return {String} + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} */ -function kindOf(val) { - if (val === null) { - return 'null'; - } - - if (val === undefined) { - return 'undefined'; - } - if (typeof val !== 'object') { - return typeof val; - } +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) - if (Array.isArray(val)) { - return 'array'; + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } } - return {}.toString.call(val) - .slice(8, -1).toLowerCase(); -}; + // 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 +} +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ - if (typeof define === 'function' && define.amd) { - define(function () { - return dateFormat; - }); - } else if (true) { - module.exports = dateFormat; - } else {} -})(this); +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} /***/ }), -/***/ 84697: -/***/ ((module) => { +/***/ 49609: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + /** - * Helpers. + * Module dependencies. */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; +var bytes = __nccwpck_require__(86966) +var debug = __nccwpck_require__(7471)('body-parser:raw') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) /** - * 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. */ -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) - ); -}; +module.exports = raw /** - * Parse the given `str` and return milliseconds. + * Create a middleware to parse raw bodies. * - * @param {String} str - * @return {Number} - * @api private + * @param {object} [options] + * @return {function} + * @api 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|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; +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') } - 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; + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf } -} -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + return function rawParser (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 + } -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'; + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) } - return ms + 'ms'; } /** - * Long format for `ms`. + * Get the simple type checker. * - * @param {Number} ms - * @return {String} - * @api private + * @param {string} type + * @return {function} */ -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'); +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) } - return ms + ' ms'; } -/** - * Pluralization helper. - */ -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} +/***/ }), +/***/ 26382: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { -/* eslint-env browser */ /** - * This is the web browser implementation of `debug()`. + * Module dependencies. */ -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`.'); - } - }; -})(); +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) /** - * Colors. + * Module exports. */ -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.exports = text /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Create a middleware to parse text bodies. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * @param {object} [options] + * @return {function} + * @api public */ -// 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; - } +function text (options) { + var opts = options || {} - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + 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 - // 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+)/)); -} + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } -/** - * Colorize log arguments if enabled. - * - * @api public - */ + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + function parse (buf) { + return buf + } - if (!this.useColors) { - return; - } + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + req.body = req.body || {} - // 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; - } - }); + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - args.splice(lastC, 0, c); -} + debug('content-type %j', req.headers['content-type']) -/** - * 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 || (() => {}); + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } -/** - * 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? - } + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } } /** - * Load `namespaces`. + * Get the charset of a request. * - * @return {String} returns the previously persisted debug modes + * @param {object} req * @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; - } - return r; +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } } /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * Get the simple type checker. * - * @return {LocalStorage} - * @api private + * @param {string} type + * @return {function} */ -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? - } +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } } -module.exports = __nccwpck_require__(46243)(exports); -const {formatters} = module.exports; +/***/ }), -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. +/***/ 76100: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; -/***/ }), +/** + * Module dependencies. + * @private + */ -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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) + +/** + * Module exports. + */ +module.exports = urlencoded /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Cache of parser modules. */ -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; +var parsers = Object.create(null) - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ - /** - * The currently active debug mode names, and names to skip. - */ +function urlencoded (options) { + var opts = options || {} - createDebug.names = []; - createDebug.skips = []; + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } - /** - * 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 = {}; + 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 - /** - * 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; + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; + function parse (body) { + return body.length + ? queryparse(body) + : {} + } - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } - const self = debug; + req.body = req.body || {} - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - args[0] = createDebug.coerce(args[0]); + debug('content-type %j', req.headers['content-type']) - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } - // 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); + // 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 + } - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +/** + * Get the extended query parser. + * + * @param {object} options + */ - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') - 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. + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, - set: v => { - enableOverride = v; - } - }); + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) - return debug; - } + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + var arrayLimit = Math.max(100, paramCount) - /** - * 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); + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} - createDebug.names = []; - createDebug.skips = []; +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ - namespaces = split[i].replace(/\*/g, '.*?'); +function parameterCount (body, limit) { + var count = 0 + var index = 0 - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ - /** - * 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; - } + if (count === limit) { + return undefined + } + } - /** - * 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; - } + return count +} - let i; - let len; +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +function parser (name) { + var mod = parsers[name] - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + if (mod !== undefined) { + return mod.parse + } - return false; - } + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = __nccwpck_require__(22760) + break + case 'querystring': + mod = __nccwpck_require__(63477) + break + } - /** - * 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(/\.\*\?$/, '*'); - } + // store to prevent invoking require() + parsers[name] = mod - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + return mod.parse +} - /** - * 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`.'); - } +/** + * Get the simple query parser. + * + * @param {object} options + */ - createDebug.enable(createDebug.load()); +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') - return createDebug; -} + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } -module.exports = setup; + 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' + }) + } -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} /** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. + * Get the simple type checker. + * + * @param {string} type + * @return {function} */ -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } } /***/ }), -/***/ 35332: +/***/ 15377: /***/ ((module, exports, __nccwpck_require__) => { /** - * Module dependencies. - */ - -const tty = __nccwpck_require__(33867); -const util = __nccwpck_require__(31669); - -/** - * This is the Node.js implementation of `debug()`. + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. */ -exports.init = init; +exports = module.exports = __nccwpck_require__(22552); 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`.' -); +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); /** * Colors. */ -exports.colors = [6, 2, 3, 4, 5, 1]; - -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 (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. -} +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; /** - * Build up the default `inspectOpts` object from the environment variables. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -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(); - }); - - // 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); - } +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; + } - obj[prop] = val; - return obj; -}, {}); + // 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+)/)); +} /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + /** - * Adds ANSI color escape codes if enabled. + * Colorize log arguments if enabled. * * @api public */ -function formatArgs(args) { - const {namespace: name, useColors} = this; +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; - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - 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]; - } -} + // 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; + } + }); -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; + args.splice(lastC, 0, c); } /** - * Invokes `util.format()` with the specified arguments and writes to stderr. + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public */ -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); +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); } /** @@ -40822,14 +23967,15 @@ function log(...args) { * @param {String} namespaces * @api private */ + 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; - } + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} } /** @@ -40840,12045 +23986,11237 @@ function save(namespaces) { */ function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ + var r; + try { + r = exports.storage.debug; + } catch(e) {} -function init(debug) { - debug.inspectOpts = {}; + // 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; + } - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } + return r; } -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; - /** - * Map %o to `util.inspect()`, all on a single line. + * Enable namespaces listed in `localStorage.debug` initially. */ -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; +exports.enable(load()); /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * 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 */ -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), - -/***/ 56323: -/***/ ((module) => { - -"use strict"; - - -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; - -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} - -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); - - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) -} - -// 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; - -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} - -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} - -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value -} - -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} - -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} - -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return target.propertyIsEnumerable(symbol) - }) - : [] -} - -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) -} - -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } -} - -// 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. -} - -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 - } - - 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 -} - -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; - - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } - - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) -}; - -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]; - } - - delayedStream.source = source; +/***/ 22552: +/***/ ((module, exports, __nccwpck_require__) => { - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - return delayedStream; -}; +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); -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); +/** + * The currently active debug mode names, and names to skip. + */ -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; +exports.names = []; +exports.skips = []; -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } +/** + * 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". + */ - this.source.resume(); -}; +exports.formatters = {}; -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; +/** + * Previous log timestamp. + */ -DelayedStream.prototype.release = function() { - this._released = true; +var prevTime; - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; +function selectColor(namespace) { + var hash = 0, i; -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - this._bufferedEvents.push(args); -}; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } +function createDebug(namespace) { - if (this.dataSize <= this.maxDataSize) { - return; - } + function debug() { + // disabled? + if (!debug.enabled) return; - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + 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]; + } -/***/ 42342: -/***/ ((module) => { + args[0] = exports.coerce(args[0]); -"use strict"; + 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); -/** - * 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); - } -} + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -/** - * ------------- - * PUBLIC API - * ------------- - */ + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); -/** - * 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 logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); } - 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]; -}; - -/** - * Alias for peakAt() - * @param i - * @returns {*} - */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; - -/** - * 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]; -}; - -/** - * Alias for peek() - * @returns {*} - */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; - -/** - * 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); -}; -/** - * Returns the current length of the queue - * @return {Number} - */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); + 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 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 debug; +} /** - * Add an item at the beginning of the list. - * @param item + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public */ -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); -}; -/** - * 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; -}; +function enable(namespaces) { + exports.save(namespaces); -/** - * 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(); - } + exports.names = []; + exports.skips = []; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; -/** - * 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; -}; + 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 + '$')); + } + } +} /** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} + * Disable debug output. + * + * @api public */ -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; -}; + +function disable() { + exports.enable(''); +} /** - * 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} + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public */ -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; + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; } - 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]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - } 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--; + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; + return false; +} /** - * 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. + * Coerce `val`. * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} + * @param {Mixed} val + * @return {Mixed} + * @api private */ -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); - } -}; + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + + +/***/ }), + +/***/ 7471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Soft clear - does not reset capacity. + * Detect Electron renderer process, which is node, but we should + * treat as a browser. */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(15377); +} else { + module.exports = __nccwpck_require__(74117); +} + + +/***/ }), + +/***/ 74117: +/***/ ((module, exports, __nccwpck_require__) => { /** - * Returns true or false whether the list is empty. - * @returns {boolean} + * Module dependencies. */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; + +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); /** - * Returns an array of all queue items. - * @returns {Array} + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; + +exports = module.exports = __nccwpck_require__(22552); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; /** - * ------------- - * INTERNALS - * ------------- + * Colors. */ +exports.colors = [6, 2, 3, 4, 5, 1]; + /** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; + +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.: * - * @param fullCopy - * @returns {Array} - * @private + * $ DEBUG_FD=3 node script.js 3>debug.log */ -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; -}; + +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); /** - * Grows the internal list array. - * @private + * Is stdout a TTY? Colored output is enabled when `true`. */ -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; - } - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; - - this._list.length *= 2; - this._capacityMask = (this._capacityMask << 1) | 1; -}; +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} /** - * Shrinks the internal list array. - * @private + * Map %o to `util.inspect()`, all on a single line. */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; + +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. + */ -module.exports = Denque; +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; -/***/ 18883: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ + 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]; + } +} /** - * Module dependencies. + * Invokes `util.format()` with the specified arguments and writes to `stream`. */ -var callSiteToString = __nccwpck_require__(69829).callSiteToString -var eventListenerCount = __nccwpck_require__(69829).eventListenerCount -var relative = __nccwpck_require__(85622).relative +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} /** - * Module exports. + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ -module.exports = depd +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; + } +} /** - * Get the path to base files on. + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -var basePath = process.cwd() +function load() { + return process.env.DEBUG; +} /** - * Determine if namespace is contained in the string. + * 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 containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); - for (var i = 0; i < vals.length; i++) { - var val = vals[i] + // Note stream._type is used for test-module-load-list.js - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true - } - } + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - return false -} + // 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; -/** - * Convert a data descriptor to accessor descriptor. - */ + case 'FILE': + var fs = __nccwpck_require__(57147); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(41808); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - descriptor.get = function getter () { return value } + // 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 (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } + // 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!'); } - delete descriptor.value - delete descriptor.writable + // For supporting legacy API we put the FD here. + stream.fd = fd; - Object.defineProperty(obj, prop, descriptor) + stream._isStdio = true; - return descriptor + return stream; } /** - * Create arguments string to keep arity. + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function createArgumentsString (arity) { - var str = '' +function init (debug) { + debug.inspectOpts = {}; - for (var i = 0; i < arity; i++) { - str += ', arg' + i + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } - - return str.substr(2) } /** - * Create stack string from stack. + * Enable namespaces listed in `process.env.DEBUG` initially. */ -function createStackString (stack) { - var str = this.name + ': ' + this.namespace +exports.enable(load()); - if (this.message) { - str += ' deprecated ' + this.message - } - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } +/***/ }), - return str -} +/***/ 73233: +/***/ ((module) => { /** - * Create deprecate for namespace in caller. + * Helpers. */ -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[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 + */ - function deprecate (message) { - // call to self as log - log.call(deprecate, message) +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) + ); +}; - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) - - deprecate.function = wrapfunction - deprecate.property = wrapproperty +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - return deprecate +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; + } } /** - * Determine if namespace is ignored. + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private */ -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true +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'; +} - var str = process.env.NO_DEPRECATION || '' +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - // namespace ignored - return containsNamespace(str, namespace) +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; } /** - * Determine if namespace is traced. + * Pluralization helper. */ -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true +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 str = process.env.TRACE_DEPRECATION || '' - // namespace traced - return containsNamespace(str, namespace) -} +/***/ }), -/** - * Display deprecation message. - */ +/***/ 85442: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - // 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 +var Batcher, Events, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); - 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 - } +Batcher = function () { + class Batcher { + constructor(options = {}) { + this.options = options; + parser.load(this.options, this.defaults, this); + this.Events = new Events(this); + this._arr = []; - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] + this._resetPromise(); - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break + this._lastFlush = Date.now(); } - } - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - if (key !== undefined && key in this._warned) { - // already warned - return - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); - this._warned[key] = true + this._resolve(); - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return - } + add(data) { + var ret; - // 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') -} + this._arr.push(data); -/** - * Get call site location as array. - */ + ret = this._promise; -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() + if (this._arr.length === this.maxSize) { + this._flush(); + } else if (this.maxTime != null && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + + return ret; + } - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file } - var site = [file, line, colm] + ; + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; + return Batcher; +}.call(void 0); - site.callSite = callSite - site.name = callSite.getFunctionName() +module.exports = Batcher; - return site -} +/***/ }), -/** - * Generate a default message from the site. - */ +/***/ 83911: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name - // make useful anonymous name - if (!funcName) { - funcName = '' - } - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } +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; } - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } +function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -/** - * Format deprecation message without color. - */ +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg +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); } } - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } +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 formatted - } +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); - if (caller) { - formatted += ' at ' + formatLocation(caller) - } +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); - return formatted -} + 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, {}); -/** - * Format deprecation message with color. - */ + 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); -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 + this._queues.on("leftzero", () => { + var base; + return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; + }); - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + this._queues.on("zero", () => { + var base; + return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; + }); } - return formatted - } + _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."); + } + } - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } + ready() { + return this._store.ready; + } - return formatted -} + clients() { + return this._store.clients; + } -/** - * Format call site location. - */ + channel() { + return `b_${this.id}`; + } -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] -} + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -/** - * Get the stack as array of call sites. - */ + publish(message) { + return this._store.__publish__(message); + } -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) + chain(_limiter) { + this._limiter = _limiter; + return this; + } - // capture the stack - Error.captureStackTrace(obj) + queued(priority) { + return this._queues.queued(priority); + } - // slice this function off the top - var stack = obj.stack.slice(1) + clusterQueued() { + return this._store.__queued__(); + } - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - return stack -} + running() { + return this._store.__running__(); + } -/** - * Capture call site stack from v8. - */ + done() { + return this._store.__done__(); + } -function prepareObjectStackTrace (obj, stack) { - return stack -} + jobStatus(id) { + return this._states.jobStatus(id); + } -/** - * Return a wrapped function in a deprecation message. - */ + jobs(status) { + return this._states.statusJobs(status); + } -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } + counts() { + return this._states.statusCounts(); + } - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - site.name = fn.name + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } - // 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' + - '})') + _randomIndex() { + return Math.random().toString(36).slice(2); + } - return deprecatedfn -} + check(weight = 1) { + return this._store.__check__(weight); + } -/** - * Wrap property in a deprecation message. - */ + _run(next, wait, index, retryCount) { + var _this = this; -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } + var completed, done; + this.Events.trigger("debug", `Scheduling ${next.options.id}`, { + args: next.args, + options: next.options + }); + done = false; - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + completed = + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (...args) { + var e, error, eventInfo, retry, retryAfter, running; - if (!descriptor) { - throw new TypeError('must call property on owner object') - } + if (!done) { + try { + done = true; + clearTimeout(_this._scheduled[index].expiration); + delete _this._scheduled[index]; + eventInfo = { + args: next.args, + options: next.options, + retryCount + }; - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } + if ((error = args[0]) != null) { + retry = yield _this.Events.trigger("failed", error, eventInfo); - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) + if (retry != null) { + retryAfter = ~~retry; - // set site name - site.name = prop + _this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } + return _this._run(next, retryAfter, index, retryCount + 1); + } + } - var get = descriptor.get - var set = descriptor.set + _this._states.next(next.options.id); // DONE - // 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) - } - } + _this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); - Object.defineProperty(obj, prop, descriptor) -} + _this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); -/** - * Create DeprecationError for deprecation - */ + var _ref2 = yield _this._store.__free__(index, next.options.weight); -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString + running = _ref2.running; - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) + _this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) + if (running === 0 && _this.empty()) { + _this.Events.trigger("idle"); + } - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) + return typeof next.cb === "function" ? next.cb(...args) : void 0; + } catch (error1) { + e = error1; + return _this.Events.trigger("error", e); + } + } + }); - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) + return function completed() { + return _ref.apply(this, arguments); + }; + }(); - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString + if (retryCount === 0) { + // RUNNING + this._states.next(next.options.id); } - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val - } - }) - - return error -} + 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 + }; + } -/***/ 35554: -/***/ ((module) => { + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; -"use strict"; -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + var _next2 = next = queue.first(); -/** - * Module exports. - */ + options = _next2.options; + args = _next2.args; -module.exports = callSiteToString + if (capacity != null && options.weight > capacity) { + return this.Promise.resolve(null); + } -/** - * Format a CallSite file location to a string. - */ + 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 + }); -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' + if (success) { + queue.shift(); + empty = this.empty(); - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() - } - } else { - fileName = callSite.getFileName() - } + if (empty) { + this.Events.trigger("empty"); + } - if (fileName) { - fileLocation += fileName + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber + this._run(next, wait, index, 0); - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); } - } - - return fileLocation || 'unknown source' -} - -/** - * Format a CallSite to a string. - */ - -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 (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then(drained => { + var newCapacity; - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' - } + 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); + }); + } - line += functionName + _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)); + } + } - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' + return this.Events.trigger("dropped", job); } - } else { - line += typeName + '.' + (methodName || '') } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } - - if (addSuffix) { - line += ' (' + fileLocation + ')' - } - - return line -} - -/** - * Get constructor name of reviver. - */ - -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null -} + _dropAllQueued(message) { + return this._queues.shiftAll(job => { + return this._drop(job, message); + }); + } -/***/ }), + stop(options = {}) { + var done, waitForExecuting; + options = parser.load(options, this.stopDefaults); -/***/ 12078: -/***/ ((module) => { + waitForExecuting = at => { + var finished; -"use strict"; -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + 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; -/** - * Module exports. - * @public - */ + for (k in ref) { + v = ref[k]; -module.exports = eventListenerCount + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); -/** - * Get the count of listeners on an event emitter of a specific type. - */ + this._drop(v.job, options.dropErrorMessage); + } + } -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length -} + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); -/***/ }), + this.submit = (...args) => { + var _ref3, _ref4, _splice$call, _splice$call2; -/***/ 69829: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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; + }; -"use strict"; -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } + submit(...args) { + var _this2 = this; -/** - * Module dependencies. - * @private - */ + var cb, job, options, ref, ref1, task; -var EventEmitter = __nccwpck_require__(28614).EventEmitter + if (typeof args[0] === "function") { + var _ref5, _ref6, _splice$call3, _splice$call4; -/** - * Module exports. - * @public - */ + 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; -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace + 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); + } - function prepareObjectStackTrace (obj, stack) { - return stack - } + job = { + options, + task, + args, + cb + }; + options.priority = this._sanitizePriority(options.priority); - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 + if (options.id === this.jobDefaults.id) { + options.id = `${options.id}-${this._randomIndex()}`; + } - // capture the stack - Error.captureStackTrace(obj) + 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})`)); + } - // slice the stack - var stack = obj.stack.slice() + return false; + } - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit + this._states.start(options.id); // RECEIVED - return stack[0].toString ? toString : __nccwpck_require__(35554) -}) -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __nccwpck_require__(12078) -}) + this.Events.trigger("debug", `Queueing ${options.id}`, { + args, + options + }); + return this._submitLock.schedule( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var blocked, e, reachedHWM, shifted, strategy; -/** - * Define a lazy property. - */ + try { + var _ref10 = yield _this2._store.__submit__(_this2.queued(), options.weight); -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() + reachedHWM = _ref10.reachedHWM; + blocked = _ref10.blocked; + strategy = _ref10.strategy; - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) + _this2.Events.trigger("debug", `Queued ${options.id}`, { + args, + options, + reachedHWM, + blocked + }); + } catch (error1) { + e = error1; - return val - } + _this2._states.remove(options.id); - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) -} + _this2.Events.trigger("debug", `Could not queue ${options.id}`, { + args, + options, + error: e + }); -/** - * Call toString() on the obj - */ + if (typeof job.cb === "function") { + job.cb(e); + } -function toString (obj) { - return obj.toString() -} + return false; + } + if (blocked) { + _this2._drop(job); -/***/ }), + 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; -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { + if (shifted != null) { + _this2._drop(shifted); + } -"use strict"; + if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + _this2._drop(job); + } + return reachedHWM; + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + _this2._states.next(job.options.id); // QUEUED -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - /* istanbul ignore next */ + _this2._queues.push(options.priority, job); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + yield _this2._drainAll(); + return reachedHWM; + })); } - this.name = 'Deprecation'; - } - -} + schedule(...args) { + var options, task, wrapped; -exports.Deprecation = Deprecation; + if (typeof args[0] === "function") { + var _args = args; + var _args2 = _toArray(_args); -/***/ }), + task = _args2[0]; + args = _args2.slice(1); + options = parser.load({}, this.jobDefaults, {}); + } else { + var _args3 = args; -/***/ 43225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var _args4 = _toArray(_args3); -"use strict"; -/*! - * destroy - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ + options = _args4[0]; + task = _args4[1]; + args = _args4.slice(2); + options = parser.load(options, this.jobDefaults); + } + wrapped = (...args) => { + var _ref11, _ref12, _splice$call7, _splice$call8; + 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); -/** - * Module dependencies. - * @private - */ + returned = function () { + try { + return task(...args); + } catch (error1) { + e = error1; + return this.Promise.reject(e); + } + }.call(this); -var ReadStream = __nccwpck_require__(35747).ReadStream -var Stream = __nccwpck_require__(92413) + 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); + }); + }; -/** - * Module exports. - * @public - */ + 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); + }); + }); + } -module.exports = destroy + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule; -/** - * Destroy a stream. - * - * @param {object} stream - * @public - */ + wrapped = function wrapped(...args) { + return schedule(fn.bind(this), ...args); + }; -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } + wrapped.withOptions = (options, ...args) => { + return schedule(options, fn, ...args); + }; - if (!(stream instanceof Stream)) { - return stream - } + return wrapped; + } - if (typeof stream.destroy === 'function') { - stream.destroy() - } + updateSettings(options = {}) { + var _this3 = this; - return stream -} + return _asyncToGenerator(function* () { + yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); + parser.overwrite(options, _this3.instanceDefaults, _this3); + return _this3; + })(); + } -/** - * Destroy a ReadStream. - * - * @param {object} stream - * @private - */ + currentReservoir() { + return this._store.__currentReservoir__(); + } -function destroyReadStream(stream) { - stream.destroy() + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) } - return stream -} - -/** - * On open handler to close stream. - * @private - */ - -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() - } -} + ; + Bottleneck.default = Bottleneck; + Bottleneck.Events = Events; + Bottleneck.version = Bottleneck.prototype.version = (__nccwpck_require__(82636)/* .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; /***/ }), -/***/ 12437: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* @flow */ -/*:: - -type DotenvParseOptions = { - debug?: boolean -} - -// keys and values from src -type DotenvParseOutput = { [string]: string } - -type DotenvConfigOptions = { - path?: string, // path to .env file - encoding?: string, // encoding of .env file - debug?: string // turn on logging for debugging purposes -} +/***/ 93529: +/***/ ((module) => { -type DotenvConfigOutput = { - parsed?: DotenvParseOutput, - error?: Error -} -*/ -const fs = __nccwpck_require__(35747) -const path = __nccwpck_require__(85622) +var BottleneckError; +BottleneckError = class BottleneckError extends Error {}; +module.exports = BottleneckError; -function log (message /*: string */) { - console.log(`[dotenv][DEBUG] ${message}`) -} +/***/ }), -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/ +/***/ 38579: +/***/ ((module) => { -// Parses src into an Object -function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { - const debug = Boolean(options && options.debug) - const obj = {} - // 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] === "'" - // if single or double quoted, remove quotes - if (isSingleQuoted || isDoubleQuoted) { - val = val.substring(1, end) +var DLList; +DLList = class DLList { + constructor(_queues) { + this._queues = _queues; + this._first = null; + this._last = null; + this.length = 0; + } - // if double quoted, expand newlines - if (isDoubleQuoted) { - val = val.replace(RE_NEWLINES, NEWLINE) - } - } else { - // remove surrounding whitespace - val = val.trim() - } + push(value) { + var node, ref1; + this.length++; - obj[key] = val - } else if (debug) { - log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + if ((ref1 = this._queues) != null) { + ref1.incr(); } - }) - - 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 + node = { + value, + next: null + }; - if (options) { - if (options.path != null) { - dotenvPath = options.path - } - if (options.encoding != null) { - encoding = options.encoding - } - if (options.debug != null) { - debug = true + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; } - } - 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 void 0; } -} -module.exports.config = config -module.exports.parse = parse + shift() { + var ref1, ref2, value; + if (this._first == null) { + return void 0; + } else { + this.length--; -/***/ }), + if ((ref1 = this._queues) != null) { + ref1.decr(); + } + } -/***/ 11728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + value = this._first.value; + this._first = (ref2 = this._first.next) != null ? ref2 : this._last = null; + return value; + } -"use strict"; + first() { + if (this._first != null) { + return this._first.value; + } + } + getArray() { + var node, ref, results; + node = this._first; + results = []; -var Buffer = __nccwpck_require__(21867).Buffer; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } -var getParamBytesForAlg = __nccwpck_require__(30528); + return results; + } -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); + forEachShift(cb) { + var node; + node = this.shift(); -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} + while (node != null) { + cb(node), node = this.shift(); + } -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } + return void 0; + } - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); -} +}; +module.exports = DLList; -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; +/***/ 107: +/***/ ((module) => { - 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++]; - } +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); } } - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } +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); }); }; } - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } +var Events; +Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; - var rLength = signature[offset++]; + if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { + throw new Error("An Emitter already exists for this object"); + } - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; - var rOffset = offset; - offset += rLength; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } + _addListener(name, status, cb) { + var base; - var sLength = signature[offset++]; + if ((base = this._events)[name] == null) { + base[name] = []; + } - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } + this._events[name].push({ + cb, + status + }); - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + return this.instance; + } - var sOffset = offset; - offset += sLength; + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } + trigger(name, ...args) { + var _this = this; - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; + return _asyncToGenerator(function* () { + var e, promises; - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + try { + if (name !== "debug") { + _this.trigger("debug", `Event triggered: ${name}`, args); + } - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + if (_this._events[name] == null) { + return; + } - offset = paramBytes; + _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; - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + if (listener.status === "none") { + return; + } - dst = dst.toString('base64'); - dst = base64Url(dst); + if (listener.status === "once") { + listener.status = "none"; + } - return dst; -} + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } + if (typeof (returned != null ? returned.then : void 0) === "function") { + return yield returned; + } else { + return returned; + } + } catch (error) { + e = error; - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } + if (true) { + _this.trigger("error", e); + } - return padding; -} + return null; + } + }); -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + return (yield Promise.all(promises)).find(function (x) { + return x != null; + }); + } catch (error) { + e = error; - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } + if (true) { + _this.trigger("error", e); + } - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; + return null; + } + })(); + } - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; +}; +module.exports = Events; - var shortLength = rsBytes < MAX_OCTET; +/***/ }), - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); +/***/ 53068: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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 -}; +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; } -/***/ 30528: -/***/ ((module) => { +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -"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); }); }; } -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} +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 paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; +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); -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } + this._startAutoCleanup(); - throw new Error('Unknown algorithm "' + alg + '"'); -} + this.sharedConnection = this.connection != null; -module.exports = getParamBytesForAlg; + 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; + })(); + } + deleteKey(key = "") { + var _this = this; -/***/ }), + return _asyncToGenerator(function* () { + var deleted, instance; + instance = _this.instances[key]; -/***/ 14401: -/***/ ((module) => { + if (_this.connection) { + deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); + } -"use strict"; -/*! - * ee-first - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ + 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 = []; -/** - * Module exports. - * @public - */ + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } -module.exports = first + return results; + } -/** - * Get the first event in a set of event emitters and event pairs. - * - * @param {array} stuff - * @param {function} done - * @public - */ + keys() { + return Object.keys(this.instances); + } -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') + clusterKeys() { + var _this2 = this; - var cleanups = [] + return _asyncToGenerator(function* () { + var cursor, end, found, i, k, keys, len, next, start; - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] + if (_this2.connection == null) { + return _this2.Promise.resolve(_this2.keys()); + } - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') + keys = []; + cursor = null; + start = `b_${_this2.id}-`.length; + end = "_settings".length; - var ee = arr[0] + while (cursor !== 0) { + var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) + var _ref2 = _slicedToArray(_ref, 2); - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } + next = _ref2[0]; + found = _ref2[1]; + cursor = ~~next; - function callback() { - cleanup() - done.apply(null, arguments) - } + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) + return keys; + })(); } - } - - function thunk(fn) { - done = fn - } - thunk.cancel = cleanup + _startAutoCleanup() { + var _this3 = this; - return thunk -} + 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 = []; -/** - * Create the event listener. - * @private - */ + for (k in ref) { + v = ref[k]; -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null + 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)); + } + } - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] + return results; + }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; } - done(err, ee, event, args) - } -} - + updateSettings(options = {}) { + parser.overwrite(options, this.defaults, this); + parser.overwrite(options, options, this.limiterOptions); -/***/ }), + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } -/***/ 18212: -/***/ ((module) => { + disconnect(flush = true) { + var ref; -"use strict"; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } + } -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; -}; + ; + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; + return Group; +}.call(void 0); +module.exports = Group; /***/ }), -/***/ 16592: -/***/ ((module) => { +/***/ 47710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -/** - * Module exports. - * @public - */ +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -module.exports = encodeUrl +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; } -/** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private - */ +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -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 +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); } } -/** - * RegExp to match unmatched surrogate pair. - * @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); }); }; } -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g +var Events, IORedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +Scripts = __nccwpck_require__(4169); -/** - * String to replace unmatched surrogate pair with. - * @private - */ +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 -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + parser.load(options, this.defaults, this); -/** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * 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`). - * - * 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} url - * @return {string} - * @public - */ + if (this.Events == null) { + this.Events = new Events(this); + } -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} + this.terminated = false; + 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); + } -/***/ }), + this.subscriber = this.client.duplicate(); + } -/***/ 23505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.limiters = {}; + this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { + this._loadScripts(); -"use strict"; + return { + client: this.client, + subscriber: this.subscriber + }; + }); + } + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); -var util = __nccwpck_require__(31669); -var isArrayish = __nccwpck_require__(7604); + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); + } -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } + if (client.status === "ready") { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); + } - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } + _loadScripts() { + return Scripts.names.forEach(name => { + return this.client.defineCommand(name, { + lua: Scripts.payload(name) + }); + }); + } - message = message instanceof Error - ? message.message - : (message || this.message); + __runCommand__(cmd) { + var _this = this; - Error.call(this, message); - Error.captureStackTrace(this, errorExError); + return _asyncToGenerator(function* () { + var _, deleted; - this.name = name; + yield _this.ready; - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); + var _ref = yield _this.client.pipeline([cmd]).exec(); - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + var _ref2 = _slicedToArray(_ref, 1); - var modifier = properties[key]; + var _ref2$ = _slicedToArray(_ref2[0], 2); - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } + _ = _ref2$[0]; + deleted = _ref2$[1]; + return deleted; + })(); + } - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); + __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(); + }); + }); + })); + } - var overwrittenStack = null; + __removeLimiter__(instance) { + var _this2 = this; - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + return [instance.channel(), instance.channel_client()].forEach( + /*#__PURE__*/ + function () { + var _ref3 = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield _this2.subscriber.unsubscribe(channel); + } - stackDescriptor.set = function (newstack) { - overwrittenStack = newstack; - }; + return delete _this2.limiters[channel]; + }); - stackDescriptor.get = function () { - var stack = (overwrittenStack || ((stackGetter) - ? stackGetter.call(this) - : stackValue)).split(/\r?\n+/g); + return function (_x) { + return _ref3.apply(this, arguments); + }; + }()); + } - // starting in Node 7, the stack builder caches the message. - // just replace it. - if (!overwrittenStack) { - stack[0] = this.name + ': ' + this.message; - } + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [keys.length].concat(keys, args, cb); + } - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + __scriptFn__(name) { + return this.client[name].bind(this.client); + } - var modifier = properties[key]; + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } + this.limiters = {}; + this.terminated = true; - return stack.join('\n'); - }; + if (flush) { + return this.Promise.all([this.client.quit(), this.subscriber.quit()]); + } else { + this.client.disconnect(); + this.subscriber.disconnect(); + return this.Promise.resolve(); + } + } - Object.defineProperty(this, 'stack', stackDescriptor); - }; + } - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } + ; + IORedisConnection.prototype.datastore = "ioredis"; + IORedisConnection.prototype.defaults = { + clientOptions: {}, + clusterNodes: null, + client: null, + Promise: Promise, + Events: null + }; + return IORedisConnection; +}.call(void 0); - return errorExError; -}; +module.exports = IORedisConnection; -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; +/***/ }), - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } +/***/ 38979: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return message; - } - }; -}; -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; - if (v) { - return str.replace('%s', v.toString()); - } +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); } } - return null; - } - }; -}; +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); }); }; } -module.exports = errorEx; +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 = {}; + this._startHeartbeat(); + } -/***/ }), + _startHeartbeat() { + var base; -/***/ 94070: -/***/ ((module) => { + if (this.heartbeat == null && this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null) { + return typeof (base = this.heartbeat = setInterval(() => { + var now; + now = Date.now(); -"use strict"; -/*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu - * MIT Licensed - */ + 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); + } + } + __publish__(message) { + var _this = this; + return _asyncToGenerator(function* () { + yield _this.yieldLoop(); + return _this.instance.Events.trigger("message", message.toString()); + })(); + } -/** - * Module variables. - * @private - */ + __disconnect__(flush) { + var _this2 = this; -var matchHtmlRegExp = /["'&<>]/; + return _asyncToGenerator(function* () { + yield _this2.yieldLoop(); + clearInterval(_this2.heartbeat); + return _this2.Promise.resolve(); + })(); + } -/** - * Module exports. - * @public - */ + yieldLoop(t = 0) { + return new this.Promise(function (resolve, reject) { + return setTimeout(resolve, t); + }); + } -module.exports = escapeHtml; + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; + } -/** - * Escape special characters in the given string of html. - * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public - */ + __updateSettings__(options) { + var _this3 = this; -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); + return _asyncToGenerator(function* () { + yield _this3.yieldLoop(); + parser.overwrite(options, options, _this3.storeOptions); - if (!match) { - return str; + _this3._startHeartbeat(); + + _this3.instance._drainAll(_this3.computeCapacity()); + + return true; + })(); } - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; + __running__() { + var _this4 = this; - 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; - } + return _asyncToGenerator(function* () { + yield _this4.yieldLoop(); + return _this4._running; + })(); + } - if (lastIndex !== index) { - html += str.substring(lastIndex, index); - } + __queued__() { + var _this5 = this; - lastIndex = index + 1; - html += escape; + return _asyncToGenerator(function* () { + yield _this5.yieldLoop(); + return _this5.instance.queued(); + })(); } - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; -} + __done__() { + var _this6 = this; + + return _asyncToGenerator(function* () { + yield _this6.yieldLoop(); + return _this6._done; + })(); + } + __groupCheck__(time) { + var _this7 = this; -/***/ }), + return _asyncToGenerator(function* () { + yield _this7.yieldLoop(); + return _this7._nextRequest + _this7.timeout < time; + })(); + } -/***/ 98691: -/***/ ((module) => { + computeCapacity() { + var maxConcurrent, reservoir; + var _this$storeOptions = this.storeOptions; + maxConcurrent = _this$storeOptions.maxConcurrent; + reservoir = _this$storeOptions.reservoir; -"use strict"; + 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; + } + } + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return capacity == null || weight <= capacity; + } -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } + __incrementReservoir__(incr) { + var _this8 = this; - // 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'); -}; + return _asyncToGenerator(function* () { + var reservoir; + yield _this8.yieldLoop(); + reservoir = _this8.storeOptions.reservoir += incr; + _this8.instance._drainAll(_this8.computeCapacity()); -/***/ }), + return reservoir; + })(); + } -/***/ 69972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + __currentReservoir__() { + var _this9 = this; -"use strict"; -/*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson - * MIT Licensed - */ + 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; + } -/** - * Module exports. - * @public - */ + __check__(weight) { + var _this10 = this; -module.exports = etag + return _asyncToGenerator(function* () { + var now; + yield _this10.yieldLoop(); + now = Date.now(); + return _this10.check(weight, now); + })(); + } -/** - * Module dependencies. - * @private - */ + __register__(index, weight, expiration) { + var _this11 = this; -var crypto = __nccwpck_require__(76417) -var Stats = __nccwpck_require__(35747).Stats + return _asyncToGenerator(function* () { + var now, wait; + yield _this11.yieldLoop(); + now = Date.now(); -/** - * Module variables. - * @private - */ + if (_this11.conditionsCheck(weight)) { + _this11._running += weight; -var toString = Object.prototype.toString + if (_this11.storeOptions.reservoir != null) { + _this11.storeOptions.reservoir -= weight; + } -/** - * Generate an entity tag. - * - * @param {Buffer|string} entity - * @return {string} - * @private - */ + 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 + }; + } + })(); + } -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + strategyIsBlock() { + return this.storeOptions.strategy === 3; } - // compute hash of entity - var hash = crypto - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27) + __submit__(queueLength, weight) { + var _this12 = this; - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length + return _asyncToGenerator(function* () { + var blocked, now, reachedHWM; + yield _this12.yieldLoop(); - return '"' + len.toString(16) + '-' + hash + '"' -} + 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}`); + } -/** - * Create a simple ETag. - * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} - * @public - */ + now = Date.now(); + reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); + blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') - } + if (blocked) { + _this12._unblockTime = now + _this12.computePenalty(); + _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; - // support fs.Stats object - var isStats = isstats(entity) - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats + _this12.instance._dropAllQueued(); + } - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + return { + reachedHWM, + blocked, + strategy: _this12.storeOptions.strategy + }; + })(); } - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) + __free__(index, weight) { + var _this13 = this; - return weak - ? 'W/' + tag - : tag -} + return _asyncToGenerator(function* () { + yield _this13.yieldLoop(); + _this13._running -= weight; + _this13._done += weight; -/** - * Determine if object is a Stats object. - * - * @param {object} obj - * @return {boolean} - * @api private - */ + _this13.instance._drainAll(_this13.computeCapacity()); -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true + return { + running: _this13._running + }; + })(); } - // 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' -} - -/** - * Generate a tag for a stat. - * - * @param {object} stat - * @return {string} - * @private - */ - -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) - - return '"' + size + '-' + mtime + '"' -} - +}; +module.exports = LocalDatastore; /***/ }), -/***/ 68883: +/***/ 65893: /***/ ((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' -] - -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 - } - }) +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; - Object.defineProperty(this, 'url', { - get: function () { - return url - } - }) + this._lists = function () { + var j, ref, results; + results = []; - var self = this - self.reconnectInterval = 1000 + for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + results.push(new DLList(this)); + } - function onConnectionClosed (message) { - if (readyState === EventSource.CLOSED) return - readyState = EventSource.CONNECTING - _emit('error', new Event('error', {message: message})) + return results; + }.call(this); + } - // The url may have been changed by a temporary - // redirect. If that's the case, revert it now. - if (reconnectUrl) { - url = reconnectUrl - reconnectUrl = null + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); } - setTimeout(function () { - if (readyState !== EventSource.CONNECTING) { - return - } - connect() - }, self.reconnectInterval) } - 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'] + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } } - var discardTrailingNewline = false - var data = '' - var eventName = '' - - var reconnectUrl = null + push(priority, job) { + return this._lists[priority].push(job); + } - 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 - } - } + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; } + } - // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, - // but for now exists as a backwards-compatibility layer - options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) - - // 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:' + shiftAll(fn) { + return this._lists.forEach(function (list) { + return list.forEachShift(fn); + }); + } - 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 - } + getFirst(arr = this._lists) { + var j, len, list; - // 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 - } + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; - var option = eventSourceInitDict.https[optName] - if (option !== undefined) { - options[optName] = option - } + if (list.length > 0) { + return list; } } - // Pass this on to the XHR - if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { - options.withCredentials = eventSourceInitDict.withCredentials - } + return []; + } - 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 - } + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } - // 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 - } +}; +module.exports = Queues; - if (res.statusCode !== 200) { - _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) - return self.close() - } +/***/ }), - readyState = EventSource.OPEN - res.on('close', function () { - res.removeAllListeners('close') - res.removeAllListeners('end') - onConnectionClosed() - }) +/***/ 29992: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - res.on('end', function () { - res.removeAllListeners('close') - res.removeAllListeners('end') - onConnectionClosed() - }) - _emit('open', new Event('open')) - // 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) - } - isFirst = false - var pos = 0 - var length = buf.length +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); } } - while (pos < length) { - if (discardTrailingNewline) { - if (buf[pos] === lineFeed) { - ++pos - } - discardTrailingNewline = false - } +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 lineLength = -1 - var fieldLength = -1 - var c +var Events, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +Scripts = __nccwpck_require__(4169); - 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 - } - } +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 - if (lineLength < 0) { - break - } + parser.load(options, this.defaults, this); - parseEventStreamLine(buf, pos, fieldLength, lineLength) + if (this.Events == null) { + this.Events = new Events(this); + } - pos += lineLength + 1 - } + this.terminated = false; - if (pos === length) { - buf = void 0 - } else if (pos > 0) { - buf = buf.slice(pos) - } - }) - }) + if (this.client == null) { + this.client = Redis.createClient(this.clientOptions); + } - req.on('error', function (err) { - onConnectionClosed(err.message) - }) + 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 + }; + }); + } - if (req.setNoDelay) req.setNoDelay(true) - req.end() - } + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); - connect() + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); + } - function _emit () { - if (self.listeners(arguments[0]).length > 0) { - self.emit.apply(self, arguments) + if (client.ready) { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); } - } - 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() - } + _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); + } - 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() + this.shas[name] = replies[0]; + return resolve(replies[0]); + }); + }); + } - if (noValue) { - step = lineLength - } else if (buf[pos + fieldLength + 1] !== space) { - step = fieldLength + 1 - } else { - step = fieldLength + 2 - } - pos += step + _loadScripts() { + return this.Promise.all(Scripts.names.map(k => { + return this._loadScript(k); + })); + } - var valueLength = lineLength - step - var value = buf.slice(pos, pos + valueLength).toString() + __runCommand__(cmd) { + var _this = this; - 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 - } - } + 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]); + } + }); + }); + })(); } - } -} - -module.exports = EventSource -util.inherits(EventSource, events.EventEmitter) -EventSource.prototype.constructor = EventSource; // make stacktraces readable + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + var handler; -['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 - }, + handler = chan => { + if (chan === channel) { + this.subscriber.removeListener("subscribe", handler); + this.limiters[channel] = instance; + return resolve(); + } + }; - /** - * 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) + this.subscriber.on("subscribe", handler); + return this.subscriber.subscribe(channel); + }); + })); } - }) -}) -/** - * 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}) + __removeLimiter__(instance) { + var _this2 = this; -EventSource.prototype.CONNECTING = 0 -EventSource.prototype.OPEN = 1 -EventSource.prototype.CLOSED = 2 + 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); + } -/** - * 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 - */ -EventSource.prototype.close = function () { - this._close() -} + if (chan === channel) { + return resolve(); + } + }); + }); + } -/** - * 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) - } -} + return delete _this2.limiters[channel]; + }); -/** - * 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 - */ -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) -} + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); + } -/** - * 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) - } -} + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [this.shas[name], keys.length].concat(keys, args, cb); + } -/** - * W3C Event - * - * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event - * @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 }) - } + __scriptFn__(name) { + return this.client.evalsha.bind(this.client); } - } -} -/** - * W3C MessageEvent - * - * @see http://www.w3.org/TR/webmessaging/#event-definitions - * @api private - */ -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 }) + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); + + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } + + this.limiters = {}; + this.terminated = true; + this.client.end(flush); + this.subscriber.end(flush); + return this.Promise.resolve(); } + } -} + ; + RedisConnection.prototype.datastore = "redis"; + RedisConnection.prototype.defaults = { + clientOptions: {}, + client: null, + Promise: Promise, + Events: null + }; + return RedisConnection; +}.call(void 0); + +module.exports = RedisConnection; /***/ }), -/***/ 71204: +/***/ 4946: /***/ ((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 - */ +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -module.exports = __nccwpck_require__(22587); +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; } -/***/ 313: -/***/ ((module, exports, __nccwpck_require__) => { +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); } } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +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; + } -/** - * Module dependencies. - * @private - */ + 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; -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; + 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(); + } -/** - * Application prototype. - */ + return this.clients; + }); + } -var app = exports = module.exports = {}; + __publish__(message) { + var _this = this; -/** - * Variable for trust proxy inheritance back-compat - * @private - */ + return _asyncToGenerator(function* () { + var client; -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + var _ref = yield _this.ready; -/** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - * - * @private - */ + client = _ref.client; + return client.publish(_this.instance.channel(), `message:${message.toString()}`); + })(); + } -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; + onMessage(channel, message) { + var _this2 = this; - this.defaultConfiguration(); -}; + return _asyncToGenerator(function* () { + var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; -/** - * Initialize application configuration. - * @private - */ + try { + pos = message.indexOf(":"); + var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; + type = _ref2[0]; + data = _ref2[1]; -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; + if (type === "capacity") { + return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); + } else if (type === "capacity-priority") { + var _data$split = data.split(":"); - // 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); + var _data$split2 = _slicedToArray(_data$split, 3); - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); + rawCapacity = _data$split2[0]; + priorityClient = _data$split2[1]; + counter = _data$split2[2]; + capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; - debug('booting in %s mode', env); + 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; - 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']; - } + 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); + } + })(); + } - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); + __disconnect__(flush) { + clearInterval(this.heartbeat); - // setup locals - this.locals = Object.create(null); + if (this.sharedConnection) { + return this.connection.__removeLimiter__(this.instance); + } else { + return this.connection.disconnect(flush); + } + } - // top-most app is mounted at / - this.mountpath = '/'; + runScript(name, args) { + var _this3 = this; + + return _asyncToGenerator(function* () { + if (!(name === "init" || name === "register_client")) { + yield _this3.ready; + } - // default locals - this.locals.settings = this.settings; + return new _this3.Promise((resolve, reject) => { + var all_args, arr; + all_args = [Date.now(), _this3.clientId].concat(args); - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); + _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); - if (env === 'production') { - this.enable('view cache'); + 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); + } + }); + })(); } - 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.'); - } - }); -}; + prepareArray(arr) { + var i, len, results, x; + results = []; -/** - * 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') - }); + for (i = 0, len = arr.length; i < len; i++) { + x = arr[i]; + results.push(x != null ? x.toString() : ""); + } - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); + return results; } -}; -/** - * 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 - */ + prepareObject(obj) { + var arr, k, v; + arr = []; -app.handle = function handle(req, res, callback) { - var router = this._router; + for (k in obj) { + v = obj[k]; + arr.push(k, v != null ? v.toString() : ""); + } - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); + return arr; + } - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - 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; } - router.handle(req, res, done); -}; + convertBool(b) { + return !!b; + } -/** - * 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 - */ + __updateSettings__(options) { + var _this4 = this; -app.use = function use(fn) { - var offset = 0; - var path = '/'; + return _asyncToGenerator(function* () { + yield _this4.runScript("update_settings", _this4.prepareObject(options)); + return parser.overwrite(options, options, _this4.storeOptions); + })(); + } - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; + __running__() { + return this.runScript("running", []); + } - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } + __queued__() { + return this.runScript("queued", []); + } - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } + __done__() { + return this.runScript("done", []); } - var fns = flatten(slice.call(arguments, offset)); + __groupCheck__() { + var _this5 = this; - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') + return _asyncToGenerator(function* () { + return _this5.convertBool((yield _this5.runScript("group_check", []))); + })(); } - // 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); - } + __incrementReservoir__(incr) { + return this.runScript("increment_reservoir", [incr]); + } - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; + __currentReservoir__() { + return this.runScript("current_reservoir", []); + } - // 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); - }); - }); + __check__(weight) { + var _this6 = this; - // mounted an app - fn.emit('mount', this); - }, this); + return _asyncToGenerator(function* () { + return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); + })(); + } - return this; -}; + __register__(index, weight, expiration) { + var _this7 = 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 - */ + return _asyncToGenerator(function* () { + var reservoir, success, wait; -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; + var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); -/** - * 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 - */ + var _ref5 = _slicedToArray(_ref4, 3); -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); + success = _ref5[0]; + wait = _ref5[1]; + reservoir = _ref5[2]; + return { + success: _this7.convertBool(success), + wait, + reservoir + }; + })(); } - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; + __submit__(queueLength, weight) { + var _this8 = this; - // store engine - this.engines[extension] = fn; + return _asyncToGenerator(function* () { + var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; - return this; -}; + try { + var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); -/** - * 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 _ref7 = _slicedToArray(_ref6, 3); -app.param = function param(name, fn) { - this.lazyrouter(); + reachedHWM = _ref7[0]; + blocked = _ref7[1]; + strategy = _ref7[2]; + return { + reachedHWM: _this8.convertBool(reachedHWM), + blocked: _this8.convertBool(blocked), + strategy + }; + } catch (error) { + e = error; - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); - } + if (e.message.indexOf("OVERWEIGHT") === 0) { + var _e$message$split = e.message.split(":"); - return this; + var _e$message$split2 = _slicedToArray(_e$message$split, 3); + + 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; + } + } + })(); } - this._router.param(name, fn); + __free__(index, weight) { + var _this9 = this; + + return _asyncToGenerator(function* () { + var running; + running = yield _this9.runScript("free", _this9.prepareArray([index])); + return { + running + }; + })(); + } - return this; }; +module.exports = RedisDatastore; -/** - * 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]; - } +/***/ 4169: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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)); +var headers, lua, templates; +lua = __nccwpck_require__(31936); +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"] +}; - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); +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`]; +}; - break; +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"] } - - return this; }; +exports.names = Object.keys(templates); -/** - * 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 - */ - -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; +exports.keys = function (name, id) { + return templates[name].keys(id); }; -/** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @public - */ - -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); +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"); }; -/** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @public - */ - -app.disabled = function disabled(setting) { - return !this.set(setting); -}; +/***/ }), -/** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ +/***/ 2527: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -app.enable = function enable(setting) { - return this.set(setting, true); -}; -/** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ -app.disable = function disable(setting) { - return this.set(setting, false); -}; +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; + }); + } -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ + next(id) { + var current, next; + current = this.jobs[id]; + next = current + 1; -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); + 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]; } - - 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 - */ - -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; -}; - -// del -> delete alias - -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + start(id) { + var initial; + initial = 0; + this.jobs[id] = initial; + return this.counts[initial]++; + } -/** - * 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 - */ + remove(id) { + var current; + current = this.jobs[id]; -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; + if (current != null) { + this.counts[current]--; + delete this.jobs[id]; + } - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; + return current != null; } - // merge app.locals - merge(renderOptions, this.locals); - - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); + jobStatus(id) { + var ref; + return (ref = this.status[this.jobs[id]]) != null ? ref : null; } - // merge options - merge(renderOptions, opts); + statusJobs(status) { + var k, pos, ref, results, v; - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } + if (status != null) { + pos = this.status.indexOf(status); - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } + if (pos < 0) { + throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); + } - // view - if (!view) { - var View = this.get('view'); + ref = this.jobs; + results = []; - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); + for (k in ref) { + v = ref[k]; - 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); - } + if (v === pos) { + results.push(k); + } + } - // prime the cache - if (renderOptions.cache) { - cache[name] = view; + return results; + } else { + return Object.keys(this.jobs); } } - // render - tryRender(view, renderOptions, done); -}; - -/** - * 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 - */ - -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; - -/** - * Log error using console.error. - * - * @param {Error} err - * @private - */ - -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); + statusCounts() { + return this.counts.reduce((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }, {}); } -} +}; +module.exports = States; /***/ }), -/***/ 22587: -/***/ ((module, 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 - */ - - - -/** - * 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); - -/** - * Expose `createApplication()`. - */ - -exports = module.exports = createApplication; - -/** - * Create an express application. - * - * @return {Function} - * @api public - */ - -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; - - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); - - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - app.init(); - return app; -} - -/** - * Expose the prototypes. - */ +/***/ 56029: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -exports.application = proto; -exports.request = req; -exports.response = res; -/** - * Expose constructors. - */ -exports.Route = Route; -exports.Router = Router; +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -/** - * Expose middleware - */ +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.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 _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } -/** - * Replace removed middleware with an appropriate error message. - */ +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -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 - }); -}); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +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(); + } -/***/ }), + isEmpty() { + return this._queue.length === 0; + } -/***/ 92636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + _tryToRun() { + var next; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + 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; + }); + } + } -/** - * Module dependencies. - * @private - */ + submit(task, ...args) { + var _ref, _ref2, _splice$call, _splice$call2; -var setPrototypeOf = __nccwpck_require__(40414) + 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); -/** - * 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 - */ + this._queue.push({ + task, + args, + cb + }); -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; + return this._tryToRun(); + } - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) + schedule(task, ...args) { + var wrapped; - res.locals = res.locals || Object.create(null); + wrapped = function wrapped(...args) { + var _ref3, _ref4, _splice$call3, _splice$call4; - next(); - }; -}; + 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); + }); + }; + return new this.Promise((resolve, reject) => { + return this.submit(wrapped, ...args, function (...args) { + return (args[0] != null ? reject : (args.shift(), resolve))(...args); + }); + }); + } +}; +module.exports = Sync; /***/ }), -/***/ 79768: +/***/ 27356: /***/ ((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 - */ +module.exports = __nccwpck_require__(83911); -/** - * Module dependencies. - */ +/***/ }), -var merge = __nccwpck_require__(44429) -var parseUrl = __nccwpck_require__(89808); -var qs = __nccwpck_require__(22760); +/***/ 67823: +/***/ ((__unused_webpack_module, exports) => { -/** - * @param {Object} options - * @return {Function} - * @api public - */ -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; - if (typeof options === 'function') { - queryparse = options; - opts = undefined; - } +exports.load = function (received, defaults, onto = {}) { + var k, ref, v; - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; } - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); + return onto; +}; + +exports.overwrite = function (received, defaults, onto = {}) { + var k, v; + + for (k in received) { + v = received[k]; + + if (defaults[k] !== void 0) { + onto[k] = v; } + } - next(); - }; + return onto; }; - /***/ }), -/***/ 71260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 11174: +/***/ (function(module) { -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +/** + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; + var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + function getCjsExportFromNamespace (n) { + return n && n.default || n; + } -/** - * Module dependencies. - * @private - */ + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; -var 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); + 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; + }; -/** - * Request prototype. - * @public - */ + var parser = { + load: load, + overwrite: overwrite + }; -var req = Object.create(http.IncomingMessage.prototype) + var DLList; -/** - * Module exports. - * @public - */ + DLList = class DLList { + constructor(_queues) { + this._queues = _queues; + this._first = null; + this._last = null; + this.length = 0; + } -module.exports = req + 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; + } -/** - * 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 - */ + 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; + } -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); - } + first() { + if (this._first != null) { + return this._first.value; + } + } - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); - } + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } - var lc = name.toLowerCase(); + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; - } -}; + }; -/** - * 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 - */ + var DLList_1 = DLList; -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; + var Events; -/** - * Check if the given `encoding`s are accepted. - * - * @param {String} ...encoding - * @return {String|Array} - * @public - */ + 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 = {}; + } + }; + } -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } -/** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public - */ + 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; + } + } -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; + }; -req.acceptsCharset = deprecate.function(req.acceptsCharsets, - 'req.acceptsCharset: Use acceptsCharsets instead'); + var Events_1 = Events; -/** - * Check if the given `lang`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...lang - * @return {String|Array} - * @public - */ + var DLList$1, Events$1, Queues; -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); -}; + DLList$1 = DLList_1; -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); + Events$1 = Events_1; -/** - * 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 - */ + 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); + } -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } -/** - * 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 - */ + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } + + push(priority, job) { + return this._lists[priority].push(job); + } + + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } + + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } + + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } - var args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + }; - 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 Queues_1 = Queues; - return defaultValue; -}; + var BottleneckError; -/** - * 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 - */ + BottleneckError = class BottleneckError extends Error {}; -req.is = function is(types) { - var arr = types; + var BottleneckError_1 = BottleneckError; - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; - } - } + var BottleneckError$1, LocalDatastore, parser$1; - return typeis(this, arr); -}; + parser$1 = parser; -/** - * 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 - */ + BottleneckError$1 = BottleneckError_1; -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); + 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(); + } - if (!trust(this.connection.remoteAddress, 0)) { - return proto; - } + _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); + } + } - // 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(',') + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() -}); + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } -/** - * Short-hand for: - * - * req.protocol === 'https' - * - * @return {Boolean} - * @public - */ + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } -/** - * Return the remote address from the trusted proxy. - * - * The is the remote address on the socket unless - * "trust proxy" is set. - * - * @return {String} - * @public - */ + async __updateSettings__(options) { + await this.yieldLoop(); + parser$1.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); + async __running__() { + await this.yieldLoop(); + return this._running; + } -/** - * 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 - */ + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); + async __done__() { + await this.yieldLoop(); + return this._done; + } - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } - return addrs -}); + 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; + } + } -/** - * 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 - */ + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } - if (!hostname) return []; + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; + isBlocked(now) { + return this._unblockTime >= now; + } - return subdomains.slice(offset); -}); + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @public - */ + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); + 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 + }; + } + } -/** - * 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 - */ + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); + 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 + }; + } - 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() - } + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } - if (!host) return; + }; - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); + var LocalDatastore_1 = LocalDatastore; - return index !== -1 - ? host.substring(0, index) - : host; -}); + var BottleneckError$2, States; -// TODO: change req.host to return host in next major + BottleneckError$2 = BottleneckError_1; -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); + States = class States { + constructor(status1) { + this.status = status1; + this.jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } -/** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @public - */ + 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]; + } + } -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode + start(id) { + var initial; + initial = 0; + this.jobs[id] = initial; + return this.counts[initial]++; + } - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; + remove(id) { + var current; + current = this.jobs[id]; + if (current != null) { + this.counts[current]--; + delete this.jobs[id]; + } + return current != null; + } - // 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') - }) - } + jobStatus(id) { + var ref; + return (ref = this.status[this.jobs[id]]) != null ? ref : null; + } - return false; -}); + 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); + } + } -/** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - * - * @return {Boolean} - * @public - */ + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); + }; -/** - * Check if the request was an _XMLHttpRequest_. - * - * @return {Boolean} - * @public - */ + var States_1 = States; -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); + var DLList$2, Sync, + splice = [].splice; -/** - * Helper function for creating a getter on an object. - * - * @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 - }); -} + DLList$2 = DLList_1; + + 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(); + } + + isEmpty() { + return this._queue.length === 0; + } + _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; + }); + } + } -/***/ }), + submit(task, ...args) { + var cb, ref; + ref = args, [...args] = ref, [cb] = splice.call(args, -1); + this._queue.push({task, args, cb}); + return this._tryToRun(); + } -/***/ 64934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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); + }); + }); + } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + }; + var Sync_1 = Sync; + var version = "2.17.1"; + var version$1 = { + version: version + }; -/** - * Module dependencies. - * @private - */ + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); -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); + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/** - * Response prototype. - * @public - */ + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -var res = Object.create(http.ServerResponse.prototype) + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/** - * Module exports. - * @public - */ + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$2; -module.exports = res + parser$2 = parser; -/** - * Module variables. - * @private - */ + Events$2 = Events_1; -var charsetRegExp = /;\s*charset\s*=/; + RedisConnection$1 = require$$2; -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @public - */ + IORedisConnection$1 = require$$3; -res.status = function status(code) { - this.statusCode = code; - return this; -}; + Scripts$1 = require$$4; -/** - * 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 - */ + 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})); + } + } + } -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(', ')); -}; + 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; + })(); + } -/** - * 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 - */ + 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; + } -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; + 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; + } - // settings - var app = this.app; + keys() { + return Object.keys(this.instances); + } - // 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]; - } - } + 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; + } - // 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'); - } + _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; + } - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = statuses[chunk] - } + updateSettings(options = {}) { + parser$2.overwrite(options, this.defaults, this); + parser$2.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } - 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; - } + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } + return Group; - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' + }).call(commonjsGlobal); - // 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 - } + var Group_1 = Group; - this.set('Content-Length', len); - } + var Batcher, Events$3, parser$3; - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } - } + parser$3 = parser; - // freshness - if (req.fresh) this.statusCode = 304; + Events$3 = Events_1; - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } + 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(); + } - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); - } + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - return this; -}; + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } -/** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ + 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; + } -res.json = function json(obj) { - var val = obj; + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; - // 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]; - } - } + return Batcher; - // 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) + }).call(commonjsGlobal); - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } + var Batcher_1 = Batcher; - return this.send(body); -}; + var require$$3$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ + var require$$7 = getCjsExportFromNamespace(version$2); -res.jsonp = function jsonp(obj) { - var val = obj; + var Bottleneck, DEFAULT_PRIORITY, Events$4, LocalDatastore$1, NUM_PRIORITIES, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$4, + splice$1 = [].splice; - // 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]; - } - } + NUM_PRIORITIES = 10; - // 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')]; + DEFAULT_PRIORITY = 5; - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); - } + parser$4 = parser; - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; - } + Queues$1 = Queues_1; - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); + LocalDatastore$1 = LocalDatastore_1; + + RedisDatastore$1 = require$$3$1; - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); + Events$4 = Events_1; - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); + States$1 = States_1; - // 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 + ');'; - } + Sync$1 = Sync_1; - return this.send(body); -}; + 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; + }); + } -/** - * 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 - */ + _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."); + } + } -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) + ready() { + return this._store.ready; + } - this.statusCode = statusCode; - this.type('txt'); + clients() { + return this._store.clients; + } - return this.send(body); -}; + channel() { + return `b_${this.id}`; + } -/** - * 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 - */ + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; + publish(message) { + return this._store.__publish__(message); + } - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); - } + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') - } + chain(_limiter) { + this._limiter = _limiter; + return this; + } - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + queued(priority) { + return this._queues.queued(priority); + } - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); - } + clusterQueued() { + return this._store.__queued__(); + } - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + running() { + return this._store.__running__(); + } - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; + done() { + return this._store.__done__(); + } -/** - * 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 - */ + jobStatus(id) { + return this._states.jobStatus(id); + } -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; + jobs(status) { + return this._states.statusJobs(status); + } - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + counts() { + return this._states.statusCounts(); + } - // create file stream - var file = send(req, path, opts); + _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; + } + } - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + _randomIndex() { + return Math.random().toString(36).slice(2); + } - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; + check(weight = 1) { + return this._store.__check__(weight); + } -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); + _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 + }; + } -/** - * 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 - */ + _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); + } + }); + }); + } -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || 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); + }); + } - // 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 - } + _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); + } + } - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; + _dropAllQueued(message) { + return this._queues.shiftAll((job) => { + return this._drop(job, message); + }); + } - // 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] - } - } - } + 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; + } - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers + 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; + }); + } - // Resolve the full path for sendFile - var fullPath = resolve(path); + 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); + }); + }); + } - // send file - return this.sendFile(fullPath, opts, done) -}; + 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; + } -/** - * 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 - */ + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$4.overwrite(options, this.storeDefaults)); + parser$4.overwrite(options, this.instanceDefaults, this); + return this; + } -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; + currentReservoir() { + return this._store.__currentReservoir__(); + } - return this.set('Content-Type', ct); -}; + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } -/** - * 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 - */ + } + Bottleneck.default = Bottleneck; -res.format = function(obj){ - var req = this.req; - var next = req.next; + Bottleneck.Events = Events$4; - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); + Bottleneck.version = Bottleneck.prototype.version = require$$7.version; - var key = keys.length > 0 - ? req.accepts(keys) - : false; + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; - this.vary("Accept"); + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; - 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); - } + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; - return this; -}; + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @public - */ + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; - this.set('Content-Disposition', contentDisposition(filename)); + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY, + weight: 1, + expiration: null, + id: "" + }; - return this; -}; + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null + }; -/** - * 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 - */ + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val]; - } + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; - return this.set(field, value); -}; + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; -/** - * 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 - */ + return Bottleneck; -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); + }).call(commonjsGlobal); - // 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(); - } - } + var Bottleneck_1 = Bottleneck; - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); - } - } - return this; -}; + var lib = Bottleneck_1; -/** - * Get value for header `field`. - * - * @param {String} field - * @return {String} - * @public - */ + return lib; -res.get = function(field){ - return this.getHeader(field); -}; +}))); -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); +/***/ }), - return this.cookie(name, '', opts); -}; +/***/ 9239: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * 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 - */ +/*jshint node:true */ -res.cookie = function (name, value, options) { - var opts = merge({}, options); - var secret = this.req.secret; - var signed = opts.signed; +var Buffer = (__nccwpck_require__(14300).Buffer); // browserify +var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); - } +module.exports = bufferEq; - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); +function bufferEq(a, b) { - if (signed) { - val = 's:' + sign(val, secret); + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; } - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; + // 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; } - if (opts.path == null) { - opts.path = '/'; + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR } + return c === 0; +} - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); - - return this; +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; }; -/** - * 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 origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; -res.location = function location(url) { - var loc = url; - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; - } +/***/ }), - // set location - return this.set('Location', encodeUrl(loc)); -}; +/***/ 86966: +/***/ ((module) => { -/** - * 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 +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed */ -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; - // 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. + * @public + */ - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; - html: function(){ - var u = escapeHtml(address); - body = '

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

' - }, +/** + * Module variables. + * @private + */ - default: function(){ - body = ''; - } - }); +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); - } +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), }; +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + /** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. + * Convert the given value in bytes into a string or parse to string to an integer in bytes. * - * @param {Array|String} field - * @return {ServerResponse} for chaining - * @public + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} */ -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); } - vary(this, field); + if (typeof value === 'number') { + return format(value, options); + } - return this; -}; + return null; +} /** - * 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. + * Format the given value in bytes into a string. * - * Options: + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered + * @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 */ -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 = {}; +function format(value, options) { + if (!Number.isFinite(value)) { + return null; } - // 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); - }; + 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) || ''; - // render - app.render(view, opts, done); -}; + 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'; + } + } -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); - // request aborted - function onaborted() { - if (done) return; - done = true; + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); + if (thousandsSeparator) { + str = str.replace(formatThousandsRegExp, thousandsSeparator); } - // directory - function ondirectory() { - if (done) return; - done = true; + return str + unitSeparator + unit; +} - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } +/** + * 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 + */ - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; } - // ended - function onend() { - if (done) return; - done = true; - callback(); + if (typeof val !== 'string') { + return null; } - // file - function onfile() { - streaming = false; + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + 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(); } - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; + return Math.floor(map[unit] * floatValue); +} - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } - if (done) return; - done = true; - callback(); - }); - } +/***/ }), - // streaming - function onstream() { - streaming = true; - } +/***/ 78818: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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); +const ansiStyles = __nccwpck_require__(52068); +const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = __nccwpck_require__(82415); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); - } +const {isArray} = Array; - // pipe - file.pipe(res); -} +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' +]; -/** - * 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 - */ +const styles = Object.create(null); -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); +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'); + } - 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 - } - }) - } + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; - return json +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } } +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); -/***/ }), - -/***/ 24963: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + chalk.template.Instance = ChalkClass; -/** - * Module dependencies. - * @private - */ + return chalk.template; +}; -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) +function Chalk(options) { + return chalkFactory(options); +} -/** - * Module variables. - * @private - */ +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; + } + }; +} -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } +}; -/** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function - * @public - */ +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; -var proto = module.exports = function(options) { - var opts = options || {}; +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); + }; + } + }; +} - function router(req, res, next) { - router.handle(req, res, next); - } +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); + }; + } + }; +} - // mixin Router class functions - setPrototypeOf(router, proto) +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } +}); - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; +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 router; + return { + open, + close, + openAll, + closeAll, + parent + }; }; -/** - * 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 - */ - -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; - } - - // apply param functions - var params = this._params; - var len = params.length; - var ret; +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_)); + } - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); - } + // 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(' ')); + }; - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } - } + // 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); - // ensure we end up with a - // middleware function - if ('function' !== typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); - } + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; - (this.params[name] = this.params[name] || []).push(fn); - return this; + return builder; }; -/** - * Dispatch a req, res into the router. - * @private - */ - -proto.handle = function handle(req, res, out) { - var self = this; +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } - debug('dispatching %s %s', req.method, req.url); + let styler = self._styler; - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; + if (styler === undefined) { + return string; + } - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; + 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); - // middleware and routes - var stack = self.stack; + styler = styler.parent; + } + } - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); + // 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); + } - // setup next layer - req.next = next; + return openAll + string + closeAll; +}; - // 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); - }); - } +let template; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; + 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(' '); + } - next(); + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; - function next(err) { - var layerError = err === 'route' - ? null - : err; + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } + if (template === undefined) { + template = __nccwpck_require__(20500); + } - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } + return template(chalk, parts.join('')); +}; - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return - } +Object.defineProperties(Chalk.prototype, styles); - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } +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; - // get pathname of request - var path = getPathname(req); +module.exports = chalk; - if (path == null) { - return done(layerError); - } - // find next matching layer - var layer; - var match; - var route; +/***/ }), - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; +/***/ 20500: +/***/ ((module) => { - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } - if (match !== true) { - continue; - } +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; - if (!route) { - // process non-route handlers normally - continue; - } +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } +function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; - var method = req.method; - var has_method = route._handles_method(method); + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } + return ESCAPES.get(c) || c; +} - // no match - if (match !== true) { - return done(layerError); - } +function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; - // store route for dispatch on change - if (route) { - req.route = route; - } + 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}')`); + } + } - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; + return results; +} - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; - if (route) { - return layer.handle_request(req, res, next); - } + const results = []; + let matches; - trim_prefix(layer, layerError, layerPath, path); - }); - } + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; - 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) + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } - // 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); + return results; +} - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } +function buildStyle(chalk, styles) { + const enabled = {}; - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } -/** - * Process any parameters for the layer. - * @private - */ + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; + return current; +} - // captured parameters from the layer, keys and values - var keys = layer.keys; +module.exports = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; - // fast track - if (!keys || keys.length === 0) { - return done(); - } + // 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'); + } - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } + chunks.push(chunk.join('')); - if (i >= keys.length ) { - return done(); - } + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; + return chunks.join(''); +}; - if (paramVal === undefined || !paramCallbacks) { - return param(); - } - // 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; +/***/ }), - // next param - return param(paramCalled.error); - } +/***/ 82415: +/***/ ((module) => { - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; - paramCallback(); - } - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; +const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } - // store updated value - paramCalled.value = req.params[key.name]; + 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); - if (err) { - // store error - paramCalled.error = err; - param(err); - return; - } + returnValue += string.substr(endIndex); + return returnValue; +}; - if (!fn) return param(); +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); - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); - } - } + returnValue += string.substr(endIndex); + return returnValue; +}; - param(); +module.exports = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex }; -/** - * 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 - */ -proto.use = function use(fn) { - var offset = 0; - var path = '/'; +/***/ }), - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; +/***/ 27972: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } +const os = __nccwpck_require__(22037); - var callbacks = flatten(slice.call(arguments, offset)); +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(); - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') - } +module.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) - } + const match = pathMatches[1]; + + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } - // add the middleware - debug('use %o %s', path, fn.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, '~'))); + } - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); + return line; + }) + .join('\n'); +}; - layer.route = undefined; - this.stack.push(layer); - } +/***/ }), - return this; -}; +/***/ 48481: +/***/ ((module) => { -/** - * Create a new Route for the given path. - * - * Each route contains a separate middleware stack and VERB handlers. +/* + * 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: * - * See the Route api documentation for details on adding handlers - * and middleware to routes. + * * 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. * - * @param {String} path - * @return {Route} - * @public + * 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. */ -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; +/* 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 + */ - this.stack.push(layer); - return route; -}; +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 +]; -// 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; - }; -}); +/** + * 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; -// 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); + 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; } } -} - -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; - } -} - -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined - } - var searchIndex = url.indexOf('?') - var pathLength = searchIndex !== -1 - ? searchIndex - : url.length - var fqdnIndex = url.substr(0, pathLength).indexOf('://') + return utf8; +}; - return fqdnIndex !== -1 - ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) - : undefined -} +/** + * 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; -// get type for error message -function gettype(obj) { - var type = typeof obj; + 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 (type !== 'object') { - return type; + result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); } - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); -} + return result & 0x3FFF; +}; /** - * Match path to a layer. - * - * @param {Layer} layer - * @param {string} path - * @private + * 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]); -function matchLayer(layer, path) { - try { - return layer.match(path); - } catch (err) { - return err; + while (i < len) { + if (generate(keys[i++]) !== base) return -1; } -} -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; - } + return base; +}; - // 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); - } +/***/ }), - var i = 0; - var o = 0; +/***/ 97391: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // determine numeric gaps - while (i in params) { - i++; - } +/* MIT license */ +/* eslint-disable no-mixed-operators */ +const cssKeywords = __nccwpck_require__(78510); - while (o in parent) { - o++; - } +// 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.) - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; +const reverseKeywords = {}; +for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; +} - // create holes for the merge when necessary - if (i < o) { - delete params[i]; - } - } +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']} +}; - return mixin(obj, params); -} +module.exports = convert; -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); +// Hide .channels and .labels properties +for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; - } + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; - } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } - return fn.apply(this, arguments); - }; + 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}); } -// 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); - } -} +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; -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); + 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; + } - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; - } + h = Math.min(h * 60, 360); - fn.apply(this, args); - }; -} + if (h < 0) { + h += 360; + } + const l = (min + max) / 2; -/***/ }), + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } -/***/ 25624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return [h, s * 100, l * 100]; +}; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + 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; + }; + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); -/** - * Module dependencies. - * @private - */ + 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 pathRegexp = __nccwpck_require__(37819); -var debug = __nccwpck_require__(52529)('express:router:layer'); + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } -/** - * Module variables. - * @private - */ + return [ + h * 360, + s * 100, + v * 100 + ]; +}; -var hasOwnProperty = Object.prototype.hasOwnProperty; +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)); -/** - * Module exports. - * @public - */ + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); -module.exports = Layer; + return [h, w * 100, b * 100]; +}; -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); - } +convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; - debug('new %o', path) - var opts = options || {}; + 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; - this.handle = fn; - this.name = fn.name || ''; - this.params = undefined; - this.path = undefined; - this.regexp = pathRegexp(path, this.keys = [], opts); + return [c * 100, m * 100, y * 100, k * 100]; +}; - // set fast path flags - this.regexp.fast_star = path === '*' - this.regexp.fast_slash = path === '/' && opts.end === false +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) + ); } -/** - * Handle the error for the layer. - * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ +convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; + let currentClosestDistance = Infinity; + let currentClosestKeyword; - if (fn.length !== 4) { - // not a standard error handler - return next(error); - } + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; - try { - fn(error, req, res, next); - } catch (err) { - next(err); - } + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; }; -/** - * Handle the request for the layer. - * - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; -Layer.prototype.handle_request = function handle(req, res, next) { - var fn = this.handle; +convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; - if (fn.length > 3) { - // not a standard request handler - return next(); - } + // 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); - try { - fn(req, res, next); - } catch (err) { - next(err); - } + 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); + + return [x * 100, y * 100, z * 100]; }; -/** - * Check if this route matches `path`, if so - * populate `.params`. - * - * @param {String} path - * @return {Boolean} - * @api private - */ +convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; -Layer.prototype.match = function match(path) { - var match + x /= 95.047; + y /= 100; + z /= 108.883; - if (path != null) { - // fast path non-ending match for / (any path matches) - if (this.regexp.fast_slash) { - this.params = {} - this.path = '' - return true - } + 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); - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true - } + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); - // match the path - match = this.regexp.exec(path) - } + return [l, a, b]; +}; - if (!match) { - this.params = undefined; - this.path = undefined; - return false; - } +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; - // store values - this.params = {}; - this.path = match[0] + if (s === 0) { + val = l * 255; + return [val, val, val]; + } - var keys = this.keys; - var params = this.params; + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } - for (var i = 1; i < match.length; i++) { - var key = keys[i - 1]; - var prop = key.name; - var val = decode_param(match[i]) + const t1 = 2 * l - t2; - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; - } - } + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } - return true; + if (t3 > 1) { + t3--; + } + + 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; + } + + rgb[i] = val * 255; + } + + return rgb; }; -/** - * Decode param value. - * - * @param {string} val - * @return {string} - * @private - */ +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); -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; - } + 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); - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; - } + return [h, sv * 100, v * 100]; +}; - throw err; - } -} +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]; + } +}; -/***/ 23699: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + 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; -/** - * Module dependencies. - * @private - */ + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } -var debug = __nccwpck_require__(52529)('express:router:route'); -var flatten = __nccwpck_require__(62003); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; -/** - * Module variables. - * @private - */ + if ((i & 0x01) !== 0) { + f = 1 - f; + } -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; + const n = wh + f * (v - wh); // Linear interpolation -/** - * Module exports. - * @public - */ + 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 */ -module.exports = Route; + return [r * 255, g * 255, b * 255]; +}; -/** - * Initialize `Route` with the given `path`, - * - * @param {String} path - * @public - */ +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; -function Route(path) { - this.path = path; - this.stack = []; + 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); - debug('new %o', path) + return [r * 255, g * 255, b * 255]; +}; - // route handlers for various http methods - this.methods = {}; -} +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; -/** - * Determine if the route handles a given method. - * @private - */ + 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); -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; - } + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; - var name = method.toLowerCase(); + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; - if (name === 'head' && !this.methods['head']) { - name = 'get'; - } + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; - return Boolean(this.methods[name]); + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; }; -/** - * @return {Array} supported HTTP methods - * @private - */ +convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); + x /= 95.047; + y /= 100; + z /= 108.883; - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); - } + 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); - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); - } + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); - return methods; + return [l, a, b]; }; -/** - * dispatch req, res into this route - * @private - */ +convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; - } + 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; - req.route = this; + x *= 95.047; + y *= 100; + z *= 108.883; - next(); + return [x, y, z]; +}; - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } +convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; - // signal to exit router - if (err && err === 'router') { - return done(err) - } + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; - var layer = stack[idx++]; - if (!layer) { - return done(err); - } + if (h < 0) { + h += 360; + } - if (layer.method && layer.method !== method) { - return next(err); - } + const c = Math.sqrt(a * a + b * b); - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } + return [l, c, h]; }; -/** - * Add a handler for all HTTP verbs to this route. - * - * 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 - */ +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); -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); + return [l, a, b]; +}; - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; +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 - 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); - } + value = Math.round(value / 50); - var layer = Layer('/', {}, handle); - layer.method = undefined; + if (value === 0) { + return 30; + } - this.methods._all = true; - this.stack.push(layer); - } + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); - return this; + if (value === 2) { + ansi += 60; + } + + return ansi; }; -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); +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]); +}; - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; +convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; - 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); - } + // 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; + } - debug('%s %o', method, this.path) + if (r > 248) { + return 231; + } - var layer = Layer('/', {}, handle); - layer.method = method; + return Math.round(((r - 8) / 247) * 24) + 232; + } - this.methods[method] = true; - this.stack.push(layer); - } + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); - return this; - }; -}); + return ansi; +}; +convert.ansi16.rgb = function (args) { + let color = args % 10; -/***/ }), + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } -/***/ 53561: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + color = color / 10.5 * 255; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + return [color, color, color]; + } + 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; + return [r, g, b]; +}; -/** - * Module dependencies. - * @api private - */ +convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } -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); + args -= 16; -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ + 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; -exports.etag = createETagGenerator({ weak: false }) + return [r, g, b]; +}; -/** - * Return weak ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ +convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); -exports.wetag = createETagGenerator({ weak: true }) + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ +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]; + } -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 + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; }; -/** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private - */ +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; -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } -/** - * Normalize the given `type`, for example "html" becomes "text/html". - * - * @param {String} type - * @return {Object} - * @api private - */ + 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; + } -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; }; -/** - * Normalize `types`, for example "html" becomes "text/html". - * - * @param {Array} types - * @return {Array} - * @api private - */ +convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; -exports.normalizeTypes = function(types){ - var ret = []; + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); - } + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } - return ret; + return [hsl[0], c * 100, f * 100]; }; -/** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added - * - * @param {String} filename - * @return {String} - * @api private - */ - -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); +convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; -/** - * 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 - */ + const c = s * v; + let f = 0; -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + if (c < 1.0) { + f = (v - c) / (1 - c); + } - 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]; - } - } + return [hsv[0], c * 100, f * 100]; +}; - return ret; -} +convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; -/** - * Compile "etag" value to function. - * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private - */ + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } -exports.compileETag = function(val) { - var fn; + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; - if (typeof val === 'function') { - return val; - } + /* 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 */ - 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); - } + mg = (1.0 - c) * g; - return fn; -} + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; -/** - * Compile "query parser" value to function. - * - * @param {String|Function} val - * @return {Function} - * @api private - */ +convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; -exports.compileQueryParser = function compileQueryParser(val) { - var fn; + const v = c + g * (1.0 - c); + let f = 0; - if (typeof val === 'function') { - return val; - } + if (v > 0.0) { + f = c / v; + } - 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); - } + return [hcg[0], f * 100, v * 100]; +}; - return fn; -} +convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; -/** - * Compile "proxy trust" value to function. - * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private - */ + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } - if (val === true) { - // Support plain true/false - return function(){ return true }; - } + return [hcg[0], s * 100, l * 100]; +}; - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; - } +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]; +}; - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); - } +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; - return proxyaddr.compile(val || []); -} + if (c < 1) { + g = (v - c) / (1 - c); + } -/** - * Set the charset in a given Content-Type string. - * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private - */ + return [hwb[0], c * 100, g * 100]; +}; -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; - } +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; - // parse type - var parsed = contentType.parse(type); +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; - // set charset - parsed.parameters.charset = charset; +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; - // format type - return contentType.format(parsed); +convert.gray.hsl = function (args) { + return [0, 0, args[0]]; }; -/** - * Create an ETag generator function, generating ETags with - * the given options. - * - * @param {object} options - * @return {function} - * @private - */ +convert.gray.hsv = convert.gray.hsl; -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; - return etag(buf, options) - } -} +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; -/** - * Parse an extended query string with qs. - * - * @return {Object} - * @private - */ +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); -} +convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; -/** - * Return new empty object. - * - * @return {Object} - * @api private - */ + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; -function newObject() { - return {}; -} +convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; /***/ }), -/***/ 99209: +/***/ 86931: /***/ ((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 - */ +const conversions = __nccwpck_require__(97391); +const route = __nccwpck_require__(30880); +const convert = {}; +const models = Object.keys(conversions); -/** - * Module dependencies. - * @private - */ +function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } -var debug = __nccwpck_require__(52529)('express:view'); -var path = __nccwpck_require__(85622); -var fs = __nccwpck_require__(35747); + if (arg0.length > 1) { + args = arg0; + } -/** - * Module variables. - * @private - */ + return fn(args); + }; -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } -/** - * Module exports. - * @public - */ + return wrappedFn; +} -module.exports = View; +function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; -/** - * 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 - * - * @param {string} name - * @param {object} options - * @public - */ + if (arg0 === undefined || arg0 === null) { + return arg0; + } -function View(name, options) { - var opts = options || {}; + if (arg0.length > 1) { + args = arg0; + } - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; + const result = fn(args); - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); - } + // 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]); + } + } - var fileName = name; + return result; + }; - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } - fileName += this.ext; - } + return wrappedFn; +} - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) +models.forEach(fromModel => { + convert[fromModel] = {}; - // default engine export - var fn = require(mod).__express + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') - } + const routes = route(fromModel); + const routeModels = Object.keys(routes); - opts.engines[this.ext] = fn - } + routeModels.forEach(toModel => { + const fn = routes[toModel]; - // store loaded engine - this.engine = opts.engines[this.ext]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); - // lookup path - this.path = this.lookup(fileName); -} +module.exports = convert; -/** - * Lookup view by the given `name` - * - * @param {string} name - * @private - */ -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); +/***/ }), - debug('lookup "%s"', name); +/***/ 30880: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; +const conversions = __nccwpck_require__(97391); - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); +/* + This function routes a model to all other models. - // resolve the file - path = this.resolve(dir, file); - } + 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). - return path; -}; + conversions that are not possible simply are not included. +*/ -/** - * Render with the given options. - * - * @param {object} options - * @param {function} callback - * @private - */ +function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; + 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 + }; + } -/** - * Resolve the file within the given directory. - * - * @param {string} dir - * @param {string} file - * @private - */ + return graph; +} -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop - // . - var path = join(dir, file); - var stat = tryStat(path); + graph[fromModel].distance = 0; - if (stat && stat.isFile()) { - return path; - } + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; - if (stat && stat.isFile()) { - return path; - } -}; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } -/** - * Return a stat, maybe. - * - * @param {string} path - * @return {fs.Stats} - * @private - */ + return graph; +} -function tryStat(path) { - debug('stat "%s"', path); +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} - try { - return fs.statSync(path); - } catch (e) { - return undefined; - } +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]; -/***/ 36654: -/***/ ((module, exports, __nccwpck_require__) => { + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + conversion[toModel] = wrapConversion(toModel, graph); + } -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(); + return conversion; +}; -/** - * 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; - } +/***/ 78510: +/***/ ((module) => { - // 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; - } +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] }; -/** - * 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; +/***/ 53921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ - // 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); -} /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public + * Module exports. + * @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); -} +module.exports = contentDisposition +module.exports.parse = parse /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Module dependencies. + * @private */ -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} +var basename = (__nccwpck_require__(71017).basename) +var Buffer = (__nccwpck_require__(21867).Buffer) /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private */ -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex - // 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; - } +/** + * RegExp to match percent encoding escape. + * @private + */ - return r; -} +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g /** - * Enable namespaces listed in `localStorage.debug` initially. + * RegExp to match non-latin1 characters. + * @private */ -exports.enable(load()); +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * RegExp to match quoted-pair in RFC 2616 * - * @return {LocalStorage} - * @api private + * quoted-pair = "\" CHAR + * CHAR = + * @private */ -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - - -/***/ }), - -/***/ 86991: -/***/ ((module, exports, __nccwpck_require__) => { - +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @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__(27025); +var QUOTE_REGEXP = /([\\"])/g /** - * The currently active debug mode names, and names to skip. + * 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 */ -exports.names = []; -exports.skips = []; +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|~-]+$/ /** - * Map of special "%n" handling functions, for the debug "format" argument. + * RegExp for various RFC 5987 grammar * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + * 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 */ -exports.formatters = {}; +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!#$&+.^_`|~-])+)$/ /** - * Previous log timestamp. + * 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 */ -var prevTime; +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private + * 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 */ -function selectColor(namespace) { - var hash = 0, i; +function contentDisposition (filename, options) { + var opts = options || {} - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + // get type + var type = opts.type || 'attachment' - return exports.colors[Math.abs(hash) % exports.colors.length]; + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) } /** - * Create a debugger with the given `namespace`. + * Create parameters object from filename and fallback. * - * @param {String} namespace - * @return {Function} - * @api public + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private */ -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; +function createparams (filename, fallback) { + if (filename === undefined) { + return + } - var self = debug; + var params = {} - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } - // 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]; - } + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } - args[0] = exports.coerce(args[0]); + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } - // 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); + // restrict to file base name + var name = basename(filename) - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name } - 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); + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name } - return debug; + return params } /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. + * Format object to Content-Disposition header. * - * @param {String} namespaces - * @api public + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private */ -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +function format (obj) { + var parameters = obj.parameters + var type = obj.type - 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 + '$')); - } + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') } -} -/** - * Disable debug output. - * - * @api public - */ + // start with normalized type + var string = String(type).toLowerCase() -function disable() { - exports.enable(''); -} + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + for (var i = 0; i < params.length; i++) { + param = params[i] -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; + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val } } - return false; + + return string } /** - * Coerce `val`. + * Decode a RFC 6987 field value (gracefully). * - * @param {Mixed} val - * @return {Mixed} - * @api private + * @param {string} str + * @return {string} + * @private */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + if (!match) { + throw new TypeError('invalid extended field value') + } -/***/ }), + var charset = match[1].toLowerCase() + var encoded = match[2] + var value -/***/ 52529: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + 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') + } -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(36654); -} else { - module.exports = __nccwpck_require__(25696); + return value } - -/***/ }), - -/***/ 25696: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * Module dependencies. - */ - -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); - -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = __nccwpck_require__(86991); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - /** - * Build up the default `inspectOpts` object from the environment variables. + * Get ISO-8859-1 version of string. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param {string} val + * @return {string} + * @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() }); - - // 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 getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * Parse Content-Disposition header string. * - * $ DEBUG_FD=3 node script.js 3>debug.log + * @param {string} string + * @return {object} + * @public */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } -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 match = DISPOSITION_TYPE_REGEXP.exec(string) -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + if (!match) { + throw new TypeError('invalid type format') + } -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} + var key + var names = [] + var params = {} + var value -/** - * Map %o to `util.inspect()`, all on a single line. - */ + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index -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(' '); -}; + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + index += match[0].length + key = match[1].toLowerCase() + value = match[2] -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + names.push(key) -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + // overwrite existing value + params[key] = value + continue + } - 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]; + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value } -} -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); + return new ContentDisposition(type, params) } /** - * Save `namespaces`. + * Percent decode a single character. * - * @param {String} namespaces - * @api private + * @param {string} str + * @param {string} hex + * @return {string} + * @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; - } +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) } /** - * Load `namespaces`. + * Percent encode a single character. * - * @return {String} returns the previously persisted debug modes - * @api private + * @param {string} char + * @return {string} + * @private */ -function load() { - return process.env.DEBUG; +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() } /** - * Copied from `node/src/node.js`. + * Quote a string for HTTP. * - * 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 {string} val + * @return {string} + * @private */ -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; +function qstring (val) { + var str = String(val) - return stream; + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' } /** - * Init logic for `debug` instances. + * Encode a Unicode string for HTTP (RFC 5987). * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * @param {string} val + * @return {string} + * @private */ -function init (debug) { - debug.inspectOpts = {}; +function ustring (val) { + var str = String(val) - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded } /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor */ -exports.enable(load()); +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} /***/ }), -/***/ 27025: -/***/ ((module) => { +/***/ 99915: +/***/ ((__unused_webpack_module, exports) => { -/** - * Helpers. +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 * - * @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 + * 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 ) */ - -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) - ); -}; +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-]+$/ /** - * Parse the given `str` and return milliseconds. + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 * - * @param {String} str - * @return {Number} - * @api private + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g -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; - } -} +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g /** - * Short format for `ms`. + * RegExp to match type in RFC 7231 sec 3.1.1.1 * - * @param {Number} ms - * @return {String} - * @api private + * media-type = type "/" subtype + * type = token + * subtype = token */ - -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'; -} +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Module exports. + * @public */ -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} +exports.format = format +exports.parse = parse /** - * Pluralization helper. + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public */ -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + var parameters = obj.parameters + var type = obj.type -/***/ }), - -/***/ 24826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + var string = type -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 + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() -const DEFAULT_CENSOR = '[REDACTED]' -fastRedact.rx = rx -fastRedact.validator = validator + for (var i = 0; i < params.length; i++) { + param = params[i] -module.exports = fastRedact + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } -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') + string += '; ' + param + '=' + qstring(parameters[param]) + } } - const censor = remove === true - ? undefined - : 'censor' in opts ? opts.censor : DEFAULT_CENSOR - const isCensorFct = typeof censor === 'function' - const censorFctTakesPath = isCensorFct && censor.length > 1 + return string +} - if (paths.length === 0) return serialize || noop +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ - validate({ paths, serialize, censor }) +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } - const { wildcards, wcLen, secret } = parse({ paths, censor }) + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string - const compileRestore = restorer({ secret, wcLen }) - const strict = 'strict' in opts ? opts.strict : true + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } - return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - })) -} + 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()) -/***/ 54865: -/***/ ((module) => { + // parse parameters + if (index !== -1) { + var key + var match + var value -"use strict"; + PARAM_REGEXP.lastIndex = index + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } -module.exports = { - groupRedact, - groupRestore, - nestedRedact, - nestedRestore -} + index += match[0].length + key = match[1].toLowerCase() + value = match[2] -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] + 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') + } } + + return obj } -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) +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - values[i] = target[key] +function getcontenttype (obj) { + var header - if (censorFctTakesPath) { - pathWithKey[pathLength] = key - target[key] = censor(target[key], pathWithKey) - } else if (isCensorFct) { - target[key] = censor(target[key]) - } else { - target[key] = censor - } + 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'] } - 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 header !== 'string') { + throw new TypeError('content-type header is missing from object') } + + return header } -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) +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ - if (exists === true && parent !== null) { - store.push({ key: ns[ns.length - 1], target: parent, value }) - } - } - return store -} +function qstring (val) { + var str = String(val) -function has (obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop) -} + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } -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 + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') } - return { value: ov, parent: oov, exists } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' } -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 +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type } /***/ }), -/***/ 96214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const rx = __nccwpck_require__(9158) +/***/ 61579: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = parse +/** + * Module dependencies. + */ -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 - } - } - return o - }, {}) +var crypto = __nccwpck_require__(6113); - return { wildcards, wcLen, secret } -} +/** + * 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 + */ -/***/ 17333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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; +}; -"use strict"; +/** + * Private + */ +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} -const rx = __nccwpck_require__(9158) -module.exports = redactor +/***/ }), -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) +/***/ 93658: +/***/ ((__unused_webpack_module, exports) => { - if (serialize === false) { - redact.restore = (o) => state.restore(o) - } +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - 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` - const circularDetection = ` - switch (true) { - ${hops.reverse().map((p) => ` - case o${delim}${p} === censor: - secret[${escPath}].circle = ${JSON.stringify(p)} - break - `).join('\n')} - } - ` +/** + * Module exports. + * @public + */ - const censorArgs = censorFctTakesPath - ? `val, ${JSON.stringify(arrPath)}` - : `val` +exports.parse = parse; +exports.serialize = serialize; - 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') -} +/** + * Module variables. + * @private + */ -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}) - } - } - ` : '' -} +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; -function resultTmpl (serialize) { - return serialize === false ? `return o` : ` - var s = this.serialize(o) - this.restore(o) - return s - ` -} +/** + * 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 + */ -function strictImpl (strict, serialize) { - return strict === true - ? `throw Error('fast-redact: primitives cannot be redacted')` - : serialize === false ? `return o` : `return this.serialize(o)` -} +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; +/** + * 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 parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } -/***/ 98806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; -"use strict"; + 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; + } -const { groupRestore, nestedRestore } = __nccwpck_require__(54865) + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); -module.exports = restorer + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } -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) + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } } + + return obj; } /** - * Mutates the original object to be censored by restoring its original values - * prior to censoring. + * Serialize data into a cookie header. * - * @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. + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. * - * @returns {string} String of JavaScript to be used by `Function()`. The - * string compiles to the function that does the work in the description. + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @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 - } - ` : '' +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; - return ` - const secret = this.secret - ${resetters} - ${dynamicReset} - return o - ` -} + 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); -/***/ 9158: -/***/ ((module) => { + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + 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); + } -"use strict"; + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + str += '; Domain=' + opt.domain; + } -module.exports = /[^.[\]]+|\[((?:.)*?)\]/g + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } -/* -Regular expression explanation: + str += '; Path=' + opt.path; + } -Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) - opening square bracket ([) or closing square bracket (]) + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } -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). -*/ + str += '; Expires=' + opt.expires.toUTCString(); + } + if (opt.httpOnly) { + str += '; HttpOnly'; + } -/***/ }), + if (opt.secure) { + str += '; Secure'; + } -/***/ 41012: -/***/ ((module) => { + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; -"use strict"; + 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 str; +} -module.exports = state +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ -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) +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } } /***/ }), -/***/ 74174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 65507: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; +/* jshint node: true */ +(function () { + "use strict"; + 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; -const { createContext, runInContext } = __nccwpck_require__(92184) + 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; -module.exports = validator + 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("; "); + }; -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 + Cookie.prototype.toValueString = function toValueString() { + return this.name + "=" + this.value; + }; - 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)) - } - }) - } -} + 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; + } -/***/ 17676: -/***/ ((module) => { + this.name = key; + this.value = value; -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify + 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; + } + } -var arr = [] -var replacerStack = [] + if (!this.explicit_path) { + this.path = request_path || "/"; + } + if (!this.explicit_domain) { + this.domain = request_domain; + } -// 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 this; } - 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() - } -} - -// Stable-stringify -function compareFunction (a, b) { - if (a < b) { - return -1 - } - if (a > b) { - return 1 - } - return 0 -} + return new Cookie().parse(str, request_domain, request_path); + }; -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 -} + 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 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]) + Cookie.prototype.collidesWith = function collidesWith(access_info) { + if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { + return false; } - 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() - } -} + 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; + }; -// 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 + function CookieJar() { + var cookies, cookies_list, collidable_cookie; + if (this instanceof CookieJar) { + cookies = Object.create(null); //name: [Cookie] + + 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; + } + + 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; + }; + + return this; } - } + return new CookieJar(); } - return replacer.call(this, key, val) - } -} + 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 successful; + }; +}()); -/***/ }), -/***/ 34578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 51512: +/***/ (function(module) { /* -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: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ -function 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; - - this.auth = null; - this.slashes = null; - this.host = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; - - this._prependSlash = false; -} - -var querystring = __nccwpck_require__(71191); - -Url.queryString = querystring; - -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; - - //Trim leading and trailing ws - while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; - while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; - - start = this._parseProtocol(str, start, end); - - //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 = ""; - } - } + * 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. + */ - if (start <= end) { - var ch = str.charCodeAt(start); +(function(global) { + 'use strict'; - if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, start, end, disableAutoEscapeChars); + 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; } - else if (ch === 0x23 /*'#'*/) { - this._parseHash(str, start, end, disableAutoEscapeChars); + + date = date || new Date; + + if(!(date instanceof Date)) { + date = new Date(date); } - else if (this._protocol !== "javascript") { - this._parsePath(str, start, end, disableAutoEscapeChars); + + if (isNaN(date)) { + throw TypeError('Invalid date'); } - else { //For javascript the pathname is just the rest of it - this.pathname = str.slice(start, end + 1 ); + + 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' + }; - if (!this.pathname && this.hostname && - this._slashProtocols[this._protocol]) { - this.pathname = "/"; - } + // Internationalization strings + 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' + ] + }; - 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); - } -}; +function pad(val, len) { + val = String(val); + len = len || 2; + while (val.length < len) { + val = '0' + val; + } + return val; +} -Url.prototype.resolve = function Url$resolve(relative) { - return this.resolveObject(Url.parse(relative, false, true)).format(); -}; +/** + * 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()); -Url.prototype.format = function Url$format() { - var auth = this.auth || ""; + // Change date to Thursday same week + targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ":"); - auth += "@"; - } + // Take January 4th as it is always in week 1 (see ISO 8601) + var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); - 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 = ""; + // Change date to Thursday same week + firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); - //Cache the result of the getter function - var q = this.query; - if (q && typeof q === "object") { - query = Url.queryString.stringify(q); - } + // Check if daylight-saving-time-switch occurred and correct for it + var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); + targetThursday.setHours(targetThursday.getHours() - ds); - if (!search) { - search = query ? "?" + query : ""; - } + // Number of weeks between target Thursday and first Thursday + var weekDiff = (targetThursday - firstThursday) / (86400000*7); + return 1 + Math.floor(weekDiff); +} - if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) - protocol += ":"; +/** + * 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; +} - if (this.host) { - host = auth + this.host; - } - else if (hostname) { - var ip6 = hostname.indexOf(":") > -1; - if (ip6) hostname = "[" + hostname + "]"; - host = auth + hostname + (port ? ":" + port : ""); - } +/** + * kind-of shortcut + * @param {*} val + * @return {String} + */ +function kindOf(val) { + if (val === null) { + return 'null'; + } - var slashes = this.slashes || - ((!protocol || - slashProtocols[protocol]) && host !== false); + if (val === undefined) { + return 'undefined'; + } + if (typeof val !== 'object') { + return typeof val; + } - if (protocol) scheme = protocol + (slashes ? "//" : ""); - else if (slashes) scheme = "//"; + if (Array.isArray(val)) { + return 'array'; + } - 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; + return {}.toString.call(val) + .slice(8, -1).toLowerCase(); +}; - pathname = escapePathName(pathname); - search = escapeSearch(search); - return scheme + (host === false ? "" : host) + pathname + search + hash; -}; -Url.prototype.resolveObject = function Url$resolveObject(relative) { - if (typeof relative === "string") - relative = Url.parse(relative, false, true); + if (typeof define === 'function' && define.amd) { + define(function () { + return dateFormat; + }); + } else if (true) { + module.exports = dateFormat; + } else {} +})(this); - var result = this._clone(); - // 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; - } +/***/ 84697: +/***/ ((module) => { - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative._protocol) { - relative._copyPropsTo(result, true); +/** + * Helpers. + */ - if (slashProtocols[result._protocol] && - result.hostname && !result.pathname) { - result.pathname = "/"; - } - result._href = ""; - return result; - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - 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; - } +/** + * 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 + */ - 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; - } +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) + ); +}; - 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; - } +/** + * Parse the given `str` and return milliseconds. + * + * @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|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; + } +} - 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)); +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - var removeAllDots = mustEndAbs; +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'; +} - var srcPath = result.pathname && result.pathname.split("/") || []; - var relPath = relative.pathname && relative.pathname.split("/") || []; - var psychotic = result._protocol && !slashProtocols[result._protocol]; +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - // 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] === ""); - } +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'; +} - 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; - } +/** + * Pluralization helper. + */ - if (!srcPath.length) { - // no path at all. easy. - // we"ve already handled the other stuff above. - result.pathname = null; - result._href = ""; - return result; - } +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - // 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 the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift(".."); - } - } +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { - if (mustEndAbs && srcPath[0] !== "" && - (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { - srcPath.unshift(""); - } +/* eslint-env browser */ - if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { - srcPath.push(""); - } +/** + * This is the web browser implementation of `debug()`. + */ - var isAbsolute = srcPath[0] === "" || - (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; - // 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 () => { + 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`.'); + } + }; +})(); - mustEndAbs = mustEndAbs || (result.host && srcPath.length); +/** + * Colors. + */ - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(""); - } +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' +]; - result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; -}; +/** + * 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 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); -}; +// 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; + } -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); -}; + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } -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); -}; + // 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+)/)); +} -Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { - var doLowerCase = false; - var protocolCharacters = this._protocolCharacters; +/** + * Colorize log arguments if enabled. + * + * @api public + */ - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - 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; - } + if (!this.useColors) { + return; + } - } - return start; -}; + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); -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; -}; + // 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; + } + }); -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; + args.splice(lastC, 0, c); +} - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +/** + * 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 || (() => {}); - 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; - } +/** + * 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? + } +} - } - if ((port === 0 && !hadChars) || !validPort) { - if (!validPort) { - this._port = -2; - } - return 0; - } +/** + * 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? + } - this._port = port; - return i - start; -}; + // 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; + } -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; + return r; +} - //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; - } +/** + * 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 + */ - var doLowerCase = false; - var idna = false; - var hostNameStart = start; - var hostNameEnd = end; - var lastCh = -1; - var portLength = 0; - var charsAfterDot = 0; - var authNeedsDecoding = false; +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? + } +} - var j = -1; +module.exports = __nccwpck_require__(46243)(exports); - //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); +const {formatters} = module.exports; - 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; - } - } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - //@-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; - } +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - //Host name is starting with a [ - if (str.charCodeAt(start) === 0x5B /*'['*/) { - for (var i = start + 1; i <= end; ++i) { - var ch = str.charCodeAt(i); - //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; - } +/***/ }), - 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); +/***/ 46243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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++; - } - //Node.js ignores this error - /* - if (lastCh === DOT) { - hostNameEnd--; - } - */ +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ - 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; - } +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 hostNameEnd + 1 + portLength; + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); -}; + /** + * The currently active debug mode names, and names to skip. + */ -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; -}; + createDebug.names = []; + createDebug.skips = []; -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; -}; + /** + * 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 = {}; -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]; + /** + * 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; - 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; -}; + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -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 ? "/:" : ""; + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - 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; - } - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; - if (pathStart > pathEnd) { - this.pathname = prePath === "" ? "/" : prePath; - return; - } + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - 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; -}; + const self = debug; -Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { - var queryStart = start; - var queryEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + args[0] = createDebug.coerce(args[0]); - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - queryEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - if (queryStart > queryEnd) { - this.search = ""; - return; - } + // 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); - var query; - if (escape) { - query = this._getComponentEscaped(str, queryStart, queryEnd, true); - } - else { - query = str.slice(queryStart, queryEnd + 1); - } - this.search = query; -}; + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { - if (start > end) { - this.hash = ""; - return; - } + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); - this.hash = disableAutoEscapeChars ? - str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); -}; + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -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); - } - } -}); + 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. -Object.defineProperty(Url.prototype, "query", { - get: function() { - var query = this._query; - if (query != null) { - return query; - } - var search = this.search; + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); - 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; - } -}); + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } -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() {} -}); + return debug; + } -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; - } - } -}); + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * 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); -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; - } -}); + createDebug.names = []; + createDebug.skips = []; -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; -}; + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -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(); -}; + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -Url.resolve = function Url$Resolve(source, relative) { - return Url.parse(source, false, true).resolve(relative); -}; + namespaces = split[i].replace(/\*/g, '.*?'); -Url.resolveObject = function Url$ResolveObject(source, relative) { - if (!source) return relative; - return Url.parse(source, false, true).resolveObject(relative); -}; + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -function _escapePath(pathname) { - return pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); -} + /** + * 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; + } -function _escapeSearch(search) { - return search.replace(/#/g, function(match) { - return encodeURIComponent(match); - }); -} + /** + * 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; + } -//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); + let i; + let len; - if (ch === char1) { - return true; - } - else if (stopCharacterTable[ch] === 1) { - return false; - } - } - return false; -} + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } -//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; -} + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } -//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] + return false; + } -//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; - } - } - }); + /** + * 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(/\.\*\?$/, '*'); + } - return ret; + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * 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`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; } +module.exports = setup; -var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", - "\t", "{", "}", "|", "\\", "^", "`", "'"]; -var autoEscapeMap = new Array(128); +/***/ }), +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ -for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { - autoEscapeMap[i] = ""; +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); } -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 /*'\'*/] = "/"; -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 -}; +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { -//Optimize back from normalized object caused by non-identifier keys -function f(){} -f.prototype = slashProtocols; +/** + * Module dependencies. + */ -Url.prototype._protocolCharacters = makeAsciiTable([ - [0x61 /*'a'*/, 0x7A /*'z'*/], - [0x41 /*'A'*/, 0x5A /*'Z'*/], - 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ -]); +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); -Url.prototype._hostEndingCharacters = makeAsciiTable([ - 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ -]); +/** + * This is the Node.js implementation of `debug()`. + */ -Url.prototype._autoEscapeCharacters = makeAsciiTable( - autoEscape.map(function(v) { - return v.charCodeAt(0); - }) +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`.' ); -//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); - }) -); +/** + * Colors. + */ -Url.prototype._autoEscapeMap = autoEscapeMap; -Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; +exports.colors = [6, 2, 3, 4, 5, 1]; -module.exports = Url; +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); -Url.replace = function Url$Replace() { - require.cache.url = { - exports: Url - }; -}; + 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. +} +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -/***/ }), +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(); + }); -/***/ 30810: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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); + } -"use strict"; -/*! - * finalhandler - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public */ +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]; + } +} +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} /** - * Module dependencies. - * @private + * Invokes `util.format()` with the specified arguments and writes to stderr. */ -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) +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} /** - * Module variables. - * @private + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ +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; + } +} -var DOUBLE_SPACE_REGEXP = /\x20{2}/g -var NEWLINE_REGEXP = /\n/g +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } -var isFinished = onFinished.isFinished +function load() { + return process.env.DEBUG; +} /** - * Create a minimal HTML document. + * Init logic for `debug` instances. * - * @param {string} message - * @private + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function createHtmlDocument (message) { - var body = escapeHtml(message) - .replace(NEWLINE_REGEXP, '
') - .replace(DOUBLE_SPACE_REGEXP, '  ') +function init(debug) { + debug.inspectOpts = {}; - return '\n' + - '\n' + - '\n' + - '\n' + - 'Error\n' + - '\n' + - '\n' + - '
' + body + '
\n' + - '\n' + - '\n' + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } +module.exports = __nccwpck_require__(46243)(exports); + +const {formatters} = module.exports; + /** - * Module exports. - * @public + * Map %o to `util.inspect()`, all on a single line. */ -module.exports = finalhandler +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; /** - * Create a function to handle the final response. - * - * @param {Request} req - * @param {Response} res - * @param {Object} [options] - * @return {Function} - * @public + * Map %O to `util.inspect()`, allowing multiple lines if needed. */ -function finalhandler (req, res, options) { - var opts = options || {} +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - // 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 +/***/ 56323: +/***/ ((module) => { - // 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) - } +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) +}; - // get error message - msg = getErrorMessage(err, status, env) - } else { - // not found - status = 404 - msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) - } +function isNonNullObject(value) { + return !!value && typeof value === 'object' +} - debug('default %s', status) +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); - // schedule onerror callback - if (err && onerror) { - defer(onerror, err, req, res) - } + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} - // cannot actually respond - if (headersSent(res)) { - debug('cannot %d after headers sent', status) - req.socket.destroy() - return - } +// 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; - // send response - send(req, res, status, headers, msg) - } +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE } -/** - * Get headers from Error object. - * - * @param {Error} err - * @return {object} - * @private - */ +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} -function getErrorHeaders (err) { - if (!err.headers || typeof err.headers !== 'object') { - return undefined - } +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value +} - var headers = Object.create(null) - var keys = Object.keys(err.headers) +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) +} - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - headers[key] = err.headers[key] - } +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge + } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge +} - return headers +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return target.propertyIsEnumerable(symbol) + }) + : [] } -/** - * Get message from Error object, fallback to status message. - * - * @param {Error} err - * @param {number} status - * @param {string} env - * @return {string} - * @private - */ +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +} -function getErrorMessage (err, status, env) { - var msg +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false + } +} - if (env !== 'production') { - // use err.stack, which typically includes err.message - msg = err.stack +// 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. +} - // fallback to err.toString() when possible - if (!msg && typeof err.toString === 'function') { - msg = err.toString() - } - } +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 + } - return msg || statuses[status] + 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 } -/** - * Get status code from Error object. - * - * @param {Error} err - * @return {number} - * @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; -function getErrorStatusCode (err) { - // check err.status - if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { - return err.status - } + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - // check err.statusCode - if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode - } + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) + } +} - return undefined +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') + } + + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) +}; + +var deepmerge_1 = deepmerge; + +module.exports = deepmerge_1; + + +/***/ }), + +/***/ 18611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); + +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); -/** - * 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 - */ +DelayedStream.create = function(source, options) { + var delayedStream = new this(); -function getResourceName (req) { - try { - return parseUrl.original(req).pathname - } catch (e) { - return 'resource' + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } -} -/** - * Get status code from response. - * - * @param {OutgoingMessage} res - * @return {number} - * @private - */ + delayedStream.source = source; -function getResponseStatusCode (res) { - var status = res.statusCode + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; - // default status code to 500 if outside valid range - if (typeof status !== 'number' || status < 400 || status > 599) { - status = 500 + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); } - return status -} + return delayedStream; +}; -/** - * Determine if the response headers have been sent. - * - * @param {object} res - * @returns {boolean} - * @private - */ +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); -function headersSent (res) { - return typeof res.headersSent !== 'boolean' - ? Boolean(res._header) - : res.headersSent -} +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; -/** - * Send response. - * - * @param {IncomingMessage} req - * @param {OutgoingMessage} res - * @param {number} status - * @param {object} headers - * @param {string} message - * @private - */ +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } -function send (req, res, status, headers, message) { - function write () { - // response body - var body = createHtmlDocument(message) + this.source.resume(); +}; - // response status - res.statusCode = status - res.statusMessage = statuses[status] +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; - // response headers - setHeaders(res, headers) +DelayedStream.prototype.release = function() { + this._released = true; - // security headers - res.setHeader('Content-Security-Policy', "default-src 'none'") - res.setHeader('X-Content-Type-Options', 'nosniff') + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; - // standard headers - res.setHeader('Content-Type', 'text/html; charset=utf-8') - res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; - if (req.method === 'HEAD') { - res.end() - return - } +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } - res.end(body, 'utf8') + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); } - if (isFinished(req)) { - write() - return + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; } - // unpipe everything from the request - unpipe(req) + if (this.dataSize <= this.maxDataSize) { + return; + } - // flush the request - onFinished(req, write) - req.resume() + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; + + +/***/ }), + +/***/ 42342: +/***/ ((module) => { + + + +/** + * 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); + } } /** - * Set response headers from an object. - * - * @param {OutgoingMessage} res - * @param {object} headers - * @private + * ------------- + * PUBLIC API + * ------------- */ -function setHeaders (res, headers) { - if (!headers) { - return +/** + * 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]; +}; - var keys = Object.keys(headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - res.setHeader(key, headers[key]) - } -} +/** + * Alias for peakAt() + * @param i + * @returns {*} + */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; + +/** + * 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]; +}; +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; -/***/ }), +/** + * 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); +}; -/***/ 56401: -/***/ ((module, exports, __nccwpck_require__) => { +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); /** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. + * Return the number of items on the list, or 0 if empty. + * @returns {number} */ - -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(); +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); +}; /** - * Colors. + * Add an item at the beginning of the list. + * @param item */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +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); +}; /** - * 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 + * 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; +}; -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; +/** + * 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(); } - // 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+)/)); -} + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } +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; }; - /** - * Colorize log arguments if enabled. - * - * @api public + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} */ - -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; +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]; } - }); - - args.splice(lastC, 0, c); -} + 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; +}; /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public + * 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} */ - -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); -} +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 (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]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } 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; +}; /** - * Save `namespaces`. + * 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} namespaces - * @api private + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); +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 { - exports.storage.debug = namespaces; + 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]); + } } - } catch(e) {} -} - -/** - * 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 removed; + } else { + return this.remove(i, count); } - - return r; -} +}; /** - * Enable namespaces listed in `localStorage.debug` initially. + * Soft clear - does not reset capacity. */ - -exports.enable(load()); +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; /** - * 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 + * Returns true or false whether the list is empty. + * @returns {boolean} */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - - -/***/ }), - -/***/ 60545: -/***/ ((module, exports, __nccwpck_require__) => { - +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. + * Returns an array of all queue items. + * @returns {Array} */ - -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); +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; /** - * The currently active debug mode names, and names to skip. + * ------------- + * INTERNALS + * ------------- */ -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". + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private */ - -exports.formatters = {}; +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); +}; /** - * Previous log timestamp. + * + * @param fullCopy + * @returns {Array} + * @private */ - -var prevTime; +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; +}; /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private + * Grows the internal list array. + * @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 +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; } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; + + this._list.length *= 2; + this._capacityMask = (this._capacityMask << 1) | 1; +}; /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public + * Shrinks the internal list array. + * @private */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; -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'); - } +module.exports = Denque; - // 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); +/***/ 18883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +/** + * Module dependencies. + */ - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +var callSiteToString = (__nccwpck_require__(69829).callSiteToString) +var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) +var relative = (__nccwpck_require__(71017).relative) - return debug; -} +/** + * Module exports. + */ + +module.exports = depd /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public + * Get the path to base files on. */ -function enable(namespaces) { - exports.save(namespaces); +var basePath = process.cwd() - exports.names = []; - exports.skips = []; +/** + * Determine if namespace is contained in the string. + */ - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() - 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 + '$')); + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true } } + + return false } /** - * Disable debug output. - * - * @api public + * Convert a data descriptor to accessor descriptor. */ -function disable() { - exports.enable(''); -} +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ + descriptor.get = function getter () { return value } -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; - } + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } } - return false; + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor } /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private + * Create arguments string to keep arity. */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - +function createArgumentsString (arity) { + var str = '' -/***/ }), + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } -/***/ 65612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return str.substr(2) +} /** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. + * Create stack string from stack. */ -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(56401); -} else { - module.exports = __nccwpck_require__(4706); -} +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]) + } -/***/ 4706: -/***/ ((module, exports, __nccwpck_require__) => { + return str +} /** - * Module dependencies. + * Create deprecate for namespace in caller. */ -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] -exports = module.exports = __nccwpck_require__(60545); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } -/** - * Colors. - */ + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) -exports.colors = [6, 2, 3, 4, 5, 1]; + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} /** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * Determine if namespace is ignored. */ -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() }); +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } - // 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); + var str = process.env.NO_DEPRECATION || '' - obj[prop] = val; - return obj; -}, {}); + // namespace ignored + return containsNamespace(str, namespace) +} /** - * 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 + * Determine if namespace is traced. */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } -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 str = process.env.TRACE_DEPRECATION || '' -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + // namespace traced + return containsNamespace(str, namespace) +} /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Display deprecation message. */ -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 -/** - * Map %o to `util.inspect()`, all on a single line. - */ + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } -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 caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + 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 + } -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + if (key !== undefined && key in this._warned) { + // already warned + return + } - 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]; + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) } -} -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); + // 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') } /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Get call site location as array. */ -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 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] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site } /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Generate a default message from the site. */ -function load() { - return process.env.DEBUG; +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName } /** - * 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. + * Format deprecation message without color. */ -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() - // Note stream._type is used for test-module-load-list.js + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } - // 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; + return formatted + } - case 'FILE': - var fs = __nccwpck_require__(35747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + if (caller) { + formatted += ' at ' + formatLocation(caller) + } - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(11631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + return formatted +} - // 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'; +/** + * Format deprecation message with color. + */ - // 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; +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 - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } - // For supporting legacy API we put the FD here. - stream.fd = fd; + return formatted + } - stream._isStdio = true; + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } - return stream; + return formatted } /** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Format call site location. */ -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 formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] } /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Get the stack as array of call sites. */ -exports.enable(load()); +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) -/***/ 80761: -/***/ ((module) => { + // slice this function off the top + var stack = obj.stack.slice(1) -/** - * Helpers. - */ + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + return stack +} /** - * 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 + * Capture call site stack from v8. */ -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) - ); -}; +function prepareObjectStackTrace (obj, stack) { + return stack +} /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private + * Return a wrapped function in a deprecation message. */ -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 wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') } -} -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) -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'; -} + site.name = fn.name -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + // 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 fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; + return deprecatedfn } /** - * Pluralization helper. + * Wrap property in a deprecation message. */ -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - - -/***/ }), - -/***/ 35298: -/***/ ((module) => { -"use strict"; + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + if (!descriptor) { + throw new TypeError('must call property on owner object') + } -// 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. + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } -function flatstr (s) { - s | 0 - return s -} + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) -module.exports = flatstr + // set site name + site.name = prop -/***/ }), + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } -/***/ 68329: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var get = descriptor.get + var set = descriptor.set -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } -var util = __nccwpck_require__(31669), - fs = __nccwpck_require__(35747), - EventEmitter = __nccwpck_require__(28614).EventEmitter, - crypto = __nccwpck_require__(76417); + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } -function File(properties) { - EventEmitter.call(this); + Object.defineProperty(obj, prop, descriptor) +} - this.size = 0; - this.path = null; - this.name = null; - this.type = null; - this.hash = null; - this.lastModifiedDate = null; +/** + * Create DeprecationError for deprecation + */ - this._writeStream = null; - - for (var key in properties) { - this[key] = properties[key]; - } +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString - if(typeof this.hash === 'string') { - this.hash = crypto.createHash(properties.hash); - } else { - this.hash = null; - } -} -module.exports = File; -util.inherits(File, EventEmitter); + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) -File.prototype.open = function() { - this._writeStream = new fs.WriteStream(this.path); -}; + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) -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; -}; + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) -File.prototype.write = function(buffer, cb) { - var self = this; - if (self.hash) { - self.hash.update(buffer); - } + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) - if (this._writeStream.closed) { - return cb(); - } + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } - this._writeStream.write(buffer, function() { - self.lastModifiedDate = new Date(); - self.size += buffer.length; - self.emit('progress', self.size); - cb(); - }); -}; + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) -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(); - }); -}; + return error +} /***/ }), -/***/ 7973: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 35554: +/***/ ((module) => { -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ -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||{}; +/** + * Module exports. + */ - this.error = null; - this.ended = false; +module.exports = callSiteToString - 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; +/** + * Format a CallSite file location to a string. + */ - this.bytesReceived = null; - this.bytesExpected = null; +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' - this._parser = null; - this._flushing = 0; - this._fieldsSize = 0; - this._fileSize = 0; - this.openedFiles = []; + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } - return this; -} -util.inherits(IncomingForm, EventEmitter); -exports.c = IncomingForm; + if (fileName) { + fileLocation += fileName -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; - }; + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber - this.resume = function() { - try { - req.resume(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber } - return false; } + } - return true; - }; + return fileLocation || 'unknown source' +} - // 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); - }); - } +/** + * Format a CallSite to a string. + */ - // Parse headers and setup the parser, ready to start listening for data. - this.writeHeaders(req.headers); +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 = '' - // 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; - } + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) - var err = self._parser.end(); - if (err) { - self._error(err); + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' } - }); - return this; -}; - -IncomingForm.prototype.writeHeaders = function(headers) { - this.headers = headers; - this._parseContentLength(); - this._parseContentType(); -}; + line += functionName -IncomingForm.prototype.write = function(buffer) { - if (this.error) { - return; - } - if (!this._parser) { - this._error(new Error('uninitialized parser')); - return; + 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 } - this.bytesReceived += buffer.length; - this.emit('progress', this.bytesReceived, this.bytesExpected); - - var bytesParsed = this._parser.write(buffer); - if (bytesParsed !== buffer.length) { - this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); + if (addSuffix) { + line += ' (' + fileLocation + ')' } - return bytesParsed; -}; - -IncomingForm.prototype.pause = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; - -IncomingForm.prototype.resume = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; + return line +} -IncomingForm.prototype.onPart = function(part) { - // this method can be overwritten by the user - this.handlePart(part); -}; +/** + * Get constructor name of reviver. + */ -IncomingForm.prototype.handlePart = function(part) { - var self = this; +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} - // 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); - 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); - }); +/***/ }), - part.on('end', function() { - self.emit('field', part.name, value); - }); - return; - } +/***/ 12078: +/***/ ((module) => { - this._flushing++; +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - var file = new File({ - path: this._uploadPath(part.filename), - name: part.filename, - type: part.mime, - hash: self.hash - }); - this.emit('fileBegin', part.name, file); - file.open(); - this.openedFiles.push(file); +/** + * Module exports. + * @public + */ - 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(); - }); - }); +module.exports = eventListenerCount - part.on('end', function() { - file.end(function() { - self._flushing--; - self.emit('file', part.name, file); - self._maybeEnd(); - }); - }); -}; +/** + * Get the count of listeners on an event emitter of a specific type. + */ -function dummyParser(self) { - return { - end: function () { - self.ended = true; - self._maybeEnd(); - return null; - } - }; +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length } -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; - } +/***/ 69829: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.headers['content-type'].match(/urlencoded/i)) { - this._initUrlencoded(); - return; - } +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - 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; - } - if (this.headers['content-type'].match(/json/i)) { - this._initJSONencoded(); - return; - } - this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); -}; +/** + * Module dependencies. + * @private + */ -IncomingForm.prototype._error = function(err) { - if (this.error || this.ended) { - return; - } +var EventEmitter = (__nccwpck_require__(82361).EventEmitter) - this.error = err; - this.emit('error', err); +/** + * Module exports. + * @public + */ - if (Array.isArray(this.openedFiles)) { - this.openedFiles.forEach(function(file) { - file._writeStream.destroy(); - setTimeout(fs.unlink, 0, file.path, function(error) { }); - }); - } -}; +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace -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; + function prepareObjectStackTrace (obj, stack) { + return stack } - if (this.bytesExpected !== null) { - this.emit('progress', this.bytesReceived, this.bytesExpected); - } -}; + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 -IncomingForm.prototype._newParser = function() { - return new MultipartParser(); -}; + // capture the stack + Error.captureStackTrace(obj) -IncomingForm.prototype._initMultipart = function(boundary) { - this.type = 'multipart'; + // slice the stack + var stack = obj.stack.slice() - var parser = new MultipartParser(), - self = this, - headerField, - headerValue, - part; + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit - parser.initWithBoundary(boundary); + return stack[0].toString ? toString : __nccwpck_require__(35554) +}) - parser.onPartBegin = function() { - part = new Stream(); - part.readable = true; - part.headers = {}; - part.name = null; - part.filename = null; - part.mime = null; +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || __nccwpck_require__(12078) +}) - part.transferEncoding = 'binary'; - part.transferBuffer = ''; +/** + * Define a lazy property. + */ - headerField = ''; - headerValue = ''; - }; +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() - parser.onHeaderField = function(b, start, end) { - headerField += b.toString(self.encoding, start, end); - }; + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString(self.encoding, start, end); - }; + return val + } - parser.onHeaderEnd = function() { - headerField = headerField.toLowerCase(); - part.headers[headerField] = headerValue; + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} - // 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] || ''; - } +/** + * Call toString() on the obj + */ - part.filename = self._fileName(headerValue); - } else if (headerField == 'content-type') { - part.mime = headerValue; - } else if (headerField == 'content-transfer-encoding') { - part.transferEncoding = headerValue.toLowerCase(); - } +function toString (obj) { + return obj.toString() +} - headerField = ''; - headerValue = ''; - }; - 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)); - }; +/***/ }), - parser.onPartEnd = function() { - part.emit('end'); - }; - break; +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { - case 'base64': - parser.onPartData = function(b, start, end) { - part.transferBuffer += b.slice(start, end).toString('ascii'); - /* - 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); - }; - parser.onPartEnd = function() { - part.emit('data', new Buffer(part.transferBuffer, 'base64')); - part.emit('end'); - }; - break; +Object.defineProperty(exports, "__esModule", ({ value: true })); - default: - return self._error(new Error('unknown transfer-encoding')); - } +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - self.onPart(part); - }; + /* istanbul ignore next */ + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; + this.name = 'Deprecation'; + } - this._parser = parser; -}; +} -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; +exports.Deprecation = Deprecation; - 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; -}; -IncomingForm.prototype._initUrlencoded = function() { - this.type = 'urlencoded'; +/***/ }), - var parser = new QuerystringParser(this.maxFields) - , self = this; +/***/ 43225: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - parser.onField = function(key, val) { - self.emit('field', key, val); - }; +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - this._parser = parser; -}; -IncomingForm.prototype._initOctetStream = function() { - this.type = 'octet-stream'; - var filename = this.headers['x-file-name']; - var mime = this.headers['content-type']; +/** + * Module dependencies. + * @private + */ - var file = new File({ - path: this._uploadPath(filename), - name: filename, - type: mime - }); +var ReadStream = (__nccwpck_require__(57147).ReadStream) +var Stream = __nccwpck_require__(12781) - this.emit('fileBegin', filename, file); - file.open(); - this.openedFiles.push(file); - this._flushing++; +/** + * Module exports. + * @public + */ - var self = this; +module.exports = destroy - self._parser = new OctetParser(); +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ - //Keep track of writes that haven't finished so we don't emit the file before it's done being written - var outstandingWrites = 0; +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } - self._parser.on('data', function(buffer){ - self.pause(); - outstandingWrites++; + if (!(stream instanceof Stream)) { + return stream + } - file.write(buffer, function() { - outstandingWrites--; - self.resume(); + if (typeof stream.destroy === 'function') { + stream.destroy() + } - if(self.ended){ - self._parser.emit('doneWritingFile'); - } - }); - }); + return stream +} - self._parser.on('end', function(){ - self._flushing--; - self.ended = true; +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ - var done = function(){ - file.end(function() { - self.emit('file', 'file', file); - self._maybeEnd(); - }); - }; +function destroyReadStream(stream) { + stream.destroy() - if(outstandingWrites === 0){ - done(); - } else { - self._parser.once('doneWritingFile', done); - } - }); -}; + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } -IncomingForm.prototype._initJSONencoded = function() { - this.type = 'json'; + return stream +} - var parser = new JSONParser(this) - , self = this; +/** + * On open handler to close stream. + * @private + */ - parser.onField = function(key, val) { - self.emit('field', key, val); - }; +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; - this._parser = parser; -}; +/***/ }), -IncomingForm.prototype._uploadPath = function(filename) { - var buf = crypto.randomBytes(16); - var name = 'upload_' + buf.toString('hex'); +/***/ 12437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.keepExtensions) { - var ext = path.extname(filename); - ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); +/* @flow */ +/*:: - name += ext; - } +type DotenvParseOptions = { + debug?: boolean +} - return path.join(this.uploadDir, name); -}; +// keys and values from src +type DotenvParseOutput = { [string]: string } -IncomingForm.prototype._maybeEnd = function() { - if (!this.ended || this._flushing || this.error) { - return; - } +type DotenvConfigOptions = { + path?: string, // path to .env file + encoding?: string, // encoding of .env file + debug?: string // turn on logging for debugging purposes +} - this.emit('end'); -}; +type DotenvConfigOutput = { + parsed?: DotenvParseOutput, + error?: Error +} +*/ -/***/ }), +const fs = __nccwpck_require__(57147) +const path = __nccwpck_require__(71017) -/***/ 95265: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function log (message /*: string */) { + console.log(`[dotenv][DEBUG] ${message}`) +} -var IncomingForm = __nccwpck_require__(7973)/* .IncomingForm */ .c; -IncomingForm.IncomingForm = IncomingForm; -module.exports = IncomingForm; +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 = {} -/***/ }), + // 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] === "'" -/***/ 715: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // if single or double quoted, remove quotes + if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + // if double quoted, expand newlines + if (isDoubleQuoted) { + val = val.replace(RE_NEWLINES, NEWLINE) + } + } else { + // remove surrounding whitespace + val = val.trim() + } -var Buffer = __nccwpck_require__(64293).Buffer; + obj[key] = val + } else if (debug) { + log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + } + }) -function JSONParser(parent) { - this.parent = parent; - this.chunks = []; - this.bytesWritten = 0; + return obj } -exports.c = JSONParser; -JSONParser.prototype.write = function(buffer) { - this.bytesWritten += buffer.length; - this.chunks.push(buffer); - return buffer.length; -}; +// 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 -JSONParser.prototype.end = function() { - try { - var fields = JSON.parse(Buffer.concat(this.chunks)); - for (var field in fields) { - this.onField(field, fields[field]); + if (options) { + if (options.path != null) { + dotenvPath = options.path + } + if (options.encoding != null) { + encoding = options.encoding + } + if (options.debug != null) { + debug = true } + } + + 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) { - this.parent.emit('error', e); + return { error: e } } - this.data = null; +} - this.onEnd(); -}; +module.exports.config = config +module.exports.parse = parse /***/ }), -/***/ 31323: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -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++ - }, +/***/ 11728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - f = 1, - F = - { PART_BOUNDARY: f, - LAST_BOUNDARY: f *= 2 - }, - LF = 10, - CR = 13, - SPACE = 32, - HYPHEN = 45, - COLON = 58, - A = 97, - Z = 122, - lower = function(c) { - return c | 0x20; - }; +var Buffer = (__nccwpck_require__(21867).Buffer); -for (s in S) { - exports[s] = S[s]; -} +var getParamBytesForAlg = __nccwpck_require__(30528); -function MultipartParser() { - this.boundary = null; - this.boundaryChars = null; - this.lookbehind = null; - this.state = S.PARSER_UNINITIALIZED; +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); - this.index = null; - this.flags = 0; +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); } -exports.MultipartParser = MultipartParser; -MultipartParser.stateToString = function(stateNumber) { - for (var state in S) { - var number = S[state]; - if (number === stateNumber) return state; - } -}; +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } -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; + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} - this.boundaryChars = {}; - for (var i = 0; i < this.boundary.length; i++) { - this.boundaryChars[this.boundary[i]] = true; - } -}; +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); -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, + // 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; - 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; - } + var inputLength = signature.length; - 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; - } + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } - if (!clear) { - callback(name, buffer, self[markSymbol], buffer.length); - self[markSymbol] = 0; - } else { - callback(name, buffer, self[markSymbol], i); - delete self[markSymbol]; - } - }; + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } - 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 (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } - 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; - } + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } - index++; - if (c == HYPHEN) { - break; - } + var rLength = signature[offset++]; - if (c == COLON) { - if (index == 1) { - // empty header field - return i; - } - dataCallback('headerField', true); - state = S.HEADER_VALUE_START; - break; - } + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } - cl = lower(c); - if (cl < A || cl > Z) { - return i; - } - break; - case S.HEADER_VALUE_START: - if (c == SPACE) { - break; - } + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } - 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; - } + var rOffset = offset; + offset += rLength; - 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; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } - 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 sLength = signature[offset++]; - 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; - } - } + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } - 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'); + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } + var sOffset = offset; + offset += sLength; - break; - case S.END: - break; - default: - return i; - } - } + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } - dataCallback('headerField'); - dataCallback('headerValue'); - dataCallback('partData'); + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; - this.index = index; - this.state = state; - this.flags = flags; + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); - return len; -}; + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); -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()); - } -}; + offset = paramBytes; -MultipartParser.prototype.explain = function() { - return 'state = ' + MultipartParser.stateToString(this.state); -}; + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + dst = dst.toString('base64'); + dst = base64Url(dst); -/***/ }), + return dst; +} -/***/ 48680: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } -var EventEmitter = __nccwpck_require__(28614).EventEmitter - , util = __nccwpck_require__(31669); + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } -function OctetParser(options){ - if(!(this instanceof OctetParser)) return new OctetParser(options); - EventEmitter.call(this); + return padding; } -util.inherits(OctetParser, EventEmitter); +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); -exports.h = OctetParser; + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } -OctetParser.prototype.write = function(buffer) { - this.emit('data', buffer); - return buffer.length; -}; + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; -OctetParser.prototype.end = function() { - this.emit('end'); + 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 }; /***/ }), -/***/ 80825: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 30528: +/***/ ((module) => { -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); -// 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); -function QuerystringParser(maxKeys) { - this.maxKeys = maxKeys; - this.buffer = ''; +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; } -exports.l = QuerystringParser; -QuerystringParser.prototype.write = function(buffer) { - this.buffer += buffer.toString('ascii'); - return buffer.length; +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) }; -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 = ''; +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } - this.onEnd(); -}; + throw new Error('Unknown algorithm "' + alg + '"'); +} +module.exports = getParamBytesForAlg; /***/ }), -/***/ 46868: +/***/ 14401: /***/ ((module) => { -"use strict"; /*! - * forwarded - * Copyright(c) 2014-2017 Douglas Christopher Wilson + * ee-first + * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ @@ -52889,52545 +35227,40650 @@ QuerystringParser.prototype.end = function() { * @public */ -module.exports = forwarded +module.exports = first /** - * Get all addresses in the request, using the `X-Forwarded-For` header. + * Get the first event in a set of event emitters and event pairs. * - * @param {object} req - * @return {array} + * @param {array} stuff + * @param {function} done * @public */ -function forwarded (req) { - if (!req) { - throw new TypeError('argument req is required') +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, 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, + }) + } } - // simple header parsing - var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') - var socketAddr = req.connection.remoteAddress - var addrs = [socketAddr].concat(proxyAddrs) + function callback() { + cleanup() + done.apply(null, arguments) + } - // return all addresses - return addrs + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk } /** - * Parse the X-Forwarded-For header. - * - * @param {string} header + * Create the event listener. * @private */ -function parse (header) { - var end = header.length - var list = [] - var start = header.length +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null - // 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 + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] } - } - // final address - if (start !== end) { - list.push(header.substring(start, end)) + done(err, ee, event, args) } - - return list } /***/ }), -/***/ 83136: +/***/ 16592: /***/ ((module) => { -"use strict"; /*! - * fresh - * Copyright(c) 2012 TJ Holowaychuk - * Copyright(c) 2016-2017 Douglas Christopher Wilson + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ /** - * RegExp to check for no-cache token in Cache-Control. + * Module exports. + * @public + */ + +module.exports = encodeUrl + +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. * @private */ -var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ +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 /** - * Module exports. - * @public + * RegExp to match unmatched surrogate pair. + * @private */ -module.exports = fresh +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g /** - * Check freshness of the response using request and response headers. + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. * - * @param {Object} reqHeaders - * @param {Object} resHeaders - * @return {Boolean} + * 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`). + * + * 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} url + * @return {string} * @public */ -function fresh (reqHeaders, resHeaders) { - // fields - var modifiedSince = reqHeaders['if-modified-since'] - var noneMatch = reqHeaders['if-none-match'] +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} - // unconditional request - if (!modifiedSince && !noneMatch) { - return false - } - // 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 - } +/***/ }), - // if-none-match - if (noneMatch && noneMatch !== '*') { - var etag = resHeaders['etag'] +/***/ 23505: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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 - } - } - if (etagStale) { - return false - } - } +var util = __nccwpck_require__(73837); +var isArrayish = __nccwpck_require__(7604); - // if-modified-since - if (modifiedSince) { - var lastModified = resHeaders['last-modified'] - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } - if (modifiedStale) { - return false - } - } + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } - return true -} + message = message instanceof Error + ? message.message + : (message || this.message); -/** - * Parse an HTTP Date into a number. - * - * @param {string} date - * @private - */ + Error.call(this, message); + Error.captureStackTrace(this, errorExError); -function parseHttpDate (date) { - var timestamp = date && Date.parse(date) + this.name = name; - // istanbul ignore next: guard against date.js Date.parse patching - return typeof timestamp === 'number' - ? timestamp - : NaN -} + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); -/** - * Parse a HTTP token list. - * - * @param {string} str - * @private - */ + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } -function parseTokenList (str) { - var end = 0 - var list = [] - var start = 0 + var modifier = properties[key]; - // 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 - } - } + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } - // final token - list.push(str.substring(start, end)) + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); - return list -} + 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; + }; -/***/ 19320: -/***/ ((module) => { + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); -"use strict"; + // 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; + } -/* eslint no-invalid-this: 1 */ + var modifier = properties[key]; -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } -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); + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } - 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)) - ); - } - }; + return stack.join('\n'); + }; - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } + 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; +}; + +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; + + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } + + return message; + } + }; +}; - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } + if (v) { + return str.replace('%s', v.toString()); + } - return bound; + return null; + } + }; }; +module.exports = errorEx; -/***/ }), - -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/***/ }), +/***/ 94070: +/***/ ((module) => { -var implementation = __nccwpck_require__(19320); +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ -module.exports = Function.prototype.bind || implementation; -/***/ }), +/** + * Module variables. + * @private + */ -/***/ 31621: -/***/ ((module) => { +var matchHtmlRegExp = /["'&<>]/; -"use strict"; +/** + * Module exports. + * @public + */ +module.exports = escapeHtml; -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); -}; +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); -/***/ }), + if (!match) { + return str; + } -/***/ 76339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; -"use strict"; + 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 (lastIndex !== index) { + html += str.substring(lastIndex, index); + } -var bind = __nccwpck_require__(88334); + lastIndex = index + 1; + html += escape; + } -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} /***/ }), -/***/ 95193: +/***/ 69972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; /*! - * http-errors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2016 Douglas Christopher Wilson + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson * MIT Licensed */ +/** + * Module exports. + * @public + */ + +module.exports = etag + /** * Module dependencies. * @private */ -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) +var crypto = __nccwpck_require__(6113) +var Stats = (__nccwpck_require__(57147).Stats) /** - * Module exports. - * @public + * Module variables. + * @private */ -module.exports = createError -module.exports.HttpError = createHttpErrorConstructor() - -// Populate exports for all constructors -populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) +var toString = Object.prototype.toString /** - * Get the code class of a status code. + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} * @private */ -function codeClass (status) { - return Number(String(status).charAt(0) + '00') +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' } /** - * Create a new HTTP Error. + * Create a simple ETag. * - * @returns {Error} + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} * @public */ -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 - } - 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 - } +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') } - if (typeof status === 'number' && (status < 400 || status >= 600)) { - deprecate('non-error status code; use only 4xx or 5xx status codes') - } + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats - if (typeof status !== 'number' || - (!statuses[status] && (status < 400 || status >= 600))) { - status = 500 + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') } - // constructor - var HttpError = createError[status] || createError[codeClass(status)] + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) - if (!err) { - // create error - err = HttpError - ? new HttpError(msg) - : new Error(msg || statuses[status]) - Error.captureStackTrace(err, createError) - } + return weak + ? 'W/' + tag + : tag +} - if (!HttpError || !(err instanceof HttpError) || err.status !== status) { - // add properties to generic error - err.expose = status < 500 - err.status = err.statusCode = status - } +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ - for (var key in props) { - if (key !== 'status' && key !== 'statusCode') { - err[key] = props[key] - } +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true } - return err + // 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' } /** - * Create HTTP error abstract base class. + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} * @private */ -function createHttpErrorConstructor () { - function HttpError () { - throw new TypeError('cannot construct abstract class') - } +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) - inherits(HttpError, Error) + return '"' + size + '-' + mtime + '"' +} - return HttpError + +/***/ }), + +/***/ 68883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var original = __nccwpck_require__(80086) +var parse = (__nccwpck_require__(57310).parse) +var events = __nccwpck_require__(82361) +var https = __nccwpck_require__(95687) +var http = __nccwpck_require__(13685) +var util = __nccwpck_require__(73837) + +var httpsOptions = [ + 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', + 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' +] + +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 + }) } /** - * Create a constructor for a client error. - * @private - */ + * 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 + } + }) -function createClientErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' + Object.defineProperty(this, 'url', { + get: function () { + return url + } + }) - function ClientError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) + var self = this + self.reconnectInterval = 1000 - // capture a stack trace to the construction point - Error.captureStackTrace(err, ClientError) + function onConnectionClosed (message) { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CONNECTING + _emit('error', new Event('error', {message: message})) - // adjust the [[Prototype]] - setPrototypeOf(err, ClientError.prototype) + // 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) + } - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) + 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'] + } - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) + var discardTrailingNewline = false + var data = '' + var eventName = '' - return err - } + var reconnectUrl = null - inherits(ClientError, HttpError) - nameFunc(ClientError, className) + 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 + } + } + } - ClientError.prototype.status = code - ClientError.prototype.statusCode = code - ClientError.prototype.expose = true + // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, + // but for now exists as a backwards-compatibility layer + options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) - return ClientError -} + // 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:' -/** - * Create a constructor for a server error. - * @private - */ + 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 + } -function createServerErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' + // 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 + } + } + } + + // Pass this on to the XHR + if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { + options.withCredentials = eventSourceInitDict.withCredentials + } + + 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 + } + + // 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 + } + + if (res.statusCode !== 200) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return self.close() + } + + readyState = EventSource.OPEN + res.on('close', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + + res.on('end', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + _emit('open', new Event('open')) + + // 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) + } + + isFirst = false + var pos = 0 + var length = buf.length + + 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 + } + } - function ServerError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) + if (lineLength < 0) { + break + } - // capture a stack trace to the construction point - Error.captureStackTrace(err, ServerError) + parseEventStreamLine(buf, pos, fieldLength, lineLength) - // adjust the [[Prototype]] - setPrototypeOf(err, ServerError.prototype) + pos += lineLength + 1 + } - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true + if (pos === length) { + buf = void 0 + } else if (pos > 0) { + buf = buf.slice(pos) + } + }) }) - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true + req.on('error', function (err) { + onConnectionClosed(err.message) }) - return err + if (req.setNoDelay) req.setNoDelay(true) + req.end() } - inherits(ServerError, HttpError) - nameFunc(ServerError, className) + connect() - ServerError.prototype.status = code - ServerError.prototype.statusCode = code - ServerError.prototype.expose = false + function _emit () { + if (self.listeners(arguments[0]).length > 0) { + self.emit.apply(self, arguments) + } + } - return ServerError -} + 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() + } -/** - * Set the name of a function, if possible. - * @private - */ + 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() -function nameFunc (func, name) { - var desc = Object.getOwnPropertyDescriptor(func, 'name') + if (noValue) { + step = lineLength + } else if (buf[pos + fieldLength + 1] !== space) { + step = fieldLength + 1 + } else { + step = fieldLength + 2 + } + pos += step - if (desc && desc.configurable) { - desc.value = name - Object.defineProperty(func, 'name', desc) + var valueLength = lineLength - step + var value = buf.slice(pos, pos + valueLength).toString() + + 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 + } + } + } } } -/** - * Populate the exports object with constructors for every error class. - * @private - */ +module.exports = EventSource -function populateConstructorExports (exports, codes, HttpError) { - codes.forEach(function forEachCode (code) { - var CodeError - var name = toIdentifier(statuses[code]) +util.inherits(EventSource, events.EventEmitter) +EventSource.prototype.constructor = EventSource; // make stacktraces readable - switch (codeClass(code)) { - case 400: - CodeError = createClientErrorConstructor(HttpError, name, code) - break - case 500: - CodeError = createServerErrorConstructor(HttpError, name, code) - break - } +['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 + }, - if (CodeError) { - // export the constructor - exports[code] = CodeError - exports[name] = CodeError + /** + * 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) } }) +}) - // backwards-compatibility - exports["I'mateapot"] = deprecate.function(exports.ImATeapot, - '"I\'mateapot"; use "ImATeapot" instead') -} - - -/***/ }), - -/***/ 15098: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/** + * 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}) -"use strict"; +EventSource.prototype.CONNECTING = 0 +EventSource.prototype.OPEN = 1 +EventSource.prototype.CLOSED = 2 -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. + * 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 */ -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!'); - } - 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); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - // 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']; - } - 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; - } - 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; - }); - } -} -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]; - } - } - return ret; +EventSource.prototype.close = function () { + this._close() } -//# 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); +/** + * 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 (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); - } - 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'); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - 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 - }); - } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); +/** + * 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 + */ +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) } -exports.default = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map -/***/ }), - -/***/ 39695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * 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) + } +} -"use strict"; +/** + * W3C Event + * + * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event + * @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 }) + } + } + } +} -var Buffer = __nccwpck_require__(15118).Buffer; +/** + * W3C MessageEvent + * + * @see http://www.w3.org/TR/webmessaging/#event-definitions + * @api private + */ +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 }) + } + } +} -// 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; +/***/ 71204: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -// 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(); +module.exports = __nccwpck_require__(22587); - // 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. +/***/ 313: +/***/ ((module, exports, __nccwpck_require__) => { - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // 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. +/** + * Module dependencies. + * @private + */ - // `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 = []; +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__(13685); +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__(71017).resolve); +var setPrototypeOf = __nccwpck_require__(40414) +var slice = Array.prototype.slice; - // 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); +/** + * Application prototype. + */ - // 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]); - } +var app = exports = module.exports = {}; - 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); +/** + * Variable for trust proxy inheritance back-compat + * @private + */ +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + this.defaultConfiguration(); +}; - 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 - } -} +/** + * Initialize application configuration. + * @private + */ -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; -// 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); + // 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); - 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]]; + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - 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)); + 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']; } - return node; -} + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); + // setup locals + this.locals = Object.create(null); - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; + // top-most app is mounted at / + this.mountpath = '/'; - // 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. + // default locals + this.locals.settings = this.settings; - 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++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + 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.'); } - 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]; -} +/** + * 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') + }); -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; -} + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; -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; +/** + * 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 + */ - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; - } - 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); - } +app.handle = function handle(req, res, callback) { + var router = this._router; - // 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 - } - } + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } -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; + router.handle(req, res, done); +}; - 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); - } -} +/** + * 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 + */ +app.use = function use(fn) { + var offset = 0; + var path = '/'; + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; -// == Encoder ================================================================== + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } -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; -} + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } -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; + var fns = flatten(slice.call(arguments, offset)); - 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; - } + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware 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; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } + // setup router + this.lazyrouter(); + var router = this._router; - // 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; + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; - } else if (resCode == undefined) { // Current character is not part of the sequence. + // 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); + }); + }); - // 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. + // mounted an app + fn.emit('mount', this); + }, this); - } 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; - } + return this; +}; - 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; - } - } - } +/** + * 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 + */ - // 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 - } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } - } +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} +/** + * 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 + */ -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } - var newBuf = Buffer.alloc(10), j = 0; + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; - 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; - } + // store engine + this.engines[extension] = fn; - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; - } - - return newBuf.slice(0, j); -} + return this; +}; -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; +/** + * 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 + */ +app.param = function param(name, fn) { + this.lazyrouter(); -// == Decoder ================================================================== + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); + return this; + } - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} + this._router.param(name, fn); -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; + return this; +}; - 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]; +/** + * 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 + */ - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } - 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); + debug('set "%s" to %o', setting, val); - // 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; + // set value + this.settings[setting] = val; - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; + // 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)); - // Reset trie node. - nodeIdx = 0; seqStart = i+1; - } + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); -} + break; + } -DBCSDecoder.prototype.end = function() { - var ret = ''; + return this; +}; - // 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); +/** + * 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 + */ - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); - } +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; - this.nodeIdx = 0; - return ret; -} +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; - 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; -} +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ +app.disabled = function disabled(setting) { + return !this.set(setting); +}; +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ -/***/ }), +app.enable = function enable(setting) { + return this.set(setting, true); +}; -/***/ 91386: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ -"use strict"; +app.disable = function disable(setting) { + return this.set(setting, false); +}; +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ -// 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. +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } -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) + this.lazyrouter(); - // 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 + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); - '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', +/** + * 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 + */ - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(72417) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, +app.all = function all(path) { + this.lazyrouter(); - // 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. + 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; +}; - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder +// del -> delete alias - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); - // 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) }, - }, +/** + * 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 + */ - // 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', +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; - // 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}, - }, + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - 'chinese': 'gb18030', + // merge app.locals + merge(renderOptions, this.locals); + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } - // == 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) }, - }, + // merge options + merge(renderOptions, opts); - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } - // == 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. + // view + if (!view) { + var View = this.get('view'); - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(33104) }, - }, + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); - // 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], - }, + 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); + } - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + // render + tryRender(view, renderOptions, done); +}; -/***/ }), +/** + * 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 + */ -/***/ 82733: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; -"use strict"; +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} -// 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), -]; +/** + * Try rendering a view. + * @private + */ -// 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]; +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } } /***/ }), -/***/ 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", +/***/ 22587: +/***/ ((module, exports, __nccwpck_require__) => { - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, - // Codec. - _internal: InternalCodec, -}; -//------------------------------------------------------------------------------ +/** + * Module dependencies. + */ -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; +var bodyParser = __nccwpck_require__(97076) +var EventEmitter = (__nccwpck_require__(82361).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); - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; +/** + * Expose `createApplication()`. + */ - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } -} +exports = module.exports = createApplication; -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; +/** + * Create an express application. + * + * @return {Function} + * @api public + */ -//------------------------------------------------------------------------------ +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = __nccwpck_require__(24304).StringDecoder; + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); + app.init(); + return app; } -InternalDecoder.prototype = StringDecoder.prototype; +/** + * Expose the prototypes. + */ +exports.application = proto; +exports.request = req; +exports.response = res; -//------------------------------------------------------------------------------ -// Encoder is mostly trivial +/** + * Expose constructors. + */ -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} +exports.Route = Route; +exports.Router = Router; -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} +/** + * Expose middleware + */ -InternalEncoder.prototype.end = function() { -} +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 +/** + * Replace removed middleware with an appropriate error message. + */ -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} +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 + }); +}); -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"); -} +/***/ 92636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -//------------------------------------------------------------------------------ -// 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 { // 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); -} +/** + * Module dependencies. + * @private + */ -InternalEncoderCesu8.prototype.end = function() { -} +var setPrototypeOf = __nccwpck_require__(40414) -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ +/** + * 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 + */ -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; -} +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; -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; - } + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) - 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; -} + res.locals = res.locals || Object.create(null); + + next(); + }; +}; -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; -} /***/ }), -/***/ 26657: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 79768: +/***/ ((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 + */ -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; - } +/** + * Module dependencies. + */ - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); +var merge = __nccwpck_require__(44429) +var parseUrl = __nccwpck_require__(89808); +var qs = __nccwpck_require__(22760); - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; +/** + * @param {Object} options + * @return {Function} + * @api public + */ - this.encodeBuf = encodeBuf; -} +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } -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; -} + next(); + }; +}; -SBCSEncoder.prototype.end = function() { -} +/***/ }), -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} +/***/ 71260: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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'); -} +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -SBCSDecoder.prototype.end = function() { -} -/***/ }), +/** + * Module dependencies. + * @private + */ -/***/ 21012: -/***/ ((module) => { +var accepts = __nccwpck_require__(83633); +var deprecate = __nccwpck_require__(18883)('express'); +var isIP = (__nccwpck_require__(41808).isIP); +var typeis = __nccwpck_require__(71159); +var http = __nccwpck_require__(13685); +var fresh = __nccwpck_require__(83136); +var parseRange = __nccwpck_require__(26435); +var parse = __nccwpck_require__(89808); +var proxyaddr = __nccwpck_require__(80140); -"use strict"; +/** + * Request prototype. + * @public + */ +var req = Object.create(http.IncomingMessage.prototype) -// 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": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} +/** + * Module exports. + * @public + */ -/***/ }), +module.exports = req -/***/ 41080: -/***/ ((module) => { +/** + * 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 + */ -"use strict"; +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } -// Manually added data to be used by sbcs codec in addition to generated one. + var lc = name.toLowerCase(); -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, +/** + * 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 + */ - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; - // 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", +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ - "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", +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; - "cp819": "iso88591", - "ibm819": "iso88591", +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); - "cyrillic": "iso88595", +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); - "hebrew": "iso88598", - "hebrew8": "iso88598", +/** + * 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 + */ - "turkish": "iso88599", - "turkish8": "iso88599", +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; - "thai": "iso885911", - "thai8": "iso885911", +/** + * 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 + */ - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", + return defaultValue; +}; - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", +/** + * 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 + */ - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", +req.is = function is(types) { + var arr = types; - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } - "strk10482002": "rk1048", + return typeis(this, arr); +}; - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", +/** + * 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 + */ - "gb198880": "iso646cn", - "cn": "iso646cn", +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", + // 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(',') - "mac": "macintosh", - "csmacintosh": "macintosh", -}; + 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'; +}); -/***/ }), +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ -/***/ 11155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); -"use strict"; +/** + * 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 + */ -var Buffer = __nccwpck_require__(15118).Buffer; +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() -// == UTF16-BE codec. ========================================================== + return addrs +}); -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} +/** + * 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 + */ -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + if (!hostname) return []; -// -- Encoding + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; -function Utf16BEEncoder() { -} + return subdomains.slice(offset); +}); -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; -} +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ -Utf16BEEncoder.prototype.end = function() { -} +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); +/** + * 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 + */ -// -- Decoding +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); -function Utf16BEDecoder() { - this.overflowByte = -1; -} + 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() + } -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; + if (!host) return; - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } + return index !== -1 + ? host.substring(0, index) + : host; +}); - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; - } +// TODO: change req.host to return host in next major - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); - return buf2.slice(0, j).toString('ucs2'); -} +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ -Utf16BEDecoder.prototype.end = function() { -} +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; -// == 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'}); + // 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') + }) + } -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + return false; +}); -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ -// -- Encoding (pass-through) +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); +/** + * Helper function for creating a getter on an object. + * + * @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 + }); } -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} +/***/ }), +/***/ 64934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// -- Decoding +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -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 ''; +/** + * Module dependencies. + * @private + */ - // 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; - } +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__(13685); +var isAbsolute = (__nccwpck_require__(53561).isAbsolute); +var onFinished = __nccwpck_require__(92098); +var path = __nccwpck_require__(71017); +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); - return this.decoder.write(buf); -} +/** + * Response prototype. + * @public + */ -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 = Object.create(http.ServerResponse.prototype) - var res = this.decoder.write(buf), - trail = this.decoder.end(); +/** + * Module exports. + * @public + */ - return trail ? (res + trail) : res; - } - return this.decoder.end(); -} +module.exports = res -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; +/** + * Module variables. + * @private + */ - 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. +var charsetRegExp = /;\s*charset\s*=/; - 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++; - } +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; - } - } +res.status = function status(code) { + this.statusCode = code; + return this; +}; - return enc; -} +/** + * 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]; + } + } -/***/ 51644: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 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'); + } -"use strict"; + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] + } -var Buffer = __nccwpck_require__(15118).Buffer; + 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; + } -// 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 + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + // 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 + } -// -- Encoding + this.set('Content-Length', len); + } -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} + // freshness + if (req.fresh) this.statusCode = 304; -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))); -} + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } -Utf7Encoder.prototype.end = function() { -} + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + return this; +}; -// -- Decoding +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} +res.json = function json(obj) { + var val = obj; -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + // 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]; + } + } -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); + // 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) -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } - // The decoder is more involved as we must handle chunks in stream. + return this.send(body); +}; - 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"); - } +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; +res.jsonp = function jsonp(obj) { + var val = obj; - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } + // 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]; } + } + + // 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')]; - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } - 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); + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); - return res; -} + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + // 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 + ');'; + } - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + 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 + */ -// 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. +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) + this.statusCode = statusCode; + this.type('txt'); -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; + return this.send(body); }; -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; +/** + * 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 || {}; -// -- Encoding + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') + } -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - 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 (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; - } 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; +/** + * 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 + */ - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } - } +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - return buf.slice(0, bufIdx); -} + // create file stream + var file = send(req, path, opts); -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; - } + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); } + }); +}; - return buf.slice(0, bufIdx); -} +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 + */ -// -- Decoding +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + // 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 + } -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + // 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] + } + } + } - // 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). + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers - 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"); - } + // Resolve the full path for sendFile + var fullPath = resolve(path); - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; + // send file + return this.sendFile(fullPath, opts, done) +}; - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } +/** + * 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 + */ - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; - 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); + return this.set('Content-Type', ct); +}; - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } +/** + * 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 + */ - this.inBase64 = inBase64; - this.base64Accum = base64Accum; +res.format = function(obj){ + var req = this.req; + var next = req.next; - return res; -} + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); -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 key = keys.length > 0 + ? req.accepts(keys) + : false; - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + 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 this; +}; + +/** + * 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)); + return this; +}; -/***/ }), +/** + * 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 + */ -/***/ 67961: -/***/ ((__unused_webpack_module, exports) => { +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; -"use strict"; + 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); +}; -var BOMChar = '\uFEFF'; +/** + * 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 + */ -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; + // 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(); + } } - return this.encoder.write(str); -} - -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ -//------------------------------------------------------------------------------ +res.get = function(field){ + return this.getHeader(field); +}; -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } + return this.cookie(name, '', opts); +}; - this.pass = true; - return res; -} +/** + * 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 + */ -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; + 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); + } -/***/ 30393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } -"use strict"; + if (opts.path == null) { + opts.path = '/'; + } -var Buffer = __nccwpck_require__(64293).Buffer; -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); -// == Extend Node primitives to use iconv-lite ================================= + return this; +}; -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. +/** + * 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 + */ - // 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); +res.location = function location(url) { + var loc = url; - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } - 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; - } + // set location + return this.set('Location', encodeUrl(loc)); +}; - 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, - }; +/** + * 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 + */ - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + // 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]; + } + } - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); + // Set location header + address = this.location(address).get('Location'); - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, - // 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); - } + html: function(){ + var u = escapeHtml(address); + body = '

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

' + }, - 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; - } + default: function(){ + body = ''; + } + }); - 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(); + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); +/** + * 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 + */ - // 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; - } +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } - // -- Buffer --------------------------------------------------------------- + vary(this, field); - original.BufferIsEncoding = Buffer.isEncoding; - Buffer.isEncoding = function(encoding) { - return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); - } + return this; +}; - original.BufferByteLength = Buffer.byteLength; - Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { - encoding = String(encoding || 'utf8').toLowerCase(); +/** + * 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 + */ - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); +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; - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); + // merge res.locals + opts._locals = self.locals; - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; - // 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); - } + // render + app.render(view, opts, done); +}; - 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; - } +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; - encoding = String(encoding || 'utf8').toLowerCase(); + // request aborted + function onaborted() { + if (done) return; + done = true; - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferWrite.call(this, string, _offset, _length, _encoding); + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } + // directory + function ondirectory() { + if (done) return; + done = true; - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } - // 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; + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } - // TODO: Set _charsWritten. - } + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + // file + function onfile() { + streaming = false; + } - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; - 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; - } + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } - Readable.prototype.collect = iconv._collect; - } - } + if (done) return; + done = true; + callback(); + }); + } - // 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.") + // streaming + function onstream() { + streaming = true; + } - delete Buffer.isNativeEncoding; + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; + // pipe + file.pipe(res); +} - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; +/** + * 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 + */ - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; - } +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); - original = undefined; - } + 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 } /***/ }), -/***/ 19032: +/***/ 24963: /***/ ((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 + */ -// 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; +/** + * Module dependencies. + * @private + */ -// 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; +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) -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; +/** + * Module variables. + * @private + */ -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; - var encoder = iconv.getEncoder(encoding, options); +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is an callable function + * @public + */ - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} +var proto = module.exports = function(options) { + var opts = options || {}; -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; - } + function router(req, res, next) { + router.handle(req, res, next); + } - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. - } + // mixin Router class functions + setPrototypeOf(router, proto) - var decoder = iconv.getDecoder(encoding, options); + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; - var res = decoder.write(buf); - var trail = decoder.end(); + return router; +}; - return trail ? (res + trail) : res; -} +/** + * 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 + */ -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } -} +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; + } -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; + // apply param functions + var params = this._params; + var len = params.length; + var ret; -// 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); + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } - var codecDef = iconv.encodings[enc]; + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; +/** + * Dispatch a req, res into the router. + * @private + */ - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; +proto.handle = function handle(req, res, out) { + var self = this; - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; + debug('dispatching %s %s', req.method, req.url); - // 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); + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } - } -} + // middleware and routes + var stack = self.stack; -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, ""); -} + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); + // setup next layer + req.next = next; - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); + // 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); + }); + } - return encoder; -} + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); + next(); - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); + function next(err) { + var layerError = err === 'route' + ? null + : err; - return decoder; -} + // 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 = ''; + } -// 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) { + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - __nccwpck_require__(76409)(iconv); + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; } - // Load Node primitive extensions. - __nccwpck_require__(30393)(iconv); -} + // get pathname of request + var path = getPathname(req); -if (false) {} + if (path == null) { + return done(layerError); + } + // find next matching layer + var layer; + var match; + var route; -/***/ }), + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; -/***/ 76409: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } + + if (match !== true) { + continue; + } -"use strict"; + if (!route) { + // process non-route handlers normally + continue; + } + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } -var Buffer = __nccwpck_require__(64293).Buffer, - Transform = __nccwpck_require__(92413).Transform; + 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()); + } -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } } - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + // no match + if (match !== true) { + return done(layerError); } - 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); -} + // store route for dispatch on change + if (route) { + req.route = route; + } -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; -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(); - } - catch (e) { - done(e); - } -} + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} + if (route) { + return layer.handle_request(req, res, next); + } -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)); + trim_prefix(layer, layerError, layerPath, path); }); - return this; -} - + } -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); -} + 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) -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); + // 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); -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); - } -} + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } -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); + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); } -} - -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; -} + 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); + } + } +}; -/***/ }), +/** + * Process any parameters for the layer. + * @private + */ -/***/ 91230: -/***/ ((module) => { +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; -// A simple implementation of make-array -function makeArray (subject) { - return Array.isArray(subject) - ? subject - : [subject] -} - -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) -} - -// > 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 = [ - - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? SPACE - : EMPTY - ], + // captured parameters from the layer, keys and values + var keys = layer.keys; - // replace (\ ) with ' ' - [ - /\\\s/g, - () => SPACE - ], + // fast track + if (!keys || keys.length === 0) { + return done(); + } - // 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}` - ], + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; - [ - // > a question mark (?) matches a single character - /(?!\\)\?/g, - () => '[^/]' - ], + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } - // leading slash - [ + if (i >= keys.length ) { + return done(); + } - // > 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 - /^\//, - () => '^' - ], + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], + if (paramVal === undefined || !paramCallbacks) { + return param(); + } - [ - // > 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' - () => '^(?:.*\\/)?' - ], + // 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; - // 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 - - // 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. - ? '(?:^|\\/)' - - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' + // next param + return param(paramCalled.error); } - ], - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer + paramCallback(); + } - // Check if it is not the last `'/**'` - (_, index, str) => index + 6 < str.length + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; - // 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. - // '/**/' - ? '(?:\\/[^\\/]+)*' + // store updated value + paramCalled.value = req.params[key.name]; - // case: /** - // > A trailing `"/**"` matches everything inside. + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } - // #21: everything inside but it should not include the current folder - : '\\/.+' - ], + if (!fn) return param(); - // intermediate wildcards - [ - // Never replace escaped '*' - // ignore rule '\*' will match the path '*' + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, + param(); +}; - // '*.js' matches '.js' - // '*.js' doesn't match 'abc' - (_, p1) => `${p1}[^\\/]*` - ], +/** + * 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 + */ - [ - // unescape, revert step 3 except for back slash - // For example, if a user escape a '\\*', - // after step 3, the result will be '\\\\\\*' - /\\\\\\(?=[$.|*+(){^])/g, - () => ESCAPE - ], +proto.use = function use(fn) { + var offset = 0; + var path = '/'; - [ - // '\\\\' -> '\\' - /\\\\/g, - () => ESCAPE - ], + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; - [ - // > The range notation, e.g. [a-zA-Z], - // > can be used to match one of the characters in a range. - - // `\` 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\\\\]' - : '[]' - : '[]' - ], + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } - // ending - [ - // 'js' will not match 'js.' - // 'ab' will not match 'abc' - /(?:[^*])$/, - - // 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}(?=$|\\/$)` - ], + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (_, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match EMPTY - // '/*' does not match everything + var callbacks = flatten(slice.call(arguments, offset)); - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*' + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; - return `${prefix}(?=$|\\/$)` + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) } - ], -] -// A simple cache, because an ignore rule only has only one certain meaning -const regexCache = Object.create(null) + // add the middleware + debug('use %o %s', path, fn.name || '') + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; -// @param {pattern} -const makeRegex = (pattern, negative, ignorecase) => { - const r = regexCache[pattern] - if (r) { - return r + this.stack.push(layer); } - // const replacers = negative - // ? NEGATIVE_REPLACERS - // : POSITIVE_REPLACERS + return this; +}; - const source = REPLACERS.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ) +/** + * 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 + */ - return regexCache[pattern] = ignorecase - ? new RegExp(source, 'i') - : new RegExp(source) -} +proto.route = function route(path) { + var route = new Route(path); -const isString = subject => typeof subject === 'string' + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); -// > 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) + layer.route = route; - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0 + this.stack.push(layer); + return route; +}; -const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) +// 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; + }; +}); -class IgnoreRule { - constructor ( - origin, - pattern, - negative, - regex - ) { - this.origin = origin - this.pattern = pattern - this.negative = negative - this.regex = regex +// 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); + } } } -const createRule = (pattern, ignorecase) => { - const origin = pattern - let negative = false - - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true - pattern = pattern.substr(1) +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; } +} - 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, '#') +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } - const regex = makeRegex(pattern, negative, ignorecase) + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') - return new IgnoreRule( - origin, - pattern, - negative, - regex - ) + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined } -const throwError = (message, Ctor) => { - throw new Ctor(message) -} +// get type for error message +function gettype(obj) { + var type = typeof obj; -const checkPath = (path, originalPath, doThrow) => { - if (!isString(path)) { - return doThrow( - `path must be a string, but got \`${originalPath}\``, - TypeError - ) + if (type !== 'object') { + return type; } - // We don't know if we should ignore EMPTY, so throw - if (!path) { - return doThrow(`path must not be empty`, TypeError) + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; } +} - // 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 - ) +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; } - return true -} + // make copy of parent for base + var obj = mixin({}, parent); -const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } -checkPath.isNotRelative = isNotRelative -checkPath.convert = p => p + var i = 0; + var o = 0; -class Ignore { - constructor ({ - ignorecase = true - } = {}) { - this._rules = [] - this._ignorecase = ignorecase - define(this, KEY_IGNORE, true) - this._initCache() + // determine numeric gaps + while (i in params) { + i++; } - _initCache () { - this._ignoreCache = Object.create(null) - this._testCache = Object.create(null) + while (o in parent) { + o++; } - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules) - this._added = true - return - } + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignorecase) - this._added = true - this._rules.push(rule) + // create holes for the merge when necessary + if (i < o) { + delete params[i]; } } - // @param {Array | string | Ignore} pattern - add (pattern) { - this._added = false - - makeArray( - isString(pattern) - ? splitPattern(pattern) - : pattern - ).forEach(this._addPattern, this) + return mixin(obj, params); +} - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache() - } +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); - return this + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; } - // legacy - addPattern (pattern) { - return this.add(pattern) - } + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } - // | ignored : unignored - // negative | 0:0 | 0:1 | 1:0 | 1:1 - // -------- | ------- | ------- | ------- | -------- - // 0 | TEST | TEST | SKIP | X - // 1 | TESTIF | SKIP | TEST | X + return fn.apply(this, arguments); + }; +} - // - SKIP: always skip - // - TEST: always test - // - TESTIF: only test if checkUnignored - // - X: that never happen +// 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); + } +} - // @param {boolean} whether should check if the path is unignored, - // setting `checkUnignored` to `false` could reduce additional - // path matching. +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); - // @returns {TestResult} true if a file is ignored - _testOne (path, checkUnignored) { - let ignored = false - let unignored = false + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } - this._rules.forEach(rule => { - const {negative} = rule - if ( - unignored === negative && ignored !== unignored - || negative && !ignored && !unignored && !checkUnignored - ) { - return - } + fn.apply(this, args); + }; +} - const matched = rule.regex.test(path) - if (matched) { - ignored = !negative - unignored = negative - } - }) +/***/ }), - return { - ignored, - unignored - } - } +/***/ 25624: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // @returns {TestResult} - _test (originalPath, cache, checkUnignored, slices) { - const path = originalPath - // Supports nullable path - && checkPath.convert(originalPath) +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - checkPath(path, originalPath, throwError) - return this._t(path, cache, checkUnignored, slices) - } - _t (path, cache, checkUnignored, slices) { - if (path in cache) { - return cache[path] - } +/** + * Module dependencies. + * @private + */ - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH) - } +var pathRegexp = __nccwpck_require__(37819); +var debug = __nccwpck_require__(52529)('express:router:layer'); - slices.pop() +/** + * Module variables. + * @private + */ - // If the path has no parent directory, just test it - if (!slices.length) { - return cache[path] = this._testOne(path, checkUnignored) - } +var hasOwnProperty = Object.prototype.hasOwnProperty; - const parent = this._t( - slices.join(SLASH) + SLASH, - cache, - checkUnignored, - slices - ) +/** + * Module exports. + * @public + */ - // 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) - } +module.exports = Layer; - ignores (path) { - return this._test(path, this._ignoreCache, false).ignored +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); } - createFilter () { - return path => !this.ignores(path) - } + debug('new %o', path) + var opts = options || {}; - filter (paths) { - return makeArray(paths).filter(this.createFilter()) - } + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); - // @returns {TestResult} - test (path) { - return this._test(path, this._testCache, true) - } + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false } -const factory = options => new Ignore(options) +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ -const returnFalse = () => false +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; -const isPathValid = path => - checkPath(path && checkPath.convert(path), path, returnFalse) + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } -factory.isPathValid = isPathValid + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; -// Fixes typescript -factory.default = factory +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ -module.exports = factory +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; -// 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, '/') + if (fn.length > 3) { + // not a standard request handler + return next(); + } - checkPath.convert = makePosix + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; - // '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) -} +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @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 + } -/***/ 98043: -/***/ ((module) => { + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } -"use strict"; + // match the path + match = this.regexp.exec(path) + } + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; + // store values + this.params = {}; + this.path = match[0] - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } + var keys = this.keys; + var params = this.params; - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ - if (count === 0) { - return string; - } +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } - return string.replace(regex, options.indent.repeat(count)); -}; + throw err; + } +} /***/ }), -/***/ 44124: +/***/ 23699: /***/ ((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__(8544); -} +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/***/ 8544: -/***/ ((module) => { +/** + * Module dependencies. + * @private + */ -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 - } -} +var debug = __nccwpck_require__(52529)('express:router:route'); +var flatten = __nccwpck_require__(62003); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); +/** + * Module variables. + * @private + */ -/***/ }), +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; -/***/ 30545: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Module exports. + * @public + */ -"use strict"; +module.exports = Route; -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 }); - } - 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); - } - 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); - } - } - 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); - } - } - return true; - } - handleMonitorReply(reply) { - if (this.redis.status !== "monitoring") { - return false; - } - 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; - } - // 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; - } - 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; - } - 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; - } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; - } - return false; +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; } +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } -/***/ }), + var name = method.toLowerCase(); -/***/ 6134: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } -"use strict"; + return Boolean(this.methods[name]); +}; -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} + * @return {Array} supported HTTP methods + * @private */ -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; +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); -/***/ }), + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } -/***/ 73527: -/***/ ((__unused_webpack_module, exports) => { + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } -"use strict"; + return methods; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Tiny class to simplify dealing with subscription set - * - * @export - * @class SubscriptionSet + * dispatch req, res into this route + * @private */ -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; -} +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } -/***/ }), + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } -/***/ 97873: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + req.route = this; -"use strict"; + next(); -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"; + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); } - // 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; + + // signal to exit router + if (err && err === 'router') { + return done(err) } - 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); - }); - }); + + var layer = stack[idx++]; + if (!layer) { + return done(err); } - 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); + + if (layer.method && layer.method !== method) { + return next(err); } - 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); + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); } - // 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; + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * 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 + */ +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); -/***/ }), + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; -/***/ 35835: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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); + } -"use strict"; + var layer = Layer('/', {}, handle); + layer.method = undefined; -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, + this.methods._all = true; + this.stack.push(layer); + } + + 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]; -/***/ 18394: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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); + } -"use strict"; + debug('%s %o', method, this.path) -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"); + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); } -} -exports.default = ClusterSubscriber; + + return this; + }; +}); /***/ }), -/***/ 34589: +/***/ 53561: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -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; -/***/ }), +/** + * Module dependencies. + * @api private + */ -/***/ 12770: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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__(63477); -"use strict"; +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) -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 + * Return weak ETag for `body`. * - * @export - * @class DelayQueue + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +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 +}; + +/** + * Flatten the given `arr`. + * + * @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". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private */ -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(); - } - 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); - } - } - 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()(); - } - } -} -exports.default = DelayQueue; +exports.normalizeTypes = function(types){ + var ret = []; -/***/ }), + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } -/***/ 17208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return ret; +}; -"use strict"; +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); -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 + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting * - * @class Cluster - * @extends {EventEmitter} + * @param {String} str + * @return {Object} + * @api 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")); - } - } - /** - * 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); - } - return; - } - 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(); - } - }); - } - 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); - } - } - 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); - } - } + +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]; } - 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; + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + 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 fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + 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); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) + } +} + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} + + +/***/ }), + +/***/ 99209: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * Module dependencies. + * @private + */ + +var debug = __nccwpck_require__(52529)('express:view'); +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * 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 + * + * @param {string} name + * @param {object} options + * @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 + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') } - 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"; - } - } - 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; - } - 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 command.promise; + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +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; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +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; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} + + +/***/ }), + +/***/ 36654: +/***/ ((module, exports, __nccwpck_require__) => { + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +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. + */ + +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; + } +}; + + +/** + * 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; } - handleError(error, ttl, handlers) { - if (typeof ttl.value === "undefined") { - ttl.value = this.options.maxRedirections; - } - else { - ttl.value -= 1; - } - if (ttl.value <= 0) { - handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); - return; - } - const errv = error.message.split(" "); - if (errv[0] === "MOVED" || errv[0] === "ASK") { - handlers[errv[0] === "MOVED" ? "moved" : "ask"](errv[1], errv[2]); - } - else if (errv[0] === "TRYAGAIN") { - this.delayQueue.push("tryagain", handlers.tryagain, { - timeout: this.options.retryDelayOnTryAgain, - }); - } - else if (errv[0] === "CLUSTERDOWN" && - this.options.retryDelayOnClusterDown > 0) { - this.delayQueue.push("clusterdown", handlers.connectionClosed, { - timeout: this.options.retryDelayOnClusterDown, - callback: this.refreshSlotsCache.bind(this), - }); - } - 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), - }); - } - else { - handlers.defaults(); - } + }); + + args.splice(lastC, 0, c); +} + +/** + * 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); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; } - getInfoFromNode(redis, callback) { - if (!redis) { - return callback(new Error("Node is disconnected")); - } - // 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)); + } catch(e) {} +} + +/** + * 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; +} + +/** + * 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) {} +} + + +/***/ }), + +/***/ 86991: +/***/ ((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__(27025); + +/** + * 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]; } - invokeReadyDelayedCallbacks(err) { - for (const c of this._readyDelayedCallbacks) { - process.nextTick(c, err); - } - this._readyDelayedCallbacks = []; + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - /** - * 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(); - } - }); + + // 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 + '$')); } - 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); - } - }); - }); + } +} + +/** + * 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; } - /** - * 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((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); - }); + } + 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; } -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; /***/ }), -/***/ 94582: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 52529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ -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)), - }; -} -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; - }); -} -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)); +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(36654); +} else { + module.exports = __nccwpck_require__(25696); } -exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; /***/ }), -/***/ 90803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 25696: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/** + * Module dependencies. + */ + +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); -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 + * This is the Node.js implementation of `debug()`. * - * @example - * ```js - * var infoCommand = new Command('info', null, function (err, result) { - * console.log('result', result); - * }); + * Expose `debug()` as the module. + */ + +exports = module.exports = __nccwpck_require__(86991); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. * - * redis.sendCommand(infoCommand); + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +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.: * - * // 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 + * $ DEBUG_FD=3 node script.js 3>debug.log */ -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); - } - 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); - } - 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 { - resolve(this.transformReply(value)); - } - catch (err) { - this.reject(err); - } - 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); - } - return result; - } + +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)')() } -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: {}, + +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(' '); }; -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]); - } - } - return args; + +/** + * 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); }; -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])); - } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); - } - } - 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]; - } - 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])); - } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); - } - } - return args; -}); -class MixedBuffers { - constructor() { - this.length = 0; - this.items = []; - } - push(x) { - this.length += Buffer.byteLength(x); - this.items.push(x); - } - 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; - } + +/** + * 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'); +} -/***/ 33642: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -"use strict"; +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; + } +} -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 + * Load `namespaces`. * - * This is the base class of Redis, Redis.Cluster and Pipeline + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. * - * @param {boolean} [options.showFriendlyErrorStack=false] - Whether to show a friendly error stack. - * Will decrease the performance significantly. - * @constructor + * 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 Commander() { - this.options = lodash_1.defaults({}, this.options || {}, { - showFriendlyErrorStack: false, - }); - this.scriptsSet = {}; + +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__(57147); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(41808); + 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; } -exports.default = Commander; -const commands = __nccwpck_require__(98020).list.filter(function (command) { - return command !== "monitor"; -}); -commands.push("sentinel"); + /** - * Return supported builtin commands + * Init logic for `debug` instances. * - * @return {string[]} command list - * @public + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -Commander.prototype.getBuiltinCommands = function () { - return commands.slice(0); -}; + +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]]; + } +} + /** - * Create a builtin command + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); + + +/***/ }), + +/***/ 27025: +/***/ ((module) => { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. * - * @param {string} commandName - command name - * @return {object} functions - * @public + * 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 */ -Commander.prototype.createBuiltinCommand = function (commandName) { - return { - string: generateFunction(commandName, "utf8"), - buffer: generateFunction(commandName, null), - }; + +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) + ); }; -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 + * Parse the given `str` and return milliseconds. * - * @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 + * @param {String} str + * @return {Number} + * @api private */ -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); -}; + +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; + } +} + /** - * Send a command + * Short format for `ms`. * - * @abstract - * @public + * @param {Number} ms + * @return {String} + * @api private */ -Commander.prototype.sendCommand = function () { }; -function generateFunction(_commandName, _encoding) { - if (typeof _encoding === "undefined") { - _encoding = _commandName; - _commandName = null; + +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'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * 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'; +} + + +/***/ }), + +/***/ 24826: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +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 + +const DEFAULT_CENSOR = '[REDACTED]' +fastRedact.rx = rx +fastRedact.validator = validator + +module.exports = fastRedact + +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 + + const isCensorFct = typeof censor === 'function' + const censorFctTakesPath = isCensorFct && censor.length > 1 + + if (paths.length === 0) return serialize || noop + + validate({ paths, serialize, censor }) + + const { wildcards, wcLen, secret } = parse({ paths, censor }) + + const compileRestore = restorer({ secret, wcLen }) + const strict = 'strict' in opts ? opts.strict : true + + return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + })) +} + + +/***/ }), + +/***/ 54865: +/***/ ((module) => { + + + +module.exports = { + groupRedact, + groupRestore, + nestedRedact, + nestedRestore +} + +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] + } +} + +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) + + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + values[i] = target[key] + + if (censorFctTakesPath) { + pathWithKey[pathLength] = key + target[key] = censor(target[key], pathWithKey) + } else if (isCensorFct) { + target[key] = censor(target[key]) + } else { + target[key] = censor } - 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); - }; + } + 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 + } +} + +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 (exists === true && parent !== null) { + store.push({ key: ns[ns.length - 1], target: parent, value }) + } + } + return store +} + +function has (obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop) +} + +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 } } -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); - }; + +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 } /***/ }), -/***/ 72712: -/***/ ((__unused_webpack_module, exports) => { +/***/ 96214: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"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(); - } + +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 + } } + return o + }, {}) + + return { wildcards, wcLen, secret } } -exports.default = AbstractConnector; /***/ }), -/***/ 72225: -/***/ ((__unused_webpack_module, exports) => { +/***/ 17333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -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)); - } - 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}`; - } -} -exports.default = SentinelIterator; +const rx = __nccwpck_require__(9158) -/***/ }), +module.exports = redactor -/***/ 10379: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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) -"use strict"; + if (serialize === false) { + redact.restore = (o) => state.restore(o) + } -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); - } - else { - this.resolveMaster(client, callback); - } - } + return redact } -exports.default = SentinelConnector; -function selectPreferredSentinel(availableSlaves, preferredSlaves) { - if (availableSlaves.length === 0) { - return null; - } - let selectedSlave; - if (typeof preferredSlaves === "function") { - selectedSlave = preferredSlaves(availableSlaves); + +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))) } - 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; - } + var existence = hops.map((p) => `o${delim}${p}`).join(' && ') + if (existence.length === 0) existence += `o${delim}${path} != null` + else existence += ` && o${delim}${path} != null` + + const circularDetection = ` + switch (true) { + ${hops.reverse().map((p) => ` + case o${delim}${p} === censor: + secret[${escPath}].circle = ${JSON.stringify(p)} + break + `).join('\n')} + } + ` + + 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}) + } } - // 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 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)` } -function noop() { } /***/ }), -/***/ 8774: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 98806: +/***/ ((module, __unused_webpack_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; + +const { groupRestore, nestedRestore } = __nccwpck_require__(54865) + +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) + } } -exports.isIIpcConnectionOptions = isIIpcConnectionOptions; -class StandaloneConnector extends AbstractConnector_1.default { - constructor(options) { - super(); - 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; - } - } - 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); - }); - }); + +/** + * 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('') +} + +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 } + ` : '' + + return ` + const secret = this.secret + ${resetters} + ${dynamicReset} + return o + ` } -exports.default = StandaloneConnector; /***/ }), -/***/ 72340: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 9158: +/***/ ((module) => { -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; -/***/ }), +module.exports = /[^.[\]]+|\[((?:.)*?)\]/g -/***/ 97282: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/* +Regular expression explanation: -"use strict"; +Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) + opening square bracket ([) or closing square bracket (]) -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; +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). +*/ /***/ }), -/***/ 90735: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41012: +/***/ ((module) => { -"use strict"; -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; - } + +module.exports = state + +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) } -exports.default = MaxRetriesPerRequestError; /***/ }), -/***/ 23961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +/***/ 74174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); -exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; -/***/ }), +const { createContext, runInContext } = __nccwpck_require__(26144) -/***/ 45069: -/***/ ((module, exports, __nccwpck_require__) => { +module.exports = validator -"use strict"; +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 -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); - } + 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)) + } + }) + } } -exports.print = print; /***/ }), -/***/ 42803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 17676: +/***/ ((module) => { -"use strict"; +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify -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; +var arr = [] +var replacerStack = [] + +// 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 + } } - return slot; + 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() + } } -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; - }, - }); + +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 } -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; - } + +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 +} + +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 + } } - this._result[position] = value; - if (--this.replyPending) { - return; + if (typeof val.toJSON === 'function') { + 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; - } - } + 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() + } +} + +// 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 } - 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; - } + } + } + return replacer.call(this, key, val) + } +} + + +/***/ }), + +/***/ 34578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +/* +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: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +function 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; + + this.auth = null; + this.slashes = null; + this.host = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.pathname = null; + + this._prependSlash = false; +} + +var querystring = __nccwpck_require__(63477); + +Url.queryString = querystring; + +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; + + //Trim leading and trailing ws + while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; + while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; + + start = this._parseProtocol(str, start, end); + + //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 = ""; } } - let ignoredCount = 0; - for (let i = 0; i < this._queue.length - ignoredCount; ++i) { - if (this._queue[i + ignoredCount].ignore) { - ignoredCount += 1; + + if (start <= end) { + var ch = str.charCodeAt(start); + + if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { + this._parsePath(str, start, end, disableAutoEscapeChars); } - this._result[i] = this._result[i + ignoredCount]; + 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 ); + } + } - this.resolve(this._result.slice(0, this._result.length - ignoredCount)); -}; -Pipeline.prototype.sendCommand = function (command) { - if (this._transactions > 0) { - command.inTransaction = true; + + if (!this.pathname && this.hostname && + this._slashProtocols[this._protocol]) { + this.pathname = "/"; } - 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); + + 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); } - return this; }; -const multi = Pipeline.prototype.multi; -Pipeline.prototype.multi = function () { - this._transactions += 1; - return multi.apply(this, arguments); + +Url.prototype.resolve = function Url$resolve(relative) { + return this.resolveObject(Url.parse(relative, false, true)).format(); }; -const execBuffer = Pipeline.prototype.execBuffer; -const exec = Pipeline.prototype.exec; -Pipeline.prototype.execBuffer = util_1.deprecate(function () { - if (this._transactions > 0) { - this._transactions -= 1; + +Url.prototype.format = function Url$format() { + var auth = this.auth || ""; + + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ":"); + auth += "@"; } - 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; + + 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); } - if (this._transactions > 0) { - this._transactions -= 1; - return (this.options.dropBufferSupport ? exec : execBuffer).apply(this, arguments); + + if (!search) { + search = query ? "?" + query : ""; } - if (!this.nodeifiedPromise) { - this.nodeifiedPromise = true; - standard_as_callback_1.default(this.promise, callback); + + if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) + protocol += ":"; + + if (this.host) { + host = auth + this.host; } - if (!this._queue.length) { - this.resolve([]); + else if (hostname) { + var ip6 = hostname.indexOf(":") > -1; + if (ip6) hostname = "[" + hostname + "]"; + host = auth + hostname + (port ? ":" + port : ""); } - 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; - } + + var slashes = this.slashes || + ((!protocol || + slashProtocols[protocol]) && host !== false); + + + if (protocol) scheme = protocol + (slashes ? "//" : ""); + else if (slashes) scheme = "//"; + + 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; + + pathname = escapePathName(pathname); + search = escapeSearch(search); + + return scheme + (host === false ? "" : host) + pathname + search + hash; +}; + +Url.prototype.resolveObject = function Url$resolveObject(relative) { + if (typeof relative === "string") + relative = Url.parse(relative, false, true); + + var result = this._clone(); + + // 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; + } + + // 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 = "/"; } - 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; + result._href = ""; + return result; + } + + 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; + } + + 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 removeAllDots = mustEndAbs; + + 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); + } + 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 = ""; } - else { - // Send the pipeline to a random node - pipelineSlot = (Math.random() * 16384) | 0; + 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(); + } } + result.search = relative.search; + result._href = ""; + return result; } - // 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; + + 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--; } - const script = this._shaToScript[item.args[0]]; - if (!script || this.redis._addedScriptHashes[script.sha]) { - continue; + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift(".."); } - scripts.push(script); - this.redis._addedScriptHashes[script.sha] = true; } - const _this = this; - if (!scripts.length) { - return execPipeline(); + + if (mustEndAbs && srcPath[0] !== "" && + (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { + srcPath.unshift(""); } - // 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); + + if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { + srcPath.push(""); } - 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]); - } + + 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(); } - 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], - }; + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } + + 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 punycode = __nccwpck_require__(85477); +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); +}; + +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); +}; + +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); +}; + +Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { + var doLowerCase = false; + var protocolCharacters = this._protocolCharacters; + + 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; } - 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); + else if (protocolCharacters[ch] === 1) { + if (ch < 0x61 /*'a'*/) + doLowerCase = true; } - return _this.promise; + else { + return start; + } + } + return start; }; +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; +}; -/***/ }), +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; -/***/ 71475: -/***/ ((__unused_webpack_module, exports) => { + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); -"use strict"; + 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; + } -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; + if ((port === 0 && !hadChars) || !validPort) { + if (!validPort) { + this._port = -2; + } + return 0; + } + this._port = port; + return i - start; +}; -/***/ }), +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; -/***/ 1422: -/***/ ((__unused_webpack_module, exports) => { + //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; + } -"use strict"; + var doLowerCase = false; + var idna = false; + var hostNameStart = start; + var hostNameEnd = end; + var lastCh = -1; + var portLength = 0; + var charsAfterDot = 0; + var authNeedsDecoding = false; -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, -}; + var j = -1; + //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); -/***/ }), + 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; + } + } -/***/ 74276: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + //@-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; + } -"use strict"; + //Host name is starting with a [ + if (str.charCodeAt(start) === 0x5B /*'['*/) { + for (var i = start + 1; i <= end; ++i) { + var ch = str.charCodeAt(i); -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); - } + //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; + } } - if (self.condition.select) { - self.select(self.condition.select); + //Empty hostname, [ starts a path + return start; + } + + for (var i = start; i <= end; ++i) { + if (charsAfterDot > 62) { + this.hostname = this.host = str.slice(start, i); + return i; } - if (!self.options.enableReadyCheck) { - exports.readyHandler(self)(); + var ch = str.charCodeAt(i); + + if (ch === 0x3A /*':'*/) { + portLength = this._parsePort(str, i + 1, end) + 1; + hostNameEnd = i - 1; + break; } - /* - 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 if (ch < 0x61 /*'a'*/) { + if (ch === 0x2E /*'.'*/) { + //Node.js ignores this error + /* + if (lastCh === DOT || lastCh === -1) { + this.hostname = this.host = ""; + return start; } - else { - self.serverInfo = info; - if (self.connector.check(info)) { - exports.readyHandler(self)(); - } - else { - self.disconnect(true); - } + */ + 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; + } } - }; -} -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; -} -// 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; + else if (ch >= 0x7B /*'{'*/) { + if (ch <= 0x7E /*'~'*/) { + if (this._noPrependSlashHostEnders[ch] === 0) { + this._prependSlash = true; + } + hostNameEnd = i - 1; + break; + } + idna = true; } - if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - continue; + lastCh = ch; + charsAfterDot++; + } + + //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; + } + + return hostNameEnd + 1 + portLength; + +}; + +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; +}; + +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]; + + if (escaped !== "" && escaped !== undefined) { + if (cur < i) ret += str.slice(cur, i); + ret += escaped; + cur = i + 1; } - i++; } -} -// 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") { + 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 ? "/:" : ""; + + 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; } - if (command.name === "exec") { - commandQueue.remove(i, 1); - command.reject(abortError(command)); + else if (ch === 0x3F /*'?'*/) { + this._parseQuery(str, i, end, disableAutoEscapeChars); + pathEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; + } + } + + if (pathStart > pathEnd) { + this.pathname = prePath === "" ? "/" : prePath; + return; + } + + 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; +}; + +Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { + var queryStart = start; + var queryEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; + + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); + + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + queryEnd = i - 1; break; } - if (command.inTransaction) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - } - else { - i++; + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; } } -} -function closeHandler(self) { - return function () { - self.setStatus("close"); - if (!self.prevCondition) { - self.prevCondition = self.condition; + + if (queryStart > queryEnd) { + this.search = ""; + return; + } + + var query; + if (escape) { + query = this._getComponentEscaped(str, queryStart, queryEnd, true); + } + else { + 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; + } + + 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); } - if (self.commandQueue.length) { - abortIncompletePipelines(self.commandQueue); - self.prevCommandQueue = self.commandQueue; + return null; + }, + set: function(v) { + if (v == null) { + this._port = -1; } - if (self.offlineQueue.length) { - abortTransactionFragments(self.offlineQueue); + else { + this._port = parseInt(v, 10); } - if (self.manuallyClosing) { - self.manuallyClosing = false; - debug("skip reconnecting since the connection is manually closed."); - return close(); + } +}); + +Object.defineProperty(Url.prototype, "query", { + get: function() { + var query = this._query; + if (query != null) { + return query; } - if (typeof self.options.retryStrategy !== "function") { - debug("skip reconnecting because `retryStrategy` is not a function"); - return close(); + var search = this.search; + + if (search) { + if (search.charCodeAt(0) === 0x3F /*'?'*/) { + search = search.slice(1); + } + if (search !== "") { + this._query = search; + return search; + } } - const retryDelay = self.options.retryStrategy(++self.retryAttempts); - if (typeof retryDelay !== "number") { - debug("skip reconnecting because `retryStrategy` doesn't return a number"); - return close(); + return search; + }, + set: function(v) { + this._query = v; + } +}); + +Object.defineProperty(Url.prototype, "path", { + get: function() { + var p = this.pathname || ""; + var s = this.search || ""; + if (p || s) { + return p + s; } - 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..."); + return (p == null && s) ? ("/" + s) : null; + }, + set: function() {} +}); + +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 { - const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); - if (remainder === 0) { - debug("reach maxRetriesPerRequest limitation, flushing command queue..."); - self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); - } + this._protocol = v; } } - }; - function close() { - self.setStatus("end"); - self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + else if (v == null) { + this._protocol = null; + } + } +}); + +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; } +}); + +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; +}; + +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(); +}; + +Url.resolve = function Url$Resolve(source, relative) { + return Url.parse(source, false, true).resolve(relative); +}; + +Url.resolveObject = function Url$ResolveObject(source, relative) { + if (!source) return relative; + return Url.parse(source, false, true).resolveObject(relative); +}; + +function _escapePath(pathname) { + return pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); } -exports.closeHandler = closeHandler; -function errorHandler(self) { - return function (error) { - debug("error: %s", error); - self.silentEmit("error", error); - }; + +function _escapeSearch(search) { + return search.replace(/#/g, function(match) { + return encodeURIComponent(match); + }); } -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); + +//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; } - 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); - } - } + else if (stopCharacterTable[ch] === 1) { + return false; } - 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; - } + } + return false; +} + +//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; } - 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); + else { + var start = item[0]; + var end = item[1]; + for (var j = start; j <= end; ++j) { + ret[j] = 1; } } - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); - } + }); + + return ret; +} + + +var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", + "\t", "{", "}", "|", "\\", "^", "`", "'"]; + +var autoEscapeMap = new Array(128); + + + +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); + } + autoEscapeMap[c.charCodeAt(0)] = esc; +} +var afterQueryAutoEscapeMap = autoEscapeMap.slice(); +autoEscapeMap[0x5C /*'\'*/] = "/"; + +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 +}; + +//Optimize back from normalized object caused by non-identifier keys +function f(){} +f.prototype = slashProtocols; + +Url.prototype._protocolCharacters = makeAsciiTable([ + [0x61 /*'a'*/, 0x7A /*'z'*/], + [0x41 /*'A'*/, 0x5A /*'Z'*/], + 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ +]); + +Url.prototype._hostEndingCharacters = makeAsciiTable([ + 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ +]); + +Url.prototype._autoEscapeCharacters = makeAsciiTable( + autoEscape.map(function(v) { + return v.charCodeAt(0); + }) +); + +//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); + }) +); + +Url.prototype._autoEscapeMap = autoEscapeMap; +Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; + +module.exports = Url; + +Url.replace = function Url$Replace() { + require.cache.url = { + exports: Url }; +}; + + +/***/ }), + +/***/ 30810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * Module dependencies. + * @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 + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @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' } -exports.readyHandler = readyHandler; +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler (req, res, options) { + var opts = options || {} + + // 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) + } -/***/ 83609: -/***/ ((__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) + } + + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } + + // send response + send(req, res, status, headers, msg) + } +} -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: + * Get headers from Error object. * - * ```javascript - * var redis = new Redis({ lazyConnect: true }); - * // No attempting to connect to the Redis server here. + * @param {Error} err + * @return {object} + * @private + */ - * // 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(); +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + var headers = Object.create(null) + var keys = Object.keys(err.headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + + return headers +} + +/** + * Get message from Error object, fallback to status message. * - * 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' }); - * ``` + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private */ -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); + +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() } + } + + return msg || statuses[status] } -util_1.inherits(Redis, events_1.EventEmitter); -Object.assign(Redis.prototype, commander_1.default.prototype); + /** - * Create a Redis instance + * Get status code from Error object. * - * @deprecated + * @param {Error} err + * @return {number} + * @private */ -// @ts-ignore -Redis.createClient = function (...args) { - // @ts-ignore - return new Redis(...args); -}; + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + /** - * Default options + * Get resource name for the request. * - * @var defaultOptions + * 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 */ -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"); - } -}; + +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} + /** - * Change instance's status + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} * @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)); -}; + +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 + } + + return status +} + /** - * Create a connection to Redis. - * This method will be invoked automatically when creating a new Redis instance - * unless `lazyConnect: true` is passed. + * Determine if the response headers have been sent. * - * 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 + * @param {object} res + * @returns {boolean} + * @private */ -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); -}; + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + res.statusMessage = statuses[status] + + // response headers + setHeaders(res, headers) + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} + /** - * Disconnect from Redis. + * Set response headers from an object. * - * 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 + * @param {OutgoingMessage} res + * @param {object} headers + * @private */ -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(); - } -}; + +function setHeaders (res, headers) { + if (!headers) { + return + } + + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} + + +/***/ }), + +/***/ 56401: +/***/ ((module, exports, __nccwpck_require__) => { + /** - * Disconnect from Redis. + * This is the web browser implementation of `debug()`. * - * @deprecated + * Expose `debug()` as the module. */ -Redis.prototype.end = function () { - this.disconnect(); -}; + +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(); + /** - * Create a new instance with the same options as the current one. - * - * @example - * ```js - * var redis = new Redis(6380); - * var anotherRedis = redis.duplicate(); - * ``` + * 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. * - * @public + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -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); - } + +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; + } }; + + /** - * Flush offline queue and command queue with error. + * Colorize log arguments if enabled. * - * @param {Error} error - The error object to send to the commands - * @param {object} options - * @private + * @api public */ -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"); - } - while (this.commandQueue.length > 0) { - item = this.commandQueue.shift(); - item.command.reject(error); - } - } + +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); +} + /** - * Check whether Redis has finished loading the persistent data and is able to - * process commands. + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". * - * @param {Function} callback - * @private + * @api public */ -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); - } - }); -}; + +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); +} + /** - * Emit only when there's at least one listener. + * Save `namespaces`. * - * @param {string} eventName - Event to emit - * @param {...*} arguments - Arguments - * @return {boolean} Returns true if event had listeners, false otherwise. - * @private + * @param {String} namespaces + * @api 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 (this.listeners(eventName).length > 0) { - return this.emit.apply(this, arguments); - } - if (error && error instanceof Error) { - console.error("[ioredis] Unhandled error event:", error.stack); + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; } - return false; -}; + } catch(e) {} +} + /** - * 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)); - * }); - * }); + * Load `namespaces`. * - * // 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 + * @return {String} returns the previously persisted debug modes + * @api private */ -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); + +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; +} + /** - * 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. + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. * - * @method sendCommand - * @memberOf Redis# - * @param {Command} command - The Command instance to send. - * @see {@link Command} - * @example - * ```js - * var redis = new Redis(); + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. * - * // Use callback - * var get = new Command('get', ['foo'], 'utf8', function (err, result) { - * console.log(result); - * }); - * redis.sendCommand(get); + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} + + +/***/ }), + +/***/ 60545: +/***/ ((module, exports, __nccwpck_require__) => { + + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. * - * // Use promise - * var set = new Command('set', ['foo', 'bar'], 'utf8'); - * set.promise.then(function (result) { - * console.log(result); - * }); - * redis.sendCommand(set); - * ``` - * @private + * Expose `debug()` as the module. */ -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.offlineQueue.push({ - command: command, - stream: stream, - select: this.condition.select, - }); - } - 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 command.promise; -}; + +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); + /** - * Get description of the connection. Used for debugging. - * @private + * The currently active debug mode names, and names to skip. */ -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 (this.options.connectionName) { - description += ` (${this.options.connectionName})`; - } - 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)); - }; -}); +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". + */ -/***/ 88540: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +exports.formatters = {}; -"use strict"; +/** + * Previous log timestamp. + */ -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"); +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]; } - execute(container, args, options, callback) { - if (typeof this.numberOfKeys === "number") { - args.unshift(this.numberOfKeys); - } - 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; + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } -} -exports.default = Script; + // 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; + }); -/***/ 14645: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); -"use strict"; + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } -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); - } - return pipeline; - }; - const { multi } = redis; - redis.multi = function (commands, options) { - if (typeof options === "undefined" && !Array.isArray(commands)) { - options = commands; - commands = null; - } - 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); - }; + 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.addTransactionSupport = addTransactionSupport; +/** + * 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); -/***/ 85356: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + exports.names = []; + exports.skips = []; -"use strict"; + 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 + '$')); + } + } +} -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 + * Disable debug output. + * + * @api public */ -function getStringValue(v) { - if (v === null) { - return; + +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; } - 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; + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } + } + return false; } -exports.getStringValue = getStringValue; + /** - * helper function that redacts a string representation of a "debug" arg + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private */ -function genRedactedString(str, maxLen) { - const { length } = str; - return length <= maxLen - ? str - : str.slice(0, maxLen) + ' ... '; + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; } -exports.genRedactedString = genRedactedString; + + +/***/ }), + +/***/ 65612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** - * a wrapper for the `debug` module, used to generate - * "debug functions" that trim the values in their output + * Detect Electron renderer process, which is node, but we should + * treat as a browser. */ -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); - } - 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; + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(56401); +} else { + module.exports = __nccwpck_require__(4706); } -exports.default = genDebugFunction; /***/ }), -/***/ 94832: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4706: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/** + * Module dependencies. + */ + +var tty = __nccwpck_require__(76224); +var util = __nccwpck_require__(73837); -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 + * This is the Node.js implementation of `debug()`. * - * @export - * @param {Buffer} a - * @param {Buffer} b - * @returns {boolean} Whether the two buffers are equal + * Expose `debug()` as the module. */ -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 = module.exports = __nccwpck_require__(60545); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +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)')() } -exports.bufferEqual = bufferEqual; + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + /** - * 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 + * Is stdout a TTY? Colored output is enabled when `true`. */ -function convertBufferToString(value, encoding) { - if (value instanceof Buffer) { - return value.toString(encoding); - } - 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; - } - return value; + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); } -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 + * Map %o to `util.inspect()`, all on a single line. */ -function wrapMultiResult(arr) { - // When using WATCH/EXEC transactions, the EXEC will return - // a null instead of an array - if (!arr) { - return null; - } - 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; -} -exports.wrapMultiResult = wrapMultiResult; + +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(' '); +}; + /** - * 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 + * Map %o to `util.inspect()`, allowing multiple lines if needed. */ -function isInt(value) { - const x = parseFloat(value); - return !isNaN(value) && (x | 0) === x; -} -exports.isInt = isInt; + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + /** - * Pack an array to an Object + * Adds ANSI color escape codes if enabled. * - * @param {array} array - * @return {object} - * @example - * ```js - * > packObject(['a', 'b', 'c', 'd']) - * { a: 'b', c: 'd' } - * ``` + * @api public */ -function packObject(array) { - const result = {}; - const length = array.length; - for (let i = 1; i < length; i += 2) { - result[array[i - 1]] = array[i]; - } - return result; + +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]; + } } -exports.packObject = packObject; + /** - * Return a callback with timeout - * - * @param {function} callback - * @param {number} timeout - * @return {function} + * Invokes `util.format()` with the specified arguments and writes to `stream`. */ -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; + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); } -exports.timeout = timeout; + /** - * Convert an object to an array + * Save `namespaces`. * - * @param {object} obj - * @return {array} - * @example - * ```js - * > convertObjectToArray({ a: '1' }) - * ['a', '1'] - * ``` + * @param {String} namespaces + * @api private */ -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]]); - } - return result; + +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; + } } -exports.convertObjectToArray = convertObjectToArray; + /** - * Convert a map to an array + * Load `namespaces`. * - * @param {Map} map - * @return {array} - * @example - * ```js - * > convertObjectToArray(new Map([[1, '2']])) - * [1, '2'] - * ``` + * @return {String} returns the previously persisted debug modes + * @api private */ -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() { + return process.env.DEBUG; } -exports.convertMapToArray = convertMapToArray; + /** - * Convert a non-string arg to a string + * Copied from `node/src/node.js`. * - * @param {*} arg - * @return {string} + * 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 toArg(arg) { - if (arg === null || typeof arg === "undefined") { - return ""; - } - return String(arg); + +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__(57147); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(41808); + 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; } -exports.toArg = toArg; + /** - * Optimize error stack + * Init logic for `debug` instances. * - * @param {Error} error - actually error - * @param {string} friendlyStack - the stack that more meaningful - * @param {string} filterPath - only show stacks with the specified path + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -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; + +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]]; + } } -exports.optimizeErrorStack = optimizeErrorStack; + /** - * Parse the redis protocol url + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); + + +/***/ }), + +/***/ 80761: +/***/ ((module) => { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. * - * @param {string} url - the redis protocol url - * @return {Object} + * 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 */ -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; - } - if (parsed.port) { - result.port = parsed.port; - } - lodash_1.defaults(result, parsed.query); - return result; -} -exports.parseURL = parseURL; + +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) + ); +}; + /** - * Get a random element from `array` + * Parse the given `str` and return milliseconds. * - * @export - * @template T - * @param {T[]} array the array - * @param {number} [from=0] start index - * @returns {T} + * @param {String} str + * @return {Number} + * @api private */ -function sample(array, from = 0) { - const length = array.length; - if (from >= length) { - return; - } - return array[from + Math.floor(Math.random() * (length - from))]; + +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; + } } -exports.sample = sample; + /** - * Shuffle the array using the Fisher-Yates Shuffle. - * This method will mutate the original array. + * Short format for `ms`. * - * @export - * @template T - * @param {T[]} array - * @returns {T[]} + * @param {Number} ms + * @return {String} + * @api private */ -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 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.shuffle = shuffle; + /** - * Error message for connection being disconnected + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private */ -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; -} -exports.zipMap = zipMap; +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} -/***/ }), +/** + * Pluralization helper. + */ -/***/ 20961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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'; +} -"use strict"; -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; +/***/ }), +/***/ 35298: +/***/ ((module) => { -/***/ }), -/***/ 37263: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function() { - var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; +// 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. - ipaddr = {}; +function flatstr (s) { + s | 0 + return s +} - root = this; +module.exports = flatstr - if (( true && module !== null) && module.exports) { - module.exports = ipaddr; - } else { - root['ipaddr'] = ipaddr; - } +/***/ }), - 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; - }; +/***/ 64334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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; - }; +var CombinedStream = __nccwpck_require__(56523); +var util = __nccwpck_require__(73837); +var path = __nccwpck_require__(71017); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(95687); +var parseUrl = (__nccwpck_require__(57310).parse); +var fs = __nccwpck_require__(57147); +var mime = __nccwpck_require__(43583); +var asynckit = __nccwpck_require__(14812); +var populate = __nccwpck_require__(17142); - 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; - } +// Public API +module.exports = FormData; - IPv4.prototype.kind = function() { - return 'ipv4'; - }; +// make it a Stream +util.inherits(FormData, CombinedStream); - IPv4.prototype.toString = function() { - return this.octets.join("."); - }; +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); + } - IPv4.prototype.toNormalizedString = function() { - return this.toString(); - }; + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; - IPv4.prototype.toByteArray = function() { - return this.octets.slice(0); - }; + CombinedStream.call(this); - 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); - }; + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } +} - 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]] - }; +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - IPv4.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; +FormData.prototype.append = function(field, value, options) { - IPv4.prototype.toIPv4MappedAddress = function() { - return ipaddr.IPv6.parse("::ffff:" + (this.toString())); - }; + options = options || {}; - 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; - }; + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } - return IPv4; + var append = CombinedStream.prototype.append.bind(this); - })(); + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } - ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } - ipv4Regexes = { - fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), - longValue: new RegExp("^" + ipv4Part + "$", 'i') - }; + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); - 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; - } - }; + append(header); + append(value); + append(footer); - 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; - } - } + // pass along options.knownLength + this._trackLength(header, value, options); +}; - IPv6.prototype.kind = function() { - return 'ipv6'; - }; +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; - IPv6.prototype.toString = function() { - return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); - }; + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } - 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); - }; + this._valueLength += valueLength; - 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; - }; + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; - 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; - }; + // empty or either doesn't have path or not an http response + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + return; + } - 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; - }; + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; - 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); - }; +FormData.prototype._lengthRetriever = function(value, callback) { - 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]] - }; + if (value.hasOwnProperty('fd')) { - IPv6.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - IPv6.prototype.isIPv4MappedAddress = function() { - return this.range() === 'ipv4Mapped'; - }; + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); - 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]); - }; + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { - 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; + var fileSize; + + if (err) { + callback(err); + return; } - } - return 128 - cidr; - }; - return IPv6; + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } - })(); + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - ipv6Part = "(?:[0-9a-f]+::?)+"; + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); - zoneIndex = "%[0-9a-z]{1,}"; + // something else + } else { + callback('Unknown stream'); + } +}; - 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') - }; +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } - 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 - }; - }; + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); - 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; + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) }; - ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { - return this.parser(string) !== null; - }; + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } - ipaddr.IPv4.isValid = function(string) { - var e; - try { - new this(this.parser(string)); - return true; - } catch (error1) { - e = error1; - return false; - } - }; + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; - 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; + // skip nullish headers. + if (header == null) { + continue; } - }; - 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; + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; } - }; - 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"); + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; } - 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); - }; + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; - 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"); - }; +FormData.prototype._getContentDisposition = function(value, options) { - 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); - }; + var filename + , contentDisposition + ; - 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'); - } - }; + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } - 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'); - } - }; + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } - 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"); - }; + return contentDisposition; +}; - ipaddr.isValid = function(string) { - return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); - }; +FormData.prototype._getContentType = function(value, options) { - 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"); - } - }; + // use custom content-type above all + var contentType = options.contentType; - 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"); - } - } - }; + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } - 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"); + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } + + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } + + return contentType; +}; + +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; + + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() }; - ipaddr.process = function(string) { - var addr; - addr = this.parse(string); - if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { - return addr.toIPv4Address(); - } else { - return addr; + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; } - }; + } -}).call(this); + return formHeaders; +}; +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } -/***/ }), + return this._boundary; +}; -/***/ 7604: -/***/ ((module) => { +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); -"use strict"; + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } + } + } - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); }; +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } -/***/ }), + this._boundary = boundary; +}; -/***/ 31310: -/***/ (function(module, exports) { +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; -;(function(root) { - 'use strict'; + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } - function isBase64(v, opts) { - if (v instanceof Boolean || typeof v === 'boolean') { - return false - } + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } - if (!(opts instanceof Object)) { - opts = {} - } + return knownLength; +}; - if (opts.allowEmpty === false && v === '') { - return false - } +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; - 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 (this._valuesToMeasure.length) { + hasKnownLength = false; + } - if (opts.mimeRequired === true) { - regex = mimeRegex + regex - } else if (opts.allowMime === true) { - regex = mimeRegex + '?' + regex + return hasKnownLength; +}; + +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; } - if (opts.paddingRequired === false) { - regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' - } + values.forEach(function(length) { + knownLength += length; + }); - return (new RegExp('^' + regex + '$', 'gi')).test(v) - } + cb(null, knownLength); + }); +}; - if (true) { - if ( true && module.exports) { - exports = module.exports = isBase64 - } - exports.isBase64 = isBase64 - } else {} -})(this); +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { -/***/ }), + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); -/***/ 56873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // use custom params + } else { -"use strict"; + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); -var has = __nccwpck_require__(76339); + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } -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('.'); + // get content length and fire away + this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } - 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 === '>='; -} + // add content length + request.setHeader('Content-Length', length); -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; -} + this.pipe(request); + if (cb) { + var onResponse; -function versionIncluded(nodeVersion, specifierValue) { - if (typeof specifierValue === 'boolean') { - return specifierValue; - } + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); - var current = typeof nodeVersion === 'undefined' - ? process.versions && process.versions.node && process.versions.node - : nodeVersion; + return cb.call(this, error, responce); + }; - if (typeof current !== 'string') { - throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); - } + onResponse = callback.bind(this, null); - 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); -} + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); -var data = __nccwpck_require__(93991); + return request; +}; -module.exports = function isCore(x, nodeVersion) { - return has(data, x) && versionIncluded(nodeVersion, data[x]); +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; + +FormData.prototype.toString = function () { + return '[object FormData]'; }; /***/ }), -/***/ 64882: +/***/ 17142: /***/ ((module) => { -"use strict"; -/* eslint-disable yoda */ - - -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } +// populates missing values +module.exports = function(dst, src) { - // 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; - } + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); - return false; + return dst; }; -module.exports = isFullwidthCodePoint; -module.exports.default = isFullwidthCodePoint; - /***/ }), -/***/ 87783: -/***/ ((__unused_webpack_module, exports) => { +/***/ 56523: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -(function(exports) { - "use strict"; +var util = __nccwpck_require__(73837); +var Stream = (__nccwpck_require__(12781).Stream); +var DelayedStream = __nccwpck_require__(18611); - function isArray(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Array]"; - } else { - return false; - } - } +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; - function isObject(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } else { - return false; - } - } + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); - function strictDeepEqual(first, second) { - // Check the scalar case first. - if (first === second) { - return true; - } +CombinedStream.create = function(options) { + var combinedStream = new this(); - // 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; + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; } - function isFalse(obj) { - // From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value + return combinedStream; +}; - // 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; - } - } +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; - function objValues(obj) { - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; } - 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; - } + this._handleErrors(stream); - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; - } else { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; + if (this.pauseStreams) { + stream.pause(); + } } - // 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 - }; + this._streams.push(stream); + return this; +}; - var skipChars = { - " ": true, - "\t": true, - "\n": true - }; +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; +CombinedStream.prototype._getNext = function() { + this._currentStream = null; - function isAlpha(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_"; + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call } - 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 === "_"; + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; } +}; - function Lexer() { +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; } - 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); - }, + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } - _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)); - }, + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } - _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("\\'", "'"); - }, + this._pipeNext(stream); + }.bind(this)); +}; - _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}; - }, +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; - _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}; - } - }, + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } - _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}; - } - } - }, + var value = stream; + this.write(value); + this._getNext(); +}; - _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; - }, +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; - _looksLikeJSON: function(literalString) { - var startingChars = "[{\""; - var jsonLiterals = ["true", "false", "null"]; - var numberLooking = "-0123456789"; +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; - 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; - } - } - }; +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } - 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(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; - function Parser() { +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); } - 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; - }, + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; - _loadTokens: function(expression) { - var lexer = new Lexer(); - var tokens = lexer.tokenize(expression); - tokens.push({type: TOK_EOF, value: "", start: expression.length}); - this.tokens = tokens; - }, +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; - 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; - }, +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; - _lookahead: function(number) { - return this.tokens[this.index + number].type; - }, +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; - _lookaheadToken: function(number) { - return this.tokens[this.index + number]; - }, +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } - _advance: function() { - this.index++; - }, + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; - 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); - } - }, +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; - 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)); - } - }, + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; + + +/***/ }), + +/***/ 68329: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + +var util = __nccwpck_require__(73837), + fs = __nccwpck_require__(57147), + EventEmitter = (__nccwpck_require__(82361).EventEmitter), + crypto = __nccwpck_require__(6113); + +function File(properties) { + EventEmitter.call(this); + + this.size = 0; + this.path = null; + this.name = null; + this.type = null; + this.hash = null; + this.lastModifiedDate = null; + + this._writeStream = null; + + for (var key in properties) { + this[key] = properties[key]; + } + + if(typeof this.hash === 'string') { + this.hash = crypto.createHash(properties.hash); + } else { + this.hash = null; + } +} +module.exports = File; +util.inherits(File, EventEmitter); + +File.prototype.open = function() { + this._writeStream = new fs.WriteStream(this.path); +}; + +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; +}; - _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; - } - }, +File.prototype.write = function(buffer, cb) { + var self = this; + if (self.hash) { + self.hash.update(buffer); + } - _errorToken: function(token) { - var error = new Error("Invalid token (" + - token.type + "): \"" + - token.value + "\""); - error.name = "ParserError"; - throw error; - }, + if (this._writeStream.closed) { + return cb(); + } + this._writeStream.write(buffer, function() { + self.lastModifiedDate = new Date(); + self.size += buffer.length; + self.emit('progress', self.size); + cb(); + }); +}; - _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; - } - }, +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(); + }); +}; - _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 - }; - }, +/***/ }), - _parseComparator: function(left, comparator) { - var right = this.expression(bindingPower[comparator]); - return {type: "Comparator", name: comparator, children: [left, right]}; - }, +/***/ 7973: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _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(); - } - }, +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); - _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 crypto = __nccwpck_require__(6113); +var fs = __nccwpck_require__(57147); +var util = __nccwpck_require__(73837), + path = __nccwpck_require__(71017), + 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__(71576).StringDecoder), + EventEmitter = (__nccwpck_require__(82361).EventEmitter), + Stream = (__nccwpck_require__(12781).Stream), + os = __nccwpck_require__(22037); - _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}; - }, +function IncomingForm(opts) { + if (!(this instanceof IncomingForm)) return new IncomingForm(opts); + EventEmitter.call(this); - _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; + opts=opts||{}; + + this.error = null; + this.ended = false; + + 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; + + this.bytesReceived = null; + this.bytesExpected = null; + + this._parser = null; + this._flushing = 0; + this._fieldsSize = 0; + this._fileSize = 0; + this.openedFiles = []; + + 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; + }; + + // 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; } - return {type: "MultiSelectHash", children: pairs}; + }) + .on('error', function(err) { + cb(err, fields, files); + }) + .on('end', function() { + cb(null, fields, files); + }); + } + + // 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); + } + }); + + return this; +}; - function TreeInterpreter(runtime) { - this.runtime = runtime; +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; } - TreeInterpreter.prototype = { - search: function(node, value) { - return this.visit(node, value); - }, + this.bytesReceived += buffer.length; + this.emit('progress', this.bytesReceived, this.bytesExpected); - 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); + var bytesParsed = this._parser.write(buffer); + if (bytesParsed !== buffer.length) { + this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); + } + + return bytesParsed; +}; - 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); - } - }, +IncomingForm.prototype.pause = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; - 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; +IncomingForm.prototype.resume = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; - if (start === null) { - start = stepValueNegative ? arrayLength - 1 : 0; - } else { - start = this.capSliceRange(arrayLength, start, step); - } +IncomingForm.prototype.onPart = function(part) { + // this method can be overwritten by the user + this.handlePart(part); +}; - 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; - }, +IncomingForm.prototype.handlePart = function(part) { + var self = this; - 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; + // 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); + + 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); + }); + + part.on('end', function() { + self.emit('field', part.name, value); + }); + return; + } + + 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); + + file.open(); + this.openedFiles.push(file); + + 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(); + }); + }); + + part.on('end', function() { + file.end(function() { + self._flushing--; + self.emit('file', part.name, file); + self._maybeEnd(); + }); + }); +}; +function dummyParser(self) { + return { + end: function () { + self.ended = true; + self._maybeEnd(); + return null; + } }; +} - 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}] - } - }; +IncomingForm.prototype._parseContentType = function() { + if (this.bytesExpected === 0) { + this._parser = dummyParser(this); + return; } - 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); - }, - - _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."); - } - } - }, + if (!this.headers['content-type']) { + this._error(new Error('bad content-type header, no content-type')); + return; + } - _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 (this.headers['content-type'].match(/octet-stream/i)) { + this._initOctetStream(); + return; + } - _functionStartsWith: function(resolvedArgs) { - return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; - }, + if (this.headers['content-type'].match(/urlencoded/i)) { + this._initUrlencoded(); + return; + } - _functionEndsWith: function(resolvedArgs) { - var searchStr = resolvedArgs[0]; - var suffix = resolvedArgs[1]; - return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; - }, + 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; + } - _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; - } - }, + if (this.headers['content-type'].match(/json/i)) { + this._initJSONencoded(); + return; + } - _functionAbs: function(resolvedArgs) { - return Math.abs(resolvedArgs[0]); - }, + this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); +}; - _functionCeil: function(resolvedArgs) { - return Math.ceil(resolvedArgs[0]); - }, +IncomingForm.prototype._error = function(err) { + if (this.error || this.ended) { + return; + } - _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; - }, + this.error = err; + this.emit('error', err); - _functionContains: function(resolvedArgs) { - return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; - }, + if (Array.isArray(this.openedFiles)) { + this.openedFiles.forEach(function(file) { + file._writeStream.destroy(); + setTimeout(fs.unlink, 0, file.path, function(error) { }); + }); + } +}; - _functionFloor: function(resolvedArgs) { - return Math.floor(resolvedArgs[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; + } - _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; - } - }, + if (this.bytesExpected !== null) { + this.emit('progress', this.bytesReceived, this.bytesExpected); + } +}; - _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; - }, +IncomingForm.prototype._newParser = function() { + return new MultipartParser(); +}; - _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; - }, +IncomingForm.prototype._initMultipart = function(boundary) { + this.type = 'multipart'; - _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; - } - }, + var parser = new MultipartParser(), + self = this, + headerField, + headerValue, + part; - _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; - } - }, + parser.initWithBoundary(boundary); - _functionSum: function(resolvedArgs) { - var sum = 0; - var listToSum = resolvedArgs[0]; - for (var i = 0; i < listToSum.length; i++) { - sum += listToSum[i]; - } - return sum; - }, + parser.onPartBegin = function() { + part = new Stream(); + part.readable = true; + part.headers = {}; + part.name = null; + part.filename = null; + part.mime = null; - _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"; - } - }, + part.transferEncoding = 'binary'; + part.transferBuffer = ''; - _functionKeys: function(resolvedArgs) { - return Object.keys(resolvedArgs[0]); - }, + headerField = ''; + headerValue = ''; + }; - _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; - }, + parser.onHeaderField = function(b, start, end) { + headerField += b.toString(self.encoding, start, end); + }; - _functionJoin: function(resolvedArgs) { - var joinChar = resolvedArgs[0]; - var listJoin = resolvedArgs[1]; - return listJoin.join(joinChar); - }, + parser.onHeaderValue = function(b, start, end) { + headerValue += b.toString(self.encoding, start, end); + }; - _functionToArray: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { - return resolvedArgs[0]; - } else { - return [resolvedArgs[0]]; - } - }, + parser.onHeaderEnd = function() { + headerField = headerField.toLowerCase(); + part.headers[headerField] = headerValue; - _functionToString: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { - return resolvedArgs[0]; - } else { - return JSON.stringify(resolvedArgs[0]); - } - }, + // 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] || ''; + } - _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; - }, + part.filename = self._fileName(headerValue); + } else if (headerField == 'content-type') { + part.mime = headerValue; + } else if (headerField == 'content-transfer-encoding') { + part.transferEncoding = headerValue.toLowerCase(); + } - _functionNotNull: function(resolvedArgs) { - for (var i = 0; i < resolvedArgs.length; i++) { - if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { - return resolvedArgs[i]; - } - } - return null; - }, + headerField = ''; + headerValue = ''; + }; - _functionSort: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - sortedArray.sort(); - return sortedArray; - }, + 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)); + }; - _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; - }, + parser.onPartEnd = function() { + part.emit('end'); + }; + break; - _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 maxRecord; - }, + case 'base64': + parser.onPartData = function(b, start, end) { + part.transferBuffer += b.slice(start, end).toString('ascii'); - _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; - }, + /* + 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); + }; - 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; + parser.onPartEnd = function() { + part.emit('data', new Buffer(part.transferBuffer, 'base64')); + part.emit('end'); }; - return keyFunc; + break; + + default: + return self._error(new Error('unknown transfer-encoding')); } + self.onPart(part); }; - 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); - } + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; - 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); - } + this._parser = parser; +}; - exports.tokenize = tokenize; - exports.compile = compile; - exports.search = search; - exports.strictDeepEqual = strictDeepEqual; -})( false ? 0 : exports); +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; + 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; +}; -/***/ }), +IncomingForm.prototype._initUrlencoded = function() { + this.type = 'urlencoded'; -/***/ 21917: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var parser = new QuerystringParser(this.maxFields) + , self = this; -"use strict"; + parser.onField = function(key, val) { + self.emit('field', key, val); + }; + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; + this._parser = parser; +}; -var yaml = __nccwpck_require__(40916); +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 + }); -module.exports = yaml; + this.emit('fileBegin', filename, file); + file.open(); + this.openedFiles.push(file); + this._flushing++; + var self = this; -/***/ }), + self._parser = new OctetParser(); -/***/ 40916: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + //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++; -"use strict"; + 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 loader = __nccwpck_require__(45190); -var dumper = __nccwpck_require__(73034); + var done = function(){ + file.end(function() { + self.emit('file', 'file', file); + self._maybeEnd(); + }); + }; + + if(outstandingWrites === 0){ + done(); + } else { + self._parser.once('doneWritingFile', done); + } + }); +}; +IncomingForm.prototype._initJSONencoded = function() { + this.type = 'json'; -function deprecated(name) { - return function () { - throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + 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(); + }; -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); + this._parser = parser; +}; -// 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); +IncomingForm.prototype._uploadPath = function(filename) { + var buf = crypto.randomBytes(16); + var name = 'upload_' + buf.toString('hex'); -// 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'); + if (this.keepExtensions) { + var ext = path.extname(filename); + ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); + name += ext; + } -/***/ }), + return path.join(this.uploadDir, name); +}; -/***/ 59136: -/***/ ((module) => { +IncomingForm.prototype._maybeEnd = function() { + if (!this.ended || this._flushing || this.error) { + return; + } -"use strict"; + this.emit('end'); +}; +/***/ }), -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} +/***/ 95265: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var IncomingForm = (__nccwpck_require__(7973)/* .IncomingForm */ .c); +IncomingForm.IncomingForm = IncomingForm; +module.exports = IncomingForm; -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} +/***/ }), -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; +/***/ 715: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return [ sequence ]; -} +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); +var Buffer = (__nccwpck_require__(14300).Buffer); -function extend(target, source) { - var index, length, key, sourceKeys; +function JSONParser(parent) { + this.parent = parent; + this.chunks = []; + this.bytesWritten = 0; +} +exports.c = JSONParser; - if (source) { - sourceKeys = Object.keys(source); +JSONParser.prototype.write = function(buffer) { + this.bytesWritten += buffer.length; + this.chunks.push(buffer); + return buffer.length; +}; - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; +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; - return target; + this.onEnd(); +}; + + +/***/ }), + +/***/ 31323: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var Buffer = (__nccwpck_require__(14300).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++ + }, + + f = 1, + F = + { PART_BOUNDARY: f, + LAST_BOUNDARY: f *= 2 + }, + + LF = 10, + CR = 13, + SPACE = 32, + HYPHEN = 45, + COLON = 58, + A = 97, + Z = 122, + + lower = function(c) { + return c | 0x20; + }; + +for (s in S) { + exports[s] = S[s]; } +function MultipartParser() { + this.boundary = null; + this.boundaryChars = null; + this.lookbehind = null; + this.state = S.PARSER_UNINITIALIZED; -function repeat(string, count) { - var result = '', cycle; + this.index = null; + this.flags = 0; +} +exports.MultipartParser = MultipartParser; - for (cycle = 0; cycle < count; cycle += 1) { - result += string; +MultipartParser.stateToString = function(stateNumber) { + for (var state in S) { + var number = S[state]; + if (number === stateNumber) return state; } +}; - return result; -} +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; + } +}; -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} +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, + 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; + } -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; + 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; + } + if (!clear) { + callback(name, buffer, self[markSymbol], buffer.length); + self[markSymbol] = 0; + } else { + callback(name, buffer, self[markSymbol], i); + delete self[markSymbol]; + } + }; -/***/ }), + 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; + } -/***/ 73034: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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; + } -"use strict"; + index++; + if (c == HYPHEN) { + break; + } + if (c == COLON) { + if (index == 1) { + // empty header field + return i; + } + dataCallback('headerField', true); + state = S.HEADER_VALUE_START; + break; + } -/*eslint-disable no-use-before-define*/ + cl = lower(c); + if (cl < A || cl > Z) { + return i; + } + break; + case S.HEADER_VALUE_START: + if (c == SPACE) { + break; + } -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); -var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); + 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; + } -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; + 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; -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; /* } */ + 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 ESCAPE_SEQUENCES = {}; + 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; + } + } -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'; + 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 DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; + break; + case S.END: + break; + default: + return i; + } + } - if (map === null) return {}; + dataCallback('headerField'); + dataCallback('headerValue'); + dataCallback('partData'); - result = {}; - keys = Object.keys(map); + this.index = index; + this.state = state; + this.flags = flags; - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); + return len; +}; - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); +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](); } - type = schema.compiledTypeMap['fallback'][tag]; + }; + 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()); + } +}; - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } +MultipartParser.prototype.explain = function() { + return 'state = ' + MultipartParser.stateToString(this.state); +}; - result[tag] = style; - } - return result; +/***/ }), + +/***/ 48680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var EventEmitter = (__nccwpck_require__(82361).EventEmitter) + , util = __nccwpck_require__(73837); + +function OctetParser(options){ + if(!(this instanceof OctetParser)) return new OctetParser(options); + EventEmitter.call(this); } -function encodeHex(character) { - var string, handle, length; +util.inherits(OctetParser, EventEmitter); - string = character.toString(16).toUpperCase(); +exports.h = OctetParser; - 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'); - } +OctetParser.prototype.write = function(buffer) { + this.emit('data', buffer); + return buffer.length; +}; - return '\\' + handle + common.repeat('0', length - string.length) + string; -} +OctetParser.prototype.end = function() { + this.emit('end'); +}; -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; +/***/ }), - this.tag = null; - this.result = ''; +/***/ 80825: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.duplicates = []; - this.usedDuplicates = null; -} +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); -// 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; +// 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__(63477); - 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; - } +function QuerystringParser(maxKeys) { + this.maxKeys = maxKeys; + this.buffer = ''; +} +exports.l = QuerystringParser; - if (line.length && line !== '\n') result += ind; +QuerystringParser.prototype.write = function(buffer) { + this.buffer += buffer.toString('ascii'); + return buffer.length; +}; - result += line; +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 = ''; - return result; -} + this.onEnd(); +}; -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); -} -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; - } - } +/***/ 46868: +/***/ ((module) => { - return false; -} +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} -// 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; -} +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ -// 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 forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } -// 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; -} + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); + // return all addresses + return addrs } -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ -// 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)); +function parse (header) { + var end = header.length + var list = [] + var start = header.length - 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; + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break } - // 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 "''"; - } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; - } + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } - 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); + return list +} - // 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)) { - 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'); - } - }()); -} +/***/ }), -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; +/***/ 83136: +/***/ ((module) => { - // 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 ? '' : '-'); +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ - 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; +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ - // 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; +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ - // 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; - } +/** + * Module exports. + * @public + */ - return result; -} +module.exports = fresh -// 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; +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ - // 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 fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] - // 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; + // unconditional request + if (!modifiedSince && !noneMatch) { + return false } - // 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); + // 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 } - return result.slice(1); // drop extra \n joiner -} + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char, nextChar; - var escapeSeq; + if (!etag) { + 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; + 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 } } - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); - } - return result; -} + if (etagStale) { + return false + } + } -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length; + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) - 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; + if (modifiedStale) { + return false } } - state.tag = _tag; - state.dump = '[' + _result + ']'; + return true } -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length; +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ - 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); - } +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} - _result += state.dump; +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +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 } } - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. + // final token + list.push(str.substring(start, end)) + + return list } -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 += ', '; +/***/ 19320: +/***/ ((module) => { - 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; +/* eslint no-invalid-this: 1 */ + +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 = 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); + + 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)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); } - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; } - pairBuffer += state.dump; + return bound; +}; - // Both key and value are valid. - _result += pairBuffer; - } - state.tag = _tag; - state.dump = '{' + _result + '}'; -} +/***/ }), -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; +/***/ 88334: +/***/ ((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'); - } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } +var implementation = __nccwpck_require__(19320); - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; +module.exports = Function.prototype.bind || implementation; - 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 += '? '; - } - } +/***/ 31621: +/***/ ((module) => { - 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. - } +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); +}; - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } - pairBuffer += state.dump; +/***/ }), - // Both key and value are valid. - _result += pairBuffer; - } +/***/ 76339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - typeList = explicit ? state.explicitTypes : state.implicitTypes; +var bind = __nccwpck_require__(88334); - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { - state.tag = explicit ? type.tag : '?'; +/***/ }), - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; +/***/ 95193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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'); - } +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ - state.dump = _result; - } - return true; - } - } - return false; -} +/** + * Module dependencies. + * @private + */ -// 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; +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) - if (!detectType(state, object, false)) { - detectType(state, object, true); - } +/** + * Module exports. + * @public + */ - var type = _toString.call(state.dump); +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; +/** + * Get the code class of a status code. + * @private + */ - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; +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 } - 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; + 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 + ', ...)') } - } - } 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; + break + case 'object': + props = arg + break } } - return true; -} - -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; - - inspectNode(object, objects, duplicatesIndexes); + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 } - state.usedDuplicates = new Array(length); -} -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; + // constructor + var HttpError = createError[status] || createError[codeClass(status)] - 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 (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] } } -} - -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 ''; -} -function safeDump(input, options) { - return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); + return err } -module.exports.dump = dump; -module.exports.safeDump = safeDump; - - -/***/ }), - -/***/ 65199: -/***/ ((module) => { - -"use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// - +/** + * Create HTTP error abstract base class. + * @private + */ -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + inherits(HttpError, Error) - // 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 || ''; - } + return HttpError } +/** + * Create a constructor for a client error. + * @private + */ -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; +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) -YAMLException.prototype.toString = function toString(compact) { - var result = this.name + ': '; + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) - result += this.reason || '(unknown reason)'; + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) - if (!compact && this.mark) { - result += ' ' + this.mark.toString(); - } + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) - return result; -}; + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return err + } -module.exports = YAMLException; + inherits(ClientError, HttpError) + nameFunc(ClientError, className) + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true -/***/ }), + return ClientError +} -/***/ 45190: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Create a constructor for a server error. + * @private + */ -"use strict"; +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) -/*eslint-disable max-len,no-use-before-define*/ + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) -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); + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) -var _hasOwnProperty = Object.prototype.hasOwnProperty; + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return err + } -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; + inherits(ServerError, HttpError) + nameFunc(ServerError, className) + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; + return ServerError +} +/** + * Set the name of a function, if possible. + * @private + */ -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 nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} -function _class(obj) { return Object.prototype.toString.call(obj); } +/** + * Populate the exports object with constructors for every error class. + * @private + */ -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') } -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; - } +/***/ 15098: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - 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; +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__(41808)); +const tls_1 = __importDefault(__nccwpck_require__(24404)); +const url_1 = __importDefault(__nccwpck_require__(57310)); +const assert_1 = __importDefault(__nccwpck_require__(39491)); +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!'); + } + 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); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // 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']; + } + 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; + } + 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; + }); + } } - -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; +exports["default"] = HttpsProxyAgent; +function resume(socket) { + socket.resume(); } - -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 isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); } - -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 - ); +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; } - -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 omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; } +//# sourceMappingURL=agent.js.map +/***/ }), -function State(input, options) { - this.input = input; +/***/ 77219: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - 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; +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 - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; +/***/ }), - this.documents = []; +/***/ 595: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ +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'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + 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 + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); } +exports["default"] = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map +/***/ }), -function generateError(state, message) { - return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); -} +/***/ 39695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function throwError(state, message) { - throw generateError(state, message); -} -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} +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. -var directiveHandlers = { +exports._dbcs = DBCSCodec; - YAML: function handleYamlDirective(state, name, args) { +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; - var match, major, minor; +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } +// 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."); - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + // Load tables. + var mappingTable = codecOptions.table(); - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); + // Decode tables: MBCS -> Unicode. - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } + // 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. - state.version = args[0]; - state.checkLineBreaks = (minor < 2); + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, + // 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]); - TAG: function handleTagDirective(state, name, args) { + this.defaultCharUnicode = iconv.defaultCharUnicode; - var handle, prefix; + + // Encode tables: Unicode -> DBCS. - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } + // `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 = []; - handle = args[0]; - prefix = args[1]; + // 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); - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + // 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]); } - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } + 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); - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - state.tagMap[handle] = prefix; - } -}; + // 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); -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; + 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; + } + 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); - if (start < end) { - _result = state.input.slice(start, end); + 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 (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'); + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); + 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)); } - - state.result += _result; - } + return node; } -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'); - } +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); - sourceKeys = Object.keys(source); + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; + // 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. - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; + 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++; + } + 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); } -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { - var index, quantity; +// 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]; +} - // 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); +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; +} - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } +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 (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + 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); } - } - - // 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]'; - } + // 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 + } + } - keyNode = String(keyNode); + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} - if (_result === null) { - _result = {}; - } +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 (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'); + 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); } - _result[keyNode] = valueNode; - 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++; - } - } else { - throwError(state, 'a line break is expected'); - } +// == Encoder ================================================================== - state.line += 1; - state.lineStart = state.position; +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; } -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); +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 (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } + 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; + } - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } + // 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; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } - if (is_EOL(ch)) { - readLineBreak(state); + // 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; - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } + } else if (resCode == undefined) { // Current character is not part of the sequence. - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } + // 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. - return lineBreaks; -} + } 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; + } -function testDocumentSeparator(state) { - var _position = state.position, - ch; + 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; + } + } + } - ch = state.input.charCodeAt(_position); + // 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 + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } - // 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)) { + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} - _position += 3; +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. - ch = state.input.charCodeAt(_position); + var newBuf = Buffer.alloc(10), j = 0; - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; + 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; } - } - return false; + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); } -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; +// == Decoder ================================================================== - ch = state.input.charCodeAt(state.position); +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); - 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; - } + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); +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 (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } + 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]; - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); + 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); - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } + // 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; - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } - if (is_WS_OR_EOL(preceding)) { - break; - } + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; +DBCSDecoder.prototype.end = function() { + var ret = ''; - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); + // 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); - 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; - } + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); } - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } + this.nodeIdx = 0; + return ret; +} - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; +// 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; +} - ch = state.input.charCodeAt(++state.position); - } - captureSegment(state, captureStart, captureEnd, false); - if (state.result) { - return true; - } +/***/ }), - state.kind = _kind; - state.result = _result; - return false; -} +/***/ 91386: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - ch = state.input.charCodeAt(state.position); - if (ch !== 0x27/* ' */) { - return false; - } +// 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. - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; +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) - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); + // 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 - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } + 'shiftjis': { + type: '_dbcs', + table: function() { return __nccwpck_require__(27014) }, + 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', - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; + 'eucjp': { + type: '_dbcs', + table: function() { return __nccwpck_require__(31532) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); + // 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. - } else { - state.position++; - captureEnd = state.position; - } - } - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', - ch = state.input.charCodeAt(state.position); + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return __nccwpck_require__(13336) }, + }, - if (ch !== 0x22/* " */) { - return false; - } + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; + // 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__(13336).concat)(__nccwpck_require__(44346)) }, + gb18030: function() { return __nccwpck_require__(36258) }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; + 'chinese': 'gb18030', - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); + // == 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__(77348) }, + }, - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); + // == 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. - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return __nccwpck_require__(74284) }, + }, - } else { - throwError(state, 'expected hexadecimal character'); - } - } + // 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__(74284).concat)(__nccwpck_require__(63480)) }, + encodeSkipVals: [0xa2cc], + }, - state.result += charFromCodepoint(hexResult); + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; - state.position++; - } else { - throwError(state, 'unknown escape sequence'); - } +/***/ }), - captureStart = captureEnd = state.position; +/***/ 82733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } 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; - } - } +// 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), +]; - throwError(state, 'unexpected end of the stream within a double quoted scalar'); +// 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]; } -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; - } +/***/ 12376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - ch = state.input.charCodeAt(++state.position); +var Buffer = (__nccwpck_require__(15118).Buffer); - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); +// Export Node.js internal encodings. - ch = state.input.charCodeAt(state.position); +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", - 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'); - } + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); + // Codec. + _internal: InternalCodec, +}; - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } +//------------------------------------------------------------------------------ - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; - ch = state.input.charCodeAt(state.position); + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; - 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; + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } } +} - 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); - } +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; - skipSeparationSpace(state, true, nodeIndent); +//------------------------------------------------------------------------------ - ch = state.input.charCodeAt(state.position); +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = (__nccwpck_require__(71576).StringDecoder); - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; - throwError(state, 'unexpected end of the stream within a flow collection'); + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); } -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; +InternalDecoder.prototype = StringDecoder.prototype; - ch = state.input.charCodeAt(state.position); - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } +//------------------------------------------------------------------------------ +// Encoder is mostly trivial - state.kind = 'scalar'; - state.result = ''; +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} - 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'); - } +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. - } 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'); - } +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} - } else { - break; - } - } +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); - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); + return Buffer.from(str, "base64"); +} - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - ch = state.input.charCodeAt(state.position); +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } +function InternalEncoderCesu8(options, codec) { +} - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; +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); +} - if (is_EOL(ch)) { - emptyLines++; - continue; - } +InternalEncoderCesu8.prototype.end = function() { +} - // End of the scalar. - if (state.lineIndent < textIndent) { +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ - // 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'; - } - } +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} - // Break this `while` cycle and go to the funciton's epilogue. - break; +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 (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; +} - // Folded style: use fancy rules to handle line breaks. - if (folding) { +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} - // 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 += ' '; - } +/***/ 26657: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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); - } +var Buffer = (__nccwpck_require__(15118).Buffer); - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; +// 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). - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); +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; } - captureSegment(state, captureStart, state.position, false); - } + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); - return true; + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; } -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - ch = state.input.charCodeAt(state.position); +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} - while (ch !== 0) { +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; +} - if (ch !== 0x2D/* - */) { - break; - } +SBCSEncoder.prototype.end = function() { +} - following = state.input.charCodeAt(state.position + 1); - if (!is_WS_OR_EOL(following)) { - break; +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'); +} - detected = true; - state.position++; +SBCSDecoder.prototype.end = function() { +} - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - _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); +/***/ 21012: +/***/ ((module) => { - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; + +// 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": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" } - 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. - } - - // - // 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 (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); - } +/***/ }), - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } +/***/ 41080: +/***/ ((module) => { - return detected; -} -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - ch = state.input.charCodeAt(state.position); +// Manually added data to be used by sbcs codec in addition to generated one. - if (ch !== 0x21/* ! */) return false; +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, - ch = state.input.charCodeAt(++state.position); + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); + // 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", - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", - } else { - tagHandle = '!'; - } + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", - _position = state.position; + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); + "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", - 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)) { + "cp819": "iso88591", + "ibm819": "iso88591", - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); + "cyrillic": "iso88595", - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", - ch = state.input.charCodeAt(++state.position); - } + "hebrew": "iso88598", + "hebrew8": "iso88598", - tagName = state.input.slice(_position, state.position); + "turkish": "iso88599", + "turkish8": "iso88599", - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } + "thai": "iso885911", + "thai8": "iso885911", - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", - if (isVerbatim) { - state.tag = tagName; + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", - } else if (tagHandle === '!') { - state.tag = '!' + tagName; + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", - return true; -} + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", -function readAnchorProperty(state) { - var _position, - ch; + "strk10482002": "rk1048", - ch = state.input.charCodeAt(state.position); + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", - if (ch !== 0x26/* & */) return false; + "gb198880": "iso646cn", + "cn": "iso646cn", - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", - ch = state.input.charCodeAt(++state.position); - _position = state.position; + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } + "mac": "macintosh", + "csmacintosh": "macintosh", +}; - 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); +/***/ 11155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (ch !== 0x2A/* * */) return false; - ch = state.input.charCodeAt(++state.position); - _position = state.position; +var Buffer = (__nccwpck_require__(15118).Buffer); - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } +// == UTF16-BE codec. ========================================================== - alias = state.input.slice(_position, state.position); +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; - 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; - } - } - } +// -- Decoding - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; +function Utf16BEDecoder() { + this.overflowByte = -1; +} - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; } - 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; + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } - } else if (readAlias(state)) { - hasContent = true; + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } + return buf2.slice(0, j).toString('ucs2'); +} - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; +Utf16BEDecoder.prototype.end = function() { +} - if (state.tag === null) { - state.tag = '?'; - } - } - 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); - } - } +// == 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'}); - 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 + '"'); - } +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} - 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]; +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; - 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 (!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 + '>'); - } - } +// -- Encoding (pass-through) - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); } -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = {}; - state.anchorMap = {}; +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} - ch = state.input.charCodeAt(state.position); - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } +// -- Decoding - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } + this.options = options || {}; + this.iconv = codec.iconv; +} - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; +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 ''; - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); + // 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; } - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } + return this.decoder.write(buf); +} - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } +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 (is_EOL(ch)) break; + var res = this.decoder.write(buf), + trail = this.decoder.end(); - _position = state.position; + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; - directiveArgs.push(state.input.slice(_position, state.position)); - } + 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. - if (ch !== 0) readLineBreak(state); + 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 (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } } - } - - 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); + return enc; +} - } 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)) { +/***/ 51644: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } -} +var Buffer = (__nccwpck_require__(15118).Buffer); +// 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 -function loadDocuments(input, options) { - input = String(input); - options = options || {}; +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; - if (input.length !== 0) { +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; - // 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); - } - } +// -- Encoding - var state = new State(input, options); +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; - var nullpos = input.indexOf('\0'); +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } +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))); +} - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; +Utf7Encoder.prototype.end = function() { +} - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - while (state.position < (state.length - 1)) { - readDocument(state); - } +// -- Decoding - return state.documents; +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)); -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); - var documents = loadDocuments(input, options); +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; - if (typeof iterator !== 'function') { - return documents; - } + // The decoder is more involved as we must handle chunks in stream. - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} + 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"); + } + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; -function load(input, options) { - var documents = loadDocuments(input, options); + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } - 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 (!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"); + } -function safeLoadAll(input, iterator, options) { - if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { - options = iterator; - iterator = null; - } + this.inBase64 = inBase64; + this.base64Accum = base64Accum; - return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); + 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"); -function safeLoad(input, options) { - return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); + this.inBase64 = false; + this.base64Accum = ''; + return res; } -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; +// 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; +}; -/***/ 55426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; -"use strict"; +// -- Encoding +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} -var common = __nccwpck_require__(59136); +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; + } -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; -} + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } - if (!this.buffer) return null; + } 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; - indent = indent || 4; - maxLength = maxLength || 75; + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } - head = ''; - start = this.position; + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; - 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; - } - } + return buf.slice(0, bufIdx); +} - tail = ''; - end = this.position; +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; + } - 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; + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; } - } - snippet = this.buffer.slice(start, end); + return buf.slice(0, bufIdx); +} - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; +// -- Decoding -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} - if (this.name) { - where += 'in "' + this.name + '" '; - } +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; - if (!compact) { - snippet = this.getSnippet(); + // 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). - if (snippet) { - where += ':\n' + snippet; + 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 where; -}; + 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); -module.exports = Mark; + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + this.inBase64 = inBase64; + this.base64Accum = base64Accum; -/***/ }), + return res; +} -/***/ 66514: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); -"use strict"; + this.inBase64 = false; + this.base64Accum = ''; + return res; +} -/*eslint-disable max-len*/ -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var Type = __nccwpck_require__(30967); +/***/ }), -function compileList(schema, name, result) { - var exclude = []; +/***/ 67961: +/***/ ((__unused_webpack_module, exports) => { - schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); - }); - schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { - exclude.push(previousIndex); - } - }); - result.push(currentType); - }); +var BOMChar = '\uFEFF'; - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); +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; + } -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {} - }, index, length; - - function collectType(type) { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } + return this.encoder.write(str); +} - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); } -function Schema(definition) { - this.include = definition.include || []; - this.implicit = definition.implicit || []; - this.explicit = definition.explicit || []; +//------------------------------------------------------------------------------ - 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.'); +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.compiledImplicit = compileList(this, 'implicit', []); - this.compiledExplicit = compileList(this, 'explicit', []); - this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); + this.pass = true; + return res; } +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} -Schema.DEFAULT = null; -Schema.create = function createSchema() { - var schemas, types; +/***/ }), - switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; +/***/ 30393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); - } +var Buffer = (__nccwpck_require__(14300).Buffer); +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer - schemas = common.toArray(schemas); - types = common.toArray(types); +// == Extend Node primitives to use iconv-lite ================================= - 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.'); - } +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. - 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.'); - } + // 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); - return new Schema({ - include: schemas, - explicit: types - }); -}; + 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; + } -module.exports = Schema; + 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()]; + } -/***/ }), + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); -/***/ 92183: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); -"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. + // 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; + } + + 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(); + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + 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; + } + // -- Buffer --------------------------------------------------------------- -var Schema = __nccwpck_require__(66514); + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); -module.exports = new Schema({ - include: [ - __nccwpck_require__(1571) - ] -}); + // 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; + } -/***/ }), + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); -/***/ 56874: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); -"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. + // 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.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(); + // 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; + } + } -var Schema = __nccwpck_require__(66514); + 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; -module.exports = Schema.DEFAULT = new Schema({ - include: [ - __nccwpck_require__(48949) - ], - explicit: [ - __nccwpck_require__(25914), - __nccwpck_require__(69242), - __nccwpck_require__(27278) - ] -}); + // TODO: Set _charsWritten. + } -/***/ }), + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = (__nccwpck_require__(12781).Readable); -/***/ 48949: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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; + } -"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/) + 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__(14300).SlowBuffer); + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; -var Schema = __nccwpck_require__(66514); + 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__(12781).Readable); -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) - ] -}); + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} /***/ }), -/***/ 66037: +/***/ 19032: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 +// 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; -var Schema = __nccwpck_require__(66514); +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. -module.exports = new Schema({ - explicit: [ - __nccwpck_require__(52672), - __nccwpck_require__(5490), - __nccwpck_require__(31173) - ] -}); + 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; + } -/***/ 1571: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + } -"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 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; + } +} +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; -var Schema = __nccwpck_require__(66514); +// 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; -module.exports = new Schema({ - include: [ - __nccwpck_require__(66037) - ], - implicit: [ - __nccwpck_require__(22671), - __nccwpck_require__(94675), - __nccwpck_require__(89963), - __nccwpck_require__(15564) - ] -}); + 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]; -/***/ 30967: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; -"use strict"; + 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); -var YAMLException = __nccwpck_require__(65199); + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'defaultStyle', - 'styleAliases' -]; + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; +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, ""); +} -function compileStyleAliases(map) { - var result = {}; +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); - return result; + return encoder; } -function Type(tag, options) { - options = options || {}; +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); - 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 (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); - // 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); + return decoder; +} - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } + +// 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); + } + + // Load Node primitive extensions. + __nccwpck_require__(30393)(iconv); } -module.exports = Type; +if (false) {} /***/ }), -/***/ 32551: +/***/ 76409: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/*eslint-disable no-bitwise*/ +var Buffer = (__nccwpck_require__(14300).Buffer), + Transform = (__nccwpck_require__(12781).Transform); -var NodeBuffer; -try { - // A trick for browserified version, to not include `Buffer` shim - var _require = require; - NodeBuffer = _require('buffer').Buffer; -} catch (__) {} +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } -var Type = __nccwpck_require__(30967); + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + iconv.supportsStreams = true; -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; -function resolveYamlBinary(data) { - if (data === null) return false; - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; +// == 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); +} - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); - // Skip CR/LF - if (code > 64) continue; +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(); + } + catch (e) { + done(e); + } +} - // Fail on illegal characters - if (code < 0) return false; +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} - bitlen += 6; - } +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; +} - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); } -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 = []; +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); - // Collect by 6*4 bits (3 bytes) +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); + } +} - 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); +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); + } +} - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } +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; +} - // 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); - } +/***/ }), - // 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); - } +/***/ 98043: +/***/ ((module) => { - return 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. +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; + + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); + } + + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); + } + + if (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); + } - 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]; - } + if (count === 0) { + return string; + } - bits = (bits << 8) + object[idx]; - } + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - // Dump tail + return string.replace(regex, options.indent.repeat(count)); +}; - 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; -} +/***/ 44124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function isBinary(object) { - return NodeBuffer && NodeBuffer.isBuffer(object); +try { + var util = __nccwpck_require__(73837); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = __nccwpck_require__(8544); } -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__) => { +/***/ 8544: +/***/ ((module) => { -"use strict"; +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 + } +} -var Type = __nccwpck_require__(30967); +/***/ }), -function resolveYamlBoolean(data) { - if (data === null) return false; +/***/ 30545: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var max = data.length; - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === '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); + }); + } + returnFatalError(err) { + err.message += ". Please report this."; + this.redis.recoverFromFatalError(err, err, { offlineQueue: false }); + } + 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); + } + 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); + } + } + 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); + } + } + return true; + } + handleMonitorReply(reply) { + if (this.redis.status !== "monitoring") { + return false; + } + 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; + } + // 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; + } + 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; + } } - -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; +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; + } + return false; } - -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; +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; + } + if (--command.remainReplies === 0) { + command.resolve(count); + return true; + } + return false; } -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__) => { +/***/ 6134: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stream_1 = __nccwpck_require__(12781); +/** + * 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 common = __nccwpck_require__(59136); -var Type = __nccwpck_require__(30967); -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 resolveYamlFloat(data) { - if (data === null) return false; +/***/ 73527: +/***/ ((__unused_webpack_module, exports) => { - 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; +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; } -function constructYamlFloat(data) { - var value, sign, base, digits; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - } else if (value === '.nan') { - return NaN; +/***/ }), - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); +/***/ 97873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - value = 0.0; - base = 1; - digits.forEach(function (d) { - value += d * base; - base *= 60; +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; + } + if (!client._autoPipelines.has(slotKey)) { + /* + Rare edge case. Somehow, something has deleted this running autopipeline in an immediate + call to executeAutoPipeline. + + Maybe the callback in the pipeline.exec is sometimes called in the same tick, + e.g. if redis is disconnected? + */ + 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]; + // Stop keeping a reference to callbacks immediately after the callbacks stop being used. + // This allows the GC to reclaim objects referenced by callbacks, especially with 16384 slots + // in Redis.Cluster + pipeline[exports.kCallbacks] = null; + // 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); + } }); - - return sign * value; - - } - return sign * parseFloat(value, 10); } - - -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - -function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; +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; + } + return arg[0]; + } + const flattened = lodash_1.flatten([arg]); + if (flattened.length > 0) { + return flattened[0]; + } } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; + 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) { + if (client.status === "wait") + client.connect().catch(lodash_1.noop); + return standard_as_callback_1.default(new CustomPromise(function (resolve, reject) { + client.delayUntilReady((err) => { + if (err) { + reject(err); + return; + } + executeWithAutoPipelining(client, functionName, commandName, args, null).then(resolve, reject); + }); + }), callback); } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; + // 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); } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // 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 isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); + 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 command in the pipeline. + 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); } - -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); +exports.executeWithAutoPipelining = executeWithAutoPipelining; /***/ }), -/***/ 89963: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var common = __nccwpck_require__(59136); -var Type = __nccwpck_require__(30967); - -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} - -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} - -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} - -function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; +/***/ 35835: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!max) return false; - ch = data[index]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const dns_1 = __nccwpck_require__(9523); +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, +}; - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; +/***/ }), - // base 2, base 8, base 16 +/***/ 18394: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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 !== '_'; +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(); + }); } - - - 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 !== '_'; + getInstance() { + return this.subscriber; } - - // base 8 - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; + 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); + }); + } } - return hasDigits && ch !== '_'; - } - - // base 10 (except 0) or base 60 - - // 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; + start() { + this.started = true; + this.selectSubscriber(); + debug("started"); + } + stop() { + this.started = false; + if (this.subscriber) { + this.subscriber.disconnect(); + this.subscriber = null; + } + debug("stopped"); } - hasDigits = true; - } - - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; - - // if !base60 - done; - if (ch !== ':') return true; - - // base60 almost not used, no needs to optimize - return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); } +exports["default"] = ClusterSubscriber; -function constructYamlInteger(data) { - var value = data, sign = 1, ch, base, digits = []; - - 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, 16); - return sign * parseInt(value, 8); - } - - if (value.indexOf(':') !== -1) { - value.split(':').forEach(function (v) { - digits.unshift(parseInt(v, 10)); - }); - - value = 0; - base = 1; - - digits.forEach(function (d) { - value += (d * base); - base *= 60; - }); - return sign * value; +/***/ }), - } +/***/ 34589: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return sign * parseInt(value, 10); -} -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(82361); +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); + }); + } } - -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' ] - } -}); +exports["default"] = ConnectionPool; /***/ }), -/***/ 27278: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +/***/ 12770: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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; +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(); + } + 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); + } + } + 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()(); + } + } } +exports["default"] = DelayQueue; -var Type = __nccwpck_require__(30967); -function resolveJavascriptFunction(data) { - if (data === null) return false; +/***/ }), - try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); +/***/ 17208: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(82361); +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); + } + return; + } + 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(); + } + }); + } + tryNode(0); } - - return true; - } catch (err) { - return false; - } -} - -function constructJavascriptFunction(data) { - /*jslint evil:true*/ - - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; - - 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'); - } - - ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); - }); - - 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)); - } - // 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(); -} - -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 -}); - - -/***/ }), - -/***/ 69242: -/***/ ((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 = ''; - - // 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; - } - - 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); - } - - return new RegExp(regexp, modifiers); -} - -function representJavascriptRegExp(object /*, style*/) { - var result = '/' + object.source + '/'; - - if (object.global) result += 'g'; - if (object.multiline) result += 'm'; - if (object.ignoreCase) result += 'i'; - - 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 -}); - - -/***/ }), - -/***/ 25914: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -function resolveJavascriptUndefined() { - return true; -} - -function constructJavascriptUndefined() { - /*eslint-disable no-undefined*/ - return undefined; -} - -function representJavascriptUndefined() { - return ''; -} - -function isUndefined(object) { - return typeof object === 'undefined'; -} - -module.exports = new Type('tag:yaml.org,2002:js/undefined', { - kind: 'scalar', - resolve: resolveJavascriptUndefined, - construct: constructJavascriptUndefined, - predicate: isUndefined, - represent: representJavascriptUndefined -}); - - -/***/ }), - -/***/ 31173: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); - - -/***/ }), - -/***/ 81393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} - -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); - - -/***/ }), - -/***/ 22671: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} - -function constructYamlNull() { - return null; -} - -function isNull(object) { - return object === null; -} - -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' -}); - - -/***/ }), - -/***/ 96668: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -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; - } + /** + * 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); + } } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; -} - -function constructYamlOmap(data) { - return data !== null ? data : []; -} - -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); - - 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 -}); - - -/***/ }), - -/***/ 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 : []; } -}); - - -/***/ }), - -/***/ 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; + 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"; + } + } + 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); + }, + }); + }; + } + 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 command.promise; } - } - - return true; -} - -function constructYamlSet(data) { - return data !== null ? data : {}; -} - -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); - - -/***/ }), - -/***/ 52672: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); - - -/***/ }), - -/***/ 83714: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"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; -} - -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'; + handleError(error, ttl, handlers) { + if (typeof ttl.value === "undefined") { + ttl.value = this.options.maxRedirections; + } + else { + ttl.value -= 1; + } + if (ttl.value <= 0) { + handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); + return; + } + 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]); + } + } + else if (errv[0] === "ASK") { + handlers.ask(errv[1], errv[2]); + } + else if (errv[0] === "TRYAGAIN") { + this.delayQueue.push("tryagain", handlers.tryagain, { + timeout: this.options.retryDelayOnTryAgain, + }); + } + else if (errv[0] === "CLUSTERDOWN" && + this.options.retryDelayOnClusterDown > 0) { + this.delayQueue.push("clusterdown", handlers.connectionClosed, { + timeout: this.options.retryDelayOnClusterDown, + callback: this.refreshSlotsCache.bind(this), + }); + } + 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), + }); + } + else { + handlers.defaults(); + } } - 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; -} - -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 -}); - - -/***/ }), - -/***/ 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) + getInfoFromNode(redis, callback) { + if (!redis) { + return callback(new Error("Node is disconnected")); + } + // 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)); } - 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)}'` + invokeReadyDelayedCallbacks(err) { + for (const c of this._readyDelayedCallbacks) { + process.nextTick(c, err); + } + this._readyDelayedCallbacks = []; } - throw e - } -} - - -/***/ }), - -/***/ 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; -}; - - -/***/ }), - -/***/ 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), -}; - - -/***/ }), - -/***/ 405: -/***/ ((module) => { - -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; - - -/***/ }), - -/***/ 4383: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var JsonWebTokenError = __nccwpck_require__(405); - -var NotBeforeError = function (message, date) { - JsonWebTokenError.call(this, message); - this.name = 'NotBeforeError'; - this.date = date; -}; - -NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); - -NotBeforeError.prototype.constructor = NotBeforeError; - -module.exports = NotBeforeError; - -/***/ }), - -/***/ 46637: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var JsonWebTokenError = __nccwpck_require__(405); - -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; + /** + * 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(); + } + }); + } + 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(); + }); + }); } - return Math.floor(timestamp + milliseconds / 1000); - } else if (typeof time === 'number') { - return timestamp + time; - } else { - return; - } + 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 }); + } + }); + }); + } +} +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; -}; /***/ }), -/***/ 27174: -/***/ ((module, exports) => { +/***/ 94582: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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) - } -} else { - debug = function () {} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const net_1 = __nccwpck_require__(41808); +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)), + }; +} +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 utils_1.resolveTLSProfile(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; +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; +} +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; + } + } +} +exports.weightSrvRecords = weightSrvRecords; +function getConnectionName(component, nodeConnectionName) { + const prefix = `ioredis-cluster(${component})`; + return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix; +} +exports.getConnectionName = getConnectionName; -// 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' - -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -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*$' -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' +/***/ }), -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' +/***/ 90803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// 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]) - } -} -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false +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; } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} - -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} - -exports.SemVer = SemVer - -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + /** + * 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; } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version + 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); + } + } } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // 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') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // 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 + /** + * 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; + }; + } + /** + * Convert buffer/buffer[] to string/string[], + * and apply reply transformer. + * + * @memberof Command + */ + transformReply(result) { + if (this.replyEncoding) { + result = utils_1.convertBufferToString(result, this.replyEncoding); } - } - return id - }) - } - - 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('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version + const transformer = Command._transformer.reply[this.name]; + if (transformer) { + result = transformer(result); + } + return result; + } + /** + * 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); + } + } } - -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) +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]); + } + } + 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])); + } + } + 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 (key in obj) { + // 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; + } + return result; +}); +class MixedBuffers { + constructor() { + this.length = 0; + this.items = []; + } + push(x) { + this.length += Buffer.byteLength(x); + this.items.push(x); + } + 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; + } } -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) - } +/***/ 33642: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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 - } - 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.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(); } - -// 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 - - 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 - } +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; + } + return function (...args) { + const commandName = _commandName || args.shift(); + let callback = args[args.length - 1]; + if (typeof callback === "function") { + args.pop(); } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) + else { + callback = undefined; } - } - 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] + 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); } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -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 - } + // 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); + }; } - -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 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; } - } - } - return defaultResult // may be 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); + }; } -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 - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} +/***/ }), -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} +/***/ 72712: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch +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; + } + check(info) { + return true; + } + 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; -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} +/***/ }), -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} +/***/ 22913: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) +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; -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} -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 -} +/***/ 72225: +/***/ ((__unused_webpack_module, exports) => { -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 +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)); } - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 +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}`; + } } +exports["default"] = SentinelIterator; -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) +/***/ 10379: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - case '<=': - return lte(a, b, loose) - default: - throw new TypeError('Invalid operator: ' + op) - } +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__(41808); +const utils_1 = __nccwpck_require__(94832); +const tls_1 = __nccwpck_require__(24404); +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."); + } + 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; + } + disconnect() { + super.disconnect(); + if (this.failoverDetector) { + this.failoverDetector.cleanup(); + } + } + 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"); + }); + } } - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false +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 (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value + // if none of the preferred slaves are available, a random available slave is returned + if (!selectedSlave) { + selectedSlave = utils_1.sample(availableSlaves); } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - 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) - } - - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } - - // 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) - } -} - -Comparator.prototype.toString = function () { - return this.value + return addressResponseToAddress(selectedSlave); } - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY) { - return true - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - return cmp(version, this.operator, this.semver, this.options) +function addressResponseToAddress(input) { + return { host: input.ip, port: Number(input.port) }; } +function noop() { } -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - var rangeTmp +/***/ }), - 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) - } +/***/ 8774: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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 +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __nccwpck_require__(41808); +const tls_1 = __nccwpck_require__(24404); +const utils_1 = __nccwpck_require__(94832); +const AbstractConnector_1 = __nccwpck_require__(72712); +function isIIpcConnectionOptions(value) { + return value.path; } - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false +exports.isIIpcConnectionOptions = isIIpcConnectionOptions; +class StandaloneConnector extends AbstractConnector_1.default { + constructor(options) { + super(options.disconnectTimeout); + this.options = options; } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, 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; + } + } + 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); + }); + }); } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // 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 - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range } +exports["default"] = StandaloneConnector; -Range.prototype.toString = function () { - return this.range -} - -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]) - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) +/***/ }), - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) +/***/ 72340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // normalize spaces - range = range.split(/\s+/).join(' ') - // At this point, the range is completely trimmed and - // ready to be split into comparators. +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; - 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) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - return set -} +/***/ }), -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } +/***/ 61823: +/***/ ((__unused_webpack_module, exports) => { - 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) - }) - }) - }) - }) -} -// 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(' ') - }) -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = { + /** + * TLS settings for Redis.com Cloud Fixed plan. Updated on 2021-10-06. + */ + RedisCloudFixed: { + ca: "-----BEGIN CERTIFICATE-----\n" + + "MIIDTzCCAjegAwIBAgIJAKSVpiDswLcwMA0GCSqGSIb3DQEBBQUAMD4xFjAUBgNV\n" + + "BAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\n" + + "dGhvcml0eTAeFw0xMzEwMDExMjE0NTVaFw0yMzA5MjkxMjE0NTVaMD4xFjAUBgNV\n" + + "BAoMDUdhcmFudGlhIERhdGExJDAiBgNVBAMMG1NTTCBDZXJ0aWZpY2F0aW9uIEF1\n" + + "dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALZqkh/DczWP\n" + + "JnxnHLQ7QL0T4B4CDKWBKCcisriGbA6ZePWVNo4hfKQC6JrzfR+081NeD6VcWUiz\n" + + "rmd+jtPhIY4c+WVQYm5PKaN6DT1imYdxQw7aqO5j2KUCEh/cznpLxeSHoTxlR34E\n" + + "QwF28Wl3eg2vc5ct8LjU3eozWVk3gb7alx9mSA2SgmuX5lEQawl++rSjsBStemY2\n" + + "BDwOpAMXIrdEyP/cVn8mkvi/BDs5M5G+09j0gfhyCzRWMQ7Hn71u1eolRxwVxgi3\n" + + "TMn+/vTaFSqxKjgck6zuAYjBRPaHe7qLxHNr1So/Mc9nPy+3wHebFwbIcnUojwbp\n" + + "4nctkWbjb2cCAwEAAaNQME4wHQYDVR0OBBYEFP1whtcrydmW3ZJeuSoKZIKjze3w\n" + + "MB8GA1UdIwQYMBaAFP1whtcrydmW3ZJeuSoKZIKjze3wMAwGA1UdEwQFMAMBAf8w\n" + + "DQYJKoZIhvcNAQEFBQADggEBAG2erXhwRAa7+ZOBs0B6X57Hwyd1R4kfmXcs0rta\n" + + "lbPpvgULSiB+TCbf3EbhJnHGyvdCY1tvlffLjdA7HJ0PCOn+YYLBA0pTU/dyvrN6\n" + + "Su8NuS5yubnt9mb13nDGYo1rnt0YRfxN+8DM3fXIVr038A30UlPX2Ou1ExFJT0MZ\n" + + "uFKY6ZvLdI6/1cbgmguMlAhM+DhKyV6Sr5699LM3zqeI816pZmlREETYkGr91q7k\n" + + "BpXJu/dtHaGxg1ZGu6w/PCsYGUcECWENYD4VQPd8N32JjOfu6vEgoEAwfPP+3oGp\n" + + "Z4m3ewACcWOAenqflb+cQYC4PsF7qbXDmRaWrbKntOlZ3n0=\n" + + "-----END CERTIFICATE-----\n", + }, + /** + * TLS settings for Redis.com Cloud Flexible plan. Updated on 2021-10-06. + */ + RedisCloudFlexible: { + ca: "-----BEGIN CERTIFICATE-----\n" + + "MIIGMTCCBBmgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwajELMAkGA1UEBhMCVVMx\n" + + "CzAJBgNVBAgMAkNBMQswCQYDVQQHDAJDQTESMBAGA1UECgwJUmVkaXNMYWJzMS0w\n" + + "KwYDVQQDDCRSZWRpc0xhYnMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN\n" + + "MTgwMjI1MTUzNzM3WhcNMjgwMjIzMTUzNzM3WjBfMQswCQYDVQQGEwJVUzELMAkG\n" + + "A1UECAwCQ0ExEjAQBgNVBAoMCVJlZGlzTGFiczEvMC0GA1UEAwwmUkNQIEludGVy\n" + + "bWVkaWF0ZSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA\n" + + "A4ICDwAwggIKAoICAQDf9dqbxc8Bq7Ctq9rWcxrGNKKHivqLAFpPq02yLPx6fsOv\n" + + "Tq7GsDChAYBBc4v7Y2Ap9RD5Vs3dIhEANcnolf27QwrG9RMnnvzk8pCvp1o6zSU4\n" + + "VuOE1W66/O1/7e2rVxyrnTcP7UgK43zNIXu7+tiAqWsO92uSnuMoGPGpeaUm1jym\n" + + "hjWKtkAwDFSqvHY+XL5qDVBEjeUe+WHkYUg40cAXjusAqgm2hZt29c2wnVrxW25W\n" + + "P0meNlzHGFdA2AC5z54iRiqj57dTfBTkHoBczQxcyw6hhzxZQ4e5I5zOKjXXEhZN\n" + + "r0tA3YC14CTabKRus/JmZieyZzRgEy2oti64tmLYTqSlAD78pRL40VNoaSYetXLw\n" + + "hhNsXCHgWaY6d5bLOc/aIQMAV5oLvZQKvuXAF1IDmhPA+bZbpWipp0zagf1P1H3s\n" + + "UzsMdn2KM0ejzgotbtNlj5TcrVwpmvE3ktvUAuA+hi3FkVx1US+2Gsp5x4YOzJ7u\n" + + "P1WPk6ShF0JgnJH2ILdj6kttTWwFzH17keSFICWDfH/+kM+k7Y1v3EXMQXE7y0T9\n" + + "MjvJskz6d/nv+sQhY04xt64xFMGTnZjlJMzfQNi7zWFLTZnDD0lPowq7l3YiPoTT\n" + + "t5Xky83lu0KZsZBo0WlWaDG00gLVdtRgVbcuSWxpi5BdLb1kRab66JptWjxwXQID\n" + + "AQABo4HrMIHoMDoGA1UdHwQzMDEwL6AtoCuGKWh0dHBzOi8vcmwtY2Etc2VydmVy\n" + + "LnJlZGlzbGFicy5jb20vdjEvY3JsMEYGCCsGAQUFBwEBBDowODA2BggrBgEFBQcw\n" + + "AYYqaHR0cHM6Ly9ybC1jYS1zZXJ2ZXIucmVkaXNsYWJzLmNvbS92MS9vY3NwMB0G\n" + + "A1UdDgQWBBQHar5OKvQUpP2qWt6mckzToeCOHDAfBgNVHSMEGDAWgBQi42wH6hM4\n" + + "L2sujEvLM0/u8lRXTzASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIB\n" + + "hjANBgkqhkiG9w0BAQsFAAOCAgEAirEn/iTsAKyhd+pu2W3Z5NjCko4NPU0EYUbr\n" + + "AP7+POK2rzjIrJO3nFYQ/LLuC7KCXG+2qwan2SAOGmqWst13Y+WHp44Kae0kaChW\n" + + "vcYLXXSoGQGC8QuFSNUdaeg3RbMDYFT04dOkqufeWVccoHVxyTSg9eD8LZuHn5jw\n" + + "7QDLiEECBmIJHk5Eeo2TAZrx4Yx6ufSUX5HeVjlAzqwtAqdt99uCJ/EL8bgpWbe+\n" + + "XoSpvUv0SEC1I1dCAhCKAvRlIOA6VBcmzg5Am12KzkqTul12/VEFIgzqu0Zy2Jbc\n" + + "AUPrYVu/+tOGXQaijy7YgwH8P8n3s7ZeUa1VABJHcxrxYduDDJBLZi+MjheUDaZ1\n" + + "jQRHYevI2tlqeSBqdPKG4zBY5lS0GiAlmuze5oENt0P3XboHoZPHiqcK3VECgTVh\n" + + "/BkJcuudETSJcZDmQ8YfoKfBzRQNg2sv/hwvUv73Ss51Sco8GEt2lD8uEdib1Q6z\n" + + "zDT5lXJowSzOD5ZA9OGDjnSRL+2riNtKWKEqvtEG3VBJoBzu9GoxbAc7wIZLxmli\n" + + "iF5a/Zf5X+UXD3s4TMmy6C4QZJpAA2egsSQCnraWO2ULhh7iXMysSkF/nzVfZn43\n" + + "iqpaB8++9a37hWq14ZmOv0TJIDz//b2+KC4VFXWQ5W5QC6whsjT+OlG4p5ZYG0jo\n" + + "616pxqo=\n" + + "-----END CERTIFICATE-----\n" + + "-----BEGIN CERTIFICATE-----\n" + + "MIIFujCCA6KgAwIBAgIJAJ1aTT1lu2ScMA0GCSqGSIb3DQEBCwUAMGoxCzAJBgNV\n" + + "BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCQ0ExEjAQBgNVBAoMCVJlZGlz\n" + + "TGFiczEtMCsGA1UEAwwkUmVkaXNMYWJzIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9y\n" + + "aXR5MB4XDTE4MDIyNTE1MjA0MloXDTM4MDIyMDE1MjA0MlowajELMAkGA1UEBhMC\n" + + "VVMxCzAJBgNVBAgMAkNBMQswCQYDVQQHDAJDQTESMBAGA1UECgwJUmVkaXNMYWJz\n" + + "MS0wKwYDVQQDDCRSZWRpc0xhYnMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkw\n" + + "ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLEjXy7YrbN5Waau5cd6g1\n" + + "G5C2tMmeTpZ0duFAPxNU4oE3RHS5gGiok346fUXuUxbZ6QkuzeN2/2Z+RmRcJhQY\n" + + "Dm0ZgdG4x59An1TJfnzKKoWj8ISmoHS/TGNBdFzXV7FYNLBuqZouqePI6ReC6Qhl\n" + + "pp45huV32Q3a6IDrrvx7Wo5ZczEQeFNbCeCOQYNDdTmCyEkHqc2AGo8eoIlSTutT\n" + + "ULOC7R5gzJVTS0e1hesQ7jmqHjbO+VQS1NAL4/5K6cuTEqUl+XhVhPdLWBXJQ5ag\n" + + "54qhX4v+ojLzeU1R/Vc6NjMvVtptWY6JihpgplprN0Yh2556ewcXMeturcKgXfGJ\n" + + "xeYzsjzXerEjrVocX5V8BNrg64NlifzTMKNOOv4fVZszq1SIHR8F9ROrqiOdh8iC\n" + + "JpUbLpXH9hWCSEO6VRMB2xJoKu3cgl63kF30s77x7wLFMEHiwsQRKxooE1UhgS9K\n" + + "2sO4TlQ1eWUvFvHSTVDQDlGQ6zu4qjbOpb3Q8bQwoK+ai2alkXVR4Ltxe9QlgYK3\n" + + "StsnPhruzZGA0wbXdpw0bnM+YdlEm5ffSTpNIfgHeaa7Dtb801FtA71ZlH7A6TaI\n" + + "SIQuUST9EKmv7xrJyx0W1pGoPOLw5T029aTjnICSLdtV9bLwysrLhIYG5bnPq78B\n" + + "cS+jZHFGzD7PUVGQD01nOQIDAQABo2MwYTAdBgNVHQ4EFgQUIuNsB+oTOC9rLoxL\n" + + "yzNP7vJUV08wHwYDVR0jBBgwFoAUIuNsB+oTOC9rLoxLyzNP7vJUV08wDwYDVR0T\n" + + "AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBAHfg\n" + + "z5pMNUAKdMzK1aS1EDdK9yKz4qicILz5czSLj1mC7HKDRy8cVADUxEICis++CsCu\n" + + "rYOvyCVergHQLREcxPq4rc5Nq1uj6J6649NEeh4WazOOjL4ZfQ1jVznMbGy+fJm3\n" + + "3Hoelv6jWRG9iqeJZja7/1s6YC6bWymI/OY1e4wUKeNHAo+Vger7MlHV+RuabaX+\n" + + "hSJ8bJAM59NCM7AgMTQpJCncrcdLeceYniGy5Q/qt2b5mJkQVkIdy4TPGGB+AXDJ\n" + + "D0q3I/JDRkDUFNFdeW0js7fHdsvCR7O3tJy5zIgEV/o/BCkmJVtuwPYOrw/yOlKj\n" + + "TY/U7ATAx9VFF6/vYEOMYSmrZlFX+98L6nJtwDqfLB5VTltqZ4H/KBxGE3IRSt9l\n" + + "FXy40U+LnXzhhW+7VBAvyYX8GEXhHkKU8Gqk1xitrqfBXY74xKgyUSTolFSfFVgj\n" + + "mcM/X4K45bka+qpkj7Kfv/8D4j6aZekwhN2ly6hhC1SmQ8qjMjpG/mrWOSSHZFmf\n" + + "ybu9iD2AYHeIOkshIl6xYIa++Q/00/vs46IzAbQyriOi0XxlSMMVtPx0Q3isp+ji\n" + + "n8Mq9eOuxYOEQ4of8twUkUDd528iwGtEdwf0Q01UyT84S62N8AySl1ZBKXJz6W4F\n" + + "UhWfa/HQYOAPDdEjNgnVwLI23b8t0TozyCWw7q8h\n" + + "-----END CERTIFICATE-----\n", + }, +}; -// 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 -} -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} +/***/ }), -// ~, ~> --> * (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(' ') -} +/***/ 97282: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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 - 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' +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); } - - 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(' ') -} - -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' - } + get name() { + return this.constructor.name; } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') } +exports["default"] = ClusterAllFailedError; -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 (gtlt === '=' && anyX) { - gtlt = '' - } +/***/ }), - 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 +/***/ 90735: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - 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 - } - } - 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' +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; + - debug('xRange return', ret) +/***/ }), - return ret - }) -} +/***/ 23961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// 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], '') -} -// 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 - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); +exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; - 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 - } - return (from + ' ' + to).trim() -} +/***/ }), -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } +/***/ 45069: +/***/ ((module, exports, __nccwpck_require__) => { - 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 +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); } - } - return false } +exports.print = print; -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 - } - } - } +/***/ 42803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Version has a -pre, but it's not one of the ones we like. - return false - } - return true +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(90803); +const util_1 = __nccwpck_require__(73837); +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); +const utils_1 = __nccwpck_require__(94832); +/* + 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; } - -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) +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; + }, + }); } - -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) - } +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; + } + } } - }) - 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) - } + 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; + } + } + } + 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"); +// NOTE: To avoid an unhandled promise rejection, this will unconditionally always return this.promise, +// which always has the rejection handled by standard-as-callback +// adding the provided rejection callback. +// +// If a different promise instance were returned, that promise would cause its own unhandled promise rejection +// errors, even if that promise unconditionally resolved to **the resolved value of** this.promise. +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) { + if (this.redis.status === "wait") + this.redis.connect().catch(utils_1.noop); + 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] || + 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) { + 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; + } + }) + .then(execPipeline, this.reject); + return this.promise; + } + 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; + } + }) + .then(execPipeline, this.reject); + return this.promise; + 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; } - }) - return min -} - -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } +}; - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - 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) - } - }) - } +/***/ 71475: +/***/ ((__unused_webpack_module, exports) => { - if (minver && range.test(minver)) { - return minver - } - return null +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isPromise(obj) { + return (!!obj && + (typeof obj === "object" || typeof obj === "function") && + typeof obj.then === "function"); } - -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 - } +exports.isPromise = isPromise; +let promise = Promise; +function get() { + return promise; } - -// 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) +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; -// 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) +/***/ }), - 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 ">"') - } +/***/ 1422: +/***/ ((__unused_webpack_module, exports) => { - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. +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, +}; - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - var high = null - var low = null +/***/ }), - 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 - } - }) +/***/ 74276: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - // 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 +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); + } + } + }); + } + }; +} +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; +} +// 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++; } - } - return true } - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +// 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++; + } + } } - -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) +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)); + } } - -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - var match = version.match(re[COERCE]) - - if (match == null) { - return null - } - - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) +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; /***/ }), -/***/ 82022: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 83609: +/***/ ((__unused_webpack_module, 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'); -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lodash_1 = __nccwpck_require__(20961); +const util_1 = __nccwpck_require__(73837); +const events_1 = __nccwpck_require__(82361); +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. -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' } + * // 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]); + } + 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) { + const sentinelConnector = new connectors_1.SentinelConnector(this.options); + sentinelConnector.emitter = this; + this.connector = sentinelConnector; + } + 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); }; - -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' } +/** + * 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"); + } + this.options = utils_1.resolveTLSProfile(this.options); +}; +/** + * 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; + } + // 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 (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); + } +}; +/** + * 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"); + } + while (this.commandQueue.length > 0) { + item = this.commandQueue.shift(); + item.command.reject(error); + } + } + } +}; +/** + * 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); + } + }); }; - -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 + '"'); +/** + * 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; } - return; - } - if (!validator.isValid(object[key])) { - throw new Error(validator.message); - } + 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 (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, }); -} - -function validateOptions(options) { - return validate(sign_options_schema, false, options, 'options'); -} - -function validatePayload(payload) { - return validate(registered_claims_schema, true, payload, 'payload'); -} - -var options_to_payload = { - 'audience': 'aud', - 'issuer': 'iss', - 'subject': 'sub', - 'jwtid': 'jti' + const Promise = PromiseContainer.get(); + return standard_as_callback_1.default(new Promise(function (resolve) { + monitorInstance.once("monitoring", function () { + resolve(monitorInstance); + }); + }), callback); }; - -var options_for_objects = [ - 'expiresIn', - 'notBefore', - 'noTimestamp', - 'audience', - 'issuer', - 'subject', - 'jwtid', -]; - -module.exports = function (payload, secretOrPrivateKey, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } else { - options = options || {}; - } - - var isObjectPayload = typeof payload === 'object' && - !Buffer.isBuffer(payload); - - var header = Object.assign({ - alg: options.algorithm || 'HS256', - typ: isObjectPayload ? 'JWT' : undefined, - kid: options.keyid - }, options.header); - - function failure(err) { - if (callback) { - return callback(err); +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); } - throw err; - } - - if (!secretOrPrivateKey && options.algorithm !== 'none') { - return failure(new Error('secretOrPrivateKey must have a value')); - } - - if (typeof payload === 'undefined') { - return failure(new Error('payload is required')); - } else if (isObjectPayload) { - try { - validatePayload(payload); + if (this.status === "end") { + command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return command.promise; } - catch (error) { - return failure(error); + 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 (!options.mutatePayload) { - payload = Object.assign({},payload); + if (typeof this.options.commandTimeout === "number") { + command.setTimeout(this.options.commandTimeout); } - } 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')); + if (command.name === "quit") { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; } - } - - 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 (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { - return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); - } - - try { - validateOptions(options); - } - catch (error) { - return failure(error); - } - - var timestamp = payload.iat || Math.floor(Date.now() / 1000); - - if (options.noTimestamp) { - delete payload.iat; - } else if (isObjectPayload) { - payload.iat = timestamp; - } - - if (typeof options.notBefore !== 'undefined') { - try { - payload.nbf = timespan(options.notBefore, timestamp); + let writable = this.status === "ready" || + (!stream && + this.status === "connect" && + commands.exists(command.name) && + commands.hasFlag(command.name, "loading")); + if (!this.stream) { + writable = false; } - catch (err) { - return failure(err); + else if (!this.stream.writable) { + writable = false; } - 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')); + else if (this.stream._writableState && this.stream._writableState.ended) { + // https://github.com/iojs/io.js/pull/1217 + writable = false; } - } - - if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { - try { - payload.exp = timespan(options.expiresIn, timestamp); + if (!writable && !this.options.enableOfflineQueue) { + command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); + return command.promise; } - catch (err) { - return failure(err); + if (!writable && command.name === "quit" && this.offlineQueue.length === 0) { + this.disconnect(); + command.resolve(Buffer.from("OK")); + return command.promise; } - 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 (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; + } } - } - - 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]; + 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, + }); } - }); - - var encoding = options.encoding || 'utf8'; - - if (typeof callback === 'function') { - callback = callback && once(callback); - - 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 (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 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 (this.options.connectionName) { + description += ` (${this.options.connectionName})`; + } + 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)); + }; +}); /***/ }), -/***/ 12327: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -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); +/***/ 88540: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; -var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; -var HS_ALGS = ['HS256', 'HS384', 'HS512']; -if (PS_SUPPORTED) { - PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); - RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const crypto_1 = __nccwpck_require__(6113); +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; + } + 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; -module.exports = function (jwtString, secretOrPublicKey, options, callback) { - if ((typeof options === 'function') && !callback) { - callback = options; - options = {}; - } - if (!options) { - options = {}; - } +/***/ }), - //clone this object since we are going to mutate it. - options = Object.assign({}, options); +/***/ 14645: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var done; - if (callback) { - done = callback; - } else { - done = function(err, data) { - if (err) throw err; - return data; +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); + } + return pipeline; + }; + const { multi } = redis; + redis.multi = function (commands, options) { + if (typeof options === "undefined" && !Array.isArray(commands)) { + options = commands; + commands = null; + } + 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) { + if (this.redis.status === "wait") + this.redis.connect().catch(utils_1.noop); + 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; }; - } - - if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { - return done(new JsonWebTokenError('clockTimestamp must be a number')); - } - - if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { - return done(new JsonWebTokenError('nonce must be a non-empty string')); - } + 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; - var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); - if (!jwtString){ - return done(new JsonWebTokenError('jwt must be provided')); - } +/***/ }), - if (typeof jwtString !== 'string') { - return done(new JsonWebTokenError('jwt must be a string')); - } +/***/ 85356: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var parts = jwtString.split('.'); - if (parts.length !== 3){ - return done(new JsonWebTokenError('jwt malformed')); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __nccwpck_require__(36215); +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 + } + // 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); + } + 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; - var decodedToken; - try { - decodedToken = decode(jwtString, { complete: true }); - } catch(err) { - return done(err); - } +/***/ }), - if (!decodedToken) { - return done(new JsonWebTokenError('invalid token')); - } +/***/ 94832: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var header = decodedToken.header; - var getSecret; - 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')); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url_1 = __nccwpck_require__(57310); +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; +const TLSProfiles_1 = __nccwpck_require__(61823); +/** + * 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); } - - getSecret = secretOrPublicKey; - } - else { - getSecret = function(header, secretCallback) { - return secretCallback(null, secretOrPublicKey); - }; - } - - return getSecret(header, function(err, secretOrPublicKey) { - if(err) { - return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); + if (a.length !== b.length) { + return false; } - - var hasSignature = parts[2].trim() !== ''; - - if (!hasSignature && secretOrPublicKey){ - return done(new JsonWebTokenError('jwt signature is required')); + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; + } } - - if (hasSignature && !secretOrPublicKey) { - return done(new JsonWebTokenError('secret or public key must be provided')); + 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 (!hasSignature && !options.algorithms) { - options.algorithms = ['none']; + 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; } - - 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; - + 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; } - - if (!~options.algorithms.indexOf(decodedToken.header.alg)) { - return done(new JsonWebTokenError('invalid algorithm')); + 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]); + } } - - var valid; - - try { - valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); - } catch (e) { - return done(e); + return result; +} +exports.wrapMultiResult = wrapMultiResult; +/** + * Detect if 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]; } - - if (!valid) { - return done(new JsonWebTokenError('invalid signature')); + 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); // Object.entries requires node 7+ + for (let i = 0, l = keys.length; i < l; i++) { + result.push(keys[i], obj[keys[i]]); } - - 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 result; +} +exports.convertObjectToArray = convertObjectToArray; +/** + * Convert a map to an array + * + * @param {Map} map + * @return {array} + * @example + * ```js + * > convertMapToArray(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; +} +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 ""; } - - 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 String(arg); +} +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; + } } - - if (options.audience) { - var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; - var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; - - 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 '))); - } + for (let j = i; j < stacks.length; ++j) { + lines += "\n" + stacks[j]; } - - 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)); - } + 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 }; } - - if (options.subject) { - if (payload.sub !== options.subject) { - return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); - } + let parsed = url_1.parse(url, true, true); + if (!parsed.slashes && url[0] !== "/") { + url = "//" + url; + parsed = url_1.parse(url, true, true); } - - if (options.jwtid) { - if (payload.jti !== options.jwtid) { - return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); - } + 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 (options.nonce) { - if (payload.nonce !== options.nonce) { - return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); - } + if (parsed.port) { + result.port = parsed.port; } - - if (options.maxAge) { - if (typeof payload.iat !== 'number') { - return done(new JsonWebTokenError('iat required when maxAge is specified')); - } - - 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))); - } + lodash_1.defaults(result, options); + return result; +} +exports.parseURL = parseURL; +/** + * Resolve TLS profile shortcut in connection options + * + * @param {Object} options - the redis connection options + * @return {Object} + */ +function resolveTLSProfile(options) { + let tls = options === null || options === void 0 ? void 0 : options.tls; + if (typeof tls === "string") + tls = { profile: tls }; + const profile = TLSProfiles_1.default[tls === null || tls === void 0 ? void 0 : tls.profile]; + if (profile) { + tls = Object.assign({}, profile, tls); + delete tls.profile; + options = Object.assign({}, options, { tls }); } - - if (options.complete === true) { - var signature = decodedToken.signature; - - return done(null, { - header: header, - payload: payload, - signature: signature - }); + return options; +} +exports.resolveTLSProfile = resolveTLSProfile; +/** + * 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 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'; + 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; +} +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; +} +exports.zipMap = zipMap; -function checkIsPublicKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return; - } - - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.type !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.asymmetricKeyType !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } -}; - -function checkIsPrivateKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - - if (typeof key === 'string') { - return; - } - if (typeof key === 'object') { - return; - } +/***/ }), - throw typeError(MSG_INVALID_SIGNER_KEY); -}; +/***/ 20961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function checkIsSecretKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - if (typeof key === 'string') { - return key; - } +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; - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_SECRET); - } - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_SECRET); - } +/***/ }), - if (key.type !== 'secret') { - throw typeError(MSG_INVALID_SECRET); - } +/***/ 1427: +/***/ ((module, exports, __nccwpck_require__) => { - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_SECRET); - } -} +/* eslint-env browser */ -function fromBase64(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} +/** + * This is the web browser implementation of `debug()`. + */ -function toBase64(base64url) { - base64url = base64url.toString(); +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; - var padding = 4 - base64url.length % 4; - if (padding !== 4) { - for (var i = 0; i < padding; ++i) { - base64url += '='; - } - } + 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`.'); + } + }; +})(); - return base64url - .replace(/\-/g, '+') - .replace(/_/g, '/'); -} +/** + * Colors. + */ -function typeError(template) { - var args = [].slice.call(arguments, 1); - var errMsg = util.format.bind(util, template).apply(null, args); - return new TypeError(errMsg); -} +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' +]; -function bufferOrString(obj) { - return Buffer.isBuffer(obj) || typeof obj === 'string'; -} +/** + * 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 normalizeInput(thing) { - if (!bufferOrString(thing)) - thing = JSON.stringify(thing); - return thing; -} +// 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; + } -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); - } -} + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } -function createHmacVerifier(bits) { - return function verify(thing, signature, secret) { - var computedSig = createHmacSigner(bits)(thing, secret); - return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); - } + // 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+)/)); } -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); - } -} +/** + * Colorize log arguments if enabled. + * + * @api public + */ -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 formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); -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); - } -} + if (!this.useColors) { + return; + } -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'); - } -} + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); -function createECDSASigner(bits) { - var inner = createKeySigner(bits); - return function sign() { - var signature = inner.apply(null, arguments); - signature = formatEcdsa.derToJose(signature, 'ES' + bits); - return signature; - }; -} + // 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; + } + }); -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; - }; + args.splice(lastC, 0, c); } -function createNoneSigner() { - return function sign() { - return ''; - } -} +/** + * 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 || (() => {}); -function createNoneVerifier() { - return function verify(thing, signature) { - return signature === ''; - } +/** + * 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? + } } -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]; +/** + * 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? + } - return { - sign: signerFactories[algo](bits), - verify: verifierFactories[algo](bits), - } -}; + // 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; +} -/***/ }), +/** + * 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 + */ -/***/ 4636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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? + } +} -/*global exports*/ -var SignStream = __nccwpck_require__(73334); -var VerifyStream = __nccwpck_require__(5522); +module.exports = __nccwpck_require__(14243)(exports); -var ALGORITHMS = [ - 'HS256', 'HS384', 'HS512', - 'RS256', 'RS384', 'RS512', - 'PS256', 'PS384', 'PS512', - 'ES256', 'ES384', 'ES512' -]; +const {formatters} = module.exports; -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); +/** + * 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; + } }; /***/ }), -/***/ 61868: +/***/ 14243: /***/ ((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; - } - - // Stream - if (typeof data.pipe === 'function') { - this.buffer = Buffer.alloc(0); - data.pipe(this); - return this; - } - - // 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; - } - - 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; -}; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ -module.exports = DataStream; +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__(92256); + createDebug.destroy = destroy; + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); -/***/ }), + /** + * The currently active debug mode names, and names to skip. + */ -/***/ 73334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + createDebug.names = []; + createDebug.skips = []; -/*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); + /** + * 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 = {}; -function base64url(string, encoding) { - return Buffer - .from(string, encoding) - .toString('base64') - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string 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; -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); -} + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -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); -} + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; -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)); + /** + * 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; - this.payload.once('close', function () { - if (!this.secret.writable && this.readable) - this.sign(); - }.bind(this)); -} -util.inherits(SignStream, Stream); + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } -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'); - } -}; + const self = debug; -SignStream.sign = jwsSign; + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -module.exports = SignStream; + 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); -/***/ 65292: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -/*global module*/ -var Buffer = __nccwpck_require__(64293).Buffer; + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -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); -}; + 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. -/***/ }), + 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); + } -/***/ 5522: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); -/*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\-_]+)?$/; + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } -function isObject(thing) { - return Object.prototype.toString.call(thing) === '[object Object]'; -} + return debug; + } -function safeJsonParse(thing) { - if (isObject(thing)) - return thing; - try { return JSON.parse(thing); } - catch (e) { return undefined; } -} + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -function headerFromJWS(jwsSig) { - var encodedHeader = jwsSig.split('.', 1)[0]; - return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); -} + /** + * 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; -function securedInputFromJWS(jwsSig) { - return jwsSig.split('.', 2).join('.'); -} + createDebug.names = []; + createDebug.skips = []; -function signatureFromJWS(jwsSig) { - return jwsSig.split('.')[2]; -} + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -function payloadFromJWS(jwsSig, encoding) { - encoding = encoding || 'utf8'; - var payload = jwsSig.split('.')[1]; - return Buffer.from(payload, 'base64').toString(encoding); -} + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -function isValidJws(string) { - return JWS_REGEX.test(string) && !!headerFromJWS(string); -} + namespaces = split[i].replace(/\*/g, '.*?'); -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); -} + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -function jwsDecode(jwsSig, opts) { - opts = opts || {}; - jwsSig = toString(jwsSig); + /** + * 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; + } - if (!isValidJws(jwsSig)) - return null; + /** + * 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; + } - var header = headerFromJWS(jwsSig); + let i; + let len; - if (!header) - return null; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - return { - header: header, - payload: payload, - signature: signatureFromJWS(jwsSig) - }; -} + return false; + } -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)); + /** + * 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.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'); - } -}; + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -VerifyStream.decode = jwsDecode; -VerifyStream.isValid = isValidJws; -VerifyStream.verify = jwsVerify; + /** + * 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`.'); + } -module.exports = VerifyStream; + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; /***/ }), -/***/ 75978: +/***/ 36215: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ -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); +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(1427); +} else { + module.exports = __nccwpck_require__(13952); +} -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)); -}; +/***/ 13952: +/***/ ((module, exports, __nccwpck_require__) => { -const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); +/** + * Module dependencies. + */ -module.exports = loadJsonFile; -module.exports.default = loadJsonFile; -module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); +/** + * This is the Node.js implementation of `debug()`. + */ -/***/ }), +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`.' +); -/***/ 70760: -/***/ ((module) => { +/** + * Colors. + */ -"use strict"; +exports.colors = [6, 2, 3, 4, 5, 1]; +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); -module.exports = clone + 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. +} -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) +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(); + }); - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + // 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); + } - return copy -} + obj[prop] = val; + return obj; +}, {}); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ -/***/ }), +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} -/***/ 18962: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -var fs = __nccwpck_require__(35747) -var polyfills = __nccwpck_require__(11566) -var legacy = __nccwpck_require__(21357) -var clone = __nccwpck_require__(70760) +function formatArgs(args) { + const {namespace: name, useColors} = this; -var queue = [] + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; -var util = __nccwpck_require__(31669) + 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]; + } +} -function noop () {} +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} -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) - } +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ -if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(queue) - __nccwpck_require__(42357).equal(queue.length, 0) - }) +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); } -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +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; + } } -// 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() +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - if (typeof cb === 'function') - cb.apply(this, arguments) - }) -}})(fs.close) +function load() { + return process.env.DEBUG; +} -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) +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -// 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; -} +function init(debug) { + debug.inspectOpts = {}; -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 + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - return go$readFile(path, options, cb) +module.exports = __nccwpck_require__(14243)(exports); - 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() - } - }) - } - } +const {formatters} = module.exports; - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/** + * Map %o to `util.inspect()`, all on a single line. + */ - return go$writeFile(path, data, options, cb) +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; - 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() - } - }) - } - } +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ - 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 +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - return go$appendFile(path, data, options, cb) - 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() - } - }) - } - } +/***/ }), - 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) +/***/ 92256: +/***/ ((module) => { - return go$readdir(args) +/** + * Helpers. + */ - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) +/** + * 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 + */ - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - } +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) + ); +}; - function go$readdir (args) { - return fs$readdir.apply(fs, args) +/** + * Parse the given `str` and return milliseconds. + * + * @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|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; } +} - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; } - - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; } - - fs.ReadStream = ReadStream - fs.WriteStream = WriteStream - - 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 (msAbs >= m) { + return Math.round(ms / m) + 'm'; } - - 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() - } - }) + if (msAbs >= s) { + return Math.round(ms / s) + 's'; } + return ms + 'ms'; +} - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); } - - function createReadStream (path, options) { - return new ReadStream(path, options) + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); } - - function createWriteStream (path, options) { - return new WriteStream(path, options) + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); } - - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - - return go$open(path, flags, mode, cb) - - function go$open (path, flags, mode, cb) { - 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() - } - }) - } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); } - - return fs + return ms + ' ms'; } -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - queue.push(elem) -} +/** + * Pluralization helper. + */ -function retry () { - var elem = queue.shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } /***/ }), -/***/ 21357: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 37263: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { -var Stream = __nccwpck_require__(92413).Stream +/* module decorator */ module = __nccwpck_require__.nmd(module); +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; -module.exports = legacy + ipaddr = {}; -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } + root = this; - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); + if (( true && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } - Stream.call(this); + 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; + }; - var self = this; + 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; + }; - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; + 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; + } - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + IPv4.prototype.kind = function() { + return 'ipv4'; + }; - options = options || {}; + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; - // 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]; - } + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; - if (this.encoding) this.setEncoding(this.encoding); + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; - if (this.start > this.end) { - throw new Error('start must be <= end'); - } + 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]] + }; - this.pos = this.start; - } + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; + 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; + }; - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } - - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; + return IPv4; - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + })(); - options = options || {}; + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; - // 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]; - } + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); + 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 (this.start < 0) { - throw new Error('start must be >= zero'); + }; + 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"); } - - this.pos = this.start; + 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.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); + 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; + } } - } -} - -/***/ }), - -/***/ 11566: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + IPv6.prototype.kind = function() { + return 'ipv6'; + }; -var constants = __nccwpck_require__(27619) + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; -var origCwd = process.cwd -var cwd = 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); + }; -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + 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; + }; -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} + 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; + }; -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} + 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; + }; -module.exports = patch + 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); + }; -function patch (fs) { - // (re-)implement some things that are known busted or missing. + 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]] + }; - // 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) - } + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; - // 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. + 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]); + }; - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + 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; + }; - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + return IPv6; - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + })(); - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + ipv6Part = "(?:[0-9a-f]+::?)+"; - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + zoneIndex = "%[0-9a-z]{1,}"; - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + 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') + }; - // 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) + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); } - 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; - } - if (cb) cb(er) - }) - }})(fs.rename) - } + 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 + }; + }; - // 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) + 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; + } } - callback_.apply(this, arguments) + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; } } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - }})(fs.read) + return null; + }; - 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 - } + 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; } - }})(fs.readSync) + }; - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) + 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; } + }; - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + 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; + } + }; - // 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 + 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); + }; - 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) - }) - }) - }) - } + 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); + }; - 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) + 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 ret + }); + return parsed; } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} + 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); + }; - 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) - }) + 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'); } - } + }; - 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 + 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); + }; - 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) - }) + 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"); } - } + }; - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); } } - } - - - 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) - }) - } - } + }; - 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; + 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"); } - } - - // 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 + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; } + }; - return false - } -} +}).call(this); /***/ }), -/***/ 81680: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 7604: +/***/ ((module) => { -const errorEx = __nccwpck_require__(23505); -const fallback = __nccwpck_require__(55586); -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s') -}); -module.exports = (input, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; +module.exports = function isArrayish(obj) { + if (!obj) { + return false; } - try { - try { - return JSON.parse(input, reviver); - } catch (err) { - fallback(input, reviver); - - throw err; - } - } catch (err) { - err.message = err.message.replace(/\n/g, ''); - - const jsonErr = new JSONError(err); - if (filename) { - jsonErr.fileName = filename; - } - - throw jsonErr; - } + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); }; /***/ }), -/***/ 11289: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * 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; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * 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) - : []; +/***/ 31310: +/***/ (function(module, exports) { - var length = result.length, - skipIndexes = !!length; +;(function(root) { + 'use strict'; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); + function isBase64(v, opts) { + if (v instanceof Boolean || typeof v === 'boolean') { + return false } - } - return result; -} - -/** - * 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; - } -} - -/** - * 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 = []; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); + if (!(opts instanceof Object)) { + opts = {} } - } - 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]; + if (opts.allowEmpty === false && v === '') { + return false } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} - -/** - * 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 = {}); - var index = -1, - length = props.length; + 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,)' - while (++index < length) { - var key = props[index]; + if (opts.mimeRequired === true) { + regex = mimeRegex + regex + } else if (opts.allowMime === true) { + regex = mimeRegex + '?' + regex + } - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + if (opts.paddingRequired === false) { + regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' + } - assignValue(object, key, newValue === undefined ? source[key] : newValue); + return (new RegExp('^' + regex + '$', 'gi')).test(v) } - return object; -} -/** - * 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; + if (true) { + if ( true && module.exports) { + exports = module.exports = isBase64 + } + exports.isBase64 = isBase64 + } else {} +})(this); - 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; - }); -} +/***/ }), -/** - * 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); -} +/***/ 56873: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * 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; -} -/** - * 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; -} +var has = __nccwpck_require__(76339); -/** - * 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 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('.'); -/** - * 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); + 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 === '>='; } -/** - * 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); +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; } -/** - * 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; +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } -/** - * 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); -} + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node && process.versions.node + : nodeVersion; -/** - * 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); -} + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } -/** - * 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; + 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); } -/** - * 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 data = __nccwpck_require__(66151); -/** - * 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'); -} +module.exports = function isCore(x, nodeVersion) { + return has(data, x) && versionIncluded(nodeVersion, data[x]); +}; -/** - * 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'; -} -/** - * 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); -}); +/***/ }), -/** - * 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); -}); +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { -/** - * 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; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/*! + * is-plain-object * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; } -module.exports = defaults; +function isPlainObject(o) { + var ctor,prot; + if (isObject(o) === false) return false; -/***/ }), + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; -/***/ 48919: -/***/ ((module) => { + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + // Most likely a plain Object + return true; +} -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +exports.isPlainObject = isPlainObject; -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; -/** 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')(); +/***/ 87783: +/***/ ((__unused_webpack_module, exports) => { -/** - * 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; +(function(exports) { + "use strict"; - while (++index < length) { - array[offset + index] = values[index]; + function isArray(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Array]"; + } else { + return false; + } } - return array; -} -/** Used for built-in method references. */ -var objectProto = Object.prototype; + function isObject(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } else { + return false; + } + } -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + function strictDeepEqual(first, second) { + // Check the scalar case first. + if (first === second) { + return true; + } + + // 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 + + // 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; + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + 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; + } -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + var trimLeft; + if (typeof String.prototype.trimLeft === "function") { + trimLeft = function(str) { + return str.trimLeft(); + }; + } else { + trimLeft = function(str) { + return str.match(/^\s*(.*)/)[1]; + }; + } -/** - * 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; + // 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; - predicate || (predicate = isFlattenable); - result || (result = []); + 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"; - 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; -} + // The "&", "[", "<", ">" tokens + // are not in basicToken because + // there are two token variants + // ("&&", "[?", "<=", ">="). This is specially handled + // below. -/** - * 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]); -} + var basicTokens = { + ".": TOK_DOT, + "*": TOK_STAR, + ",": TOK_COMMA, + ":": TOK_COLON, + "{": TOK_LBRACE, + "}": TOK_RBRACE, + "]": TOK_RBRACKET, + "(": TOK_LPAREN, + ")": TOK_RPAREN, + "@": TOK_CURRENT + }; -/** - * 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) : []; -} + var operatorStartToken = { + "<": true, + ">": true, + "=": true, + "!": true + }; -/** - * 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); -} + var skipChars = { + " ": true, + "\t": true, + "\n": true + }; -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; -/** - * 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); -} + function isAlpha(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_"; + } -/** - * 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 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 === "_"; + } -/** - * 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; -} + 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; + }, -/** - * 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; -} + _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); + }, -/** - * 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'); -} + _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)); + }, -/** - * 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'; -} + _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("\\'", "'"); + }, -module.exports = flatten; + _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}; + }, + _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}; + } + } + }, -/***/ 17931: -/***/ ((module) => { + _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; + }, -/** - * 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 - */ + _looksLikeJSON: function(literalString) { + var startingChars = "[{\""; + var jsonLiterals = ["true", "false", "null"]; + var numberLooking = "-0123456789"; -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + 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#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - stringTag = '[object String]', - symbolTag = '[object Symbol]'; + 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; -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; + function Parser() { + } -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + 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; + }, -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + _loadTokens: function(expression) { + var lexer = new Lexer(); + var tokens = lexer.tokenize(expression); + tokens.push({type: TOK_EOF, value: "", start: expression.length}); + this.tokens = tokens; + }, -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; + 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; + }, -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; + _lookahead: function(number) { + return this.tokens[this.index + number].type; + }, -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + _lookaheadToken: function(number) { + return this.tokens[this.index + number]; + }, -/** - * 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); + _advance: function() { + this.index++; + }, - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} + 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); + } + }, -/** - * 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); + 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)); + } + }, - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} + _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; + } + }, -/** - * 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; + _errorToken: function(token) { + var error = new Error("Invalid token (" + + token.type + "): \"" + + token.value + "\""); + error.name = "ParserError"; + throw error; + }, - while (++index < length) { - if (array[index] === value) { - return index; - } - } - 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; -} + _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 + }; + }, + + _parseComparator: function(left, comparator) { + var right = this.expression(bindingPower[comparator]); + return {type: "Comparator", name: comparator, children: [left, right]}; + }, -/** - * 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); + _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(); + } + }, - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} + _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; + }, -/** - * 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]; - }); -} + _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}; + }, -/** - * 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)); + _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}; + } }; -} -/** Used for built-in method references. */ -var objectProto = Object.prototype; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + function TreeInterpreter(runtime) { + this.runtime = runtime; + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + TreeInterpreter.prototype = { + search: function(node, value) { + return this.visit(node, value); + }, -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; + 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); -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max; + 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); + } + }, -/** - * 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) - : []; + 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; - var length = result.length, - skipIndexes = !!length; + if (start === null) { + start = stepValueNegative ? arrayLength - 1 : 0; + } else { + start = this.capSliceRange(arrayLength, start, step); + } - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; -} + 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; + }, -/** - * 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); - } + 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}] + } + }; } - 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); -} + 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); + }, -/** - * 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; + _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."); + } + } + }, - return value === proto; -} + _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; + } + } + }, -/** - * 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; + _functionStartsWith: function(resolvedArgs) { + return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 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); -} + _functionEndsWith: function(resolvedArgs) { + var searchStr = resolvedArgs[0]; + var suffix = resolvedArgs[1]; + return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -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); -} + _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; + } + }, -/** - * 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; + _functionAbs: function(resolvedArgs) { + return Math.abs(resolvedArgs[0]); + }, -/** - * 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); -} + _functionCeil: function(resolvedArgs) { + return Math.ceil(resolvedArgs[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); -} + _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; + }, -/** - * 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; -} + _functionContains: function(resolvedArgs) { + return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; + }, -/** - * 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; -} + _functionFloor: function(resolvedArgs) { + return Math.floor(resolvedArgs[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'); -} + _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; + } + }, -/** - * 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'; -} + _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; + }, -/** - * 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); -} + _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; + }, + + _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; + } + }, + + _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; + } + }, -/** - * 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); -} + _functionSum: function(resolvedArgs) { + var sum = 0; + var listToSum = resolvedArgs[0]; + for (var i = 0; i < listToSum.length; i++) { + sum += listToSum[i]; + } + return sum; + }, -/** - * 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; -} + _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"; + } + }, -/** - * 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; + _functionKeys: function(resolvedArgs) { + return Object.keys(resolvedArgs[0]); + }, - return result === result ? (remainder ? result - remainder : result) : 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]]); + } + return values; + }, -/** - * 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); -} + _functionJoin: function(resolvedArgs) { + var joinChar = resolvedArgs[0]; + var listJoin = resolvedArgs[1]; + return listJoin.join(joinChar); + }, -/** - * 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); -} + _functionToArray: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { + return resolvedArgs[0]; + } else { + return [resolvedArgs[0]]; + } + }, -/** - * 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)) : []; -} + _functionToString: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { + return resolvedArgs[0]; + } else { + return JSON.stringify(resolvedArgs[0]); + } + }, -module.exports = includes; + _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; + }, + _functionNotNull: function(resolvedArgs) { + for (var i = 0; i < resolvedArgs.length; i++) { + if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { + return resolvedArgs[i]; + } + } + return null; + }, -/***/ }), + _functionSort: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + sortedArray.sort(); + return sortedArray; + }, -/***/ 16501: -/***/ ((module) => { + _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; + }, -/** - * 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 - */ + _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 maxRecord; + }, -/** `Object#toString` result references. */ -var boolTag = '[object Boolean]'; + _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; + }, -/** Used for built-in method references. */ -var objectProto = Object.prototype; + 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; + } -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + }; -/** - * 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); -} + function compile(stream) { + var parser = new Parser(); + var ast = parser.parse(stream); + return ast; + } -/** - * 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'; -} + function tokenize(stream) { + var lexer = new Lexer(); + return lexer.tokenize(stream); + } -module.exports = isBoolean; + 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); /***/ }), -/***/ 21441: -/***/ ((module) => { +/***/ 21917: +/***/ ((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 - */ -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +var yaml = __nccwpck_require__(40916); -/** 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; +module.exports = yaml; -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; +/***/ }), -/** Used for built-in method references. */ -var objectProto = Object.prototype; +/***/ 40916: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; -/** - * 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); -} -/** - * 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 loader = __nccwpck_require__(45190); +var dumper = __nccwpck_require__(73034); -/** - * 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); -} -/** - * 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; +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; } -/** - * 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; - return result === result ? (remainder ? result - remainder : result) : 0; -} +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); -/** - * 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); -} +// 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); -module.exports = isInteger; +// 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'); /***/ }), -/***/ 40298: +/***/ 59136: /***/ ((module) => { -/** - * 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 - */ -/** `Object#toString` result references. */ -var numberTag = '[object Number]'; -/** Used for built-in method references. */ -var objectProto = Object.prototype; -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === 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'; + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); } -/** - * 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); + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; } -module.exports = isNumber; +function extend(target, source) { + var index, length, key, sourceKeys; -/***/ }), + if (source) { + sourceKeys = Object.keys(source); -/***/ 25723: -/***/ ((module) => { + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } -/** - * 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 - */ + return target; +} -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; } + 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)); - }; + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString.call(Object); +/***/ }), -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +/***/ 73034: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} -/** - * 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); -} +/*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; /* } */ -module.exports = isPlainObject; +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' +]; -/***/ 25180: -/***/ ((module) => { +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; -/** - * 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 (map === null) return {}; -/** `Object#toString` result references. */ -var stringTag = '[object String]'; + result = {}; + keys = Object.keys(map); -/** Used for built-in method references. */ -var objectProto = Object.prototype; + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; -/** - * 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 (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } -/** - * 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'; -} + result[tag] = style; + } -/** - * 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); + return result; } -module.exports = isString; +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'); + } -/***/ 94499: -/***/ ((module) => { + return '\\' + handle + common.repeat('0', length - string.length) + string; +} -/** - * 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 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; -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + this.tag = null; + this.result = ''; -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; + this.duplicates = []; + this.usedDuplicates = null; +} -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +// 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; -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + 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; + } -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + if (line.length && line !== '\n') result += ind; -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; + result += line; + } -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; + return result; +} -/** Used for built-in method references. */ -var objectProto = Object.prototype; +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +function testImplicitResolving(state, str) { + var index, length, type; -/** - * 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); - } - if (n <= 1) { - func = undefined; + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + 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); + 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'); +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; } -/** - * 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'; +// 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); } -/** - * 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); +// [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; } -/** - * 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; +// 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))); } -/** - * 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; +// 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; +} - return result === result ? (remainder ? result - remainder : result) : 0; +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); } -/** - * 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; +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)); + + 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] !== ' ')); } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; + // 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; } - if (typeof value != 'string') { - return value === 0 ? value : +value; + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; } - 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); + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } -module.exports = once; +// 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); -/***/ }), + // 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); + } -/***/ 90250: -/***/ (function(module, exports, __nccwpck_require__) { + 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'); + } + }()); +} -/* 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() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '4.17.21'; - - /** 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; - - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** 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; - - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; - - /** 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; - - /** 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] - ]; +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - /** `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]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** 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); - - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + // 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 ? '' : '-'); - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); + return indentIndicator + chomp + '\n'; +} - /** Used to match leading whitespace. */ - var reTrimStart = /^\s+/; +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; +// 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; - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; + // 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; - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + // 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; + } - /** - * 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]/; + return result; +} - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; +// 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; - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** 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 host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; - - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - - /** 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('|') + ')'; - - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); + // 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 = ''; - /** - * 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'); - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** 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'); - - /** 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 + ']'); - - /** 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 ]/; - - /** 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' - ]; + // 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; + } - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; - - /** 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; - - /** 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; - - /** 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' - }; + // 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); + } - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; + return result.slice(1); // drop extra \n joiner +} - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; + 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; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + 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; + } + } - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + state.tag = _tag; + state.dump = '[' + _result + ']'; +} - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; - /** Detect free variable `exports`. */ - var freeExports = true && exports && !exports.nodeType && exports; + 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); + } - /** Detect free variable `module`. */ - var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + _result += state.dump; + } + } - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} - /** 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; +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; - if (types) { - return types; - } + for (index = 0, length = objectKeyList.length; index < length; index += 1) { - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; - /* 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 (state.condenseFlow) pairBuffer += '"'; - /*--------------------------------------------------------------------------*/ + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; - /** - * 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]); + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; } - 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 (state.dump.length > 1024) pairBuffer += '? '; - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. } - 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; + pairBuffer += state.dump; - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; + // Both key and value are valid. + _result += pairBuffer; } - /** - * 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; + state.tag = _tag; + state.dump = '{' + _result + '}'; +} - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; +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'); } - /** - * 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; + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); } - 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 = []; + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. } - 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; - } - - /** - * 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; + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); - while (++index < length) { - if (comparator(value, array[index])) { - return true; + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; } } - 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); + pairBuffer += state.dump; - while (++index < length) { - result[index] = iteratee(array[index], index, array); + if (explicitPair) { + pairBuffer += generateNextLine(state, level); } - 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 (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } - while (++index < length) { - array[offset + index] = values[index]; + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; } - return array; - } - /** - * 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; + pairBuffer += state.dump; - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; + // Both key and value are valid. + _result += pairBuffer; } - /** - * 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; - } + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +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 : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; - /** - * 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 (_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'); + } - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; + state.dump = _result; } + + return true; } - return false; } - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); + return false; +} - /** - * 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(''); - } +// 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; - /** - * 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 (!detectType(state, object, false)) { + detectType(state, object, true); } - /** - * 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; + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); } - /** - * 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); + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; } - /** - * 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 ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; } - /** - * 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; + 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; + } + } 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 { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); } - 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; + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } } - /** - * 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; - } + return true; +} - /** - * 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 getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; - /** - * 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]; - }; - } + inspectNode(object, objects, duplicatesIndexes); - /** - * 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; + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); } + state.usedDuplicates = new Array(length); +} - /** - * 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 inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } + 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); - /** - * 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; + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } } } - return result; } +} - /** - * 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; - } +function dump(input, options) { + options = options || {}; - /** - * 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]]; - }); - } + var state = new State(options); - /** - * 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; - } + if (!state.noRefs) getDuplicateReferences(input, state); - /** - * 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); - }; - } + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; - /** - * 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 ''; +} - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} - /** - * 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; +module.exports.dump = dump; +module.exports.safeDump = safeDump; - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - /** - * 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; +/***/ }), - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } +/***/ 65199: +/***/ ((module) => { - /** - * 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; +// YAML error class. http://stackoverflow.com/questions/8458984 +// - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - /** - * 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); +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); - /** - * 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); + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); - /** - * 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]; + // 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 || ''; } +} - /** - * 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]; - } - /** - * 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); - } +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; - /** - * 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 = []; +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); } - /** - * 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); + return result; +}; - 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)); - }; - } +module.exports = YAMLException; - /** - * 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 (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } +/***/ }), - /** - * 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); +/***/ 45190: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - /** - * 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); - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } +/*eslint-disable max-len,no-use-before-define*/ - /** - * 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; +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); - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - /** - * 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 _hasOwnProperty = Object.prototype.hasOwnProperty; - /** - * 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); - } - /** - * 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 CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; - /** - * 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; - } +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; - /** - * 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; - } +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; - /** - * 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) || []; - } +function _class(obj) { return Object.prototype.toString.call(obj); } - /*--------------------------------------------------------------------------*/ +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} - /** - * 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)); - - /** 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; - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to generate unique IDs. */ - var idCounter = 0; - - /** 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) : ''; - }()); +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; +function fromHexCode(c) { + var lc; - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } - /** 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; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** 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; - - /* 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; - - /* 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 = {}; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /*------------------------------------------------------------------------*/ + /*eslint-disable no-bitwise*/ + lc = c | 0x20; - /** - * 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); - } + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } - /** - * 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; - }; - }()); + return -1; +} - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} - /** - * 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; - } +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } - /** - * 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 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': { + 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' : ''; +} - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; +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 + ); +} - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; +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); +} - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - /*------------------------------------------------------------------------*/ +function State(input, options) { + this.input = input; - /** - * 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__ = []; - } + 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; - /** - * 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; - } + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; - /** - * 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; - } + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; - /** - * 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__); - - 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; - } + this.documents = []; - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ - /*------------------------------------------------------------------------*/ +} - /** - * 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; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} - /** - * 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; - } +function throwError(state, message) { + throw generateError(state, message); +} - /** - * 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; - } +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } +var directiveHandlers = { - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; + YAML: function handleYamlDirective(state, name, args) { - /*------------------------------------------------------------------------*/ + var match, major, minor; - /** - * 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; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); } - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); } - /** - * 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); + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - 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; + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); } - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); - /** - * 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; + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); } - /** - * 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); + state.version = args[0]; + state.checkLineBreaks = (minor < 2); - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); } + }, - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; + TAG: function handleTagDirective(state, name, args) { - /*------------------------------------------------------------------------*/ + var handle, prefix; - /** - * 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; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); } - /** - * 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 - }; - } + handle = args[0]; + prefix = args[1]; - /** - * 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; + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } - /** - * 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); + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } - /** - * 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); + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } - /** - * 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; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } + state.tagMap[handle] = prefix; + } +}; - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - /*------------------------------------------------------------------------*/ +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; - /** - * - * 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; + if (start < end) { + _result = state.input.slice(start, end); - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); + 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'); } - /** - * 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; - } + state.result += _result; + } +} - /** - * 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); - } +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } - /*------------------------------------------------------------------------*/ + sourceKeys = Object.keys(source); - /** - * 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; - } + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; } + } +} - /** - * 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); - - this.size = data.size; - return result; - } +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; - /** - * 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); - } + // 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); - /** - * 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); - } + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } - /** - * 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); + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; } - 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; + // 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]'; + } - /*------------------------------------------------------------------------*/ - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } + keyNode = String(keyNode); + + 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); } - return result; + } else { + mergeMappings(state, _result, valueNode, overridableKeys); } - - /** - * 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; + } 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]; + } - /** - * 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)); - } + return _result; +} - /** - * 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)); - } +function readLineBreak(state) { + var ch; - /** - * 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); - } - } + ch = state.input.charCodeAt(state.position); - /** - * 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); - } + 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'); + } - /** - * 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; - } + state.line += 1; + state.lineStart = state.position; +} - /** - * 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; - } +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); - /** - * 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); + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); } - /** - * 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); + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } - /** - * 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; - } - } + if (is_EOL(ch)) { + readLineBreak(state); - /** - * 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; - - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; - /** - * 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; - } + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - return number; + } else { + break; } + } - /** - * 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; - - 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; - - 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); + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } - 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)); - }); - } + return lineBreaks; +} - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); +function testDocumentSeparator(state) { + var _position = state.position, + ch; - 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; - } + ch = state.input.charCodeAt(_position); - /** - * 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); - }; - } + // 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)) { - /** - * 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]; + _position += 3; + + ch = state.input.charCodeAt(_position); - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } + if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } + } - /** - * 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); - } + return false; +} - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} - /** - * 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 `_.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); +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; - /** - * 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; - } + ch = state.input.charCodeAt(state.position); - /** - * 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; + 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; + } - while (++index < length) { - var value = array[index], - current = iteratee(value); + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; } + } - /** - * 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; + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; - 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; + 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; } - return array; - } - /** - * 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; - } + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } + if (is_WS_OR_EOL(preceding)) { + break; } - return result; - } - /** - * 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(); + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; - /** - * 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); + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); - /** - * 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); + 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; + } } - /** - * 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); + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; } - /** - * 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]); - }); + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; } - /** - * 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); + ch = state.input.charCodeAt(++state.position); + } - var index = 0, - length = path.length; + captureSegment(state, captureStart, captureEnd, false); - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } + if (state.result) { + return true; + } - /** - * 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)); - } + state.kind = _kind; + state.result = _result; + return false; +} - /** - * 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); - } +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; - /** - * 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; - } + ch = state.input.charCodeAt(state.position); - /** - * 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); - } + if (ch !== 0x27/* ' */) { + return false; + } - /** - * 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); - } + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - /** - * 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); - } + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - /** - * 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 = []; - - 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); - } + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; } - return result; - } - /** - * 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; - } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - /** - * 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); - } + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); - /** - * 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; + } else { + state.position++; + captureEnd = state.position; } + } - /** - * 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; - } + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} - /** - * 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; - } +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; - /** - * 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); - } + ch = state.input.charCodeAt(state.position); - /** - * 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); + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - 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 (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; - 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); - } + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; - /** - * 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; - } + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); - /** - * 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; + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; - 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]; - - 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; + } else { + throwError(state, 'expected hexadecimal character'); } } - } - return true; - } - /** - * 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; + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - /** - * 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; - } + captureStart = captureEnd = state.position; - /** - * 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; - } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - /** - * 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)]; - } + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); - /** - * 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); + } else { + state.position++; + captureEnd = state.position; } + } - /** - * 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; + 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'); } - /** - * 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 = []; + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } + 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); } - return result; } - /** - * 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; - } + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); - /** - * 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) : []; + ch = state.input.charCodeAt(state.position); - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; + 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; } - /** - * 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); - }; + 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); } - /** - * 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); - }; - } + skipSeparationSpace(state, true, nodeIndent); - /** - * 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; + ch = state.input.charCodeAt(state.position); - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; } + } - /** - * 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); + throwError(state, 'unexpected end of the stream within a flow collection'); +} - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; - var isCommon = newValue === undefined; + ch = state.input.charCodeAt(state.position); - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } - 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); - } + state.kind = 'scalar'; + state.result = ''; - /** - * 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; - } + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); - /** - * 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; - }); + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; } else { - iteratees = [identity]; + throwError(state, 'repeat of a chomping mode identifier'); } - 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 }; - }); + } 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'); + } - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); + } else { + break; } + } - /** - * 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); - }); + 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)); } + } - /** - * 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 = {}; + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); + ch = state.input.charCodeAt(state.position); - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - /** - * 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); - }; + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; } - /** - * 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; - - 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; + if (is_EOL(ch)) { + emptyLines++; + continue; } - /** - * 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); - } + // 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'; } } - 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)); + // Break this `while` cycle and go to the funciton's epilogue. + break; } - /** - * 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); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } + // Folded style: use fancy rules to handle line breaks. + if (folding) { - /** - * 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; + // 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 += ' '; } - } while (n); - return result; - } + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } - /** - * 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 + ''); + // 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); } - /** - * 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)); - } + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; - /** - * 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)); + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); } - /** - * 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); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; + captureSegment(state, captureStart, state.position, false); + } - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; + return true; +} - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; - 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; - } + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } - /** - * 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; - }; + ch = state.input.charCodeAt(state.position); - /** - * 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 - }); - }; + while (ch !== 0) { - /** - * 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)); + if (ch !== 0x2D/* - */) { + break; } - /** - * 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; + following = state.input.charCodeAt(state.position + 1); - 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; + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; } - return result; } - /** - * 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; + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } + ch = state.input.charCodeAt(state.position); - /** - * 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; - - 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); + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; } + } - /** - * 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; - } + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} - 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); - } +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; - /** - * 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 = []; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + 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 (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; } - } - return result; - } - /** - * 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; - } + detected = true; + atExplicitKey = true; + allowCompact = true; - /** - * 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; - } + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; - /** - * 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; - - 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); - } + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } - return result; - } - /** - * 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))]; - } + state.position += 1; + ch = following; - /** - * 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); - } + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - /** - * 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; + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); - /** - * 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); - } + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } - /** - * 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); + 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`. + } - while (++index < length) { - var array = arrays[index], - othIndex = -1; + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); + + } else { + break; // Reading is done. Go to the epilogue. } - /** - * 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 = {}; - - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); + // + // 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; + } } - 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 : []; - } + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } - /** - * 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; + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); } - /** - * 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)); + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; } + } - /** - * 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; - - /** - * 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); - } + // + // Epilogue. + // - /** - * 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); - }; + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } - /** - * 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); + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } - buffer.copy(result); - return result; - } + return detected; +} - /** - * 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; - } +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; - /** - * 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); - } + ch = state.input.charCodeAt(state.position); - /** - * 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; - } + if (ch !== 0x21/* ! */) return false; - /** - * 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)) : {}; - } + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } - /** - * 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); - } + ch = state.input.charCodeAt(++state.position); - /** - * 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); - - 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; - } + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); - /** - * 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; - - 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; - } + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); - /** - * 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; - - 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; - } + } else { + tagHandle = '!'; + } - /** - * 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; - - 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; - } + _position = state.position; - /** - * 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; + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; + 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)) { - /** - * 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 = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); + isNamed = true; + _position = state.position + 1; } else { - assignValue(object, key, newValue); + throwError(state, 'tag suffix cannot contain exclamation marks'); } } - return object; - } - /** - * 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); + ch = state.input.charCodeAt(++state.position); } - /** - * 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); + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); } + } - /** - * 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() : {}; + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } + if (isVerbatim) { + state.tag = tagName; - /** - * 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 object; - }); - } + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; - /** - * 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); + } else if (tagHandle === '!') { + state.tag = '!' + tagName; - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; - /** - * 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; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } - /** - * 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); + return true; +} - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } +function readAnchorProperty(state) { + var _position, + ch; - /** - * 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); + ch = state.input.charCodeAt(state.position); - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; + if (ch !== 0x26/* & */) return false; - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); + ch = state.input.charCodeAt(++state.position); + _position = state.position; - return chr[methodName]() + trailing; - }; - } + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } - /** - * 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, ''); - }; - } + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } - /** - * 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); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } + state.anchor = state.input.slice(_position, state.position); + return true; +} - /** - * 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 wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); - - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); - - 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 readAlias(state) { + var _position, alias, + ch; - /** - * 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; - }; - } + ch = state.input.charCodeAt(state.position); - /** - * 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; - - 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]; + if (ch !== 0x2A/* * */) return false; - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; + ch = state.input.charCodeAt(++state.position); + _position = state.position; - 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]; + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } + alias = state.input.slice(_position, state.position); - /** - * 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); - - 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; - - 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); - } - return wrapper; - } + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } - /** - * 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), {}); - }; - } + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} - /** - * 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; - }; - } +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 result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); } + } - /** - * 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; + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; } - return apply(fn, isBind ? thisArg : this, args); + } else { + allowBlockCollections = false; } - return wrapper; } + } - /** - * 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); - }; - } + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } - /** - * 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); - }; + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; } - /** - * 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; - - 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); - } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; + blockIndent = state.position - state.lineStart; - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } + 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; - /** - * 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)); - - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; - } + } else if (readAlias(state)) { + hasContent = true; - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } - /** - * 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); + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } } - if (tag == setTag) { - return setToPairs(object); + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; } - return baseToPairs(object, keysFunc(object)); - }; + } + } 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); } + } - /** - * 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; + 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 + '"'); } - 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; + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; - partials = holders = undefined; + 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; + } } - var data = isBindKey ? undefined : getData(func); - - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; - 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 (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 (!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); + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); } else { - result = createHybrid.apply(undefined, newData); + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); } + } - /** - * 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; - } - return objValue; - } + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} - /** - * 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); - } - return objValue; +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); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; } - /** - * 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; + 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); } - /** - * 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; + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - stack.set(array, other); - stack.set(other, array); + if (is_EOL(ch)) break; - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; + _position = state.position; - 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; - } + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); } - stack['delete'](array); - stack['delete'](other); - return result; + + directiveArgs.push(state.input.slice(_position, state.position)); } - /** - * 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; + if (ch !== 0) readLineBreak(state); - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } - 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); + skipSeparationSpace(state, true, -1); - case errorTag: - return object.name == other.name && object.message == other.message; + 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); - 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 + ''); + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } - case mapTag: - var convert = mapToArray; + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); + 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 (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; + state.documents.push(state.result); - // 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; + if (state.position === state.lineStart && testDocumentSeparator(state)) { - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); } + return; + } - /** - * 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; - - 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; + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} - // 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; - } - /** - * 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 + ''); - } +function loadDocuments(input, options) { + input = String(input); + options = options || {}; - /** - * 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); + 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'; } - /** - * 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); + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); } + } - /** - * 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); - }; + var state = new State(input, options); - /** - * 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; + var nullpos = input.indexOf('\0'); - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } - /** - * 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; - } + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; - /** - * 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; - } + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } - /** - * 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; - } + while (state.position < (state.length - 1)) { + readDocument(state); + } - /** - * 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; + return state.documents; +} - while (length--) { - var key = result[length], - value = object[key]; - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } - /** - * 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; - } + var documents = loadDocuments(input, options); - /** - * 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]; + if (typeof iterator !== 'function') { + return documents; + } - 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; - } + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} - /** - * 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; - }; +function load(input, options) { + var documents = loadDocuments(input, options); - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - 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; - }; - } + 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'); +} - /** - * 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; - while (++index < length) { - var data = transforms[index], - size = data.size; +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } - 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 }; - } + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} - /** - * 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) : []; - } - /** - * 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); +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} - 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)); - } +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - 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; - } - return result; - } - /** - * 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)) - : {}; - } +/***/ }), - /** - * 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); +/***/ 55426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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; +var common = __nccwpck_require__(59136); - case numberTag: - case stringTag: - return new Ctor(object); - case regexpTag: - return cloneRegExp(object); +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} - case setTag: - return new Ctor; - case symbolTag: - return cloneSymbol(object); - } - } +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; - /** - * 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'); - } + if (!this.buffer) return null; - /** - * 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]); - } + indent = indent || 4; + maxLength = maxLength || 75; - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; + head = ''; + start = this.position; - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); + 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; } + } - /** - * 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; - } + tail = ''; + end = this.position; - /** - * Checks if `value` is a property name and not a property path. - * - * @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)); + 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; } + } - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } + snippet = this.buffer.slice(start, end); - /** - * Checks if `func` has a lazy counterpart. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. - */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - 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); +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; } + } - /** - * 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; + return where; +}; - /** - * 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; - } +module.exports = Mark; - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @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 matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } +/***/ }), - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); +/***/ 66514: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var cache = result.cache; - return result; - } - /** - * 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. - * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ - 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; - } - // 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]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - return data; - } +/*eslint-disable max-len*/ - /** - * 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; - } +var common = __nccwpck_require__(59136); +var YAMLException = __nccwpck_require__(65199); +var Type = __nccwpck_require__(30967); - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); - } - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - 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 compileList(schema, name, result) { + var exclude = []; - /** - * Gets the parent value at `path` of `object`. - * - * @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 parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); - /** - * 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. - * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ - 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; + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); } - return array; - } + }); - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } + result.push(currentType); + }); - if (key == '__proto__') { - return; - } + return result.filter(function (type, index) { + return exclude.indexOf(index) === -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. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var setData = shortOut(baseSetData); +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). - * - * @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. - */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} - /** - * 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. - * - * @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`. - */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - 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); - }; - } +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; - /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. - * - * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. - */ - 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; - } - array.length = size; - return array; + 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.'); } + }); - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - 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; - }); + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} - /** - * 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 `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } +Schema.DEFAULT = null; - /** - * Updates wrapper `details` based on `bitmask` flags. - * - * @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`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - 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; - } +Schema.create = function createSchema() { + var schemas, types; - /*------------------------------------------------------------------------*/ + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; - /** - * 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)); + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; - } + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } - /** - * 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 - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + schemas = common.toArray(schemas); + types = common.toArray(types); - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; - } + 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.'); + } - /** - * 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]] - * - * console.log(array); - * // => [1] - */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; + 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.'); + } - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } + return new Schema({ + include: schemas, + explicit: types + }); +}; - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - /** - * 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)) - : []; - }); +module.exports = Schema; - /** - * 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); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ - 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 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); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ - 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); - } +/***/ 92183: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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'] - * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; - } +// 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. - /** - * 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'] - * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; - } - /** - * 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] - * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] - */ - 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 `_.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 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ - 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); - } - /** - * 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 - * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 - */ - 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); - } - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } +var Schema = __nccwpck_require__(66514); - /** - * 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 - * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - /** - * 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]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] - * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } +module.exports = new Schema({ + include: [ + __nccwpck_require__(1571) + ] +}); - /** - * 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 - * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ - 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 first element of `array`. - * - * @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 - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } +/***/ }), - /** - * 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 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ - 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); - } +/***/ 56874: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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 - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } +// 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. - /** - * 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 - * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); - /** - * 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 `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); - /** - * 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 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - 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) - : []; - }); +var Schema = __nccwpck_require__(66514); - /** - * 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 - * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); - } - /** - * 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 - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } +module.exports = Schema.DEFAULT = new Schema({ + include: [ + __nccwpck_require__(48949) + ], + explicit: [ + __nccwpck_require__(25914), + __nccwpck_require__(69242), + __nccwpck_require__(27278) + ] +}); + + +/***/ }), + +/***/ 48949: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// 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/) + - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @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=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 - */ - 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); - } - /** - * 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; - } - /** - * 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']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); - /** - * 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']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; - } +var Schema = __nccwpck_require__(66514); - /** - * 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 - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; - } - /** - * 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 - * @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. - * @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; - } +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) + ] +}); - /** - * 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'] - * - * console.log(pulled); - * // => ['b', 'd'] - */ - 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; - }); +/***/ 66037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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] - * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); - } - } - 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 - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - /** - * 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. - * - * @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 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 - * - * _.sortedIndex([30, 50], 40); - * // => 1 - */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); - } - /** - * 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 `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 - */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); - } +var Schema = __nccwpck_require__(66514); - /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @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 - * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ - 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; - } - /** - * 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 - * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 - */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); - } +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(52672), + __nccwpck_require__(5490), + __nccwpck_require__(31173) + ] +}); - /** - * 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 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 - * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 - */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); - } - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @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 - * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ - 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 `_.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 - * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } +/***/ 1571: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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 - * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; - } +// 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. - /** - * 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 - * - * _.tail([1, 2, 3]); - * // => [2, 3] - */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - /** - * 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] - * - * _.take([1, 2, 3], 0); - * // => [] - */ - 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); - } - /** - * 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] - * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ - 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); - } - /** - * 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 `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] - */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; - } - /** - * 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'] - * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] - */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; - } +var Schema = __nccwpck_require__(66514); - /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - /** - * 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 `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); +module.exports = new Schema({ + include: [ + __nccwpck_require__(66037) + ], + implicit: [ + __nccwpck_require__(22671), + __nccwpck_require__(94675), + __nccwpck_require__(89963), + __nccwpck_require__(15564) + ] +}); - /** - * 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); - }); - /** - * 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 - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; - } +/***/ }), - /** - * 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 `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; - } +/***/ 30967: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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 }]; - * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; - } - /** - * 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 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 - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ - 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)); - }); - } - /** - * 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]] - * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ - 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); - }); - } +var YAMLException = __nccwpck_require__(65199); - /** - * 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 - * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] - */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; - /** - * 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 - * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] - */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; - /** - * 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 `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); +function compileStyleAliases(map) { + var result = {}; - /** - * 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 }]; - * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); }); + } - /** - * 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 - * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ - var zip = baseRest(unzip); + return result; +} - /** - * 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 - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); - } +function Type(tag, options) { + options = options || {}; - /** - * 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 - * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } - */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); + 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.'); } + }); - /** - * 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 - * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] - */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; + // 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); - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} - /*------------------------------------------------------------------------*/ +module.exports = Type; - /** - * 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 - * - * 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 chain(value) { - var result = lodash(value); - result.__chain__ = true; - 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 - * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor) { - interceptor(value); - return value; - } +/***/ }), - /** - * 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 - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor) { - return interceptor(value); - } +/***/ 32551: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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] }; - * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] - */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; - - 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); - } - 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 } - * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - /** - * 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 - * - * console.log(array); - * // => [1, 2, 3] - */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } +/*eslint-disable no-bitwise*/ - /** - * 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 } - * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } - */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; +var NodeBuffer; - return { 'done': done, 'value': value }; - } +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} - /** - * 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 - * - * Array.from(wrapped); - * // => [1, 2] - */ - function wrapperToIterator() { - return this; - } +var Type = __nccwpck_require__(30967); + + +// [ 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; - /** - * 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; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ - function wrapperPlant(value) { - var result, - parent = this; - - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; - } - previous.__wrapped__ = value; - return result; - } + // Fail on illegal characters + if (code < 0) return false; - /** - * 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] - * - * console.log(array); - * // => [3, 2, 1] - */ - 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); - } + bitlen += 6; + } - /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} - /*------------------------------------------------------------------------*/ +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 = []; - /** - * 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 `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); - } - }); + // Collect by 6*4 bits (3 bytes) - /** - * 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. - * - * @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 all elements pass 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)); + 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); } - /** - * 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'] - * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] - */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } - /** - * 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 `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); + // Dump tail - /** - * 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 - * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ - var findLast = createFind(findLastIndex); + tailbits = (max % 4) * 6; - /** - * 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]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); - } + 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); + } - /** - * 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]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); - } + // 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); + } - /** - * 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]]]; - * } - * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] - */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); - } + 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`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); - } +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; - /** - * 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 - * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. - */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); + // 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]; } - /** - * 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 - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } - }); + bits = (bits << 8) + object[idx]; + } - /** - * 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; + // Dump tail - 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); - } + tail = max % 3; - /** - * 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]] - * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; + 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]; + } - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result; - }); + 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 } } - * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} - /** - * 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' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); - } +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); - /** - * 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 } - * ]; - * - * // 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]] - */ - 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]; - } - return baseOrderBy(collection, iteratees, orders); - } - /** - * 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']] - * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); +/***/ }), - /** - * 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 - * - * _.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) - */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; +/***/ 94675: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); - } - /** - * 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 - * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); - } +var Type = __nccwpck_require__(30967); - /** - * 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 } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } +function resolveYamlBoolean(data) { + if (data === null) return false; - /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } + var max = data.length; - /** - * 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 - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] - * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] - */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); - } + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} - /** - * 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 - * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} - /** - * 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 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} - /** - * 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 - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } +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' +}); - /** - * 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]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] - */ - 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), []); - }); - /*------------------------------------------------------------------------*/ +/***/ }), - /** - * 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(); - }; +/***/ 15564: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /*------------------------------------------------------------------------*/ - /** - * 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!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. - */ - 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); - } - }; - } - /** - * 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 - * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ - 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); - } +var common = __nccwpck_require__(59136); +var Type = __nccwpck_require__(30967); - /** - * 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); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } +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))$'); - /** - * 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!' - * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - 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 resolveYamlFloat(data) { + if (data === null) return false; - /** - * 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!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' - * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ - 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; - } - return createWrap(key, bitmask, object, partials, holders); - }); + 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; + } - /** - * 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] - * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ - 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; - } + return true; +} - /** - * 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] - * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ - 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 constructYamlFloat(data) { + var value, sign, base, digits; - /** - * 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); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - 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; - } + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - 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; - } + } else if (value === '.nan') { + return NaN; - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } + value = 0.0; + base = 1; - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); - // 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)); - } + return sign * value; - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } + } + return sign * parseFloat(value, 10); +} - function trailingEdge(time) { - timerId = undefined; - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; - return result; - } +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } +function representYamlFloat(object, style) { + var res; - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } + 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'; + } - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); + res = object.toString(10); - lastArgs = arguments; - lastThis = this; - lastCallTime = time; + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack - 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); - } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} - /** - * 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); - }); +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} - /** - * 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); - }); +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); - /** - * 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); - * }); - * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] - */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - /** - * 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'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - 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); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } +/***/ 89963: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - 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); - }; - } - /** - * 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); - } +var common = __nccwpck_require__(59136); +var Type = __nccwpck_require__(30967); - /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @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] - */ - 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 isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} - /** - * 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); - }); +function resolveYamlInteger(data) { + if (data === null) return false; - /** - * 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' - * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); + var max = data.length, + index = 0, + hasDigits = false, + ch; - /** - * 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]); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); + if (!max) return false; - /** - * 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); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); - } + ch = data[index]; - /** - * 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) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ - 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); + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); - } + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; - /** - * 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)); - * - * // 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); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; + // base 2, base 8, base 16 - if (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; - } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); - } + if (ch === 'b') { + // base 2 + index++; - /** - * 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 - * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ - function unary(func) { - return ary(func, 1); + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - /** - * 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) + '

'; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' - */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - /*------------------------------------------------------------------------*/ + if (ch === 'x') { + // base 16 + index++; - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @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(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ - function castArray() { - if (!arguments.length) { - return []; + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; } - var value = arguments[0]; - return isArray(value) ? value : [value]; + return hasDigits && ch !== '_'; } - /** - * 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 - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; } + return hasDigits && ch !== '_'; + } - /** - * 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); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 - */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } + // base 10 (except 0) or base 60 - /** - * 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); - } + // value should not start with `_`; + if (ch === '_') return false; - /** - * 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); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 - */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; } + hasDigits = true; + } - /** - * 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 - * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false - */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); - } + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } + // if !base60 - done; + if (ch !== ':') return true; - /** - * 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 - * - * _.gt(1, 3); - * // => false - */ - var gt = createRelationalOperation(baseGt); + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} - /** - * 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 - * - * _.gte(1, 3); - * // => false - */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } - /** - * 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; + ch = value[0]; - /** - * 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 - * - * _.isArrayBuffer(new Array(2)); - * // => false - */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } - /** - * 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); - } + if (value === '0') return 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); - } + 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); + } - /** - * 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 - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); - } + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; + value = 0; + base = 1; - /** - * 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 - * - * _.isDate('Mon April 23 2012'); - * // => false - */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); - /** - * 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 - * - * _.isElement(''); - * // => false - */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } + return sign * value; - /** - * 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 - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ - 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; - } - } - return true; - } + } - /** - * 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 - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} - /** - * 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']; - * - * _.isEqualWith(array, other, customizer); - * // => true - */ - 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; - } +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' ] + } +}); - /** - * 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 - * - * _.isError(Error); - * // => false - */ - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); - } - /** - * 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 - * - * _.isFinite('3'); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(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) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } +/***/ 27278: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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); - } - /** - * 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; - } - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } +var esprima; - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } +// 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; +} - /** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @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 - */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; +var Type = __nccwpck_require__(30967); - /** - * 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 - * - * _.isMatch(object, { 'b': 1 }); - * // => false - */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } +function resolveJavascriptFunction(data) { + if (data === null) return false; - /** - * 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' }; - * - * _.isMatchWith(object, source, customizer); - * // => true - */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); - } + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); - /** - * 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. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @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 - */ - 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; + 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; } - /** - * 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. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @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 - */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } + return true; + } catch (err) { + return false; + } +} - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } +function constructJavascriptFunction(data) { + /*jslint evil:true*/ - /** - * 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 - * - * _.isNil(NaN); - * // => false - */ - function isNil(value) { - return value == null; - } + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; - /** - * 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 - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } + 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'); + } - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - 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; - } + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); - /** - * 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 - * - * _.isRegExp('/abc/'); - * // => false - */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + body = ast.body[0].expression.body.range; - /** - * 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 - * - * _.isSafeInteger('3'); - * // => false - */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } + // 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])); +} - /** - * 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 - * - * _.isSet(new WeakSet); - * // => false - */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} - /** - * 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); - } +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} - /** - * 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) && baseGetTag(value) == symbolTag); - } +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - /** - * 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 - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } +/***/ }), - /** - * 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 - * - * _.isWeakMap(new WeakMap); - * // => true - * - * _.isWeakMap(new Map); - * // => false - */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } +/***/ 69242: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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 - * - * _.isWeakSet(new Set); - * // => false - */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - /** - * 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 - * - * _.lt(3, 1); - * // => false - */ - var lt = createRelationalOperation(baseLt); - /** - * 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 - * - * _.lte(3, 1); - * // => false - */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); +var Type = __nccwpck_require__(30967); - /** - * 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); - * // => [] - * - * _.toArray(null); - * // => [] - */ - 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 resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; - return func(value); - } + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; - /** - * 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; - } + // 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]; - /** - * 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 (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } - return result === result ? (remainder ? result - remainder : result) : 0; - } + return true; +} - /** - * 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 - * - * _.toLength('3.2'); - * // => 3 - */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; - /** - * 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 = baseTrim(value); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); - } + // `/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); + } - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } + return new RegExp(regexp, modifiers); +} - /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 - */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - } +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; - /*------------------------------------------------------------------------*/ + return result; +} - /** - * 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. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @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 - * @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 } - */ - 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]); - } - } - }); +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} - /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @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 - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } - */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); - /** - * 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); - }); - /** - * 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`. - * - * @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 - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); +/***/ }), + +/***/ 25914: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Creates an array of values corresponding to `paths` of `object`. - * - * @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. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] - */ - var at = flatRest(baseAt); - /** - * 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. - * - * @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. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); - } - /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var defaults = baseRest(function(object, sources) { - object = Object(object); +var Type = __nccwpck_require__(30967); - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; +function resolveJavascriptUndefined() { + return true; +} - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; +function representJavascriptUndefined() { + return ''; +} - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; +function isUndefined(object) { + return typeof object === 'undefined'; +} - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } - } +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); - return object; - }); - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @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 - * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } - */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); +/***/ }), - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @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`. - * @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) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } +/***/ 31173: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.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`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' - */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } - /** - * 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`. - * - * @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 - * @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. - * - * @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 - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. - */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); - } +var Type = __nccwpck_require__(30967); - /** - * 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`. - * - * @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 - * @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). - */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); - } +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @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 - * @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'. - */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); - } - /** - * Creates an array of function property names from own enumerable properties - * of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functions(new Foo); - * // => ['a', 'b'] - */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); - } +/***/ }), - /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] - */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } +/***/ 81393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @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. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - /** - * Checks if `path` is a direct property of `object`. - * - * @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`. - * @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 - * - * _.has(other, 'a'); - * // => false - */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @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`. - * @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 - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } +var Type = __nccwpck_require__(30967); - /** - * 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. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } - */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} - result[value] = key; - }, constant(identity)); +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); - /** - * 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). - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } - * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } - */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; - } - }, getIteratee); +/***/ }), - /** - * Invokes the method at `path` of `object`. - * - * @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); +/***/ 22671: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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); - } - /** - * 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); - } - /** - * 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). - * - * @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 - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); +var Type = __nccwpck_require__(30967); - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } +function resolveYamlNull(data) { + if (data === null) return true; - /** - * 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). - * - * @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 - * @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) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); + var max = data.length; - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} - /** - * 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`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); +function constructYamlNull() { + return null; +} - /** - * 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). - * - * **Note:** This method mutates `object`. - * - * @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`. - * @example - * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; - * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } - */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); +function isNull(object) { + return object === null; +} - /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. - * - * **Note:** This method is considerably slower than `_.pick`. - * - * @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. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } - */ - 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; - }); +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' +}); - /** - * 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). - * - * @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. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } - /** - * Creates an object composed of the picked `object` properties. - * - * @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. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); +/***/ }), - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @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. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - 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]); - }); - } +/***/ 96668: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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. - * - * @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. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' - * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' - */ - function result(object, path, defaultValue) { - path = castPath(path, object); - var index = -1, - length = path.length; - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; - } - return object; - } +var Type = __nccwpck_require__(30967); - /** - * 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. - * - * **Note:** This method mutates `object`. - * - * @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`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 - */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); - } +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; - /** - * 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). - * - * **Note:** This method mutates `object`. - * - * @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`. - * @example - * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } - */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); - } +function resolveYamlOmap(data) { + if (data === null) return true; - /** - * 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. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) - */ - var toPairs = createToPairs(keys); + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; - /** - * 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. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @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) - */ - var toPairsIn = createToPairs(keysIn); + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; - /** - * 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`. - * - * @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. - * @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'] } - */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); + if (_toString.call(pair) !== '[object Object]') return false; - 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 = {}; - } + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; } - /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. - * - * @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`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } + if (!pairHasKey) return false; - /** - * 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`. - * - * @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`. - * @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 - */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } - /** - * 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`. - * - * @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`. - * @example - * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } - */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } + return true; +} - /** - * 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 == null ? [] : baseValues(object, keys(object)); - } +function constructYamlOmap(data) { + return data !== null ? data : []; +} - /** - * Creates an array of the own and inherited enumerable string keyed property - * values 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 values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) - */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); - /*------------------------------------------------------------------------*/ - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. - * - * @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. - * @example - * - * _.clamp(-10, -5, 5); - * // => -5 - * - * _.clamp(10, -5, 5); - * // => 5 - */ - 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; - } - return baseClamp(toNumber(number), lower, upper); - } +/***/ }), - /** - * 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. - * - * @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 - * @example - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false - * - * _.inRange(-3, -2, -6); - * // => true - */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); - } +/***/ 76039: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +var Type = __nccwpck_require__(30967); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; - /** - * 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. - * - * @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. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.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); - } + var index, length, pair, keys, result, + object = data; - /*------------------------------------------------------------------------*/ + result = new Array(object.length); - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; - /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } + if (_toString.call(pair) !== '[object Object]') return false; - /** - * 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). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } + keys = Object.keys(pair); - /** - * Checks if `string` ends with the given target string. - * - * @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`. - * @example - * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true - */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); + if (keys.length !== 1) return false; - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); + result[index] = [ keys[0], pair[keys[0]] ]; + } - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } + return true; +} - /** - * 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. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } +function constructYamlPairs(data) { + if (data === null) return []; - /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' - */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; - } + var index, length, pair, keys, result, + object = data; - /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' - */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); + result = new Array(object.length); - /** - * Converts `string`, as space separated words, to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. - * @example - * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' - * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' - */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; - /** - * Converts the first character of `string` to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.lowerFirst('Fred'); - * // => 'fred' - * - * _.lowerFirst('FRED'); - * // => 'fRED' - */ - var lowerFirst = createCaseFirst('toLowerCase'); + keys = Object.keys(pair); - /** - * 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`. - * - * @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. - * @example - * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' - * - * _.pad('abc', 3); - * // => 'abc' - */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); + result[index] = [ keys[0], pair[keys[0]] ]; + } - 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) - ); - } + return result; +} - /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @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. - * @example - * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padEnd('abc', 3); - * // => 'abc' - */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; - } - /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @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. - * @example - * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padStart('abc', 3); - * // => 'abc' - */ - 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; - } +/***/ 5490: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * 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`. - * - * @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. - * @example - * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] - */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } - /** - * Repeats the given string `n` times. - * - * @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. - * @example - * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' - */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); - } - /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). - * - * @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. - * @example - * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' - */ - function replace() { - var args = arguments, - string = toString(args[0]); +var Type = __nccwpck_require__(30967); - return args.length < 3 ? string : string.replace(args[1], args[2]); - } +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); - /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. - * @example - * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' - */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); - /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). - * - * @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. - * @example - * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] - */ - 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); - } +/***/ }), - /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). - * - * @static - * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. - * @example - * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' - */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); +/***/ 69237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Checks if `string` starts with the given target string. - * - * @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`. - * @example - * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true - */ - 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; - } - /** - * 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). - * - * @static - * @since 0.1.0 - * @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. - * @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': '