diff --git a/dist/index.js b/dist/index.js index 8b4d32249..af13282fb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -8040,7 +8040,7 @@ exports.emitterEventNames = emitterEventNames; /***/ 93159: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const ProbotExports = __nccwpck_require__(93181); +const ProbotExports = __nccwpck_require__(58930); const pino = __nccwpck_require__(79608); const { transport } = __nccwpck_require__(96645); @@ -8493,4572 +8493,3079 @@ exports.toCommandValue = toCommandValue; /***/ }), -/***/ 3598: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 96645: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const { inspect } = __nccwpck_require__(73837); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +const through = __nccwpck_require__(18180); +const core = __nccwpck_require__(68648); +const pino = __nccwpck_require__(79608); + +const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = { + trace: "debug", + debug: "debug", + info: "info", + warn: "warning", + error: "error", + fatal: "error", }; -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 -/***/ }), +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]; -/***/ 36769: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + const output = [ + msg, + Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "", + ] + .join("\n") + .trim(); -"use strict"; + if (logMethodName in core) { + core[logMethodName](output); + } else { + core.error(`"${level}" is not a known log level - ${output}`); + } + + cb(); +}); + +module.exports = { transport }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -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 /***/ }), -/***/ 81084: +/***/ 97743: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; + 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 -/***/ }), +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -/***/ 57767: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); +var isBase64 = _interopDefault(__nccwpck_require__(31310)); -"use strict"; +const VERSION = "0.0.0-development"; -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__(61904)); -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 +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"); + } -/***/ 74420: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (env.PRIVATE_KEY) { + let privateKey = env.PRIVATE_KEY; -"use strict"; + if (isBase64(privateKey)) { + // Decode base64-encoded certificate + privateKey = Buffer.from(privateKey, "base64").toString(); + } -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 + 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"); + } -/***/ 45006: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + 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.`); + } -"use strict"; + if (env.PRIVATE_KEY_PATH) { + const filepath = path.resolve(cwd, env.PRIVATE_KEY_PATH); -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; + 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; } -exports.Context = Context; -//# sourceMappingURL=context.js.map +getPrivateKey.VERSION = VERSION; + +exports.getPrivateKey = getPrivateKey; +//# sourceMappingURL=index.js.map + /***/ }), -/***/ 44488: +/***/ 59326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; + 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 -/***/ }), +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -/***/ 52728: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var yaml = _interopDefault(__nccwpck_require__(21917)); -"use strict"; +const VERSION = "1.0.1"; -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, +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; } -exports.createProbot = createProbot; -//# sourceMappingURL=create-probot.js.map -/***/ }), +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); -/***/ 19752: -/***/ ((__unused_webpack_module, exports) => { + 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); + } -"use strict"; + return keys; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.aliasLog = void 0; +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"]; /** - * `probot.log()`, `app.log()` and `context.log()` are aliasing `.log.info()`. - * We will probably remove the aliasing in future. + * Load configuration from a given repository and path. + * + * @param octokit Octokit instance + * @param options */ -function aliasLog(log) { - function logInfo() { - // @ts-ignore - log.info(...arguments); + +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" } - for (const key in log) { - // @ts-ignore - logInfo[key] = - typeof log[key] === "function" ? log[key].bind(log) : log[key]; + }, 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.`); } - // @ts-ignore - return logInfo; -} -exports.aliasLog = aliasLog; -//# sourceMappingURL=alias-log.js.map -/***/ }), + if (fileExtension === "json") { + if (typeof data === "string") { + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (invalid JSON)`); + } -/***/ 5789: -/***/ ((__unused_webpack_module, exports) => { + return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { + config: data + }); + } -"use strict"; + const config = yaml.safeLoad(data) || {}; -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 + 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; + } -/***/ 90751: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + 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})`); + } -"use strict"; + throw error; + } +} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getLog = void 0; +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"); /** - * A logger backed by [pino](https://getpino.io/) + * Computes parameters to retrieve the configuration file specified in _extends * - * 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"`. + * Base can either be the name of a repository in the same organization or + * a full slug "organization/repo". * - * ```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!"); - * ``` + * @param options + * @return The params needed to retrieve a configuration file */ -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 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}`); + } -/***/ 75381: -/***/ ((__unused_webpack_module, exports) => { + const match = extendsValue.match(EXTENDS_REGEX); -"use strict"; + if (match === null) { + throw new Error(`[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}`); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isProduction = void 0; -function isProduction() { - return process.env.NODE_ENV === "production"; + return { + owner: match[1] || owner, + repo: match[2], + path: match[3] || path + }; } -exports.isProduction = isProduction; -//# sourceMappingURL=is-production.js.map -/***/ }), +/** + * 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 + */ -/***/ 33208: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +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 -"use strict"; + if (!requestedRepoFile.config) { + if (repo === ".github") { + return [requestedRepoFile]; + } -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 + const defaultRepoConfig = await getConfigFile(octokit, { + owner, + repo: ".github", + path + }); + return [requestedRepoFile, defaultRepoConfig]; + } // if the configuration has no `_extends` key, we are done here. -/***/ }), -/***/ 66217: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!requestedRepoFile.config._extends) { + return [requestedRepoFile]; + } // parse the value of `_extends` into request parameters to + // retrieve the new configuration file -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createWebhookProxy = void 0; -const createWebhookProxy = (opts) => { - try { - const SmeeClient = __nccwpck_require__(24807); - const smee = new SmeeClient({ - logger: opts.logger, - source: opts.url, - target: `http://localhost:${opts.port}${opts.path}`, - }); - return smee.start(); + 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; } - catch (error) { - opts.logger.warn("Run `npm install --save-dev smee-client` to proxy webhooks to localhost."); - return; + + 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.`); } -}; -exports.createWebhookProxy = createWebhookProxy; -//# sourceMappingURL=webhook-proxy.js.map + } 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 + */ -/***/ 93181: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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) + }; +} -"use strict"; +/** + * @param octokit Octokit instance + */ -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; } })); +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 + /***/ }), -/***/ 18785: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 39662: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +module.exports = { getTransformStream }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +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", }; -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__(24807); - 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 - -/***/ }), -/***/ 53535: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +/** + * 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; -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); - }, + 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, }); -} -exports.getAuthenticatedOctokit = getAuthenticatedOctokit; -//# sourceMappingURL=get-authenticated-octokit.js.map + } -/***/ }), + 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(","), + }); -/***/ 51729: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + return new Transform({ + objectMode: true, + transform(chunk, enc, cb) { + const line = chunk.toString().trim(); -"use strict"; + /* istanbul ignore if */ + if (line === undefined) return cb(); -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 + 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); -/***/ 1330: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (const extra of ["event", "headers", "request", "status"]) { + if (!data[extra]) continue; -"use strict"; + scope.setExtra(extra, data[extra]); + } -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 + // 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; -/***/ 879: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + scope.setUser({ + id: id, + username: account || organization || owner, + }); + } -"use strict"; + Sentry.captureException(toSentryError(data)); + }); + } -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 + if (formattingEnabled) { + return cb(null, pretty(data || line)); + } -/***/ }), + if (levelAsString) { + return cb(null, stringifyLogLevel(data || JSON.parse(line))); + } -/***/ 7828: -/***/ ((__unused_webpack_module, exports) => { + cb(null, line + "\n"); + }, + }); +} -"use strict"; +function stringifyLogLevel(data) { + data.level = LEVEL_MAP[data.level]; + return JSON.stringify(data) + "\n"; +} -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); - }); +function toSentryError(data) { + const error = new Error(data.msg); + error.name = data.type; + error.stack = data.stack; + return error; } -exports.probotRequestLogging = probotRequestLogging; -//# sourceMappingURL=octokit-plugin-probot-request-logging.js.map + /***/ }), -/***/ 16973: +/***/ 90785: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - 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 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 /***/ }), -/***/ 97268: +/***/ 25886: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - 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 - -/***/ }), - -/***/ 22357: -/***/ (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 })); -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); +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(); } - async load(appFn) { - if (Array.isArray(appFn)) { - for (const fn of appFn) { - await this.load(fn); - } + /** + * @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; } - return appFn(this, {}); - } -} -exports.Probot = Probot; -Probot.version = version_1.VERSION; -//# sourceMappingURL=probot.js.map + 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 /***/ }), -/***/ 57124: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +/***/ 25684: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -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); +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. * - * @param appFnOrArgv set to either a probot application function: `(app) => { ... }` or to process.argv + * 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); + * } + * + * // ... + * } */ -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, +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; }; - const log = get_log_1.getLog(logOptions); - const probotOptions = { - appId, - privateKey, - redisConfig, - secret, - baseUrl, - log: log.child({ name: "probot" }), + /** + * @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; }; - const serverOptions = { - host, - port, - webhookPath, - webhookProxy, - log: log.child({ name: "server" }), - Probot: index_1.Probot.defaults(probotOptions), + /** + * @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; }; - 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."); + /** + * @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; + } + } } - 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"); + 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; } } } - // 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); + 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; } } - 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 - -/***/ }), - -/***/ 24631: -/***/ (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 })); -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 - -/***/ }), - -/***/ 83148: -/***/ (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 (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, - }); + } + 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); } - 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.`, - }); + else { + ticked += tick; + if (timeout && ticked >= timeout) { + clearInterval(interval); + resolve(false); + } } - this.log.error(error); - reject(error); - }); + }, 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), })); - 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 + // 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 /***/ }), -/***/ 1403: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; +/***/ 79212: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { 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 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 /***/ }), -/***/ 96645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { inspect } = __nccwpck_require__(73837); - -const through = __nccwpck_require__(18180); -const core = __nccwpck_require__(68648); -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(); +/***/ 58500: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (logMethodName in core) { - core[logMethodName](output); - } else { - core.error(`"${level}" is not a known log level - ${output}`); - } +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 - cb(); -}); +/***/ }), -module.exports = { transport }; +/***/ 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 /***/ }), -/***/ 97743: +/***/ 54838: /***/ ((__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__(71017); -var fs = __nccwpck_require__(57147); -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.`); +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; } - } - - const pemFiles = fs.readdirSync(cwd).filter(path => path.endsWith(".pem")); + /** + * @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 - 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; +/***/ 96727: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.getPrivateKey = getPrivateKey; +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 - /***/ }), -/***/ 59326: +/***/ 1553: /***/ ((__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 +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(), }); - } 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; + var itemHeaders = JSON.stringify({ + type: 'session', }); - keys.push.apply(keys, symbols); - } - - return keys; + return { + body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), + type: 'session', + url: api.getEnvelopeEndpointWithUrlEncodedAuth(), + }; } - -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)); - }); +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 target; + return req; } +exports.eventToSentryRequest = eventToSentryRequest; +//# sourceMappingURL=request.js.map -const SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"]; +/***/ }), + +/***/ 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); /** - * Load configuration from a given repository and path. + * Internal function to create a new SDK client instance. The client is + * installed and then bound to the current scope. * - * @param octokit Octokit instance - * @param options + * @param clientClass The client class to instantiate. + * @param options Options to pass to the client. */ - -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 - }); +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 - 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)`); - } +/***/ 68641: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { - config - }); - } catch (error) { - if (error.status === 404) { - return emptyConfigResult; +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 - 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; - } -} +/***/ 53536: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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"); +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); /** - * Computes parameters to retrieve the configuration file specified in _extends + * API compatibility version of this hub. * - * Base can either be the name of a repository in the same organization or - * a full slug "organization/repo". + * WARNING: This number should only be increased when the global interface + * changes and new methods are introduced. * - * @param options - * @return The params needed to retrieve a configuration file + * @hidden */ - -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 - }; -} - +exports.API_VERSION = 3; /** - * 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 + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. */ - -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) - }; -} - +var DEFAULT_BREADCRUMBS = 100; /** - * @param octokit Octokit instance + * Absolute maximum number of breadcrumbs added to an event. The + * `maxBreadcrumbs` option cannot be higher than this value. */ - -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", -}; - +var MAX_BREADCRUMBS = 100; /** - * Implements Probot's default logging formatting and error captionaing using Sentry. - * - * @param {import("./").Options} options - * @returns Transform - * @see https://getpino.io/#/docs/transports + * @inheritDoc */ -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'); - }; +var Hub = /** @class */ (function () { /** - * Returns the store endpoint URL with auth in the query string. + * Creates a new instance of the hub, will push one {@link Layer} into the + * internal stack on creation. * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + * @param client bound to the hub. + * @param scope bound to the hub. + * @param version number, higher number means higher priority. */ - API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { - return this.getStoreEndpoint() + "?" + this._encodedAuth(); + 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; }; /** - * 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. + * @inheritDoc */ - API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { - return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); + Hub.prototype.bindClient = function (client) { + var top = this.getStackTop(); + top.client = client; + if (client && client.setupIntegrations) { + client.setupIntegrations(); + } }; - /** 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/"; + /** + * @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; }; /** - * Returns an object that can be used in request headers. - * This is needed for node and the old /store endpoint in sentry + * @inheritDoc */ - 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(', '), - }; + Hub.prototype.popScope = function () { + if (this.getStack().length <= 1) + return false; + return !!this.getStack().pop(); }; - /** 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])); - } + /** + * @inheritDoc + */ + Hub.prototype.withScope = function (callback) { + var scope = this.pushScope(); + try { + callback(scope); } - if (encodedOptions.length) { - return endpoint + "?" + encodedOptions.join('&'); + finally { + this.popScope(); } - return endpoint; }; - /** Returns the envelope endpoint URL. */ - API.prototype._getEnvelopeEndpoint = function () { - return this._getIngestEndpoint('envelope'); + /** + * @inheritDoc + */ + Hub.prototype.getClient = function () { + return this.getStackTop().client; }; - /** 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 the scope of the top stack. */ + Hub.prototype.getScope = function () { + return this.getStackTop().scope; }; - /** 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); + /** 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]; }; - 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'); + 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 */ - BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) { - throw new utils_1.SentryError('Backend has to implement `eventFromMessage` method'); + 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 */ - BaseBackend.prototype.sendEvent = function (event) { - this._transport.sendEvent(event).then(null, function (reason) { - utils_1.logger.error("Error while sending event: " + reason); - }); + 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 */ - 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); - }); + Hub.prototype.lastEventId = function () { + return this._lastEventId; }; /** * @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; + 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 */ - 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; + Hub.prototype.setUser = function (user) { + var scope = this.getScope(); + if (scope) + scope.setUser(user); }; /** * @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; + Hub.prototype.setTags = function (tags) { + var scope = this.getScope(); + if (scope) + scope.setTags(tags); }; /** * @inheritDoc */ - BaseClient.prototype.captureSession = function (session) { - if (!session.release) { - utils_1.logger.warn('Discarded session because of missing release'); - } - else { - this._sendSession(session); - } + Hub.prototype.setExtras = function (extras) { + var scope = this.getScope(); + if (scope) + scope.setExtras(extras); }; /** * @inheritDoc */ - BaseClient.prototype.getDsn = function () { - return this._dsn; + Hub.prototype.setTag = function (key, value) { + var scope = this.getScope(); + if (scope) + scope.setTag(key, value); }; /** * @inheritDoc */ - BaseClient.prototype.getOptions = function () { - return this._options; + Hub.prototype.setExtra = function (key, extra) { + var scope = this.getScope(); + if (scope) + scope.setExtra(key, extra); }; /** * @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; }); - }); + // 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 */ - BaseClient.prototype.close = function (timeout) { - var _this = this; - return this.flush(timeout).then(function (result) { - _this.getOptions().enabled = false; - return result; - }); + Hub.prototype.configureScope = function (callback) { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (scope && client) { + callback(scope); + } }; /** - * Sets up the integrations + * @inheritDoc */ - BaseClient.prototype.setupIntegrations = function () { - if (this._isEnabled()) { - this._integrations = integration_1.setupIntegrations(this._options); + Hub.prototype.run = function (callback) { + var oldHub = makeMain(this); + try { + callback(this); + } + finally { + makeMain(oldHub); } }; /** * @inheritDoc */ - BaseClient.prototype.getIntegration = function (integration) { + Hub.prototype.getIntegration = function (integration) { + var client = this.getClient(); + if (!client) + return null; try { - return this._integrations[integration.id] || null; + return client.getIntegration(integration); } catch (_oO) { - utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Client"); + utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); 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. + * @inheritDoc */ - 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; - }); + Hub.prototype.startSpan = function (context) { + return this._callExtensionMethod('startSpan', context); }; /** - * 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 + * @inheritDoc */ - 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; + Hub.prototype.startTransaction = function (context, customSamplingContext) { + return this._callExtensionMethod('startTransaction', context, customSamplingContext); }; /** - * 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 + * @inheritDoc */ - 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); - } + Hub.prototype.traceHeaders = function () { + return this._callExtensionMethod('traceHeaders'); }; /** - * 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. + * @inheritDoc */ - BaseClient.prototype._applyIntegrationsMetadata = function (event) { - var sdkInfo = event.sdk; - var integrationsArray = Object.keys(this._integrations); - if (sdkInfo && integrationsArray.length > 0) { - sdkInfo.integrations = integrationsArray; + 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; }; /** - * 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 + * @inheritDoc */ - 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; - }); + 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(); + } }; /** - * 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. - * + * Internal helper function to call a method on the top client if it exists. * - * @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. + * @param method The method to call on the client. + * @param args Arguments to pass to the client function. */ - 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.')); + // 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 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.')); + 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])); } - 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 + * Calls global extension method and binding current instance to the function call */ - 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 + // @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 /***/ }), -/***/ 79212: +/***/ 6393: /***/ ((__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; +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.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; +exports.setHubOnCarrier = hub_1.setHubOnCarrier; //# sourceMappingURL=index.js.map /***/ }), -/***/ 58500: +/***/ 4213: /***/ ((__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 + * Holds additional event information. {@link Scope.applyToEvent} will be + * called by the client before an event will be sent. */ -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; +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 = {}; } /** - * @inheritDoc + * Inherit values from the parent scope. + * @param scope to clone. */ - 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); - }; + 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; }; /** - * @inheritDoc + * Add internal on change listener. Used for sub SDKs that need to store the scope. + * @hidden */ - 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; - } + Scope.prototype.addScopeListener = function (callback) { + this._scopeListeners.push(callback); + }; /** * @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; - } + Scope.prototype.addEventProcessor = function (callback) { + this._eventProcessors.push(callback); + return this; }; - /** JSDoc */ - InboundFilters.prototype._isIgnoredError = function (event, options) { - if (!options.ignoreErrors || !options.ignoreErrors.length) { - return false; + /** + * @inheritDoc + */ + Scope.prototype.setUser = function (user) { + this._user = user || {}; + if (this._session) { + this._session.update({ user: user }); } - 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); }); - }); + this._notifyScopeListeners(); + return this; }; - /** 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); }); + /** + * @inheritDoc + */ + Scope.prototype.getUser = function () { + return this._user; }; - /** 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); }); + /** + * @inheritDoc + */ + Scope.prototype.setTags = function (tags) { + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags); + this._notifyScopeListeners(); + return this; }; - /** 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, - }; + /** + * @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; }; - /** 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 []; + /** + * @inheritDoc + */ + Scope.prototype.setExtras = function (extras) { + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras); + this._notifyScopeListeners(); + return this; }; - /** 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 + */ + 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 */ - 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(), + Scope.prototype.setFingerprint = function (fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; }; - // 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, - }); + Scope.prototype.setLevel = function (level) { + this._level = level; + this._notifyScopeListeners(); + return this; }; /** * @inheritDoc */ - NoopTransport.prototype.close = function (_) { - return utils_1.SyncPromise.resolve(true); + Scope.prototype.setTransactionName = function (name) { + this._transactionName = name; + this._notifyScopeListeners(); + return this; }; - 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. + * Can be removed in major version. + * @deprecated in favor of {@link this.setTransactionName} */ - 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); - } + Scope.prototype.setTransaction = function (name) { + return this.setTransactionName(name); + }; /** * @inheritDoc */ - Hub.prototype.isOlderThan = function (version) { - return this._version < version; + 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 */ - Hub.prototype.bindClient = function (client) { - var top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } + Scope.prototype.setSpan = function (span) { + this._span = span; + this._notifyScopeListeners(); + return this; }; /** * @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; + Scope.prototype.getSpan = function () { + return this._span; }; /** * @inheritDoc */ - Hub.prototype.popScope = function () { - if (this.getStack().length <= 1) - return false; - return !!this.getStack().pop(); + 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 */ - Hub.prototype.withScope = function (callback) { - var scope = this.pushScope(); - try { - callback(scope); + Scope.prototype.setSession = function (session) { + if (!session) { + delete this._session; } - finally { - this.popScope(); + else { + this._session = session; } + this._notifyScopeListeners(); + return this; }; /** * @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]; + Scope.prototype.getSession = function () { + return this._session; }; /** * @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'); + 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; } - catch (exception) { - syntheticException = exception; + if (captureContext._level) { + this._level = captureContext._level; + } + if (captureContext._fingerprint) { + this._fingerprint = captureContext._fingerprint; } - 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); + 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; } - catch (exception) { - syntheticException = exception; + if (captureContext.level) { + this._level = captureContext.level; + } + if (captureContext.fingerprint) { + this._fingerprint = captureContext.fingerprint; } - finalHint = { - originalException: message, - syntheticException: syntheticException, - }; } - this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); - return eventId; + return this; }; /** * @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; + 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 */ - Hub.prototype.lastEventId = function () { - return this._lastEventId; + 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 */ - 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)); + Scope.prototype.clearBreadcrumbs = function () { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; }; /** - * @inheritDoc + * 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 */ - Hub.prototype.setUser = function (user) { - var scope = this.getScope(); - if (scope) - scope.setUser(user); + 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); }; /** - * @inheritDoc + * This will be called after {@link applyToEvent} is finished. */ - Hub.prototype.setTags = function (tags) { - var scope = this.getScope(); - if (scope) - scope.setTags(tags); + 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); + } + } + }); }; /** - * @inheritDoc + * This will be called on every set call. */ - Hub.prototype.setExtras = function (extras) { - var scope = this.getScope(); - if (scope) - scope.setExtras(extras); + 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; + } }; /** - * @inheritDoc + * 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 */ - Hub.prototype.setTag = function (key, value) { - var scope = this.getScope(); - if (scope) - scope.setTag(key, value); + 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; + } }; - /** - * @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); + 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); } - }; - /** - * @inheritDoc - */ - Hub.prototype.run = function (callback) { - var oldHub = makeMain(this); - try { - callback(this); + } + /** 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; + } } - finally { - makeMain(oldHub); + 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(); } - }; - /** - * @inheritDoc - */ - Hub.prototype.getIntegration = function (integration) { - var client = this.getClient(); - if (!client) - return null; - try { - return client.getIntegration(integration); + if (context.did) { + this.did = "" + context.did; } - catch (_oO) { - utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); - return null; + if (typeof context.started === 'number') { + this.started = context.started; } - }; - /** - * @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); + if (typeof context.duration === 'number') { + this.duration = context.duration; } - 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(); + else { + this.duration = this.timestamp - this.started; } - }; - /** - * 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]; + if (context.release) { + this.release = context.release; } - var _b = this.getStackTop(), scope = _b.scope, client = _b.client; - if (client && client[method]) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - (_a = client)[method].apply(_a, tslib_1.__spread(args, [scope])); + if (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; } }; - /** - * 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]; + /** JSDoc */ + Session.prototype.close = function (status) { + if (status) { + this.update({ status: status }); } - var carrier = getMainCarrier(); - var sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); + else if (this.status === types_1.SessionStatus.Ok) { + this.update({ status: types_1.SessionStatus.Exited }); + } + else { + this.update(); } - 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, + /** 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 carrier; + 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."); } -exports.getMainCarrier = getMainCarrier; /** - * Replaces the current main hub with the passed one on the global object + * Captures an exception event and sends it to Sentry. * - * @returns The old replaced hub + * @param exception An exception-like object. + * @returns The generated eventId. */ -function makeMain(hub) { - var registry = getMainCarrier(); - var oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; +// 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.makeMain = makeMain; +exports.captureException = captureException; /** - * Returns the default hub instance. + * Captures a message event and sends it to Sentry. * - * 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. + * @param message The message to send to Sentry. + * @param level Define the level of the message. + * @returns The generated eventId. */ -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()); +function captureMessage(message, captureContext) { + var syntheticException; + try { + throw new Error(message); } - // Prefer domains over global if they are there (applicable only to Node environment) - if (utils_1.isNodeEnv()) { - return getHubFromActiveDomain(registry); + catch (exception) { + syntheticException = exception; } - // Return hub that lives on a global object - return getHubFromCarrier(registry); + // 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.getCurrentHub = getCurrentHub; +exports.captureMessage = captureMessage; /** - * Returns the active domain, if one exists + * Captures a manually created event and sends it to Sentry. * - * @returns The domain, or undefined if there is no active domain + * @param event The event to send to Sentry. + * @returns The generated eventId. */ -function getActiveDomain() { - var sentry = getMainCarrier().__SENTRY__; - return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; +function captureEvent(event) { + return callOnHub('captureEvent', event); } -exports.getActiveDomain = getActiveDomain; +exports.captureEvent = captureEvent; /** - * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist - * @returns discovered hub + * Callback to set context information onto the scope. + * @param callback Callback function that receives Scope. */ -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); - } +function configureScope(callback) { + callOnHub('configureScope', callback); } +exports.configureScope = configureScope; /** - * This will tell whether a carrier has a hub on it or not - * @param carrier object + * 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 hasHubOnCarrier(carrier) { - return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); +function addBreadcrumb(breadcrumb) { + callOnHub('addBreadcrumb', breadcrumb); } +exports.addBreadcrumb = addBreadcrumb; /** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object + * 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 */ -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; +// 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.getHubFromCarrier = getHubFromCarrier; +exports._callOnClient = _callOnClient; /** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub + * 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 setHubOnCarrier(carrier, hub) { - if (!carrier) - return false; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = hub; - return true; +function startTransaction(context, customSamplingContext) { + return callOnHub('startTransaction', tslib_1.__assign({}, context), customSamplingContext); } -exports.setHubOnCarrier = setHubOnCarrier; -//# sourceMappingURL=hub.js.map +exports.startTransaction = startTransaction; +//# sourceMappingURL=index.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: +/***/ 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); /** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. + * The Sentry Node SDK Backend. + * @hidden */ -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 = {}; +var NodeBackend = /** @class */ (function (_super) { + tslib_1.__extends(NodeBackend, _super); + function NodeBackend() { + return _super !== null && _super.apply(this, arguments) || this; } - /** - * 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; + // 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; } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; + 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 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; + 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 */ - 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) { + NodeBackend.prototype.eventFromMessage = function (message, level, hint) { 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); + 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 { - 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); - } + resolve(event); } }); }; /** - * This will be called on every set call. + * @inheritDoc */ - 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; + 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); } - }; - /** - * 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); + 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 we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; + if (dsn.protocol === 'http') { + return new transports_1.HTTPTransport(transportOptions); } + return new transports_1.HTTPSTransport(transportOptions); }; - 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 + return NodeBackend; +}(core_1.BaseBackend)); +exports.NodeBackend = NodeBackend; +//# sourceMappingURL=backend.js.map /***/ }), -/***/ 12474: +/***/ 86147: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var backend_1 = __nccwpck_require__(40508); +var version_1 = __nccwpck_require__(31271); /** - * @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. + * 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); @@ -59276,7 +57783,7 @@ function versionIncluded(nodeVersion, specifierValue) { } var current = typeof nodeVersion === 'undefined' - ? process.versions && process.versions.node && process.versions.node + ? process.versions && process.versions.node : nodeVersion; if (typeof current !== 'string') { @@ -98430,2377 +96937,3153 @@ module.exports = once; var props = keys(source), methodNames = baseFunctions(source, props); - if (options == null && - !(isObject(source) && (methodNames.length || !props.length))) { - options = source; - source = object; - object = this; - methodNames = baseFunctions(source, keys(source)); - } - var chain = !(isObject(options) && 'chain' in options) || !!options.chain, - isFunc = isFunction(object); + if (options == null && + !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); + } + var chain = !(isObject(options) && 'chain' in options) || !!options.chain, + isFunc = isFunction(object); + + arrayEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), + actions = result.__actions__ = copyArray(this.__actions__); + + actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); + result.__chain__ = chainAll; + return result; + } + return func.apply(object, arrayPush([this.value()], arguments)); + }; + } + }); + + return object; + } + + /** + * Reverts the `_` variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + if (root._ === this) { + root._ = oldDash; + } + return this; + } + + /** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + /** + * Creates a function that gets the argument at index `n`. If `n` is negative, + * the nth argument from the end is returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {number} [n=0] The index of the argument to return. + * @returns {Function} Returns the new pass-thru function. + * @example + * + * var func = _.nthArg(1); + * func('a', 'b', 'c', 'd'); + * // => 'b' + * + * var func = _.nthArg(-2); + * func('a', 'b', 'c', 'd'); + * // => 'c' + */ + function nthArg(n) { + n = toInteger(n); + return baseRest(function(args) { + return baseNth(args, n); + }); + } + + /** + * Creates a function that invokes `iteratees` with the arguments it receives + * and returns their results. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to invoke. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.over([Math.max, Math.min]); + * + * func(1, 2, 3, 4); + * // => [4, 1] + */ + var over = createOver(arrayMap); + + /** + * Creates a function that checks if **all** of the `predicates` return + * truthy when invoked with the arguments it receives. + * + * Following shorthands are possible for providing predicates. + * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. + * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [predicates=[_.identity]] + * The predicates to check. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.overEvery([Boolean, isFinite]); + * + * func('1'); + * // => true + * + * func(null); + * // => false + * + * func(NaN); + * // => false + */ + var overEvery = createOver(arrayEvery); + + /** + * Creates a function that checks if **any** of the `predicates` return + * truthy when invoked with the arguments it receives. + * + * Following shorthands are possible for providing predicates. + * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. + * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [predicates=[_.identity]] + * The predicates to check. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.overSome([Boolean, isFinite]); + * + * func('1'); + * // => true + * + * func(null); + * // => true + * + * func(NaN); + * // => false + * + * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) + * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) + */ + var overSome = createOver(arraySome); + + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + + /** + * The opposite of `_.property`; this method creates a function that returns + * the value at a given path of `object`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + * @example + * + * var array = [0, 1, 2], + * object = { 'a': array, 'b': array, 'c': array }; + * + * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); + * // => [2, 0] + * + * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); + * // => [2, 0] + */ + function propertyOf(object) { + return function(path) { + return object == null ? undefined : baseGet(object, path); + }; + } + + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to, but not including, `end`. A step of `-1` is used if a negative + * `start` is specified without an `end` or `step`. If `end` is not specified, + * it's set to `start` with `start` then set to `0`. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns the range of numbers. + * @see _.inRange, _.rangeRight + * @example + * + * _.range(4); + * // => [0, 1, 2, 3] + * + * _.range(-4); + * // => [0, -1, -2, -3] + * + * _.range(1, 5); + * // => [1, 2, 3, 4] + * + * _.range(0, 20, 5); + * // => [0, 5, 10, 15] + * + * _.range(0, -4, -1); + * // => [0, -1, -2, -3] + * + * _.range(1, 4, 0); + * // => [1, 1, 1] + * + * _.range(0); + * // => [] + */ + var range = createRange(); + + /** + * This method is like `_.range` except that it populates values in + * descending order. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns the range of numbers. + * @see _.inRange, _.range + * @example + * + * _.rangeRight(4); + * // => [3, 2, 1, 0] + * + * _.rangeRight(-4); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 5); + * // => [4, 3, 2, 1] + * + * _.rangeRight(0, 20, 5); + * // => [15, 10, 5, 0] + * + * _.rangeRight(0, -4, -1); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 4, 0); + * // => [1, 1, 1] + * + * _.rangeRight(0); + * // => [] + */ + var rangeRight = createRange(true); + + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } + + /** + * This method returns a new empty object. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Object} Returns the new empty object. + * @example + * + * var objects = _.times(2, _.stubObject); + * + * console.log(objects); + * // => [{}, {}] + * + * console.log(objects[0] === objects[1]); + * // => false + */ + function stubObject() { + return {}; + } + + /** + * This method returns an empty string. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {string} Returns the empty string. + * @example + * + * _.times(2, _.stubString); + * // => ['', ''] + */ + function stubString() { + return ''; + } + + /** + * This method returns `true`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `true`. + * @example + * + * _.times(2, _.stubTrue); + * // => [true, true] + */ + function stubTrue() { + return true; + } + + /** + * Invokes the iteratee `n` times, returning an array of the results of + * each invocation. The iteratee is invoked with one argument; (index). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of results. + * @example + * + * _.times(3, String); + * // => ['0', '1', '2'] + * + * _.times(4, _.constant(0)); + * // => [0, 0, 0, 0] + */ + function times(n, iteratee) { + n = toInteger(n); + if (n < 1 || n > MAX_SAFE_INTEGER) { + return []; + } + var index = MAX_ARRAY_LENGTH, + length = nativeMin(n, MAX_ARRAY_LENGTH); + + iteratee = getIteratee(iteratee); + n -= MAX_ARRAY_LENGTH; + + var result = baseTimes(length, iteratee); + while (++index < n) { + iteratee(index); + } + return result; + } + + /** + * Converts `value` to a property path array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {*} value The value to convert. + * @returns {Array} Returns the new property path array. + * @example + * + * _.toPath('a.b.c'); + * // => ['a', 'b', 'c'] + * + * _.toPath('a[0].b.c'); + * // => ['a', '0', 'b', 'c'] + */ + function toPath(value) { + if (isArray(value)) { + return arrayMap(value, toKey); + } + return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); + } + + /** + * Generates a unique ID. If `prefix` is given, the ID is appended to it. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {string} [prefix=''] The value to prefix the ID with. + * @returns {string} Returns the unique ID. + * @example + * + * _.uniqueId('contact_'); + * // => 'contact_104' + * + * _.uniqueId(); + * // => '105' + */ + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + + /*------------------------------------------------------------------------*/ + + /** + * Adds two numbers. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {number} augend The first number in an addition. + * @param {number} addend The second number in an addition. + * @returns {number} Returns the total. + * @example + * + * _.add(6, 4); + * // => 10 + */ + var add = createMathOperation(function(augend, addend) { + return augend + addend; + }, 0); + + /** + * Computes `number` rounded up to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round up. + * @param {number} [precision=0] The precision to round up to. + * @returns {number} Returns the rounded up number. + * @example + * + * _.ceil(4.006); + * // => 5 + * + * _.ceil(6.004, 2); + * // => 6.01 + * + * _.ceil(6040, -2); + * // => 6100 + */ + var ceil = createRound('ceil'); + + /** + * Divide two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} dividend The first number in a division. + * @param {number} divisor The second number in a division. + * @returns {number} Returns the quotient. + * @example + * + * _.divide(6, 4); + * // => 1.5 + */ + var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; + }, 1); + + /** + * Computes `number` rounded down to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round down. + * @param {number} [precision=0] The precision to round down to. + * @returns {number} Returns the rounded down number. + * @example + * + * _.floor(4.006); + * // => 4 + * + * _.floor(0.046, 2); + * // => 0.04 + * + * _.floor(4060, -2); + * // => 4000 + */ + var floor = createRound('floor'); + + /** + * Computes the maximum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => undefined + */ + function max(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseGt) + : undefined; + } + + /** + * This method is like `_.max` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {*} Returns the maximum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.maxBy(objects, function(o) { return o.n; }); + * // => { 'n': 2 } + * + * // The `_.property` iteratee shorthand. + * _.maxBy(objects, 'n'); + * // => { 'n': 2 } + */ + function maxBy(array, iteratee) { + return (array && array.length) + ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) + : undefined; + } + + /** + * Computes the mean of the values in `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @returns {number} Returns the mean. + * @example + * + * _.mean([4, 2, 8, 6]); + * // => 5 + */ + function mean(array) { + return baseMean(array, identity); + } + + /** + * This method is like `_.mean` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the value to be averaged. + * The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the mean. + * @example + * + * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * + * _.meanBy(objects, function(o) { return o.n; }); + * // => 5 + * + * // The `_.property` iteratee shorthand. + * _.meanBy(objects, 'n'); + * // => 5 + */ + function meanBy(array, iteratee) { + return baseMean(array, getIteratee(iteratee, 2)); + } + + /** + * Computes the minimum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => undefined + */ + function min(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseLt) + : undefined; + } + + /** + * This method is like `_.min` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {*} Returns the minimum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.minBy(objects, function(o) { return o.n; }); + * // => { 'n': 1 } + * + * // The `_.property` iteratee shorthand. + * _.minBy(objects, 'n'); + * // => { 'n': 1 } + */ + function minBy(array, iteratee) { + return (array && array.length) + ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) + : undefined; + } + + /** + * Multiply two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} multiplier The first number in a multiplication. + * @param {number} multiplicand The second number in a multiplication. + * @returns {number} Returns the product. + * @example + * + * _.multiply(6, 4); + * // => 24 + */ + var multiply = createMathOperation(function(multiplier, multiplicand) { + return multiplier * multiplicand; + }, 1); + + /** + * Computes `number` rounded to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round. + * @param {number} [precision=0] The precision to round to. + * @returns {number} Returns the rounded number. + * @example + * + * _.round(4.006); + * // => 4 + * + * _.round(4.006, 2); + * // => 4.01 + * + * _.round(4060, -2); + * // => 4100 + */ + var round = createRound('round'); + + /** + * Subtract two numbers. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {number} minuend The first number in a subtraction. + * @param {number} subtrahend The second number in a subtraction. + * @returns {number} Returns the difference. + * @example + * + * _.subtract(6, 4); + * // => 2 + */ + var subtract = createMathOperation(function(minuend, subtrahend) { + return minuend - subtrahend; + }, 0); + + /** + * Computes the sum of the values in `array`. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {Array} array The array to iterate over. + * @returns {number} Returns the sum. + * @example + * + * _.sum([4, 2, 8, 6]); + * // => 20 + */ + function sum(array) { + return (array && array.length) + ? baseSum(array, identity) + : 0; + } + + /** + * This method is like `_.sum` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the value to be summed. + * The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the sum. + * @example + * + * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * + * _.sumBy(objects, function(o) { return o.n; }); + * // => 20 + * + * // The `_.property` iteratee shorthand. + * _.sumBy(objects, 'n'); + * // => 20 + */ + function sumBy(array, iteratee) { + return (array && array.length) + ? baseSum(array, getIteratee(iteratee, 2)) + : 0; + } + + /*------------------------------------------------------------------------*/ + + // Add methods that return wrapped values in chain sequences. + lodash.after = after; + lodash.ary = ary; + lodash.assign = assign; + lodash.assignIn = assignIn; + lodash.assignInWith = assignInWith; + lodash.assignWith = assignWith; + lodash.at = at; + lodash.before = before; + lodash.bind = bind; + lodash.bindAll = bindAll; + lodash.bindKey = bindKey; + lodash.castArray = castArray; + lodash.chain = chain; + lodash.chunk = chunk; + lodash.compact = compact; + lodash.concat = concat; + lodash.cond = cond; + lodash.conforms = conforms; + lodash.constant = constant; + lodash.countBy = countBy; + lodash.create = create; + lodash.curry = curry; + lodash.curryRight = curryRight; + lodash.debounce = debounce; + lodash.defaults = defaults; + lodash.defaultsDeep = defaultsDeep; + lodash.defer = defer; + lodash.delay = delay; + lodash.difference = difference; + lodash.differenceBy = differenceBy; + lodash.differenceWith = differenceWith; + lodash.drop = drop; + lodash.dropRight = dropRight; + lodash.dropRightWhile = dropRightWhile; + lodash.dropWhile = dropWhile; + lodash.fill = fill; + lodash.filter = filter; + lodash.flatMap = flatMap; + lodash.flatMapDeep = flatMapDeep; + lodash.flatMapDepth = flatMapDepth; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.flattenDepth = flattenDepth; + lodash.flip = flip; + lodash.flow = flow; + lodash.flowRight = flowRight; + lodash.fromPairs = fromPairs; + lodash.functions = functions; + lodash.functionsIn = functionsIn; + lodash.groupBy = groupBy; + lodash.initial = initial; + lodash.intersection = intersection; + lodash.intersectionBy = intersectionBy; + lodash.intersectionWith = intersectionWith; + lodash.invert = invert; + lodash.invertBy = invertBy; + lodash.invokeMap = invokeMap; + lodash.iteratee = iteratee; + lodash.keyBy = keyBy; + lodash.keys = keys; + lodash.keysIn = keysIn; + lodash.map = map; + lodash.mapKeys = mapKeys; + lodash.mapValues = mapValues; + lodash.matches = matches; + lodash.matchesProperty = matchesProperty; + lodash.memoize = memoize; + lodash.merge = merge; + lodash.mergeWith = mergeWith; + lodash.method = method; + lodash.methodOf = methodOf; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.nthArg = nthArg; + lodash.omit = omit; + lodash.omitBy = omitBy; + lodash.once = once; + lodash.orderBy = orderBy; + lodash.over = over; + lodash.overArgs = overArgs; + lodash.overEvery = overEvery; + lodash.overSome = overSome; + lodash.partial = partial; + lodash.partialRight = partialRight; + lodash.partition = partition; + lodash.pick = pick; + lodash.pickBy = pickBy; + lodash.property = property; + lodash.propertyOf = propertyOf; + lodash.pull = pull; + lodash.pullAll = pullAll; + lodash.pullAllBy = pullAllBy; + lodash.pullAllWith = pullAllWith; + lodash.pullAt = pullAt; + lodash.range = range; + lodash.rangeRight = rangeRight; + lodash.rearg = rearg; + lodash.reject = reject; + lodash.remove = remove; + lodash.rest = rest; + lodash.reverse = reverse; + lodash.sampleSize = sampleSize; + lodash.set = set; + lodash.setWith = setWith; + lodash.shuffle = shuffle; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.sortedUniq = sortedUniq; + lodash.sortedUniqBy = sortedUniqBy; + lodash.split = split; + lodash.spread = spread; + lodash.tail = tail; + lodash.take = take; + lodash.takeRight = takeRight; + lodash.takeRightWhile = takeRightWhile; + lodash.takeWhile = takeWhile; + lodash.tap = tap; + lodash.throttle = throttle; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.toPairs = toPairs; + lodash.toPairsIn = toPairsIn; + lodash.toPath = toPath; + lodash.toPlainObject = toPlainObject; + lodash.transform = transform; + lodash.unary = unary; + lodash.union = union; + lodash.unionBy = unionBy; + lodash.unionWith = unionWith; + lodash.uniq = uniq; + lodash.uniqBy = uniqBy; + lodash.uniqWith = uniqWith; + lodash.unset = unset; + lodash.unzip = unzip; + lodash.unzipWith = unzipWith; + lodash.update = update; + lodash.updateWith = updateWith; + lodash.values = values; + lodash.valuesIn = valuesIn; + lodash.without = without; + lodash.words = words; + lodash.wrap = wrap; + lodash.xor = xor; + lodash.xorBy = xorBy; + lodash.xorWith = xorWith; + lodash.zip = zip; + lodash.zipObject = zipObject; + lodash.zipObjectDeep = zipObjectDeep; + lodash.zipWith = zipWith; + + // Add aliases. + lodash.entries = toPairs; + lodash.entriesIn = toPairsIn; + lodash.extend = assignIn; + lodash.extendWith = assignInWith; + + // Add methods to `lodash.prototype`. + mixin(lodash, lodash); + + /*------------------------------------------------------------------------*/ + + // Add methods that return unwrapped values in chain sequences. + lodash.add = add; + lodash.attempt = attempt; + lodash.camelCase = camelCase; + lodash.capitalize = capitalize; + lodash.ceil = ceil; + lodash.clamp = clamp; + lodash.clone = clone; + lodash.cloneDeep = cloneDeep; + lodash.cloneDeepWith = cloneDeepWith; + lodash.cloneWith = cloneWith; + lodash.conformsTo = conformsTo; + lodash.deburr = deburr; + lodash.defaultTo = defaultTo; + lodash.divide = divide; + lodash.endsWith = endsWith; + lodash.eq = eq; + lodash.escape = escape; + lodash.escapeRegExp = escapeRegExp; + lodash.every = every; + lodash.find = find; + lodash.findIndex = findIndex; + lodash.findKey = findKey; + lodash.findLast = findLast; + lodash.findLastIndex = findLastIndex; + lodash.findLastKey = findLastKey; + lodash.floor = floor; + lodash.forEach = forEach; + lodash.forEachRight = forEachRight; + lodash.forIn = forIn; + lodash.forInRight = forInRight; + lodash.forOwn = forOwn; + lodash.forOwnRight = forOwnRight; + lodash.get = get; + lodash.gt = gt; + lodash.gte = gte; + lodash.has = has; + lodash.hasIn = hasIn; + lodash.head = head; + lodash.identity = identity; + lodash.includes = includes; + lodash.indexOf = indexOf; + lodash.inRange = inRange; + lodash.invoke = invoke; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isArrayBuffer = isArrayBuffer; + lodash.isArrayLike = isArrayLike; + lodash.isArrayLikeObject = isArrayLikeObject; + lodash.isBoolean = isBoolean; + lodash.isBuffer = isBuffer; + lodash.isDate = isDate; + lodash.isElement = isElement; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isEqualWith = isEqualWith; + lodash.isError = isError; + lodash.isFinite = isFinite; + lodash.isFunction = isFunction; + lodash.isInteger = isInteger; + lodash.isLength = isLength; + lodash.isMap = isMap; + lodash.isMatch = isMatch; + lodash.isMatchWith = isMatchWith; + lodash.isNaN = isNaN; + lodash.isNative = isNative; + lodash.isNil = isNil; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isObjectLike = isObjectLike; + lodash.isPlainObject = isPlainObject; + lodash.isRegExp = isRegExp; + lodash.isSafeInteger = isSafeInteger; + lodash.isSet = isSet; + lodash.isString = isString; + lodash.isSymbol = isSymbol; + lodash.isTypedArray = isTypedArray; + lodash.isUndefined = isUndefined; + lodash.isWeakMap = isWeakMap; + lodash.isWeakSet = isWeakSet; + lodash.join = join; + lodash.kebabCase = kebabCase; + lodash.last = last; + lodash.lastIndexOf = lastIndexOf; + lodash.lowerCase = lowerCase; + lodash.lowerFirst = lowerFirst; + lodash.lt = lt; + lodash.lte = lte; + lodash.max = max; + lodash.maxBy = maxBy; + lodash.mean = mean; + lodash.meanBy = meanBy; + lodash.min = min; + lodash.minBy = minBy; + lodash.stubArray = stubArray; + lodash.stubFalse = stubFalse; + lodash.stubObject = stubObject; + lodash.stubString = stubString; + lodash.stubTrue = stubTrue; + lodash.multiply = multiply; + lodash.nth = nth; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.now = now; + lodash.pad = pad; + lodash.padEnd = padEnd; + lodash.padStart = padStart; + lodash.parseInt = parseInt; + lodash.random = random; + lodash.reduce = reduce; + lodash.reduceRight = reduceRight; + lodash.repeat = repeat; + lodash.replace = replace; + lodash.result = result; + lodash.round = round; + lodash.runInContext = runInContext; + lodash.sample = sample; + lodash.size = size; + lodash.snakeCase = snakeCase; + lodash.some = some; + lodash.sortedIndex = sortedIndex; + lodash.sortedIndexBy = sortedIndexBy; + lodash.sortedIndexOf = sortedIndexOf; + lodash.sortedLastIndex = sortedLastIndex; + lodash.sortedLastIndexBy = sortedLastIndexBy; + lodash.sortedLastIndexOf = sortedLastIndexOf; + lodash.startCase = startCase; + lodash.startsWith = startsWith; + lodash.subtract = subtract; + lodash.sum = sum; + lodash.sumBy = sumBy; + lodash.template = template; + lodash.times = times; + lodash.toFinite = toFinite; + lodash.toInteger = toInteger; + lodash.toLength = toLength; + lodash.toLower = toLower; + lodash.toNumber = toNumber; + lodash.toSafeInteger = toSafeInteger; + lodash.toString = toString; + lodash.toUpper = toUpper; + lodash.trim = trim; + lodash.trimEnd = trimEnd; + lodash.trimStart = trimStart; + lodash.truncate = truncate; + lodash.unescape = unescape; + lodash.uniqueId = uniqueId; + lodash.upperCase = upperCase; + lodash.upperFirst = upperFirst; + + // Add aliases. + lodash.each = forEach; + lodash.eachRight = forEachRight; + lodash.first = head; + + mixin(lodash, (function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }()), { 'chain': false }); + + /*------------------------------------------------------------------------*/ + + /** + * The semantic version number. + * + * @static + * @memberOf _ + * @type {string} + */ + lodash.VERSION = VERSION; + + // Assign default placeholders. + arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { + lodash[methodName].placeholder = lodash; + }); + + // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. + arrayEach(['drop', 'take'], function(methodName, index) { + LazyWrapper.prototype[methodName] = function(n) { + n = n === undefined ? 1 : nativeMax(toInteger(n), 0); + + var result = (this.__filtered__ && !index) + ? new LazyWrapper(this) + : this.clone(); + + if (result.__filtered__) { + result.__takeCount__ = nativeMin(n, result.__takeCount__); + } else { + result.__views__.push({ + 'size': nativeMin(n, MAX_ARRAY_LENGTH), + 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') + }); + } + return result; + }; + + LazyWrapper.prototype[methodName + 'Right'] = function(n) { + return this.reverse()[methodName](n).reverse(); + }; + }); + + // Add `LazyWrapper` methods that accept an `iteratee` value. + arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { + var type = index + 1, + isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; + + LazyWrapper.prototype[methodName] = function(iteratee) { + var result = this.clone(); + result.__iteratees__.push({ + 'iteratee': getIteratee(iteratee, 3), + 'type': type + }); + result.__filtered__ = result.__filtered__ || isFilter; + return result; + }; + }); + + // Add `LazyWrapper` methods for `_.head` and `_.last`. + arrayEach(['head', 'last'], function(methodName, index) { + var takeName = 'take' + (index ? 'Right' : ''); + + LazyWrapper.prototype[methodName] = function() { + return this[takeName](1).value()[0]; + }; + }); + + // Add `LazyWrapper` methods for `_.initial` and `_.tail`. + arrayEach(['initial', 'tail'], function(methodName, index) { + var dropName = 'drop' + (index ? '' : 'Right'); + + LazyWrapper.prototype[methodName] = function() { + return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); + }; + }); + + LazyWrapper.prototype.compact = function() { + return this.filter(identity); + }; + + LazyWrapper.prototype.find = function(predicate) { + return this.filter(predicate).head(); + }; + + LazyWrapper.prototype.findLast = function(predicate) { + return this.reverse().find(predicate); + }; + + LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { + if (typeof path == 'function') { + return new LazyWrapper(this); + } + return this.map(function(value) { + return baseInvoke(value, path, args); + }); + }); + + LazyWrapper.prototype.reject = function(predicate) { + return this.filter(negate(getIteratee(predicate))); + }; + + LazyWrapper.prototype.slice = function(start, end) { + start = toInteger(start); + + var result = this; + if (result.__filtered__ && (start > 0 || end < 0)) { + return new LazyWrapper(result); + } + if (start < 0) { + result = result.takeRight(-start); + } else if (start) { + result = result.drop(start); + } + if (end !== undefined) { + end = toInteger(end); + result = end < 0 ? result.dropRight(-end) : result.take(end - start); + } + return result; + }; + + LazyWrapper.prototype.takeRightWhile = function(predicate) { + return this.reverse().takeWhile(predicate).reverse(); + }; + + LazyWrapper.prototype.toArray = function() { + return this.take(MAX_ARRAY_LENGTH); + }; + + // Add `LazyWrapper` methods to `lodash.prototype`. + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), + isTaker = /^(?:head|last)$/.test(methodName), + lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], + retUnwrapped = isTaker || /^find/.test(methodName); + + if (!lodashFunc) { + return; + } + lodash.prototype[methodName] = function() { + var value = this.__wrapped__, + args = isTaker ? [1] : arguments, + isLazy = value instanceof LazyWrapper, + iteratee = args[0], + useLazy = isLazy || isArray(value); + + var interceptor = function(value) { + var result = lodashFunc.apply(lodash, arrayPush([value], args)); + return (isTaker && chainAll) ? result[0] : result; + }; + + if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { + // Avoid lazy use if the iteratee has a "length" value other than `1`. + isLazy = useLazy = false; + } + var chainAll = this.__chain__, + isHybrid = !!this.__actions__.length, + isUnwrapped = retUnwrapped && !chainAll, + onlyLazy = isLazy && !isHybrid; + + if (!retUnwrapped && useLazy) { + value = onlyLazy ? value : new LazyWrapper(this); + var result = func.apply(value, args); + result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); + return new LodashWrapper(result, chainAll); + } + if (isUnwrapped && onlyLazy) { + return func.apply(this, args); + } + result = this.thru(interceptor); + return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; + }; + }); + + // Add `Array` methods to `lodash.prototype`. + arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { + var func = arrayProto[methodName], + chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', + retUnwrapped = /^(?:pop|shift)$/.test(methodName); + + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value) { + return func.apply(isArray(value) ? value : [], args); + }); + }; + }); + + // Map minified method names to their real names. + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var lodashFunc = lodash[methodName]; + if (lodashFunc) { + var key = lodashFunc.name + ''; + if (!hasOwnProperty.call(realNames, key)) { + realNames[key] = []; + } + realNames[key].push({ 'name': methodName, 'func': lodashFunc }); + } + }); + + realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ + 'name': 'wrapper', + 'func': undefined + }]; + + // Add methods to `LazyWrapper`. + LazyWrapper.prototype.clone = lazyClone; + LazyWrapper.prototype.reverse = lazyReverse; + LazyWrapper.prototype.value = lazyValue; + + // Add chain sequence methods to the `lodash` wrapper. + lodash.prototype.at = wrapperAt; + lodash.prototype.chain = wrapperChain; + lodash.prototype.commit = wrapperCommit; + lodash.prototype.next = wrapperNext; + lodash.prototype.plant = wrapperPlant; + lodash.prototype.reverse = wrapperReverse; + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; + + // Add lazy aliases. + lodash.prototype.first = lodash.prototype.head; + + if (symIterator) { + lodash.prototype[symIterator] = wrapperToIterator; + } + return lodash; + }); + + /*--------------------------------------------------------------------------*/ + + // Export lodash. + var _ = runInContext(); + + // Some AMD build optimizers, like r.js, check for condition patterns like: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // Expose Lodash on the global object to prevent errors when Lodash is + // loaded by a script tag in the presence of an AMD loader. + // See http://requirejs.org/docs/errors.html#mismatch for more details. + // Use `_.noConflict` to remove Lodash from the global object. + root._ = _; + + // Define as an anonymous module so, through path mapping, it can be + // referenced as the "underscore" module. + define(function() { + return _; + }); + } + // Check for `exports` after `define` in case a build optimizer adds it. + else if (freeModule) { + // Export for Node.js. + (freeModule.exports = _)._ = _; + // Export for CommonJS support. + freeExports._ = _; + } + else { + // Export to the global object. + root._ = _; + } +}.call(this)); + + +/***/ }), + +/***/ 7129: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +// A linked list to keep track of recently-used-ness +const Yallist = __nccwpck_require__(40665) + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache + + +/***/ }), + +/***/ 18424: +/***/ (function(__unused_webpack_module, exports) { + +/** + * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most + * recently used items while discarding least recently used items when its limit + * is reached. + * + * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson + * See README.md for details. + * + * Illustration of the design: + * + * entry entry entry entry + * ______ ______ ______ ______ + * | head |.newer => | |.newer => | |.newer => | tail | + * | A | | B | | C | | D | + * |______| <= older.|______| <= older.|______| <= older.|______| + * + * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added + */ +(function(g,f){ + const e = true ? exports : 0; + f(e); + if (typeof define == 'function' && define.amd) { define('lru', e); } +})(this, function(exports) { + +const NEWER = Symbol('newer'); +const OLDER = Symbol('older'); + +function LRUMap(limit, entries) { + if (typeof limit !== 'number') { + // called as (entries) + entries = limit; + limit = 0; + } + + this.size = 0; + this.limit = limit; + this.oldest = this.newest = undefined; + this._keymap = new Map(); + + if (entries) { + this.assign(entries); + if (limit < 1) { + this.limit = this.size; + } + } +} + +exports.LRUMap = LRUMap; + +function Entry(key, value) { + this.key = key; + this.value = value; + this[NEWER] = undefined; + this[OLDER] = undefined; +} + + +LRUMap.prototype._markEntryAsUsed = function(entry) { + if (entry === this.newest) { + // Already the most recenlty used entry, so no need to update the list + return; + } + // HEAD--------------TAIL + // <.older .newer> + // <--- add direction -- + // A B C E + if (entry[NEWER]) { + if (entry === this.oldest) { + this.oldest = entry[NEWER]; + } + entry[NEWER][OLDER] = entry[OLDER]; // C <-- E. + } + if (entry[OLDER]) { + entry[OLDER][NEWER] = entry[NEWER]; // C. --> E + } + entry[NEWER] = undefined; // D --x + entry[OLDER] = this.newest; // D. --> E + if (this.newest) { + this.newest[NEWER] = entry; // E. <-- D + } + this.newest = entry; +}; + +LRUMap.prototype.assign = function(entries) { + let entry, limit = this.limit || Number.MAX_VALUE; + this._keymap.clear(); + let it = entries[Symbol.iterator](); + for (let itv = it.next(); !itv.done; itv = it.next()) { + let e = new Entry(itv.value[0], itv.value[1]); + this._keymap.set(e.key, e); + if (!entry) { + this.oldest = e; + } else { + entry[NEWER] = e; + e[OLDER] = entry; + } + entry = e; + if (limit-- == 0) { + throw new Error('overflow'); + } + } + this.newest = entry; + this.size = this._keymap.size; +}; + +LRUMap.prototype.get = function(key) { + // First, find our cache entry + var entry = this._keymap.get(key); + if (!entry) return; // Not cached. Sorry. + // As was found in the cache, register it as being requested recently + this._markEntryAsUsed(entry); + return entry.value; +}; + +LRUMap.prototype.set = function(key, value) { + var entry = this._keymap.get(key); - arrayEach(methodNames, function(methodName) { - var func = source[methodName]; - object[methodName] = func; - if (isFunc) { - object.prototype[methodName] = function() { - var chainAll = this.__chain__; - if (chain || chainAll) { - var result = object(this.__wrapped__), - actions = result.__actions__ = copyArray(this.__actions__); + if (entry) { + // update existing + entry.value = value; + this._markEntryAsUsed(entry); + return this; + } - actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); - result.__chain__ = chainAll; - return result; - } - return func.apply(object, arrayPush([this.value()], arguments)); - }; - } - }); + // new entry + this._keymap.set(key, (entry = new Entry(key, value))); - return object; - } + if (this.newest) { + // link previous tail to the new tail (entry) + this.newest[NEWER] = entry; + entry[OLDER] = this.newest; + } else { + // we're first in -- yay + this.oldest = entry; + } - /** - * Reverts the `_` variable to its previous value and returns a reference to - * the `lodash` function. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @returns {Function} Returns the `lodash` function. - * @example - * - * var lodash = _.noConflict(); - */ - function noConflict() { - if (root._ === this) { - root._ = oldDash; - } - return this; - } + // add new entry to the end of the linked list -- it's now the freshest entry. + this.newest = entry; + ++this.size; + if (this.size > this.limit) { + // we hit the limit -- remove the head + this.shift(); + } - /** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ - function noop() { - // No operation performed. - } + return this; +}; - /** - * Creates a function that gets the argument at index `n`. If `n` is negative, - * the nth argument from the end is returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {number} [n=0] The index of the argument to return. - * @returns {Function} Returns the new pass-thru function. - * @example - * - * var func = _.nthArg(1); - * func('a', 'b', 'c', 'd'); - * // => 'b' - * - * var func = _.nthArg(-2); - * func('a', 'b', 'c', 'd'); - * // => 'c' - */ - function nthArg(n) { - n = toInteger(n); - return baseRest(function(args) { - return baseNth(args, n); - }); +LRUMap.prototype.shift = function() { + // todo: handle special case when limit == 1 + var entry = this.oldest; + if (entry) { + if (this.oldest[NEWER]) { + // advance the list + this.oldest = this.oldest[NEWER]; + this.oldest[OLDER] = undefined; + } else { + // the cache is exhausted + this.oldest = undefined; + this.newest = undefined; } + // Remove last strong reference to and remove links from the purged + // entry being returned: + entry[NEWER] = entry[OLDER] = undefined; + this._keymap.delete(entry.key); + --this.size; + return [entry.key, entry.value]; + } +}; - /** - * Creates a function that invokes `iteratees` with the arguments it receives - * and returns their results. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to invoke. - * @returns {Function} Returns the new function. - * @example - * - * var func = _.over([Math.max, Math.min]); - * - * func(1, 2, 3, 4); - * // => [4, 1] - */ - var over = createOver(arrayMap); +// ---------------------------------------------------------------------------- +// Following code is optional and can be removed without breaking the core +// functionality. - /** - * Creates a function that checks if **all** of the `predicates` return - * truthy when invoked with the arguments it receives. - * - * Following shorthands are possible for providing predicates. - * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. - * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {...(Function|Function[])} [predicates=[_.identity]] - * The predicates to check. - * @returns {Function} Returns the new function. - * @example - * - * var func = _.overEvery([Boolean, isFinite]); - * - * func('1'); - * // => true - * - * func(null); - * // => false - * - * func(NaN); - * // => false - */ - var overEvery = createOver(arrayEvery); +LRUMap.prototype.find = function(key) { + let e = this._keymap.get(key); + return e ? e.value : undefined; +}; - /** - * Creates a function that checks if **any** of the `predicates` return - * truthy when invoked with the arguments it receives. - * - * Following shorthands are possible for providing predicates. - * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. - * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {...(Function|Function[])} [predicates=[_.identity]] - * The predicates to check. - * @returns {Function} Returns the new function. - * @example - * - * var func = _.overSome([Boolean, isFinite]); - * - * func('1'); - * // => true - * - * func(null); - * // => true - * - * func(NaN); - * // => false - * - * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) - * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) - */ - var overSome = createOver(arraySome); +LRUMap.prototype.has = function(key) { + return this._keymap.has(key); +}; - /** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } +LRUMap.prototype['delete'] = function(key) { + var entry = this._keymap.get(key); + if (!entry) return; + this._keymap.delete(entry.key); + if (entry[NEWER] && entry[OLDER]) { + // relink the older entry with the newer entry + entry[OLDER][NEWER] = entry[NEWER]; + entry[NEWER][OLDER] = entry[OLDER]; + } else if (entry[NEWER]) { + // remove the link to us + entry[NEWER][OLDER] = undefined; + // link the newer entry to head + this.oldest = entry[NEWER]; + } else if (entry[OLDER]) { + // remove the link to us + entry[OLDER][NEWER] = undefined; + // link the newer entry to head + this.newest = entry[OLDER]; + } else {// if(entry[OLDER] === undefined && entry.newer === undefined) { + this.oldest = this.newest = undefined; + } - /** - * The opposite of `_.property`; this method creates a function that returns - * the value at a given path of `object`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Util - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - * @example - * - * var array = [0, 1, 2], - * object = { 'a': array, 'b': array, 'c': array }; - * - * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); - * // => [2, 0] - * - * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); - * // => [2, 0] - */ - function propertyOf(object) { - return function(path) { - return object == null ? undefined : baseGet(object, path); - }; - } + this.size--; + return entry.value; +}; - /** - * Creates an array of numbers (positive and/or negative) progressing from - * `start` up to, but not including, `end`. A step of `-1` is used if a negative - * `start` is specified without an `end` or `step`. If `end` is not specified, - * it's set to `start` with `start` then set to `0`. - * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @param {number} [step=1] The value to increment or decrement by. - * @returns {Array} Returns the range of numbers. - * @see _.inRange, _.rangeRight - * @example - * - * _.range(4); - * // => [0, 1, 2, 3] - * - * _.range(-4); - * // => [0, -1, -2, -3] - * - * _.range(1, 5); - * // => [1, 2, 3, 4] - * - * _.range(0, 20, 5); - * // => [0, 5, 10, 15] - * - * _.range(0, -4, -1); - * // => [0, -1, -2, -3] - * - * _.range(1, 4, 0); - * // => [1, 1, 1] - * - * _.range(0); - * // => [] - */ - var range = createRange(); +LRUMap.prototype.clear = function() { + // Not clearing links should be safe, as we don't expose live links to user + this.oldest = this.newest = undefined; + this.size = 0; + this._keymap.clear(); +}; - /** - * This method is like `_.range` except that it populates values in - * descending order. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @param {number} [step=1] The value to increment or decrement by. - * @returns {Array} Returns the range of numbers. - * @see _.inRange, _.range - * @example - * - * _.rangeRight(4); - * // => [3, 2, 1, 0] - * - * _.rangeRight(-4); - * // => [-3, -2, -1, 0] - * - * _.rangeRight(1, 5); - * // => [4, 3, 2, 1] - * - * _.rangeRight(0, 20, 5); - * // => [15, 10, 5, 0] - * - * _.rangeRight(0, -4, -1); - * // => [-3, -2, -1, 0] - * - * _.rangeRight(1, 4, 0); - * // => [1, 1, 1] - * - * _.rangeRight(0); - * // => [] - */ - var rangeRight = createRange(true); - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } +function EntryIterator(oldestEntry) { this.entry = oldestEntry; } +EntryIterator.prototype[Symbol.iterator] = function() { return this; } +EntryIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: [ent.key, ent.value] }; + } else { + return { done: true, value: undefined }; + } +}; - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - /** - * This method returns a new empty object. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Object} Returns the new empty object. - * @example - * - * var objects = _.times(2, _.stubObject); - * - * console.log(objects); - * // => [{}, {}] - * - * console.log(objects[0] === objects[1]); - * // => false - */ - function stubObject() { - return {}; - } +function KeyIterator(oldestEntry) { this.entry = oldestEntry; } +KeyIterator.prototype[Symbol.iterator] = function() { return this; } +KeyIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: ent.key }; + } else { + return { done: true, value: undefined }; + } +}; - /** - * This method returns an empty string. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {string} Returns the empty string. - * @example - * - * _.times(2, _.stubString); - * // => ['', ''] - */ - function stubString() { - return ''; - } +function ValueIterator(oldestEntry) { this.entry = oldestEntry; } +ValueIterator.prototype[Symbol.iterator] = function() { return this; } +ValueIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: ent.value }; + } else { + return { done: true, value: undefined }; + } +}; - /** - * This method returns `true`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `true`. - * @example - * - * _.times(2, _.stubTrue); - * // => [true, true] - */ - function stubTrue() { - return true; - } - /** - * Invokes the iteratee `n` times, returning an array of the results of - * each invocation. The iteratee is invoked with one argument; (index). - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of results. - * @example - * - * _.times(3, String); - * // => ['0', '1', '2'] - * - * _.times(4, _.constant(0)); - * // => [0, 0, 0, 0] - */ - function times(n, iteratee) { - n = toInteger(n); - if (n < 1 || n > MAX_SAFE_INTEGER) { - return []; - } - var index = MAX_ARRAY_LENGTH, - length = nativeMin(n, MAX_ARRAY_LENGTH); +LRUMap.prototype.keys = function() { + return new KeyIterator(this.oldest); +}; + +LRUMap.prototype.values = function() { + return new ValueIterator(this.oldest); +}; - iteratee = getIteratee(iteratee); - n -= MAX_ARRAY_LENGTH; +LRUMap.prototype.entries = function() { + return this; +}; - var result = baseTimes(length, iteratee); - while (++index < n) { - iteratee(index); - } - return result; - } +LRUMap.prototype[Symbol.iterator] = function() { + return new EntryIterator(this.oldest); +}; - /** - * Converts `value` to a property path array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {*} value The value to convert. - * @returns {Array} Returns the new property path array. - * @example - * - * _.toPath('a.b.c'); - * // => ['a', 'b', 'c'] - * - * _.toPath('a[0].b.c'); - * // => ['a', '0', 'b', 'c'] - */ - function toPath(value) { - if (isArray(value)) { - return arrayMap(value, toKey); - } - return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); - } +LRUMap.prototype.forEach = function(fun, thisObj) { + if (typeof thisObj !== 'object') { + thisObj = this; + } + let entry = this.oldest; + while (entry) { + fun.call(thisObj, entry.value, entry.key, this); + entry = entry[NEWER]; + } +}; - /** - * Generates a unique ID. If `prefix` is given, the ID is appended to it. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {string} [prefix=''] The value to prefix the ID with. - * @returns {string} Returns the unique ID. - * @example - * - * _.uniqueId('contact_'); - * // => 'contact_104' - * - * _.uniqueId(); - * // => '105' - */ - function uniqueId(prefix) { - var id = ++idCounter; - return toString(prefix) + id; +/** Returns a JSON (array) representation */ +LRUMap.prototype.toJSON = function() { + var s = new Array(this.size), i = 0, entry = this.oldest; + while (entry) { + s[i++] = { key: entry.key, value: entry.value }; + entry = entry[NEWER]; + } + return s; +}; + +/** Returns a String representation */ +LRUMap.prototype.toString = function() { + var s = '', entry = this.oldest; + while (entry) { + s += String(entry.key)+':'+entry.value; + entry = entry[NEWER]; + if (entry) { + s += ' < '; } + } + return s; +}; - /*------------------------------------------------------------------------*/ +}); - /** - * Adds two numbers. - * - * @static - * @memberOf _ - * @since 3.4.0 - * @category Math - * @param {number} augend The first number in an addition. - * @param {number} addend The second number in an addition. - * @returns {number} Returns the total. - * @example - * - * _.add(6, 4); - * // => 10 - */ - var add = createMathOperation(function(augend, addend) { - return augend + addend; - }, 0); - /** - * Computes `number` rounded up to `precision`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Math - * @param {number} number The number to round up. - * @param {number} [precision=0] The precision to round up to. - * @returns {number} Returns the rounded up number. - * @example - * - * _.ceil(4.006); - * // => 5 - * - * _.ceil(6.004, 2); - * // => 6.01 - * - * _.ceil(6040, -2); - * // => 6100 - */ - var ceil = createRound('ceil'); +/***/ }), - /** - * Divide two numbers. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Math - * @param {number} dividend The first number in a division. - * @param {number} divisor The second number in a division. - * @returns {number} Returns the quotient. - * @example - * - * _.divide(6, 4); - * // => 1.5 - */ - var divide = createMathOperation(function(dividend, divisor) { - return dividend / divisor; - }, 1); +/***/ 19955: +/***/ ((__unused_webpack_module, exports) => { - /** - * Computes `number` rounded down to `precision`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Math - * @param {number} number The number to round down. - * @param {number} [precision=0] The precision to round down to. - * @returns {number} Returns the rounded down number. - * @example - * - * _.floor(4.006); - * // => 4 - * - * _.floor(0.046, 2); - * // => 0.04 - * - * _.floor(4060, -2); - * // => 4000 - */ - var floor = createRound('floor'); +/*! + * media-typer + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ - /** - * Computes the maximum value of `array`. If `array` is empty or falsey, - * `undefined` is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Math - * @param {Array} array The array to iterate over. - * @returns {*} Returns the maximum value. - * @example - * - * _.max([4, 2, 8, 6]); - * // => 8 - * - * _.max([]); - * // => undefined - */ - function max(array) { - return (array && array.length) - ? baseExtremum(array, identity, baseGt) - : undefined; - } +/** + * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 + * + * 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 = + * SHT = + * CTL = + * OCTET = + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; +var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ - /** - * This method is like `_.max` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * the value is ranked. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {*} Returns the maximum value. - * @example - * - * var objects = [{ 'n': 1 }, { 'n': 2 }]; - * - * _.maxBy(objects, function(o) { return o.n; }); - * // => { 'n': 2 } - * - * // The `_.property` iteratee shorthand. - * _.maxBy(objects, 'n'); - * // => { 'n': 2 } - */ - function maxBy(array, iteratee) { - return (array && array.length) - ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) - : undefined; - } +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ +var qescRegExp = /\\([\u0000-\u007f])/g; - /** - * Computes the mean of the values in `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @returns {number} Returns the mean. - * @example - * - * _.mean([4, 2, 8, 6]); - * // => 5 - */ - function mean(array) { - return baseMean(array, identity); - } +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ +var quoteRegExp = /([\\"])/g; - /** - * This method is like `_.mean` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the value to be averaged. - * The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the mean. - * @example - * - * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; - * - * _.meanBy(objects, function(o) { return o.n; }); - * // => 5 - * - * // The `_.property` iteratee shorthand. - * _.meanBy(objects, 'n'); - * // => 5 - */ - function meanBy(array, iteratee) { - return baseMean(array, getIteratee(iteratee, 2)); - } +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; - /** - * Computes the minimum value of `array`. If `array` is empty or falsey, - * `undefined` is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Math - * @param {Array} array The array to iterate over. - * @returns {*} Returns the minimum value. - * @example - * - * _.min([4, 2, 8, 6]); - * // => 2 - * - * _.min([]); - * // => undefined - */ - function min(array) { - return (array && array.length) - ? baseExtremum(array, identity, baseLt) - : undefined; - } +/** + * Module exports. + */ - /** - * This method is like `_.min` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * the value is ranked. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {*} Returns the minimum value. - * @example - * - * var objects = [{ 'n': 1 }, { 'n': 2 }]; - * - * _.minBy(objects, function(o) { return o.n; }); - * // => { 'n': 1 } - * - * // The `_.property` iteratee shorthand. - * _.minBy(objects, 'n'); - * // => { 'n': 1 } - */ - function minBy(array, iteratee) { - return (array && array.length) - ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) - : undefined; - } +exports.format = format +exports.parse = parse - /** - * Multiply two numbers. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Math - * @param {number} multiplier The first number in a multiplication. - * @param {number} multiplicand The second number in a multiplication. - * @returns {number} Returns the product. - * @example - * - * _.multiply(6, 4); - * // => 24 - */ - var multiply = createMathOperation(function(multiplier, multiplicand) { - return multiplier * multiplicand; - }, 1); +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @api public + */ - /** - * Computes `number` rounded to `precision`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Math - * @param {number} number The number to round. - * @param {number} [precision=0] The precision to round to. - * @returns {number} Returns the rounded number. - * @example - * - * _.round(4.006); - * // => 4 - * - * _.round(4.006, 2); - * // => 4.01 - * - * _.round(4060, -2); - * // => 4100 - */ - var round = createRound('round'); +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } - /** - * Subtract two numbers. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {number} minuend The first number in a subtraction. - * @param {number} subtrahend The second number in a subtraction. - * @returns {number} Returns the difference. - * @example - * - * _.subtract(6, 4); - * // => 2 - */ - var subtract = createMathOperation(function(minuend, subtrahend) { - return minuend - subtrahend; - }, 0); + var parameters = obj.parameters + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type - /** - * Computes the sum of the values in `array`. - * - * @static - * @memberOf _ - * @since 3.4.0 - * @category Math - * @param {Array} array The array to iterate over. - * @returns {number} Returns the sum. - * @example - * - * _.sum([4, 2, 8, 6]); - * // => 20 - */ - function sum(array) { - return (array && array.length) - ? baseSum(array, identity) - : 0; - } + if (!type || !typeNameRegExp.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !subtypeNameRegExp.test(subtype)) { + throw new TypeError('invalid subtype') + } - /** - * This method is like `_.sum` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the value to be summed. - * The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the sum. - * @example - * - * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; - * - * _.sumBy(objects, function(o) { return o.n; }); - * // => 20 - * - * // The `_.property` iteratee shorthand. - * _.sumBy(objects, 'n'); - * // => 20 - */ - function sumBy(array, iteratee) { - return (array && array.length) - ? baseSum(array, getIteratee(iteratee, 2)) - : 0; + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!typeNameRegExp.test(suffix)) { + throw new TypeError('invalid suffix') } - /*------------------------------------------------------------------------*/ + string += '+' + suffix + } - // Add methods that return wrapped values in chain sequences. - lodash.after = after; - lodash.ary = ary; - lodash.assign = assign; - lodash.assignIn = assignIn; - lodash.assignInWith = assignInWith; - lodash.assignWith = assignWith; - lodash.at = at; - lodash.before = before; - lodash.bind = bind; - lodash.bindAll = bindAll; - lodash.bindKey = bindKey; - lodash.castArray = castArray; - lodash.chain = chain; - lodash.chunk = chunk; - lodash.compact = compact; - lodash.concat = concat; - lodash.cond = cond; - lodash.conforms = conforms; - lodash.constant = constant; - lodash.countBy = countBy; - lodash.create = create; - lodash.curry = curry; - lodash.curryRight = curryRight; - lodash.debounce = debounce; - lodash.defaults = defaults; - lodash.defaultsDeep = defaultsDeep; - lodash.defer = defer; - lodash.delay = delay; - lodash.difference = difference; - lodash.differenceBy = differenceBy; - lodash.differenceWith = differenceWith; - lodash.drop = drop; - lodash.dropRight = dropRight; - lodash.dropRightWhile = dropRightWhile; - lodash.dropWhile = dropWhile; - lodash.fill = fill; - lodash.filter = filter; - lodash.flatMap = flatMap; - lodash.flatMapDeep = flatMapDeep; - lodash.flatMapDepth = flatMapDepth; - lodash.flatten = flatten; - lodash.flattenDeep = flattenDeep; - lodash.flattenDepth = flattenDepth; - lodash.flip = flip; - lodash.flow = flow; - lodash.flowRight = flowRight; - lodash.fromPairs = fromPairs; - lodash.functions = functions; - lodash.functionsIn = functionsIn; - lodash.groupBy = groupBy; - lodash.initial = initial; - lodash.intersection = intersection; - lodash.intersectionBy = intersectionBy; - lodash.intersectionWith = intersectionWith; - lodash.invert = invert; - lodash.invertBy = invertBy; - lodash.invokeMap = invokeMap; - lodash.iteratee = iteratee; - lodash.keyBy = keyBy; - lodash.keys = keys; - lodash.keysIn = keysIn; - lodash.map = map; - lodash.mapKeys = mapKeys; - lodash.mapValues = mapValues; - lodash.matches = matches; - lodash.matchesProperty = matchesProperty; - lodash.memoize = memoize; - lodash.merge = merge; - lodash.mergeWith = mergeWith; - lodash.method = method; - lodash.methodOf = methodOf; - lodash.mixin = mixin; - lodash.negate = negate; - lodash.nthArg = nthArg; - lodash.omit = omit; - lodash.omitBy = omitBy; - lodash.once = once; - lodash.orderBy = orderBy; - lodash.over = over; - lodash.overArgs = overArgs; - lodash.overEvery = overEvery; - lodash.overSome = overSome; - lodash.partial = partial; - lodash.partialRight = partialRight; - lodash.partition = partition; - lodash.pick = pick; - lodash.pickBy = pickBy; - lodash.property = property; - lodash.propertyOf = propertyOf; - lodash.pull = pull; - lodash.pullAll = pullAll; - lodash.pullAllBy = pullAllBy; - lodash.pullAllWith = pullAllWith; - lodash.pullAt = pullAt; - lodash.range = range; - lodash.rangeRight = rangeRight; - lodash.rearg = rearg; - lodash.reject = reject; - lodash.remove = remove; - lodash.rest = rest; - lodash.reverse = reverse; - lodash.sampleSize = sampleSize; - lodash.set = set; - lodash.setWith = setWith; - lodash.shuffle = shuffle; - lodash.slice = slice; - lodash.sortBy = sortBy; - lodash.sortedUniq = sortedUniq; - lodash.sortedUniqBy = sortedUniqBy; - lodash.split = split; - lodash.spread = spread; - lodash.tail = tail; - lodash.take = take; - lodash.takeRight = takeRight; - lodash.takeRightWhile = takeRightWhile; - lodash.takeWhile = takeWhile; - lodash.tap = tap; - lodash.throttle = throttle; - lodash.thru = thru; - lodash.toArray = toArray; - lodash.toPairs = toPairs; - lodash.toPairsIn = toPairsIn; - lodash.toPath = toPath; - lodash.toPlainObject = toPlainObject; - lodash.transform = transform; - lodash.unary = unary; - lodash.union = union; - lodash.unionBy = unionBy; - lodash.unionWith = unionWith; - lodash.uniq = uniq; - lodash.uniqBy = uniqBy; - lodash.uniqWith = uniqWith; - lodash.unset = unset; - lodash.unzip = unzip; - lodash.unzipWith = unzipWith; - lodash.update = update; - lodash.updateWith = updateWith; - lodash.values = values; - lodash.valuesIn = valuesIn; - lodash.without = without; - lodash.words = words; - lodash.wrap = wrap; - lodash.xor = xor; - lodash.xorBy = xorBy; - lodash.xorWith = xorWith; - lodash.zip = zip; - lodash.zipObject = zipObject; - lodash.zipObjectDeep = zipObjectDeep; - lodash.zipWith = zipWith; + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - // Add aliases. - lodash.entries = toPairs; - lodash.entriesIn = toPairsIn; - lodash.extend = assignIn; - lodash.extendWith = assignInWith; + for (var i = 0; i < params.length; i++) { + param = params[i] - // Add methods to `lodash.prototype`. - mixin(lodash, lodash); + if (!tokenRegExp.test(param)) { + throw new TypeError('invalid parameter name') + } - /*------------------------------------------------------------------------*/ + string += '; ' + param + '=' + qstring(parameters[param]) + } + } - // Add methods that return unwrapped values in chain sequences. - lodash.add = add; - lodash.attempt = attempt; - lodash.camelCase = camelCase; - lodash.capitalize = capitalize; - lodash.ceil = ceil; - lodash.clamp = clamp; - lodash.clone = clone; - lodash.cloneDeep = cloneDeep; - lodash.cloneDeepWith = cloneDeepWith; - lodash.cloneWith = cloneWith; - lodash.conformsTo = conformsTo; - lodash.deburr = deburr; - lodash.defaultTo = defaultTo; - lodash.divide = divide; - lodash.endsWith = endsWith; - lodash.eq = eq; - lodash.escape = escape; - lodash.escapeRegExp = escapeRegExp; - lodash.every = every; - lodash.find = find; - lodash.findIndex = findIndex; - lodash.findKey = findKey; - lodash.findLast = findLast; - lodash.findLastIndex = findLastIndex; - lodash.findLastKey = findLastKey; - lodash.floor = floor; - lodash.forEach = forEach; - lodash.forEachRight = forEachRight; - lodash.forIn = forIn; - lodash.forInRight = forInRight; - lodash.forOwn = forOwn; - lodash.forOwnRight = forOwnRight; - lodash.get = get; - lodash.gt = gt; - lodash.gte = gte; - lodash.has = has; - lodash.hasIn = hasIn; - lodash.head = head; - lodash.identity = identity; - lodash.includes = includes; - lodash.indexOf = indexOf; - lodash.inRange = inRange; - lodash.invoke = invoke; - lodash.isArguments = isArguments; - lodash.isArray = isArray; - lodash.isArrayBuffer = isArrayBuffer; - lodash.isArrayLike = isArrayLike; - lodash.isArrayLikeObject = isArrayLikeObject; - lodash.isBoolean = isBoolean; - lodash.isBuffer = isBuffer; - lodash.isDate = isDate; - lodash.isElement = isElement; - lodash.isEmpty = isEmpty; - lodash.isEqual = isEqual; - lodash.isEqualWith = isEqualWith; - lodash.isError = isError; - lodash.isFinite = isFinite; - lodash.isFunction = isFunction; - lodash.isInteger = isInteger; - lodash.isLength = isLength; - lodash.isMap = isMap; - lodash.isMatch = isMatch; - lodash.isMatchWith = isMatchWith; - lodash.isNaN = isNaN; - lodash.isNative = isNative; - lodash.isNil = isNil; - lodash.isNull = isNull; - lodash.isNumber = isNumber; - lodash.isObject = isObject; - lodash.isObjectLike = isObjectLike; - lodash.isPlainObject = isPlainObject; - lodash.isRegExp = isRegExp; - lodash.isSafeInteger = isSafeInteger; - lodash.isSet = isSet; - lodash.isString = isString; - lodash.isSymbol = isSymbol; - lodash.isTypedArray = isTypedArray; - lodash.isUndefined = isUndefined; - lodash.isWeakMap = isWeakMap; - lodash.isWeakSet = isWeakSet; - lodash.join = join; - lodash.kebabCase = kebabCase; - lodash.last = last; - lodash.lastIndexOf = lastIndexOf; - lodash.lowerCase = lowerCase; - lodash.lowerFirst = lowerFirst; - lodash.lt = lt; - lodash.lte = lte; - lodash.max = max; - lodash.maxBy = maxBy; - lodash.mean = mean; - lodash.meanBy = meanBy; - lodash.min = min; - lodash.minBy = minBy; - lodash.stubArray = stubArray; - lodash.stubFalse = stubFalse; - lodash.stubObject = stubObject; - lodash.stubString = stubString; - lodash.stubTrue = stubTrue; - lodash.multiply = multiply; - lodash.nth = nth; - lodash.noConflict = noConflict; - lodash.noop = noop; - lodash.now = now; - lodash.pad = pad; - lodash.padEnd = padEnd; - lodash.padStart = padStart; - lodash.parseInt = parseInt; - lodash.random = random; - lodash.reduce = reduce; - lodash.reduceRight = reduceRight; - lodash.repeat = repeat; - lodash.replace = replace; - lodash.result = result; - lodash.round = round; - lodash.runInContext = runInContext; - lodash.sample = sample; - lodash.size = size; - lodash.snakeCase = snakeCase; - lodash.some = some; - lodash.sortedIndex = sortedIndex; - lodash.sortedIndexBy = sortedIndexBy; - lodash.sortedIndexOf = sortedIndexOf; - lodash.sortedLastIndex = sortedLastIndex; - lodash.sortedLastIndexBy = sortedLastIndexBy; - lodash.sortedLastIndexOf = sortedLastIndexOf; - lodash.startCase = startCase; - lodash.startsWith = startsWith; - lodash.subtract = subtract; - lodash.sum = sum; - lodash.sumBy = sumBy; - lodash.template = template; - lodash.times = times; - lodash.toFinite = toFinite; - lodash.toInteger = toInteger; - lodash.toLength = toLength; - lodash.toLower = toLower; - lodash.toNumber = toNumber; - lodash.toSafeInteger = toSafeInteger; - lodash.toString = toString; - lodash.toUpper = toUpper; - lodash.trim = trim; - lodash.trimEnd = trimEnd; - lodash.trimStart = trimStart; - lodash.truncate = truncate; - lodash.unescape = unescape; - lodash.uniqueId = uniqueId; - lodash.upperCase = upperCase; - lodash.upperFirst = upperFirst; + return string +} - // Add aliases. - lodash.each = forEach; - lodash.eachRight = forEachRight; - lodash.first = head; +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @api public + */ - mixin(lodash, (function() { - var source = {}; - baseForOwn(lodash, function(func, methodName) { - if (!hasOwnProperty.call(lodash.prototype, methodName)) { - source[methodName] = func; - } - }); - return source; - }()), { 'chain': false }); +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } - /*------------------------------------------------------------------------*/ + // support req/res-like objects as argument + if (typeof string === 'object') { + string = getcontenttype(string) + } - /** - * The semantic version number. - * - * @static - * @memberOf _ - * @type {string} - */ - lodash.VERSION = VERSION; + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } - // Assign default placeholders. - arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { - lodash[methodName].placeholder = lodash; - }); + var index = string.indexOf(';') + var type = index !== -1 + ? string.substr(0, index) + : string - // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. - arrayEach(['drop', 'take'], function(methodName, index) { - LazyWrapper.prototype[methodName] = function(n) { - n = n === undefined ? 1 : nativeMax(toInteger(n), 0); + var key + var match + var obj = splitType(type) + var params = {} + var value - var result = (this.__filtered__ && !index) - ? new LazyWrapper(this) - : this.clone(); + paramRegExp.lastIndex = index - if (result.__filtered__) { - result.__takeCount__ = nativeMin(n, result.__takeCount__); - } else { - result.__views__.push({ - 'size': nativeMin(n, MAX_ARRAY_LENGTH), - 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') - }); - } - return result; - }; + while (match = paramRegExp.exec(string)) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } - LazyWrapper.prototype[methodName + 'Right'] = function(n) { - return this.reverse()[methodName](n).reverse(); - }; - }); + index += match[0].length + key = match[1].toLowerCase() + value = match[2] - // Add `LazyWrapper` methods that accept an `iteratee` value. - arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { - var type = index + 1, - isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(qescRegExp, '$1') + } - LazyWrapper.prototype[methodName] = function(iteratee) { - var result = this.clone(); - result.__iteratees__.push({ - 'iteratee': getIteratee(iteratee, 3), - 'type': type - }); - result.__filtered__ = result.__filtered__ || isFilter; - return result; - }; - }); + params[key] = value + } - // Add `LazyWrapper` methods for `_.head` and `_.last`. - arrayEach(['head', 'last'], function(methodName, index) { - var takeName = 'take' + (index ? 'Right' : ''); + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } - LazyWrapper.prototype[methodName] = function() { - return this[takeName](1).value()[0]; - }; - }); + obj.parameters = params - // Add `LazyWrapper` methods for `_.initial` and `_.tail`. - arrayEach(['initial', 'tail'], function(methodName, index) { - var dropName = 'drop' + (index ? '' : 'Right'); + return obj +} - LazyWrapper.prototype[methodName] = function() { - return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); - }; - }); +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @api private + */ - LazyWrapper.prototype.compact = function() { - return this.filter(identity); - }; +function getcontenttype(obj) { + if (typeof obj.getHeader === 'function') { + // res-like + return obj.getHeader('content-type') + } - LazyWrapper.prototype.find = function(predicate) { - return this.filter(predicate).head(); - }; + if (typeof obj.headers === 'object') { + // req-like + return obj.headers && obj.headers['content-type'] + } +} - LazyWrapper.prototype.findLast = function(predicate) { - return this.reverse().find(predicate); - }; +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @api private + */ - LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { - if (typeof path == 'function') { - return new LazyWrapper(this); - } - return this.map(function(value) { - return baseInvoke(value, path, args); - }); - }); +function qstring(val) { + var str = String(val) - LazyWrapper.prototype.reject = function(predicate) { - return this.filter(negate(getIteratee(predicate))); - }; + // no need to quote tokens + if (tokenRegExp.test(str)) { + return str + } - LazyWrapper.prototype.slice = function(start, end) { - start = toInteger(start); + if (str.length > 0 && !textRegExp.test(str)) { + throw new TypeError('invalid parameter value') + } - var result = this; - if (result.__filtered__ && (start > 0 || end < 0)) { - return new LazyWrapper(result); - } - if (start < 0) { - result = result.takeRight(-start); - } else if (start) { - result = result.drop(start); - } - if (end !== undefined) { - end = toInteger(end); - result = end < 0 ? result.dropRight(-end) : result.take(end - start); - } - return result; - }; + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} - LazyWrapper.prototype.takeRightWhile = function(predicate) { - return this.reverse().takeWhile(predicate).reverse(); - }; +/** + * Simply "type/subtype+siffx" into parts. + * + * @param {string} string + * @return {Object} + * @api private + */ - LazyWrapper.prototype.toArray = function() { - return this.take(MAX_ARRAY_LENGTH); - }; +function splitType(string) { + var match = typeRegExp.exec(string.toLowerCase()) - // Add `LazyWrapper` methods to `lodash.prototype`. - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), - isTaker = /^(?:head|last)$/.test(methodName), - lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], - retUnwrapped = isTaker || /^find/.test(methodName); + if (!match) { + throw new TypeError('invalid media type') + } - if (!lodashFunc) { - return; - } - lodash.prototype[methodName] = function() { - var value = this.__wrapped__, - args = isTaker ? [1] : arguments, - isLazy = value instanceof LazyWrapper, - iteratee = args[0], - useLazy = isLazy || isArray(value); + var type = match[1] + var subtype = match[2] + var suffix - var interceptor = function(value) { - var result = lodashFunc.apply(lodash, arrayPush([value], args)); - return (isTaker && chainAll) ? result[0] : result; - }; + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } - if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { - // Avoid lazy use if the iteratee has a "length" value other than `1`. - isLazy = useLazy = false; - } - var chainAll = this.__chain__, - isHybrid = !!this.__actions__.length, - isUnwrapped = retUnwrapped && !chainAll, - onlyLazy = isLazy && !isHybrid; + var obj = { + type: type, + subtype: subtype, + suffix: suffix + } - if (!retUnwrapped && useLazy) { - value = onlyLazy ? value : new LazyWrapper(this); - var result = func.apply(value, args); - result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); - return new LodashWrapper(result, chainAll); - } - if (isUnwrapped && onlyLazy) { - return func.apply(this, args); - } - result = this.thru(interceptor); - return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; - }; - }); + return obj +} - // Add `Array` methods to `lodash.prototype`. - arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { - var func = arrayProto[methodName], - chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', - retUnwrapped = /^(?:pop|shift)$/.test(methodName); - lodash.prototype[methodName] = function() { - var args = arguments; - if (retUnwrapped && !this.__chain__) { - var value = this.value(); - return func.apply(isArray(value) ? value : [], args); - } - return this[chainName](function(value) { - return func.apply(isArray(value) ? value : [], args); - }); - }; - }); +/***/ }), - // Map minified method names to their real names. - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var lodashFunc = lodash[methodName]; - if (lodashFunc) { - var key = lodashFunc.name + ''; - if (!hasOwnProperty.call(realNames, key)) { - realNames[key] = []; - } - realNames[key].push({ 'name': methodName, 'func': lodashFunc }); - } - }); +/***/ 11149: +/***/ ((module) => { - realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ - 'name': 'wrapper', - 'func': undefined - }]; +"use strict"; +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - // Add methods to `LazyWrapper`. - LazyWrapper.prototype.clone = lazyClone; - LazyWrapper.prototype.reverse = lazyReverse; - LazyWrapper.prototype.value = lazyValue; - // Add chain sequence methods to the `lodash` wrapper. - lodash.prototype.at = wrapperAt; - lodash.prototype.chain = wrapperChain; - lodash.prototype.commit = wrapperCommit; - lodash.prototype.next = wrapperNext; - lodash.prototype.plant = wrapperPlant; - lodash.prototype.reverse = wrapperReverse; - lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; - // Add lazy aliases. - lodash.prototype.first = lodash.prototype.head; +/** + * Module exports. + * @public + */ - if (symIterator) { - lodash.prototype[symIterator] = wrapperToIterator; - } - return lodash; - }); +module.exports = merge - /*--------------------------------------------------------------------------*/ +/** + * Module variables. + * @private + */ - // Export lodash. - var _ = runInContext(); +var hasOwnProperty = Object.prototype.hasOwnProperty - // Some AMD build optimizers, like r.js, check for condition patterns like: - if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { - // Expose Lodash on the global object to prevent errors when Lodash is - // loaded by a script tag in the presence of an AMD loader. - // See http://requirejs.org/docs/errors.html#mismatch for more details. - // Use `_.noConflict` to remove Lodash from the global object. - root._ = _; +/** + * Merge the property descriptors of `src` into `dest` + * + * @param {object} dest Object to add descriptors to + * @param {object} src Object to clone descriptors from + * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties + * @returns {object} Reference to dest + * @public + */ - // Define as an anonymous module so, through path mapping, it can be - // referenced as the "underscore" module. - define(function() { - return _; - }); - } - // Check for `exports` after `define` in case a build optimizer adds it. - else if (freeModule) { - // Export for Node.js. - (freeModule.exports = _)._ = _; - // Export for CommonJS support. - freeExports._ = _; +function merge(dest, src, redefine) { + if (!dest) { + throw new TypeError('argument dest is required') } - else { - // Export to the global object. - root._ = _; + + if (!src) { + throw new TypeError('argument src is required') } -}.call(this)); + if (redefine === undefined) { + // Default to true + redefine = true + } -/***/ }), + Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { + if (!redefine && hasOwnProperty.call(dest, name)) { + // Skip desriptor + return + } -/***/ 7129: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Copy descriptor + var descriptor = Object.getOwnPropertyDescriptor(src, name) + Object.defineProperty(dest, name, descriptor) + }) -"use strict"; + return dest +} -// A linked list to keep track of recently-used-ness -const Yallist = __nccwpck_require__(40665) +/***/ }), -const MAX = Symbol('max') -const LENGTH = Symbol('length') -const LENGTH_CALCULATOR = Symbol('lengthCalculator') -const ALLOW_STALE = Symbol('allowStale') -const MAX_AGE = Symbol('maxAge') -const DISPOSE = Symbol('dispose') -const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') -const LRU_LIST = Symbol('lruList') -const CACHE = Symbol('cache') -const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') +/***/ 58752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const naiveLength = () => 1 +"use strict"; +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options } - if (!options) - options = {} - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - const max = this[MAX] = options.max || Infinity +/** + * Module dependencies. + * @private + */ - const lc = options.length || naiveLength - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc - this[ALLOW_STALE] = options.stale || false - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0 - this[DISPOSE] = options.dispose - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false - this.reset() - } +var http = __nccwpck_require__(13685); - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') +/** + * Module exports. + * @public + */ - this[MAX] = mL || Infinity - trim(this) - } - get max () { - return this[MAX] - } +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale - } - get allowStale () { - return this[ALLOW_STALE] - } +/** + * Get the current Node.js methods. + * @private + */ - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} - this[MAX_AGE] = mA - trim(this) - } - get maxAge () { - return this[MAX_AGE] - } +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC - this[LENGTH] = 0 - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) - this[LENGTH] += hit.length - }) - } - trim(this) - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } +/***/ }), - rforEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev - } - } +/***/ 47426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - forEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } - } +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } +/** + * Module exports. + */ - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } +module.exports = __nccwpck_require__(53765) - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) - } - this[CACHE] = new Map() // hash of items by key - this[LRU_LIST] = new Yallist() // list of items in order of use recency - this[LENGTH] = 0 // length of items in the list - } +/***/ }), - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } +/***/ 43583: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - dumpLru () { - return this[LRU_LIST] - } +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE] - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - const now = maxAge ? Date.now() : 0 - const len = this[LENGTH_CALCULATOR](value, key) +/** + * Module dependencies. + * @private + */ - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)) - return false - } +var db = __nccwpck_require__(47426) +var extname = (__nccwpck_require__(71017).extname) - const node = this[CACHE].get(key) - const item = node.value +/** + * Module variables. + * @private + */ - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value) - } +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i - item.now = now - item.maxAge = maxAge - item.value = value - this[LENGTH] += len - item.length - item.length = len - this.get(key) - trim(this) - return true - } +/** + * Module exports. + * @public + */ - const hit = new Entry(key, value, len, now, maxAge) +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) - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value) +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) - return false - } +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ - this[LENGTH] += hit.length - this[LRU_LIST].unshift(hit) - this[CACHE].set(key, this[LRU_LIST].head) - trim(this) - return true +function charset (type) { + if (!type || typeof type !== 'string') { + return false } - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value - return !isStale(this, hit) - } + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] - get (key) { - return get(this, key, true) + if (mime && mime.charset) { + return mime.charset } - peek (key) { - return get(this, key, false) + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' } - pop () { - const node = this[LRU_LIST].tail - if (!node) - return null + return false +} - del(this, node) - return node.value - } +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ - del (key) { - del(this, this[CACHE].get(key)) +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false } - load (arr) { - // reset the cache - this.reset() + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str - const now = Date.now() - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l] - const expiresAt = hit.e || 0 - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - else { - const maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } - } + if (!mime) { + return false } - prune () { - this[CACHE].forEach((value, key) => get(this, key, false)) + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() } -} -const get = (self, key, doUse) => { - const node = self[CACHE].get(key) - if (node) { - const hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now() - self[LRU_LIST].unshiftNode(node) - } - } - return hit.value - } + return mime } -const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) -} +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev - del(self, walker) - walker = prev - } +function extension (type) { + if (!type || typeof type !== 'string') { + return false } -} -const del = (self, node) => { - if (node) { - const hit = node.value - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value) + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) - self[LENGTH] -= hit.length - self[CACHE].delete(hit.key) - self[LRU_LIST].removeNode(node) - } -} + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] -class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 + if (!exts || !exts.length) { + return false } -} -const forEachStep = (self, fn, node, thisp) => { - let hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - hit = undefined - } - if (hit) - fn.call(thisp, hit.value, hit.key, self) + return exts[0] } -module.exports = LRUCache - - -/***/ }), - -/***/ 18424: -/***/ (function(__unused_webpack_module, exports) { - /** - * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most - * recently used items while discarding least recently used items when its limit - * is reached. - * - * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson - * See README.md for details. - * - * Illustration of the design: - * - * entry entry entry entry - * ______ ______ ______ ______ - * | head |.newer => | |.newer => | |.newer => | tail | - * | A | | B | | C | | D | - * |______| <= older.|______| <= older.|______| <= older.|______| + * Lookup the MIME type for a file path/extension. * - * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added + * @param {string} path + * @return {boolean|string} */ -(function(g,f){ - const e = true ? exports : 0; - f(e); - if (typeof define == 'function' && define.amd) { define('lru', e); } -})(this, function(exports) { - -const NEWER = Symbol('newer'); -const OLDER = Symbol('older'); -function LRUMap(limit, entries) { - if (typeof limit !== 'number') { - // called as (entries) - entries = limit; - limit = 0; +function lookup (path) { + if (!path || typeof path !== 'string') { + return false } - this.size = 0; - this.limit = limit; - this.oldest = this.newest = undefined; - this._keymap = new Map(); + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) - if (entries) { - this.assign(entries); - if (limit < 1) { - this.limit = this.size; - } + if (!extension) { + return false } -} - -exports.LRUMap = LRUMap; -function Entry(key, value) { - this.key = key; - this.value = value; - this[NEWER] = undefined; - this[OLDER] = undefined; + return exports.types[extension] || false } +/** + * Populate the extensions and types maps. + * @private + */ -LRUMap.prototype._markEntryAsUsed = function(entry) { - if (entry === this.newest) { - // Already the most recenlty used entry, so no need to update the list - return; - } - // HEAD--------------TAIL - // <.older .newer> - // <--- add direction -- - // A B C E - if (entry[NEWER]) { - if (entry === this.oldest) { - this.oldest = entry[NEWER]; - } - entry[NEWER][OLDER] = entry[OLDER]; // C <-- E. - } - if (entry[OLDER]) { - entry[OLDER][NEWER] = entry[NEWER]; // C. --> E - } - entry[NEWER] = undefined; // D --x - entry[OLDER] = this.newest; // D. --> E - if (this.newest) { - this.newest[NEWER] = entry; // E. <-- D - } - this.newest = entry; -}; +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] -LRUMap.prototype.assign = function(entries) { - let entry, limit = this.limit || Number.MAX_VALUE; - this._keymap.clear(); - let it = entries[Symbol.iterator](); - for (let itv = it.next(); !itv.done; itv = it.next()) { - let e = new Entry(itv.value[0], itv.value[1]); - this._keymap.set(e.key, e); - if (!entry) { - this.oldest = e; - } else { - entry[NEWER] = e; - e[OLDER] = entry; - } - entry = e; - if (limit-- == 0) { - throw new Error('overflow'); + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return } - } - this.newest = entry; - this.size = this._keymap.size; -}; -LRUMap.prototype.get = function(key) { - // First, find our cache entry - var entry = this._keymap.get(key); - if (!entry) return; // Not cached. Sorry. - // As was found in the cache, register it as being requested recently - this._markEntryAsUsed(entry); - return entry.value; -}; + // mime -> extensions + extensions[type] = exts -LRUMap.prototype.set = function(key, value) { - var entry = this._keymap.get(key); + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] - if (entry) { - // update existing - entry.value = value; - this._markEntryAsUsed(entry); - return this; - } + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) - // new entry - this._keymap.set(key, (entry = new Entry(key, value))); + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } - if (this.newest) { - // link previous tail to the new tail (entry) - this.newest[NEWER] = entry; - entry[OLDER] = this.newest; - } else { - // we're first in -- yay - this.oldest = entry; - } + // set the extension -> mime + types[extension] = type + } + }) +} - // add new entry to the end of the linked list -- it's now the freshest entry. - this.newest = entry; - ++this.size; - if (this.size > this.limit) { - // we hit the limit -- remove the head - this.shift(); - } - return this; -}; +/***/ }), -LRUMap.prototype.shift = function() { - // todo: handle special case when limit == 1 - var entry = this.oldest; - if (entry) { - if (this.oldest[NEWER]) { - // advance the list - this.oldest = this.oldest[NEWER]; - this.oldest[OLDER] = undefined; - } else { - // the cache is exhausted - this.oldest = undefined; - this.newest = undefined; - } - // Remove last strong reference to and remove links from the purged - // entry being returned: - entry[NEWER] = entry[OLDER] = undefined; - this._keymap.delete(entry.key); - --this.size; - return [entry.key, entry.value]; - } -}; +/***/ 65018: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// ---------------------------------------------------------------------------- -// Following code is optional and can be removed without breaking the core -// functionality. +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); -LRUMap.prototype.find = function(key) { - let e = this._keymap.get(key); - return e ? e.value : undefined; -}; +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); -LRUMap.prototype.has = function(key) { - return this._keymap.has(key); -}; + // Map of mime type -> extension + this.extensions = Object.create(null); +} -LRUMap.prototype['delete'] = function(key) { - var entry = this._keymap.get(key); - if (!entry) return; - this._keymap.delete(entry.key); - if (entry[NEWER] && entry[OLDER]) { - // relink the older entry with the newer entry - entry[OLDER][NEWER] = entry[NEWER]; - entry[NEWER][OLDER] = entry[OLDER]; - } else if (entry[NEWER]) { - // remove the link to us - entry[NEWER][OLDER] = undefined; - // link the newer entry to head - this.oldest = entry[NEWER]; - } else if (entry[OLDER]) { - // remove the link to us - entry[OLDER][NEWER] = undefined; - // link the newer entry to head - this.newest = entry[OLDER]; - } else {// if(entry[OLDER] === undefined && entry.newer === undefined) { - this.oldest = this.newest = undefined; - } +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts[i]]) { + console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts[i]] + ' to ' + type); + } - this.size--; - return entry.value; -}; + this.types[exts[i]] = type; + } -LRUMap.prototype.clear = function() { - // Not clearing links should be safe, as we don't expose live links to user - this.oldest = this.newest = undefined; - this.size = 0; - this._keymap.clear(); + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } }; +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); -function EntryIterator(oldestEntry) { this.entry = oldestEntry; } -EntryIterator.prototype[Symbol.iterator] = function() { return this; } -EntryIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: [ent.key, ent.value] }; - } else { - return { done: true, value: undefined }; - } -}; + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + this.define(map); -function KeyIterator(oldestEntry) { this.entry = oldestEntry; } -KeyIterator.prototype[Symbol.iterator] = function() { return this; } -KeyIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: ent.key }; - } else { - return { done: true, value: undefined }; - } + this._loading = null; }; -function ValueIterator(oldestEntry) { this.entry = oldestEntry; } -ValueIterator.prototype[Symbol.iterator] = function() { return this; } -ValueIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: ent.value }; - } else { - return { done: true, value: undefined }; - } -}; +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); + return this.types[ext] || fallback || this.default_type; +}; -LRUMap.prototype.keys = function() { - return new KeyIterator(this.oldest); +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; }; -LRUMap.prototype.values = function() { - return new ValueIterator(this.oldest); -}; +// Default instance +var mime = new Mime(); -LRUMap.prototype.entries = function() { - return this; -}; +// Define built-in types +mime.define(__nccwpck_require__(55799)); -LRUMap.prototype[Symbol.iterator] = function() { - return new EntryIterator(this.oldest); -}; +// Default type +mime.default_type = mime.lookup('bin'); -LRUMap.prototype.forEach = function(fun, thisObj) { - if (typeof thisObj !== 'object') { - thisObj = this; - } - let entry = this.oldest; - while (entry) { - fun.call(thisObj, entry.value, entry.key, this); - entry = entry[NEWER]; - } -}; +// +// Additional API specific to the default instance +// -/** Returns a JSON (array) representation */ -LRUMap.prototype.toJSON = function() { - var s = new Array(this.size), i = 0, entry = this.oldest; - while (entry) { - s[i++] = { key: entry.key, value: entry.value }; - entry = entry[NEWER]; - } - return s; -}; +mime.Mime = Mime; -/** Returns a String representation */ -LRUMap.prototype.toString = function() { - var s = '', entry = this.oldest; - while (entry) { - s += String(entry.key)+':'+entry.value; - entry = entry[NEWER]; - if (entry) { - s += ' < '; - } +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; } - return s; }; -}); +module.exports = mime; /***/ }), -/***/ 19955: -/***/ ((__unused_webpack_module, exports) => { - -/*! - * media-typer - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ 80900: +/***/ ((module) => { /** - * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 - * - * 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 = - * SHT = - * CTL = - * OCTET = + * Helpers. */ -var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; -var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ -var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; /** - * RegExp to match quoted-pair in RFC 2616 + * Parse or format the given `val`. * - * quoted-pair = "\" CHAR - * CHAR = + * 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 */ -var qescRegExp = /\\([\u0000-\u007f])/g; -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - */ -var quoteRegExp = /([\\"])/g; +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) + ); +}; /** - * RegExp to match type in RFC 6838 + * Parse the given `str` and return milliseconds. * - * type-name = restricted-name - * subtype-name = restricted-name - * restricted-name = restricted-name-first *126restricted-name-chars - * restricted-name-first = ALPHA / DIGIT - * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / - * "$" / "&" / "-" / "^" / "_" - * restricted-name-chars =/ "." ; Characters before first dot always - * ; specify a facet name - * restricted-name-chars =/ "+" ; Characters after last plus always - * ; specify a structured syntax suffix - * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z - * DIGIT = %x30-39 ; 0-9 - */ -var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ -var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ -var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; - -/** - * Module exports. + * @param {String} str + * @return {Number} + * @api private */ -exports.format = format -exports.parse = parse +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\-?\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; + } +} /** - * Format object to media type. + * Short format for `ms`. * - * @param {object} obj - * @return {string} - * @api public + * @param {Number} ms + * @return {String} + * @api private */ -function format(obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - - var parameters = obj.parameters - var subtype = obj.subtype - var suffix = obj.suffix - var type = obj.type - - if (!type || !typeNameRegExp.test(type)) { - throw new TypeError('invalid type') +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; } - - if (!subtype || !subtypeNameRegExp.test(subtype)) { - throw new TypeError('invalid subtype') + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; } - - // format as type/subtype - var string = type + '/' + subtype - - // append +suffix - if (suffix) { - if (!typeNameRegExp.test(suffix)) { - throw new TypeError('invalid suffix') - } - - string += '+' + suffix + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; } - - // 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] - - if (!tokenRegExp.test(param)) { - throw new TypeError('invalid parameter name') - } - - string += '; ' + param + '=' + qstring(parameters[param]) - } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; } - - return string + return ms + 'ms'; } /** - * Parse media type to object. + * Long format for `ms`. * - * @param {string|object} string - * @return {Object} - * @api public + * @param {Number} ms + * @return {String} + * @api private */ -function parse(string) { - if (!string) { - throw new TypeError('argument string is required') +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); } - - // support req/res-like objects as argument - if (typeof string === 'object') { - string = getcontenttype(string) + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); } - - if (typeof string !== 'string') { - throw new TypeError('argument string is required to be a string') + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); } + return ms + ' ms'; +} - var index = string.indexOf(';') - var type = index !== -1 - ? string.substr(0, index) - : string +/** + * Pluralization helper. + */ - var key - var match - var obj = splitType(type) - var params = {} - var value +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - paramRegExp.lastIndex = index - while (match = paramRegExp.exec(string)) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } +/***/ }), - index += match[0].length - key = match[1].toLowerCase() - value = match[2] +/***/ 95385: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(qescRegExp, '$1') - } +"use strict"; +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - params[key] = value - } - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } - obj.parameters = params +/** + * Cached loaded submodules. + * @private + */ - return obj -} +var modules = Object.create(null); /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @api private + * Module exports. + * @public */ -function getcontenttype(obj) { - if (typeof obj.getHeader === 'function') { - // res-like - return obj.getHeader('content-type') - } +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; - if (typeof obj.headers === 'object') { - // req-like - return obj.headers && obj.headers['content-type'] +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); } + + this.request = request; } -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @api private - */ +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; -function qstring(val) { - var str = String(val) +Negotiator.prototype.charsets = function charsets(available) { + var preferredCharsets = loadModule('charset').preferredCharsets; + return preferredCharsets(this.request.headers['accept-charset'], available); +}; - // no need to quote tokens - if (tokenRegExp.test(str)) { - return str - } +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; - if (str.length > 0 && !textRegExp.test(str)) { - throw new TypeError('invalid parameter value') - } +Negotiator.prototype.encodings = function encodings(available) { + var preferredEncodings = loadModule('encoding').preferredEncodings; + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; - return '"' + str.replace(quoteRegExp, '\\$1') + '"' -} +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + var preferredLanguages = loadModule('language').preferredLanguages; + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes; + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; /** - * Simply "type/subtype+siffx" into parts. - * - * @param {string} string - * @return {Object} - * @api private + * Load the given module. + * @private */ -function splitType(string) { - var match = typeRegExp.exec(string.toLowerCase()) +function loadModule(moduleName) { + var module = modules[moduleName]; - if (!match) { - throw new TypeError('invalid media type') + if (module !== undefined) { + return module; } - var type = match[1] - var subtype = match[2] - var suffix - - // suffix after last + - var index = subtype.lastIndexOf('+') - if (index !== -1) { - suffix = subtype.substr(index + 1) - subtype = subtype.substr(0, index) + // This uses a switch for static require analysis + switch (moduleName) { + case 'charset': + module = __nccwpck_require__(99296); + break; + case 'encoding': + module = __nccwpck_require__(25297); + break; + case 'language': + module = __nccwpck_require__(19722); + break; + case 'mediaType': + module = __nccwpck_require__(62563); + break; + default: + throw new Error('Cannot find module \'' + moduleName + '\''); } - var obj = { - type: type, - subtype: subtype, - suffix: suffix - } + // Store to prevent invoking require() + modules[moduleName] = module; - return obj + return module; } /***/ }), -/***/ 11149: +/***/ 99296: /***/ ((module) => { "use strict"; -/*! - * merge-descriptors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -100811,949 +100094,1065 @@ function splitType(string) { * @public */ -module.exports = merge +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; /** * Module variables. * @private */ -var hasOwnProperty = Object.prototype.hasOwnProperty +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; /** - * Merge the property descriptors of `src` into `dest` - * - * @param {object} dest Object to add descriptors to - * @param {object} src Object to clone descriptors from - * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties - * @returns {object} Reference to dest - * @public + * Parse the Accept-Charset header. + * @private */ -function merge(dest, src, redefine) { - if (!dest) { - throw new TypeError('argument dest is required') - } - - if (!src) { - throw new TypeError('argument src is required') - } +function parseAcceptCharset(accept) { + var accepts = accept.split(','); - if (redefine === undefined) { - // Default to true - redefine = true - } + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); - Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { - if (!redefine && hasOwnProperty.call(dest, name)) { - // Skip desriptor - return + if (charset) { + accepts[j++] = charset; } + } - // Copy descriptor - var descriptor = Object.getOwnPropertyDescriptor(src, name) - Object.defineProperty(dest, name, descriptor) - }) + // trim accepts + accepts.length = j; - return dest + return accepts; } +/** + * Parse a charset from the Accept-Charset header. + * @private + */ -/***/ }), +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; -/***/ 58752: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } -"use strict"; -/*! - * methods - * Copyright(c) 2013-2014 TJ Holowaychuk - * Copyright(c) 2015-2016 Douglas Christopher Wilson - * MIT Licensed + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private */ +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + return priority; +} /** - * Module dependencies. + * Get the specificity of the charset. * @private */ -var http = __nccwpck_require__(13685); +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} /** - * Module exports. + * Get the preferred charsets from an Accept-Charset header. * @public */ -module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); -/** - * Get the current Node.js methods. - * @private - */ + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } -function getCurrentNodeMethods() { - return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { - return method.toLowerCase(); + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; }); } /** - * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * Compare two specs. * @private */ -function getBasicNodeMethods() { - return [ - 'get', - 'post', - 'put', - 'head', - 'delete', - 'options', - 'trace', - 'copy', - 'lock', - 'mkcol', - 'move', - 'purge', - 'propfind', - 'proppatch', - 'unlock', - 'report', - 'mkactivity', - 'checkout', - 'merge', - 'm-search', - 'notify', - 'subscribe', - 'unsubscribe', - 'patch', - 'search', - 'connect' - ]; +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } - -/***/ }), - -/***/ 47426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed +/** + * Get full charset string. + * @private */ +function getFullCharset(spec) { + return spec.charset; +} + /** - * Module exports. + * Check if a spec has any quality. + * @private */ -module.exports = __nccwpck_require__(53765) +function isQuality(spec) { + return spec.q > 0; +} /***/ }), -/***/ 43583: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 25297: +/***/ ((module) => { "use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Module dependencies. - * @private + * Module exports. + * @public */ -var db = __nccwpck_require__(47426) -var extname = (__nccwpck_require__(71017).extname) +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; /** * Module variables. * @private */ -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; /** - * Module exports. - * @public + * Parse the Accept-Encoding header. + * @private */ -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) +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); -function charset (type) { - if (!type || typeof type !== 'string') { - return false + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } } - // 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 + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; } - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } + // trim accepts + accepts.length = j; - return false + return accepts; } /** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} + * Parse an encoding from the Accept-Encoding header. + * @private */ -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 - } +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } } - return mime + return { + encoding: encoding, + q: q, + i: i + }; } /** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} + * Get the priority of an encoding. + * @private */ -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) +function getEncodingPriority(encoding, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); - if (!exts || !exts.length) { - return false + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } } - return exts[0] + return priority; } /** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} + * Get the specificity of the encoding. + * @private */ -function lookup (path) { - if (!path || typeof path !== 'string') { - return false +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null } - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - - if (!extension) { - return false + return { + i: index, + o: spec.i, + q: spec.q, + s: s } - - return exports.types[extension] || false -} +}; /** - * Populate the extensions and types maps. - * @private + * Get the preferred encodings from an Accept-Encoding header. + * @public */ -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] +function preferredEncodings(accept, provided) { + var accepts = parseAcceptEncoding(accept || ''); - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullEncoding); + } - if (!exts || !exts.length) { - return - } + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); - // mime -> extensions - extensions[type] = exts + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] +/** + * Compare two specs. + * @private + */ - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } +/** + * Get full encoding string. + * @private + */ - // set the extension -> mime - types[extension] = type - } - }) +function getFullEncoding(spec) { + return spec.encoding; } +/** + * Check if a spec has any quality. + * @private + */ -/***/ }), - -/***/ 65018: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function isQuality(spec) { + return spec.q > 0; +} -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); -function Mime() { - // Map of extension -> mime type - this.types = Object.create(null); +/***/ }), - // Map of mime type -> extension - this.extensions = Object.create(null); -} +/***/ 19722: +/***/ ((module) => { +"use strict"; /** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -Mime.prototype.define = function (map) { - for (var type in map) { - var exts = map[type]; - for (var i = 0; i < exts.length; i++) { - if (process.env.DEBUG_MIME && this.types[exts[i]]) { - console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + - this.types[exts[i]] + ' to ' + type); - } - this.types[exts[i]] = type; - } - // Default extension is the first one we encounter - if (!this.extensions[type]) { - this.extensions[type] = exts[0]; - } - } -}; /** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. + * Module exports. + * @public */ -Mime.prototype.load = function(file) { - this._loading = file; - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); - - lines.forEach(function(line) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); - - this.define(map); - this._loading = null; -}; +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; /** - * Lookup a mime type based on extension + * Module variables. + * @private */ -Mime.prototype.lookup = function(path, fallback) { - var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); - return this.types[ext] || fallback || this.default_type; -}; +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; /** - * Return file extension associated with a mime type + * Parse the Accept-Language header. + * @private */ -Mime.prototype.extension = function(mimeType) { - var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); - return this.extensions[type]; -}; -// Default instance -var mime = new Mime(); +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); -// Define built-in types -mime.define(__nccwpck_require__(55799)); + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); -// Default type -mime.default_type = mime.lookup('bin'); + if (language) { + accepts[j++] = language; + } + } -// -// Additional API specific to the default instance -// + // trim accepts + accepts.length = j; -mime.Mime = Mime; + return accepts; +} /** - * Lookup a charset based on mime type. + * Parse a language from the Accept-Language header. + * @private */ -mime.charsets = { - lookup: function(mimeType, fallback) { - // Assume text types are utf8 - return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; - } -}; -module.exports = mime; +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + var prefix = match[1], + suffix = match[2], + full = prefix; -/***/ }), + if (suffix) full += "-" + suffix; -/***/ 80900: -/***/ ((module) => { + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} /** - * Helpers. + * Get the priority of a language. + * @private */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} /** - * 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 + * Get the specificity of the language. + * @private */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); }; /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private + * Get the preferred languages from an Accept-Language header. + * @public */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\-?\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; +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); } /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Compare two specs. + * @private */ -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'; +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Get full language string. + * @private */ -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'; +function getFullLanguage(spec) { + return spec.full; } /** - * Pluralization helper. + * Check if a spec has any quality. + * @private */ -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +function isQuality(spec) { + return spec.q > 0; } /***/ }), -/***/ 95385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 62563: +/***/ ((module) => { "use strict"; -/*! +/** * negotiator - * Copyright(c) 2012 Federico Romero - * Copyright(c) 2012-2014 Isaac Z. Schlueter - * Copyright(c) 2015 Douglas Christopher Wilson + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Cached loaded submodules. - * @private + * Module exports. + * @public */ -var modules = Object.create(null); +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; /** - * Module exports. - * @public + * Module variables. + * @private */ -module.exports = Negotiator; -module.exports.Negotiator = Negotiator; +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; /** - * Create a Negotiator instance from a request. - * @param {object} request - * @public + * Parse the Accept header. + * @private */ -function Negotiator(request) { - if (!(this instanceof Negotiator)) { - return new Negotiator(request); +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } } - this.request = request; + // trim accepts + accepts.length = j; + + return accepts; } -Negotiator.prototype.charset = function charset(available) { - var set = this.charsets(available); - return set && set[0]; -}; +/** + * Parse a media type from the Accept header. + * @private + */ -Negotiator.prototype.charsets = function charsets(available) { - var preferredCharsets = loadModule('charset').preferredCharsets; - return preferredCharsets(this.request.headers['accept-charset'], available); -}; +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; -Negotiator.prototype.encoding = function encoding(available) { - var set = this.encodings(available); - return set && set[0]; -}; + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; -Negotiator.prototype.encodings = function encodings(available) { - var preferredEncodings = loadModule('encoding').preferredEncodings; - return preferredEncodings(this.request.headers['accept-encoding'], available); -}; + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); -Negotiator.prototype.language = function language(available) { - var set = this.languages(available); - return set && set[0]; -}; + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; -Negotiator.prototype.languages = function languages(available) { - var preferredLanguages = loadModule('language').preferredLanguages; - return preferredLanguages(this.request.headers['accept-language'], available); -}; + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.substr(1, val.length - 2) + : val; -Negotiator.prototype.mediaType = function mediaType(available) { - var set = this.mediaTypes(available); - return set && set[0]; -}; + if (key === 'q') { + q = parseFloat(value); + break; + } -Negotiator.prototype.mediaTypes = function mediaTypes(available) { - var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes; - return preferredMediaTypes(this.request.headers.accept, available); -}; + // store parameter + params[key] = value; + } + } -// Backwards compatibility -Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; -Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; -Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; -Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; -Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; -Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; -Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; -Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} /** - * Load the given module. + * Get the priority of a media type. * @private */ -function loadModule(moduleName) { - var module = modules[moduleName]; +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; - if (module !== undefined) { - return module; + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } } - // This uses a switch for static require analysis - switch (moduleName) { - case 'charset': - module = __nccwpck_require__(99296); - break; - case 'encoding': - module = __nccwpck_require__(25297); - break; - case 'language': - module = __nccwpck_require__(19722); - break; - case 'mediaType': - module = __nccwpck_require__(62563); - break; - default: - throw new Error('Cannot find module \'' + moduleName + '\''); + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; } - // Store to prevent invoking require() - modules[moduleName] = module; + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ - return module; +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } +/** + * Get full type string. + * @private + */ -/***/ }), - -/***/ 99296: -/***/ ((module) => { +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} -"use strict"; /** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed + * Check if a spec has any quality. + * @private */ - +function isQuality(spec) { + return spec.q > 0; +} /** - * Module exports. - * @public + * Count the number of quotes in a string. + * @private */ -module.exports = preferredCharsets; -module.exports.preferredCharsets = preferredCharsets; +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} /** - * Module variables. + * Split a key value pair. * @private */ -var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.substr(0, index); + val = str.substr(index + 1); + } + + return [key, val]; +} /** - * Parse the Accept-Charset header. + * Split an Accept header into media types. * @private */ -function parseAcceptCharset(accept) { +function splitMediaTypes(accept) { var accepts = accept.split(','); - for (var i = 0, j = 0; i < accepts.length; i++) { - var charset = parseCharset(accepts[i].trim(), i); - - if (charset) { - accepts[j++] = charset; + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; } } // trim accepts - accepts.length = j; + accepts.length = j + 1; return accepts; } /** - * Parse a charset from the Accept-Charset header. + * Split a string of parameters. * @private */ -function parseCharset(str, i) { - var match = simpleCharsetRegExp.exec(str); - if (!match) return null; +function splitParameters(str) { + var parameters = str.split(';'); - var charset = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';') - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; } } - return { - charset: charset, - q: q, - i: i - }; + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; } -/** - * Get the priority of a charset. - * @private - */ -function getCharsetPriority(charset, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; +/***/ }), - for (var i = 0; i < accepted.length; i++) { - var spec = specify(charset, accepted[i], index); +/***/ 80536: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var authUnauthenticated = __nccwpck_require__(79567); +var authToken = __nccwpck_require__(40334); +var authApp = __nccwpck_require__(47541); + +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 priority; + return target; } -/** - * Get the specificity of the charset. - * @private - */ +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; -function specify(charset, spec, index) { - var s = 0; - if(spec.charset.toLowerCase() === charset.toLowerCase()){ - s |= 1; - } else if (spec.charset !== '*' ) { - return null + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - return { - i: index, - o: spec.i, - q: spec.q, - s: s + 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; } -/** - * Get the preferred charsets from an Accept-Charset header. - * @public - */ +async function auth(state, options) { + // return authentication from internal auth instance unless the event is "event-octokit" + if (options.type !== "event-octokit") { + if (state.type === "token" && options.type === "installation" && options.factory) { + const { + type, + factory + } = options, + factoryAuthOptions = _objectWithoutProperties(options, ["type", "factory"]); -function preferredCharsets(accept, provided) { - // RFC 2616 sec 14.2: no header = * - var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + return factory( // @ts-ignore factory options differ if internal auth type is token + Object.assign({}, factoryAuthOptions, { + octokit: state.octokit, + octokitOptions: state.octokitOptions + })); + } - if (!provided) { - // sorted list of all charsets - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullCharset); + return state.auth(options); + } // unless the internal event type is "app", return the octokit + // instance passed as strategy option + + + if (state.type !== "app") { + return state.octokit; } - var priorities = provided.map(function getPriority(type, index) { - return getCharsetPriority(type, accepts, index); - }); + const action = options.event.payload.action; + const installationId = options.event.payload.installation && options.event.payload.installation.id; + const fullEventName = options.event.name + (action ? "." + action : ""); + const OctokitWithEventAuth = state.octokit.constructor; - // sorted list of accepted charsets - return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { - return provided[priorities.indexOf(priority)]; + if (!installationId) { + const _state$octokitOptions = state.octokitOptions, + octokitOptions = _objectWithoutProperties(_state$octokitOptions, ["auth"]); + + return new OctokitWithEventAuth(_objectSpread2({ + authStrategy: authUnauthenticated.createUnauthenticatedAuth, + auth: { + reason: `Handling a "${fullEventName}" event: an "installation" key is missing. The installation ID cannot be determined` + } + }, octokitOptions)); + } + + if (options.event.name === "installation" && ["suspend", "deleted"].includes(String(action))) { + const _state$octokitOptions2 = state.octokitOptions, + octokitOptions = _objectWithoutProperties(_state$octokitOptions2, ["auth"]); + + return new OctokitWithEventAuth(_objectSpread2({ + authStrategy: authUnauthenticated.createUnauthenticatedAuth, + auth: { + reason: `Handling a "${fullEventName}" event: The app's access has been revoked from @octokit (id: ${installationId})` + } + }, octokitOptions)); + } // otherwise create a pre-authenticated (or unauthenticated) Octokit instance + // depending on the event payload + + + return state.auth({ + type: "installation", + installationId, + factory: auth => { + const options = Object.assign({}, state.octokitOptions, { + auth: Object.assign({}, auth, { + installationId + }) + }); + return new OctokitWithEventAuth(options); + } }); } -/** - * Compare two specs. - * @private - */ +function getState(options) { + const common = { + octokit: options.octokit, + octokitOptions: options.octokitOptions + }; -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} + if ("token" in options) { + return _objectSpread2({ + type: "token", + auth: authToken.createTokenAuth(String(options.token)) + }, common); + } -/** - * Get full charset string. - * @private - */ + if ("appId" in options && "privateKey" in options) { + return _objectSpread2({ + type: "app", + auth: authApp.createAppAuth(options) + }, common); + } -function getFullCharset(spec) { - return spec.charset; + return _objectSpread2({ + type: "unauthenticated", + auth: authUnauthenticated.createUnauthenticatedAuth({ + reason: `Neither "appId"/"privateKey" nor "token" have been set as auth options` + }) + }, common); } -/** - * Check if a spec has any quality. - * @private - */ +const VERSION = "0.0.0-development"; -function isQuality(spec) { - return spec.q > 0; +function createProbotAuth(options) { + const state = getState(options); + return Object.assign(auth.bind(null, state), { + hook: state.auth.hook + }); } +createProbotAuth.VERSION = VERSION; + +exports.createProbotAuth = createProbotAuth; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 25297: -/***/ ((module) => { +/***/ 92098: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ @@ -101764,2680 +101163,3107 @@ function isQuality(spec) { * @public */ -module.exports = preferredEncodings; -module.exports.preferredEncodings = preferredEncodings; +module.exports = onFinished +module.exports.isFinished = isFinished /** - * Module variables. + * Module dependencies. * @private */ -var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; +var first = __nccwpck_require__(14401) /** - * Parse the Accept-Encoding header. + * Variables. * @private */ -function parseAcceptEncoding(accept) { - var accepts = accept.split(','); - var hasIdentity = false; - var minQuality = 1; - - for (var i = 0, j = 0; i < accepts.length; i++) { - var encoding = parseEncoding(accepts[i].trim(), i); +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } - if (encoding) { - accepts[j++] = encoding; - hasIdentity = hasIdentity || specify('identity', encoding); - minQuality = Math.min(minQuality, encoding.q || 1); - } - } +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ - if (!hasIdentity) { - /* - * If identity doesn't explicitly appear in the accept-encoding header, - * it's added to the list of acceptable encoding with the lowest q - */ - accepts[j++] = { - encoding: 'identity', - q: minQuality, - i: i - }; +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg } - // trim accepts - accepts.length = j; + // attach the listener to the message + attachListener(msg, listener) - return accepts; + return msg } /** - * Parse an encoding from the Accept-Encoding header. - * @private + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public */ -function parseEncoding(str, i) { - var match = simpleEncodingRegExp.exec(str); - if (!match) return null; +function isFinished(msg) { + var socket = msg.socket - var encoding = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';'); - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) } - return { - encoding: encoding, - q: q, - i: i - }; + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined } /** - * Get the priority of an encoding. + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback * @private */ -function getEncodingPriority(encoding, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false - for (var i = 0; i < accepted.length; i++) { - var spec = specify(encoding, accepted[i], index); + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) } - - return priority; } /** - * Get the specificity of the encoding. + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} * @private */ -function specify(encoding, spec, index) { - var s = 0; - if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ - s |= 1; - } else if (spec.encoding !== '*' ) { - return null - } +function attachListener(msg, listener) { + var attached = msg.__onFinished - return { - i: index, - o: spec.i, - q: spec.q, - s: s + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) } -}; + + attached.queue.push(listener) +} /** - * Get the preferred encodings from an Accept-Encoding header. - * @public + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private */ -function preferredEncodings(accept, provided) { - var accepts = parseAcceptEncoding(accept || ''); +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return - if (!provided) { - // sorted list of all encodings - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullEncoding); + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } } - var priorities = provided.map(function getPriority(type, index) { - return getEncodingPriority(type, accepts, index); - }); + listener.queue = [] - // sorted list of accepted encodings - return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { - return provided[priorities.indexOf(priority)]; - }); + return listener } /** - * Compare two specs. + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback * @private */ -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket -/** - * Get full encoding string. - * @private - */ + if (typeof assignSocket !== 'function') return -function getFullEncoding(spec) { - return spec.encoding; + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } } -/** - * Check if a spec has any quality. - * @private - */ -function isQuality(spec) { - return spec.q > 0; -} +/***/ }), +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +var wrappy = __nccwpck_require__(62940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -/***/ 19722: -/***/ ((module) => { +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -"use strict"; -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} -/** - * Module exports. - * @public - */ -module.exports = preferredLanguages; -module.exports.preferredLanguages = preferredLanguages; +/***/ }), -/** - * Module variables. - * @private - */ +/***/ 57684: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; +"use strict"; -/** - * Parse the Accept-Language header. - * @private - */ +const pTry = __nccwpck_require__(80746); -function parseAcceptLanguage(accept) { - var accepts = accept.split(','); +const pLimit = concurrency => { + if (concurrency < 1) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } - for (var i = 0, j = 0; i < accepts.length; i++) { - var language = parseLanguage(accepts[i].trim(), i); + const queue = []; + let activeCount = 0; - if (language) { - accepts[j++] = language; - } - } + const next = () => { + activeCount--; - // trim accepts - accepts.length = j; + if (queue.length > 0) { + queue.shift()(); + } + }; - return accepts; -} + const run = (fn, resolve, ...args) => { + activeCount++; -/** - * Parse a language from the Accept-Language header. - * @private - */ + const result = pTry(fn, ...args); -function parseLanguage(str, i) { - var match = simpleLanguageRegExp.exec(str); - if (!match) return null; + resolve(result); - var prefix = match[1], - suffix = match[2], - full = prefix; + result.then(next, next); + }; - if (suffix) full += "-" + suffix; + const enqueue = (fn, resolve, ...args) => { + if (activeCount < concurrency) { + run(fn, resolve, ...args); + } else { + queue.push(run.bind(null, fn, resolve, ...args)); + } + }; - var q = 1; - if (match[3]) { - var params = match[3].split(';') - for (var j = 0; j < params.length; j++) { - var p = params[j].split('='); - if (p[0] === 'q') q = parseFloat(p[1]); - } - } + const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.length + } + }); - return { - prefix: prefix, - suffix: suffix, - q: q, - i: i, - full: full - }; -} + return generator; +}; -/** - * Get the priority of a language. - * @private - */ +module.exports = pLimit; +module.exports["default"] = pLimit; -function getLanguagePriority(language, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - for (var i = 0; i < accepted.length; i++) { - var spec = specify(language, accepted[i], index); +/***/ }), - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } +/***/ 91855: +/***/ ((module) => { - return priority; -} +"use strict"; -/** - * Get the specificity of the language. - * @private - */ -function specify(language, spec, index) { - var p = parseLanguage(language) - if (!p) return null; - var s = 0; - if(spec.full.toLowerCase() === p.full.toLowerCase()){ - s |= 4; - } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { - s |= 2; - } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { - s |= 1; - } else if (spec.full !== '*' ) { - return null - } +const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { + options = Object.assign({ + concurrency: Infinity + }, options); - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -}; + if (typeof mapper !== 'function') { + throw new TypeError('Mapper function is required'); + } -/** - * Get the preferred languages from an Accept-Language header. - * @public - */ + const {concurrency} = options; -function preferredLanguages(accept, provided) { - // RFC 2616 sec 14.4: no header = * - var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + if (!(typeof concurrency === 'number' && concurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); + } - if (!provided) { - // sorted list of all languages - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullLanguage); - } + const ret = []; + const iterator = iterable[Symbol.iterator](); + let isRejected = false; + let isIterableDone = false; + let resolvingCount = 0; + let currentIndex = 0; - var priorities = provided.map(function getPriority(type, index) { - return getLanguagePriority(type, accepts, index); - }); + const next = () => { + if (isRejected) { + return; + } - // sorted list of accepted languages - return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { - return provided[priorities.indexOf(priority)]; - }); -} + const nextItem = iterator.next(); + const i = currentIndex; + currentIndex++; -/** - * Compare two specs. - * @private - */ + if (nextItem.done) { + isIterableDone = true; -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} + if (resolvingCount === 0) { + resolve(ret); + } -/** - * Get full language string. - * @private - */ + return; + } -function getFullLanguage(spec) { - return spec.full; -} + resolvingCount++; -/** - * Check if a spec has any quality. - * @private - */ + Promise.resolve(nextItem.value) + .then(element => mapper(element, i)) + .then( + value => { + ret[i] = value; + resolvingCount--; + next(); + }, + error => { + isRejected = true; + reject(error); + } + ); + }; -function isQuality(spec) { - return spec.q > 0; -} + for (let i = 0; i < concurrency; i++) { + next(); + + if (isIterableDone) { + break; + } + } +}); + +module.exports = pMap; +// TODO: Remove this for the next major release +module.exports["default"] = pMap; /***/ }), -/***/ 62563: +/***/ 80746: /***/ ((module) => { "use strict"; -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +const pTry = (fn, ...arguments_) => new Promise(resolve => { + resolve(fn(...arguments_)); +}); -/** - * Module exports. - * @public - */ +module.exports = pTry; +module.exports["default"] = pTry; -module.exports = preferredMediaTypes; -module.exports.preferredMediaTypes = preferredMediaTypes; -/** - * Module variables. - * @private - */ +/***/ }), -var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; +/***/ 86615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Parse the Accept header. - * @private - */ +"use strict"; -function parseAccept(accept) { - var accepts = splitMediaTypes(accept); +const errorEx = __nccwpck_require__(23505); +const fallback = __nccwpck_require__(55586); - for (var i = 0, j = 0; i < accepts.length; i++) { - var mediaType = parseMediaType(accepts[i].trim(), i); +const JSONError = errorEx('JSONError', { + fileName: errorEx.append('in %s') +}); - if (mediaType) { - accepts[j++] = mediaType; - } - } +module.exports = (input, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } - // trim accepts - accepts.length = j; + try { + try { + return JSON.parse(input, reviver); + } catch (err) { + fallback(input, reviver); - return accepts; -} + throw err; + } + } catch (err) { + err.message = err.message.replace(/\n/g, ''); -/** - * Parse a media type from the Accept header. - * @private - */ + const jsonErr = new JSONError(err); + if (filename) { + jsonErr.fileName = filename; + } -function parseMediaType(str, i) { - var match = simpleMediaTypeRegExp.exec(str); - if (!match) return null; + throw jsonErr; + } +}; - var params = Object.create(null); - var q = 1; - var subtype = match[2]; - var type = match[1]; - if (match[3]) { - var kvps = splitParameters(match[3]).map(splitKeyValuePair); +/***/ }), - for (var j = 0; j < kvps.length; j++) { - var pair = kvps[j]; - var key = pair[0].toLowerCase(); - var val = pair[1]; +/***/ 89808: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // get the value, unwrapping quotes - var value = val && val[0] === '"' && val[val.length - 1] === '"' - ? val.substr(1, val.length - 2) - : val; +"use strict"; +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ - if (key === 'q') { - q = parseFloat(value); - break; - } - // store parameter - params[key] = value; - } - } - return { - type: type, - subtype: subtype, - params: params, - q: q, - i: i - }; -} +/** + * Module dependencies. + * @private + */ + +var url = __nccwpck_require__(57310) +var parse = url.parse +var Url = url.Url /** - * Get the priority of a media type. - * @private + * Module exports. + * @public */ -function getMediaTypePriority(type, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(type, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} +module.exports = parseurl +module.exports.original = originalurl /** - * Get the specificity of the media type. - * @private + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public */ -function specify(type, spec, index) { - var p = parseMediaType(type); - var s = 0; +function parseurl (req) { + var url = req.url - if (!p) { - return null; + if (url === undefined) { + // URL is undefined + return undefined } - if(spec.type.toLowerCase() == p.type.toLowerCase()) { - s |= 4 - } else if(spec.type != '*') { - return null; - } + var parsed = req._parsedUrl - if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { - s |= 2 - } else if(spec.subtype != '*') { - return null; + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed } - var keys = Object.keys(spec.params); - if (keys.length > 0) { - if (keys.every(function (k) { - return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); - })) { - s |= 1 - } else { - return null - } - } + // Parse the URL + parsed = fastparse(url) + parsed._raw = url - return { - i: index, - o: spec.i, - q: spec.q, - s: s, - } -} + return (req._parsedUrl = parsed) +}; /** - * Get the preferred media types from an Accept header. + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} * @public */ -function preferredMediaTypes(accept, provided) { - // RFC 2616 sec 14.2: no header = */* - var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); +function originalurl (req) { + var url = req.originalUrl - if (!provided) { - // sorted list of all types - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullType); + if (typeof url !== 'string') { + // Fallback + return parseurl(req) } - var priorities = provided.map(function getPriority(type, index) { - return getMediaTypePriority(type, accepts, index); - }); + var parsed = req._parsedOriginalUrl - // sorted list of accepted types - return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { - return provided[priorities.indexOf(priority)]; - }); -} + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } -/** - * Compare two specs. - * @private - */ + // Parse the URL + parsed = fastparse(url) + parsed._raw = url -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} + return (req._parsedOriginalUrl = parsed) +}; /** - * Get full type string. + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} * @private */ -function getFullType(spec) { - return spec.type + '/' + spec.subtype; -} +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse(str) + } -/** - * Check if a spec has any quality. - * @private - */ + var pathname = str + var query = null + var search = null -function isQuality(spec) { - return spec.q > 0; -} + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i) + query = str.substring(i + 1) + search = str.substring(i) + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse(str) + } + } -/** - * Count the number of quotes in a string. - * @private - */ + var url = Url !== undefined + ? new Url() + : {} -function quoteCount(string) { - var count = 0; - var index = 0; + url.path = str + url.href = str + url.pathname = pathname - while ((index = string.indexOf('"', index)) !== -1) { - count++; - index++; + if (search !== null) { + url.query = query + url.search = search } - return count; + return url } /** - * Split a key value pair. + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} * @private */ -function splitKeyValuePair(str) { - var index = str.indexOf('='); - var key; - var val; +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} - if (index === -1) { - key = str; - } else { - key = str.substr(0, index); - val = str.substr(index + 1); - } - return [key, val]; -} +/***/ }), -/** - * Split an Accept header into media types. - * @private - */ +/***/ 5980: +/***/ ((module) => { -function splitMediaTypes(accept) { - var accepts = accept.split(','); +"use strict"; - for (var i = 1, j = 0; i < accepts.length; i++) { - if (quoteCount(accepts[j]) % 2 == 0) { - accepts[++j] = accepts[i]; - } else { - accepts[j] += ',' + accepts[i]; - } - } - // trim accepts - accepts.length = j + 1; +var isWindows = process.platform === 'win32'; - return accepts; -} +// Regex to split a windows path into into [dir, root, basename, name, ext] +var splitWindowsRe = + /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; -/** - * Split a string of parameters. - * @private - */ +var win32 = {}; -function splitParameters(str) { - var parameters = str.split(';'); +function win32SplitPath(filename) { + return splitWindowsRe.exec(filename).slice(1); +} - for (var i = 1, j = 0; i < parameters.length; i++) { - if (quoteCount(parameters[j]) % 2 == 0) { - parameters[++j] = parameters[i]; - } else { - parameters[j] += ';' + parameters[i]; - } +win32.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); } + return { + root: allParts[1], + dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3] + }; +}; - // trim parameters - parameters.length = j + 1; - for (var i = 0; i < parameters.length; i++) { - parameters[i] = parameters[i].trim(); - } - return parameters; +// Split a filename into [dir, root, basename, name, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; +var posix = {}; + + +function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); } -/***/ }), +posix.parse = function(pathString) { + if (typeof pathString !== 'string') { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 5) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + + return { + root: allParts[1], + dir: allParts[0].slice(0, -1), + base: allParts[2], + ext: allParts[4], + name: allParts[3], + }; +}; -/***/ 80536: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +if (isWindows) + module.exports = win32.parse; +else /* posix */ + module.exports = posix.parse; +module.exports.posix = posix.parse; +module.exports.win32 = win32.parse; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var authUnauthenticated = __nccwpck_require__(79567); -var authToken = __nccwpck_require__(40334); -var authApp = __nccwpck_require__(47541); +/***/ }), -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; - } +/***/ 37819: +/***/ ((module) => { - return obj; -} +/** + * Expose `pathtoRegexp`. + */ -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); +module.exports = pathtoRegexp; - 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); - } +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; - return keys; -} +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; - 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 (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index }); } - } - return target; -} + return path; + } -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; + return new RegExp('(?:' + path.join('|') + ')', flags); } - return target; -} + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); - var target = _objectWithoutPropertiesLoose(source, excluded); + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; - var key, i; + extraOffset += result.length - match.length; - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length - 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]; - } - } + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } - return target; -} + return '(.*)'; + }); -async function auth(state, options) { - // return authentication from internal auth instance unless the event is "event-octokit" - if (options.type !== "event-octokit") { - if (state.type === "token" && options.type === "installation" && options.factory) { - const { - type, - factory - } = options, - factoryAuthOptions = _objectWithoutProperties(options, ["type", "factory"]); + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; - return factory( // @ts-ignore factory options differ if internal auth type is token - Object.assign({}, factoryAuthOptions, { - octokit: state.octokit, - octokitOptions: state.octokitOptions - })); + while (path.charAt(--index) === '\\') { + escapeCount++; } - return state.auth(options); - } // unless the internal event type is "app", return the octokit - // instance passed as strategy option - - - if (state.type !== "app") { - return state.octokit; - } - - const action = options.event.payload.action; - const installationId = options.event.payload.installation && options.event.payload.installation.id; - const fullEventName = options.event.name + (action ? "." + action : ""); - const OctokitWithEventAuth = state.octokit.constructor; + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } - if (!installationId) { - const _state$octokitOptions = state.octokitOptions, - octokitOptions = _objectWithoutProperties(_state$octokitOptions, ["auth"]); + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } - return new OctokitWithEventAuth(_objectSpread2({ - authStrategy: authUnauthenticated.createUnauthenticatedAuth, - auth: { - reason: `Handling a "${fullEventName}" event: an "installation" key is missing. The installation ID cannot be determined` - } - }, octokitOptions)); + i++; } - if (options.event.name === "installation" && ["suspend", "deleted"].includes(String(action))) { - const _state$octokitOptions2 = state.octokitOptions, - octokitOptions = _objectWithoutProperties(_state$octokitOptions2, ["auth"]); + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); - return new OctokitWithEventAuth(_objectSpread2({ - authStrategy: authUnauthenticated.createUnauthenticatedAuth, - auth: { - reason: `Handling a "${fullEventName}" event: The app's access has been revoked from @octokit (id: ${installationId})` - } - }, octokitOptions)); - } // otherwise create a pre-authenticated (or unauthenticated) Octokit instance - // depending on the event payload + return new RegExp(path, flags); +}; - return state.auth({ - type: "installation", - installationId, - factory: auth => { - const options = Object.assign({}, state.octokitOptions, { - auth: Object.assign({}, auth, { - installationId - }) - }); - return new OctokitWithEventAuth(options); - } - }); -} +/***/ }), -function getState(options) { - const common = { - octokit: options.octokit, - octokitOptions: options.octokitOptions - }; +/***/ 64810: +/***/ ((module) => { - if ("token" in options) { - return _objectSpread2({ - type: "token", - auth: authToken.createTokenAuth(String(options.token)) - }, common); - } +"use strict"; - if ("appId" in options && "privateKey" in options) { - return _objectSpread2({ - type: "app", - auth: authApp.createAppAuth(options) - }, common); - } - return _objectSpread2({ - type: "unauthenticated", - auth: authUnauthenticated.createUnauthenticatedAuth({ - reason: `Neither "appId"/"privateKey" nor "token" have been set as auth options` - }) - }, common); -} +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); -const VERSION = "0.0.0-development"; + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } -function createProbotAuth(options) { - const state = getState(options); - return Object.assign(auth.bind(null, state), { - hook: state.auth.hook - }); -} -createProbotAuth.VERSION = VERSION; + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); -exports.createProbotAuth = createProbotAuth; -//# sourceMappingURL=index.js.map + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } -/***/ }), + resolve(results); + } else { + resolve(result); + } + }); + } -/***/ 92098: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + fn.apply(this, args); + }); +}; -"use strict"; -/*! - * on-finished - * Copyright(c) 2013 Jonathan Ong - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } -/** - * Module exports. - * @public - */ + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } -module.exports = onFinished -module.exports.isFinished = isFinished + return ret; +}; -/** - * Module dependencies. - * @private - */ -var first = __nccwpck_require__(14401) +/***/ }), -/** - * Variables. - * @private - */ +/***/ 31778: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } +"use strict"; -/** - * Invoke callback when the response has finished, useful for - * cleaning up resources afterwards. - * - * @param {object} msg - * @param {function} listener - * @return {object} - * @public - */ -function onFinished(msg, listener) { - if (isFinished(msg) !== false) { - defer(listener, null, msg) - return msg - } +var pino = __nccwpck_require__(79608) +var serializers = __nccwpck_require__(72571) +var URL = __nccwpck_require__(34578) +var startTime = Symbol('startTime') - // attach the listener to the message - attachListener(msg, listener) +function pinoLogger (opts, stream) { + if (opts && opts._writableState) { + stream = opts + opts = null + } - return msg -} + opts = Object.assign({}, opts) -/** - * Determine if message is already finished. - * - * @param {object} msg - * @return {boolean} - * @public - */ + opts.customAttributeKeys = opts.customAttributeKeys || {} + var reqKey = opts.customAttributeKeys.req || 'req' + var resKey = opts.customAttributeKeys.res || 'res' + var errKey = opts.customAttributeKeys.err || 'err' + var responseTimeKey = opts.customAttributeKeys.responseTime || 'responseTime' + delete opts.customAttributeKeys -function isFinished(msg) { - var socket = msg.socket + var reqCustomProps = opts.reqCustomProps || {} - if (typeof msg.finished === 'boolean') { - // OutgoingMessage - return Boolean(msg.finished || (socket && !socket.writable)) + opts.wrapSerializers = 'wrapSerializers' in opts ? opts.wrapSerializers : true + if (opts.wrapSerializers) { + opts.serializers = Object.assign({}, opts.serializers) + var requestSerializer = opts.serializers[reqKey] || opts.serializers.req || serializers.req + var responseSerializer = opts.serializers[resKey] || opts.serializers.res || serializers.res + var errorSerializer = opts.serializers[errKey] || opts.serializers.err || serializers.err + opts.serializers[reqKey] = serializers.wrapRequestSerializer(requestSerializer) + opts.serializers[resKey] = serializers.wrapResponseSerializer(responseSerializer) + opts.serializers[errKey] = serializers.wrapErrorSerializer(errorSerializer) } + delete opts.wrapSerializers - if (typeof msg.complete === 'boolean') { - // IncomingMessage - return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + if (opts.useLevel && opts.customLogLevel) { + throw new Error("You can't pass 'useLevel' and 'customLogLevel' together") } - // don't know - return undefined -} + var useLevel = opts.useLevel || 'info' + var customLogLevel = opts.customLogLevel + delete opts.useLevel + delete opts.customLogLevel -/** - * Attach a finished listener to the message. - * - * @param {object} msg - * @param {function} callback - * @private - */ + var theStream = opts.stream || stream + delete opts.stream -function attachFinishedListener(msg, callback) { - var eeMsg - var eeSocket - var finished = false + var autoLogging = (opts.autoLogging !== false) + var autoLoggingIgnorePaths = (opts.autoLogging && opts.autoLogging.ignorePaths) ? opts.autoLogging.ignorePaths : [] + var autoLoggingGetPath = opts.autoLogging && opts.autoLogging.getPath ? opts.autoLogging.getPath : null + delete opts.autoLogging - function onFinish(error) { - eeMsg.cancel() - eeSocket.cancel() + var successMessage = opts.customSuccessMessage || function () { return 'request completed' } + var errorMessage = opts.customErrorMessage || function () { return 'request errored' } + delete opts.customSuccessfulMessage + delete opts.customErroredMessage - finished = true - callback(error) - } + var logger = wrapChild(opts, theStream) + var genReqId = reqIdGenFactory(opts.genReqId) + loggingMiddleware.logger = logger + return loggingMiddleware - // finished on first message event - eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + function onResFinished (err) { + this.removeListener('error', onResFinished) + this.removeListener('finish', onResFinished) - function onSocket(socket) { - // remove listener - msg.removeListener('socket', onSocket) + var log = this.log + var responseTime = Date.now() - this[startTime] + var level = customLogLevel ? customLogLevel(this, err) : useLevel - if (finished) return - if (eeMsg !== eeSocket) return + if (err || this.err || this.statusCode >= 500) { + var error = err || this.err || new Error('failed with status code ' + this.statusCode) - // finished on first socket event - eeSocket = first([[socket, 'error', 'close']], onFinish) - } + log[level]({ + [resKey]: this, + [errKey]: error, + [responseTimeKey]: responseTime + }, errorMessage(error, this)) + return + } - if (msg.socket) { - // socket already assigned - onSocket(msg.socket) - return + log[level]({ + [resKey]: this, + [responseTimeKey]: responseTime + }, successMessage(this)) } - // wait for socket to be assigned - msg.on('socket', onSocket) + function loggingMiddleware (req, res, next) { + var shouldLogSuccess = true - if (msg.socket === undefined) { - // node.js 0.8 patch - patchAssignSocket(msg, onSocket) - } -} + req.id = genReqId(req) -/** - * Attach the listener to the message. - * - * @param {object} msg - * @return {function} - * @private - */ + var log = logger.child({ [reqKey]: req }) -function attachListener(msg, listener) { - var attached = msg.__onFinished + if (reqCustomProps) { + var customPropBindings = (typeof reqCustomProps === 'function') ? reqCustomProps(req) : reqCustomProps + log = log.child(customPropBindings) + } + req.log = res.log = log - // create a private single listener with queue - if (!attached || !attached.queue) { - attached = msg.__onFinished = createListener(msg) - attachFinishedListener(msg, attached) - } + res[startTime] = res[startTime] || Date.now() - attached.queue.push(listener) -} + if (autoLogging) { + if (autoLoggingIgnorePaths.length) { + var url + if (autoLoggingGetPath) { + url = URL.parse(autoLoggingGetPath(req)) + } else if (req.url) { + url = URL.parse(req.url) + } + if (url && url.pathname) { + shouldLogSuccess = !autoLoggingIgnorePaths.find(ignorePath => { + if (ignorePath instanceof RegExp) { + return ignorePath.test(url.pathname) + } -/** - * Create listener on message. - * - * @param {object} msg - * @return {function} - * @private - */ + return ignorePath === url.pathname + }) + } + } -function createListener(msg) { - function listener(err) { - if (msg.__onFinished === listener) msg.__onFinished = null - if (!listener.queue) return + if (shouldLogSuccess) { + res.on('finish', onResFinished) + } - var queue = listener.queue - listener.queue = null + res.on('error', onResFinished) + } - for (var i = 0; i < queue.length; i++) { - queue[i](err, msg) + if (next) { + next() } } - - listener.queue = [] - - return listener } -/** - * Patch ServerResponse.prototype.assignSocket for node.js 0.8. - * - * @param {ServerResponse} res - * @param {function} callback - * @private - */ +function wrapChild (opts, stream) { + var prevLogger = opts.logger + var prevGenReqId = opts.genReqId + var logger = null -function patchAssignSocket(res, callback) { - var assignSocket = res.assignSocket + if (prevLogger) { + opts.logger = undefined + opts.genReqId = undefined + logger = prevLogger.child(opts) + opts.logger = prevLogger + opts.genReqId = prevGenReqId + } else { + logger = pino(opts, stream) + } - if (typeof assignSocket !== 'function') return + return logger +} - // res.on('socket', callback) is broken in 0.8 - res.assignSocket = function _assignSocket(socket) { - assignSocket.call(this, socket) - callback(socket) +function reqIdGenFactory (func) { + if (typeof func === 'function') return func + var maxInt = 2147483647 + var nextReqId = 0 + return function genReqId (req) { + return req.id || (nextReqId = (nextReqId + 1) & maxInt) } } +module.exports = pinoLogger +module.exports.stdSerializers = { + err: serializers.err, + req: serializers.req, + res: serializers.res +} +module.exports.startTime = startTime + /***/ }), -/***/ 1223: +/***/ 31691: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var wrappy = __nccwpck_require__(62940) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) +"use strict"; -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) +const chalk = __nccwpck_require__(78818) +const jmespath = __nccwpck_require__(87783) +const colors = __nccwpck_require__(31297) +const { ERROR_LIKE_KEYS, MESSAGE_KEY, TIMESTAMP_KEY } = __nccwpck_require__(12186) +const { + isObject, + prettifyErrorLog, + prettifyLevel, + prettifyMessage, + prettifyMetadata, + prettifyObject, + prettifyTime +} = __nccwpck_require__(24694) -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) +const bourne = __nccwpck_require__(97174) +const jsonParser = input => { + try { + return { value: bourne.parse(input, { protoAction: 'remove' }) } + } catch (err) { + return { err } } - f.called = false - return f } -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f +const defaultOptions = { + colorize: chalk.supportsColor, + crlf: false, + errorLikeObjectKeys: ERROR_LIKE_KEYS, + errorProps: '', + levelFirst: false, + messageKey: MESSAGE_KEY, + messageFormat: false, + timestampKey: TIMESTAMP_KEY, + translateTime: false, + useMetadata: false, + outputStream: process.stdout, + customPrettifiers: {} } +module.exports = function prettyFactory (options) { + const opts = Object.assign({}, defaultOptions, options) + const EOL = opts.crlf ? '\r\n' : '\n' + const IDENT = ' ' + const messageKey = opts.messageKey + const levelKey = opts.levelKey + const levelLabel = opts.levelLabel + const messageFormat = opts.messageFormat + const timestampKey = opts.timestampKey + const errorLikeObjectKeys = opts.errorLikeObjectKeys + const errorProps = opts.errorProps.split(',') + const customPrettifiers = opts.customPrettifiers + const ignoreKeys = opts.ignore ? new Set(opts.ignore.split(',')) : undefined -/***/ }), + const colorizer = colors(opts.colorize) + const search = opts.search -/***/ 57684: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return pretty -"use strict"; + function pretty (inputData) { + let log + if (!isObject(inputData)) { + const parsed = jsonParser(inputData) + if (parsed.err || !isObject(parsed.value)) { + // pass through + return inputData + EOL + } + log = parsed.value + } else { + log = inputData + } -const pTry = __nccwpck_require__(80746); + if (search && !jmespath.search(log, search)) { + return + } -const pLimit = concurrency => { - if (concurrency < 1) { - throw new TypeError('Expected `concurrency` to be a number from 1 and up'); - } + const prettifiedMessage = prettifyMessage({ log, messageKey, colorizer, messageFormat, levelLabel }) - const queue = []; - let activeCount = 0; + if (ignoreKeys) { + log = Object.keys(log) + .filter(key => !ignoreKeys.has(key)) + .reduce((res, key) => { + res[key] = log[key] + return res + }, {}) + } - const next = () => { - activeCount--; + const prettifiedLevel = prettifyLevel({ log, colorizer, levelKey }) + const prettifiedMetadata = prettifyMetadata({ log }) + const prettifiedTime = prettifyTime({ log, translateFormat: opts.translateTime, timestampKey }) - if (queue.length > 0) { - queue.shift()(); - } - }; + let line = '' + if (opts.levelFirst && prettifiedLevel) { + line = `${prettifiedLevel}` + } - const run = (fn, resolve, ...args) => { - activeCount++; + if (prettifiedTime && line === '') { + line = `${prettifiedTime}` + } else if (prettifiedTime) { + line = `${line} ${prettifiedTime}` + } - const result = pTry(fn, ...args); + if (!opts.levelFirst && prettifiedLevel) { + if (line.length > 0) { + line = `${line} ${prettifiedLevel}` + } else { + line = prettifiedLevel + } + } - resolve(result); + if (prettifiedMetadata) { + if (line.length > 0) { + line = `${line} ${prettifiedMetadata}:` + } else { + line = prettifiedMetadata + } + } - result.then(next, next); - }; + if (line.endsWith(':') === false && line !== '') { + line += ':' + } - const enqueue = (fn, resolve, ...args) => { - if (activeCount < concurrency) { - run(fn, resolve, ...args); - } else { - queue.push(run.bind(null, fn, resolve, ...args)); - } - }; + if (prettifiedMessage) { + if (line.length > 0) { + line = `${line} ${prettifiedMessage}` + } else { + line = prettifiedMessage + } + } - const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); - Object.defineProperties(generator, { - activeCount: { - get: () => activeCount - }, - pendingCount: { - get: () => queue.length - } - }); + if (line.length > 0) { + line += EOL + } - return generator; -}; + if (log.type === 'Error' && log.stack) { + const prettifiedErrorLog = prettifyErrorLog({ + log, + errorLikeKeys: errorLikeObjectKeys, + errorProperties: errorProps, + ident: IDENT, + eol: EOL + }) + line += prettifiedErrorLog + } else { + const skipKeys = [messageKey, levelKey, timestampKey].filter(key => typeof log[key] === 'string' || typeof log[key] === 'number') + const prettifiedObject = prettifyObject({ + input: log, + skipKeys, + customPrettifiers, + errorLikeKeys: errorLikeObjectKeys, + eol: EOL, + ident: IDENT + }) + line += prettifiedObject + } -module.exports = pLimit; -module.exports["default"] = pLimit; + return line + } +} /***/ }), -/***/ 91855: -/***/ ((module) => { +/***/ 31297: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const pMap = (iterable, mapper, options) => new Promise((resolve, reject) => { - options = Object.assign({ - concurrency: Infinity - }, options); - - if (typeof mapper !== 'function') { - throw new TypeError('Mapper function is required'); - } +const { LEVELS, LEVEL_NAMES } = __nccwpck_require__(12186) - const {concurrency} = options; +const nocolor = input => input +const plain = { + default: nocolor, + 60: nocolor, + 50: nocolor, + 40: nocolor, + 30: nocolor, + 20: nocolor, + 10: nocolor, + message: nocolor +} - if (!(typeof concurrency === 'number' && concurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); - } +const chalk = __nccwpck_require__(78818) +const ctx = new chalk.Instance({ level: 3 }) +const colored = { + default: ctx.white, + 60: ctx.bgRed, + 50: ctx.red, + 40: ctx.yellow, + 30: ctx.green, + 20: ctx.blue, + 10: ctx.grey, + message: ctx.cyan +} - const ret = []; - const iterator = iterable[Symbol.iterator](); - let isRejected = false; - let isIterableDone = false; - let resolvingCount = 0; - let currentIndex = 0; +function colorizeLevel (level, colorizer) { + if (Number.isInteger(+level)) { + return Object.prototype.hasOwnProperty.call(LEVELS, level) + ? colorizer[level](LEVELS[level]) + : colorizer.default(LEVELS.default) + } + const levelNum = LEVEL_NAMES[level.toLowerCase()] || 'default' + return colorizer[levelNum](LEVELS[levelNum]) +} - const next = () => { - if (isRejected) { - return; - } +function plainColorizer (level) { + return colorizeLevel(level, plain) +} +plainColorizer.message = plain.message - const nextItem = iterator.next(); - const i = currentIndex; - currentIndex++; +function coloredColorizer (level) { + return colorizeLevel(level, colored) +} +coloredColorizer.message = colored.message - if (nextItem.done) { - isIterableDone = true; +/** + * Factory function get a function to colorized levels. The returned function + * also includes a `.message(str)` method to colorize strings. + * + * @param {bool} [useColors=false] When `true` a function that applies standard + * terminal colors is returned. + * + * @returns {function} `function (level) {}` has a `.message(str)` method to + * apply colorization to a string. The core function accepts either an integer + * `level` or a `string` level. The integer level will map to a known level + * string or to `USERLVL` if not known. The string `level` will map to the same + * colors as the integer `level` and will also default to `USERLVL` if the given + * string is not a recognized level name. + */ +module.exports = function getColorizer (useColors = false) { + return useColors ? coloredColorizer : plainColorizer +} - if (resolvingCount === 0) { - resolve(ret); - } - return; - } +/***/ }), - resolvingCount++; +/***/ 12186: +/***/ ((module) => { - Promise.resolve(nextItem.value) - .then(element => mapper(element, i)) - .then( - value => { - ret[i] = value; - resolvingCount--; - next(); - }, - error => { - isRejected = true; - reject(error); - } - ); - }; +"use strict"; - for (let i = 0; i < concurrency; i++) { - next(); - if (isIterableDone) { - break; - } - } -}); +module.exports = { + DATE_FORMAT: 'yyyy-mm-dd HH:MM:ss.l o', -module.exports = pMap; -// TODO: Remove this for the next major release -module.exports["default"] = pMap; + ERROR_LIKE_KEYS: ['err', 'error'], + MESSAGE_KEY: 'msg', -/***/ }), + LEVEL_KEY: 'level', -/***/ 80746: -/***/ ((module) => { + LEVEL_LABEL: 'levelLabel', -"use strict"; + TIMESTAMP_KEY: 'time', + LEVELS: { + default: 'USERLVL', + 60: 'FATAL', + 50: 'ERROR', + 40: 'WARN', + 30: 'INFO', + 20: 'DEBUG', + 10: 'TRACE' + }, -const pTry = (fn, ...arguments_) => new Promise(resolve => { - resolve(fn(...arguments_)); -}); + LEVEL_NAMES: { + fatal: 60, + error: 50, + warn: 40, + info: 30, + debug: 20, + trace: 10 + }, -module.exports = pTry; -module.exports["default"] = pTry; + // Object keys that probably came from a logger like Pino or Bunyan. + LOGGER_KEYS: [ + 'pid', + 'hostname', + 'name', + 'level', + 'time', + 'timestamp', + 'caller' + ] +} /***/ }), -/***/ 86615: +/***/ 24694: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const errorEx = __nccwpck_require__(23505); -const fallback = __nccwpck_require__(55586); -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s') -}); +const dateformat = __nccwpck_require__(51512) +const stringifySafe = __nccwpck_require__(17676) +const defaultColorizer = __nccwpck_require__(31297)() +const { + DATE_FORMAT, + ERROR_LIKE_KEYS, + MESSAGE_KEY, + LEVEL_KEY, + LEVEL_LABEL, + TIMESTAMP_KEY, + LOGGER_KEYS, + LEVELS +} = __nccwpck_require__(12186) -module.exports = (input, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; - } +module.exports = { + isObject, + prettifyErrorLog, + prettifyLevel, + prettifyMessage, + prettifyMetadata, + prettifyObject, + prettifyTime +} - try { - try { - return JSON.parse(input, reviver); - } catch (err) { - fallback(input, reviver); +module.exports.internals = { + formatTime, + joinLinesWithIndentation +} - throw err; - } - } catch (err) { - err.message = err.message.replace(/\n/g, ''); +/** + * Converts a given `epoch` to a desired display format. + * + * @param {number|string} epoch The time to convert. May be any value that is + * valid for `new Date()`. + * @param {bool|string} [translateTime=false] When `false`, the given `epoch` + * will simply be returned. When `true`, the given `epoch` will be converted + * to a string at UTC using the `DATE_FORMAT` constant. If `translateTime` is + * a string, the following rules are available: + * + * - ``: The string is a literal format string. This format + * string will be used to interpret the `epoch` and return a display string + * at UTC. + * - `SYS:STANDARD`: The returned display string will follow the `DATE_FORMAT` + * constant at the system's local timezone. + * - `SYS:`: The returned display string will follow the given + * `` at the system's local timezone. + * - `UTC:`: The returned display string will follow the given + * `` at UTC. + * + * @returns {number|string} The formatted time. + */ +function formatTime (epoch, translateTime = false) { + if (translateTime === false) { + return epoch + } - const jsonErr = new JSONError(err); - if (filename) { - jsonErr.fileName = filename; - } + const instant = new Date(epoch) + if (translateTime === true) { + return dateformat(instant, 'UTC:' + DATE_FORMAT) + } - throw jsonErr; - } -}; + const upperFormat = translateTime.toUpperCase() + if (upperFormat === 'SYS:STANDARD') { + return dateformat(instant, DATE_FORMAT) + } + + const prefix = upperFormat.substr(0, 4) + if (prefix === 'SYS:' || prefix === 'UTC:') { + if (prefix === 'UTC:') { + return dateformat(instant, translateTime) + } + return dateformat(instant, translateTime.slice(4)) + } + return dateformat(instant, `UTC:${translateTime}`) +} -/***/ }), +function isObject (input) { + return Object.prototype.toString.apply(input) === '[object Object]' +} -/***/ 89808: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Given a string with line separators, either `\r\n` or `\n`, add indentation + * to all lines subsequent to the first line and rejoin the lines using an + * end of line sequence. + * + * @param {object} input + * @param {string} input.input The string to split and reformat. + * @param {string} [input.ident] The indentation string. Default: ` ` (4 spaces). + * @param {string} [input.eol] The end of line sequence to use when rejoining + * the lines. Default: `'\n'`. + * + * @returns {string} A string with lines subsequent to the first indented + * with the given indentation sequence. + */ +function joinLinesWithIndentation ({ input, ident = ' ', eol = '\n' }) { + const lines = input.split(/\r?\n/) + for (var i = 1; i < lines.length; i += 1) { + lines[i] = ident + lines[i] + } + return lines.join(eol) +} -"use strict"; -/*! - * parseurl - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed +/** + * Given a log object that has a `type: 'Error'` key, prettify the object and + * return the result. In other + * + * @param {object} input + * @param {object} input.log The error log to prettify. + * @param {string} [input.messageKey] The name of the key that contains a + * general log message. This is not the error's message property but the logger + * messsage property. Default: `MESSAGE_KEY` constant. + * @param {string} [input.ident] The sequence to use for indentation. Default: `' '`. + * @param {string} [input.eol] The sequence to use for EOL. Default: `'\n'`. + * @param {string[]} [input.errorLikeKeys] A set of keys that should be considered + * to have error objects as values. Default: `ERROR_LIKE_KEYS` constant. + * @param {string[]} [input.errorProperties] A set of specific error object + * properties, that are not the value of `messageKey`, `type`, or `stack`, to + * include in the prettified result. The first entry in the list may be `'*'` + * to indicate that all sibiling properties should be prettified. Default: `[]`. + * + * @returns {string} A sring that represents the prettified error log. */ +function prettifyErrorLog ({ + log, + messageKey = MESSAGE_KEY, + ident = ' ', + eol = '\n', + errorLikeKeys = ERROR_LIKE_KEYS, + errorProperties = [] +}) { + const stack = log.stack + const joinedLines = joinLinesWithIndentation({ input: stack, ident, eol }) + let result = `${ident}${joinedLines}${eol}` + + if (errorProperties.length > 0) { + const excludeProperties = LOGGER_KEYS.concat(messageKey, 'type', 'stack') + let propertiesToPrint + if (errorProperties[0] === '*') { + // Print all sibling properties except for the standard exclusions. + propertiesToPrint = Object.keys(log).filter(k => excludeProperties.includes(k) === false) + } else { + // Print only sepcified properties unless the property is a standard exclusion. + propertiesToPrint = errorProperties.filter(k => excludeProperties.includes(k) === false) + } + for (var i = 0; i < propertiesToPrint.length; i += 1) { + const key = propertiesToPrint[i] + if (key in log === false) continue + if (isObject(log[key])) { + // The nested object may have "logger" type keys but since they are not + // at the root level of the object being processed, we want to print them. + // Thus, we invoke with `excludeLoggerKeys: false`. + const prettifiedObject = prettifyObject({ input: log[key], errorLikeKeys, excludeLoggerKeys: false, eol, ident }) + result = `${result}${key}: {${eol}${prettifiedObject}}${eol}` + continue + } + result = `${result}${key}: ${log[key]}${eol}` + } + } + return result +} /** - * Module dependencies. - * @private + * Checks if the passed in log has a `level` value and returns a prettified + * string for that level if so. + * + * @param {object} input + * @param {object} input.log The log object. + * @param {function} [input.colorizer] A colorizer function that accepts a level + * value and returns a colorized string. Default: a no-op colorizer. + * @param {string} [levelKey='level'] The key to find the level under. + * + * @returns {undefined|string} If `log` does not have a `level` property then + * `undefined` will be returned. Otherwise, a string from the specified + * `colorizer` is returned. */ - -var url = __nccwpck_require__(57310) -var parse = url.parse -var Url = url.Url +function prettifyLevel ({ log, colorizer = defaultColorizer, levelKey = LEVEL_KEY }) { + if (levelKey in log === false) return undefined + return colorizer(log[levelKey]) + '\t' +} /** - * Module exports. - * @public + * Prettifies a message string if the given `log` has a message property. + * + * @param {object} input + * @param {object} input.log The log object with the message to colorize. + * @param {string} [input.messageKey='msg'] The property of the `log` that is the + * message to be prettified. + * @param {string} [input.messageFormat=undefined] A format string that defines how the + * logged message should be formatted, e.g. `'{level} - {pid}'`. + * @param {function} [input.colorizer] A colorizer function that has a + * `.message(str)` method attached to it. This function should return a colorized + * string which will be the "prettified" message. Default: a no-op colorizer. + * + * @returns {undefined|string} If the message key is not found, or the message + * key is not a string, then `undefined` will be returned. Otherwise, a string + * that is the prettified message. */ - -module.exports = parseurl -module.exports.original = originalurl +function prettifyMessage ({ log, messageFormat, messageKey = MESSAGE_KEY, colorizer = defaultColorizer, levelLabel = LEVEL_LABEL }) { + if (messageFormat) { + const message = String(messageFormat).replace(/{([^{}]+)}/g, function (match, p1) { + // return log level as string instead of int + if (p1 === levelLabel && log[LEVEL_KEY]) { + return LEVELS[log[LEVEL_KEY]] + } + // Parse nested key access, e.g. `{keyA.subKeyB}`. + return p1.split('.').reduce(function (prev, curr) { + if (prev && prev[curr]) { + return prev[curr] + } + return '' + }, log) + }) + return colorizer.message(message) + } + if (messageKey in log === false) return undefined + if (typeof log[messageKey] !== 'string') return undefined + return colorizer.message(log[messageKey]) +} /** - * Parse the `req` url with memoization. + * Prettifies metadata that is usually present in a Pino log line. It looks for + * fields `name`, `pid`, `hostname`, and `caller` and returns a formatted string using + * the fields it finds. * - * @param {ServerRequest} req - * @return {Object} - * @public + * @param {object} input + * @param {object} input.log The log that may or may not contain metadata to + * be prettified. + * + * @returns {undefined|string} If no metadata is found then `undefined` is + * returned. Otherwise, a string of prettified metadata is returned. */ +function prettifyMetadata ({ log }) { + let line = '' -function parseurl (req) { - var url = req.url + if (log.name || log.pid || log.hostname) { + line += '(' - if (url === undefined) { - // URL is undefined - return undefined - } + if (log.name) { + line += log.name + } - var parsed = req._parsedUrl + if (log.name && log.pid) { + line += '/' + log.pid + } else if (log.pid) { + line += log.pid + } - if (fresh(url, parsed)) { - // Return cached URL parse - return parsed + if (log.hostname) { + // If `pid` and `name` were in the ignore keys list then we don't need + // the leading space. + line += `${line === '(' ? 'on' : ' on'} ${log.hostname}` + } + + line += ')' } - // Parse the URL - parsed = fastparse(url) - parsed._raw = url + if (log.caller) { + line += `${line === '' ? '' : ' '}<${log.caller}>` + } - return (req._parsedUrl = parsed) -}; + if (line === '') { + return undefined + } else { + return line + } +} /** - * Parse the `req` original url with fallback and memoization. + * Prettifies a standard object. Special care is taken when processing the object + * to handle child objects that are attached to keys known to contain error + * objects. * - * @param {ServerRequest} req - * @return {Object} - * @public + * @param {object} input + * @param {object} input.input The object to prettify. + * @param {string} [input.ident] The identation sequence to use. Default: `' '`. + * @param {string} [input.eol] The EOL sequence to use. Default: `'\n'`. + * @param {string[]} [input.skipKeys] A set of object keys to exclude from the + * prettified result. Default: `[]`. + * @param {Object} [input.customPrettifiers] Dictionary of + * custom prettifiers. Default: `{}`. + * @param {string[]} [input.errorLikeKeys] A set of object keys that contain + * error objects. Default: `ERROR_LIKE_KEYS` constant. + * @param {boolean} [input.excludeLoggerKeys] Indicates if known logger specific + * keys should be excluded from prettification. Default: `true`. + * + * @returns {string} The prettified string. This can be as little as `''` if + * there was nothing to prettify. */ +function prettifyObject ({ + input, + ident = ' ', + eol = '\n', + skipKeys = [], + customPrettifiers = {}, + errorLikeKeys = ERROR_LIKE_KEYS, + excludeLoggerKeys = true +}) { + const objectKeys = Object.keys(input) + const keysToIgnore = [].concat(skipKeys) -function originalurl (req) { - var url = req.originalUrl - - if (typeof url !== 'string') { - // Fallback - return parseurl(req) - } - - var parsed = req._parsedOriginalUrl + if (excludeLoggerKeys === true) Array.prototype.push.apply(keysToIgnore, LOGGER_KEYS) - if (fresh(url, parsed)) { - // Return cached URL parse - return parsed - } + let result = '' - // Parse the URL - parsed = fastparse(url) - parsed._raw = url + const keysToIterate = objectKeys.filter(k => keysToIgnore.includes(k) === false) + for (var i = 0; i < objectKeys.length; i += 1) { + const keyName = keysToIterate[i] + const keyValue = input[keyName] - return (req._parsedOriginalUrl = parsed) -}; + if (keyValue === undefined) continue -/** - * Parse the `str` url with fast-path short-cut. - * - * @param {string} str - * @return {Object} - * @private - */ + let lines + if (typeof customPrettifiers[keyName] === 'function') { + lines = customPrettifiers[keyName](keyValue, keyName, input) + } else { + lines = stringifySafe(keyValue, null, 2) + } -function fastparse (str) { - if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { - return parse(str) - } + if (lines === undefined) continue + const joinedLines = joinLinesWithIndentation({ input: lines, ident, eol }) - var pathname = str - var query = null - var search = null + if (errorLikeKeys.includes(keyName) === true) { + const splitLines = `${ident}${keyName}: ${joinedLines}${eol}`.split(eol) + for (var j = 0; j < splitLines.length; j += 1) { + if (j !== 0) result += eol - // This takes the regexp from https://github.com/joyent/node/pull/7878 - // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ - // And unrolls it into a for loop - for (var i = 1; i < str.length; i++) { - switch (str.charCodeAt(i)) { - case 0x3f: /* ? */ - if (search === null) { - pathname = str.substring(0, i) - query = str.substring(i + 1) - search = str.substring(i) + const line = splitLines[j] + if (/^\s*"stack"/.test(line)) { + const matches = /^(\s*"stack":)\s*(".*"),?$/.exec(line) + /* istanbul ignore else */ + if (matches && matches.length === 3) { + const indentSize = /^\s*/.exec(line)[0].length + 4 + const indentation = ' '.repeat(indentSize) + const stackMessage = matches[2] + result += matches[1] + eol + indentation + JSON.parse(stackMessage).replace(/\n/g, eol + indentation) + } + } else { + result += line } - break - case 0x09: /* \t */ - case 0x0a: /* \n */ - case 0x0c: /* \f */ - case 0x0d: /* \r */ - case 0x20: /* */ - case 0x23: /* # */ - case 0xa0: - case 0xfeff: - return parse(str) + } + } else { + result += `${ident}${keyName}: ${joinedLines}${eol}` } } - var url = Url !== undefined - ? new Url() - : {} - - url.path = str - url.href = str - url.pathname = pathname - - if (search !== null) { - url.query = query - url.search = search - } - - return url + return result } /** - * Determine if parsed is still fresh for url. + * Prettifies a timestamp if the given `log` has either `time`, `timestamp` or custom specified timestamp + * property. * - * @param {string} url - * @param {object} parsedUrl - * @return {boolean} - * @private + * @param {object} input + * @param {object} input.log The log object with the timestamp to be prettified. + * @param {string} [input.timestampKey='time'] The log property that should be used to resolve timestamp value + * @param {bool|string} [input.translateFormat=undefined] When `true` the + * timestamp will be prettified into a string at UTC using the default + * `DATE_FORMAT`. If a string, then `translateFormat` will be used as the format + * string to determine the output; see the `formatTime` function for details. + * + * @returns {undefined|string} If a timestamp property cannot be found then + * `undefined` is returned. Otherwise, the prettified time is returned as a + * string. */ +function prettifyTime ({ log, timestampKey = TIMESTAMP_KEY, translateFormat = undefined }) { + let time = null -function fresh (url, parsedUrl) { - return typeof parsedUrl === 'object' && - parsedUrl !== null && - (Url === undefined || parsedUrl instanceof Url) && - parsedUrl._raw === url + if (timestampKey in log) { + time = log[timestampKey] + } else if ('timestamp' in log) { + time = log.timestamp + } + + if (time === null) return undefined + if (translateFormat) { + return '[' + formatTime(time, translateFormat) + ']' + } + + return `[${time}]` } /***/ }), -/***/ 5980: -/***/ ((module) => { +/***/ 72571: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var isWindows = process.platform === 'win32'; +var errSerializer = __nccwpck_require__(96522) +var reqSerializers = __nccwpck_require__(75492) +var resSerializers = __nccwpck_require__(9048) -// Regex to split a windows path into into [dir, root, basename, name, ext] -var splitWindowsRe = - /^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; +module.exports = { + err: errSerializer, + mapHttpRequest: reqSerializers.mapHttpRequest, + mapHttpResponse: resSerializers.mapHttpResponse, + req: reqSerializers.reqSerializer, + res: resSerializers.resSerializer, -var win32 = {}; + wrapErrorSerializer: function wrapErrorSerializer (customSerializer) { + if (customSerializer === errSerializer) return customSerializer + return function wrapErrSerializer (err) { + return customSerializer(errSerializer(err)) + } + }, -function win32SplitPath(filename) { - return splitWindowsRe.exec(filename).slice(1); -} + wrapRequestSerializer: function wrapRequestSerializer (customSerializer) { + if (customSerializer === reqSerializers.reqSerializer) return customSerializer + return function wrappedReqSerializer (req) { + return customSerializer(reqSerializers.reqSerializer(req)) + } + }, -win32.parse = function(pathString) { - if (typeof pathString !== 'string') { - throw new TypeError( - "Parameter 'pathString' must be a string, not " + typeof pathString - ); - } - var allParts = win32SplitPath(pathString); - if (!allParts || allParts.length !== 5) { - throw new TypeError("Invalid path '" + pathString + "'"); + wrapResponseSerializer: function wrapResponseSerializer (customSerializer) { + if (customSerializer === resSerializers.resSerializer) return customSerializer + return function wrappedResSerializer (res) { + return customSerializer(resSerializers.resSerializer(res)) + } } - return { - root: allParts[1], - dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), - base: allParts[2], - ext: allParts[4], - name: allParts[3] - }; -}; +} +/***/ }), -// Split a filename into [dir, root, basename, name, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; -var posix = {}; +/***/ 96522: +/***/ ((module) => { +"use strict"; -function posixSplitPath(filename) { - return splitPathRe.exec(filename).slice(1); -} +module.exports = errSerializer -posix.parse = function(pathString) { - if (typeof pathString !== 'string') { - throw new TypeError( - "Parameter 'pathString' must be a string, not " + typeof pathString - ); - } - var allParts = posixSplitPath(pathString); - if (!allParts || allParts.length !== 5) { - throw new TypeError("Invalid path '" + pathString + "'"); +const seen = Symbol('circular-ref-tag') +const rawSymbol = Symbol('pino-raw-err-ref') +const pinoErrProto = Object.create({}, { + type: { + enumerable: true, + writable: true, + value: undefined + }, + message: { + enumerable: true, + writable: true, + value: undefined + }, + stack: { + enumerable: true, + writable: true, + value: undefined + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val + } } - - return { - root: allParts[1], - dir: allParts[0].slice(0, -1), - base: allParts[2], - ext: allParts[4], - name: allParts[3], - }; -}; +}) +Object.defineProperty(pinoErrProto, rawSymbol, { + writable: true, + value: {} +}) +function errSerializer (err) { + if (!(err instanceof Error)) { + return err + } -if (isWindows) - module.exports = win32.parse; -else /* posix */ - module.exports = posix.parse; + err[seen] = undefined // tag to prevent re-looking at this + const _err = Object.create(pinoErrProto) + _err.type = err.constructor.name + _err.message = err.message + _err.stack = err.stack + for (const key in err) { + if (_err[key] === undefined) { + const val = err[key] + if (val instanceof Error) { + if (!val.hasOwnProperty(seen)) { + _err[key] = errSerializer(val) + } + } else { + _err[key] = val + } + } + } -module.exports.posix = posix.parse; -module.exports.win32 = win32.parse; + delete err[seen] // clean up tag in case err is serialized again later + _err.raw = err + return _err +} /***/ }), -/***/ 37819: +/***/ 75492: /***/ ((module) => { -/** - * Expose `pathtoRegexp`. - */ - -module.exports = pathtoRegexp; - -/** - * Match matching groups in a regular expression. - */ -var MATCHING_GROUP_REGEXP = /\((?!\?)/g; +"use strict"; -/** - * Normalize the given path string, - * returning a regular expression. - * - * An empty array should be passed, - * which will contain the placeholder - * key names. For example "/user/:id" will - * then contain ["id"]. - * - * @param {String|RegExp|Array} path - * @param {Array} keys - * @param {Object} options - * @return {RegExp} - * @api private - */ -function pathtoRegexp(path, keys, options) { - options = options || {}; - keys = keys || []; - var strict = options.strict; - var end = options.end !== false; - var flags = options.sensitive ? '' : 'i'; - var extraOffset = 0; - var keysOffset = keys.length; - var i = 0; - var name = 0; - var m; +module.exports = { + mapHttpRequest, + reqSerializer +} - if (path instanceof RegExp) { - while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { - keys.push({ - name: name++, - optional: false, - offset: m.index - }); +var rawSymbol = Symbol('pino-raw-req-ref') +var pinoReqProto = Object.create({}, { + id: { + enumerable: true, + writable: true, + value: '' + }, + method: { + enumerable: true, + writable: true, + value: '' + }, + url: { + enumerable: true, + writable: true, + value: '' + }, + headers: { + enumerable: true, + writable: true, + value: {} + }, + remoteAddress: { + enumerable: true, + writable: true, + value: '' + }, + remotePort: { + enumerable: true, + writable: true, + value: '' + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val } - - return path; } +}) +Object.defineProperty(pinoReqProto, rawSymbol, { + writable: true, + value: {} +}) - if (Array.isArray(path)) { - // Map array parts into regexps and return their source. We also pass - // the same keys and options instance into every generation to get - // consistent matching groups before we join the sources together. - path = path.map(function (value) { - return pathtoRegexp(value, keys, options).source; - }); - - return new RegExp('(?:' + path.join('|') + ')', flags); +function reqSerializer (req) { + // req.info is for hapi compat. + var connection = req.info || req.connection + const _req = Object.create(pinoReqProto) + _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined))) + _req.method = req.method + // req.originalUrl is for expressjs compat. + if (req.originalUrl) { + _req.url = req.originalUrl + } else { + // req.url.path is for hapi compat. + _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined) } + _req.headers = req.headers + _req.remoteAddress = connection && connection.remoteAddress + _req.remotePort = connection && connection.remotePort + // req.raw is for hapi compat/equivalence + _req.raw = req.raw || req + return _req +} - path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) - .replace(/\/\(/g, '/(?:') - .replace(/([\/\.])/g, '\\$1') - .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { - slash = slash || ''; - format = format || ''; - capture = capture || '([^\\/' + format + ']+?)'; - optional = optional || ''; - - keys.push({ - name: key, - optional: !!optional, - offset: offset + extraOffset - }); - - var result = '' - + (optional ? '' : slash) - + '(?:' - + format + (optional ? slash : '') + capture - + (star ? '((?:[\\/' + format + '].+?)?)' : '') - + ')' - + optional; - - extraOffset += result.length - match.length; +function mapHttpRequest (req) { + return { + req: reqSerializer(req) + } +} - return result; - }) - .replace(/\*/g, function (star, index) { - var len = keys.length - while (len-- > keysOffset && keys[len].offset > index) { - keys[len].offset += 3; // Replacement length minus asterisk length. - } +/***/ }), - return '(.*)'; - }); +/***/ 9048: +/***/ ((module) => { - // This is a workaround for handling unnamed matching groups. - while (m = MATCHING_GROUP_REGEXP.exec(path)) { - var escapeCount = 0; - var index = m.index; +"use strict"; - while (path.charAt(--index) === '\\') { - escapeCount++; - } - // It's possible to escape the bracket. - if (escapeCount % 2 === 1) { - continue; - } +module.exports = { + mapHttpResponse, + resSerializer +} - if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { - keys.splice(keysOffset + i, 0, { - name: name++, // Unnamed matching groups must be consistently linear. - optional: false, - offset: m.index - }); +var rawSymbol = Symbol('pino-raw-res-ref') +var pinoResProto = Object.create({}, { + statusCode: { + enumerable: true, + writable: true, + value: 0 + }, + headers: { + enumerable: true, + writable: true, + value: '' + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val } - - i++; } +}) +Object.defineProperty(pinoResProto, rawSymbol, { + writable: true, + value: {} +}) - // If the path is non-ending, match until the end or a slash. - path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); +function resSerializer (res) { + const _res = Object.create(pinoResProto) + _res.statusCode = res.statusCode + _res.headers = res.getHeaders ? res.getHeaders() : res._headers + _res.raw = res + return _res +} - return new RegExp(path, flags); -}; +function mapHttpResponse (res) { + return { + res: resSerializer(res) + } +} /***/ }), -/***/ 64810: -/***/ ((module) => { +/***/ 90591: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/* eslint no-prototype-builtins: 0 */ +const flatstr = __nccwpck_require__(35298) +const { + lsCacheSym, + levelValSym, + useOnlyCustomLevelsSym, + streamSym, + formattersSym, + hooksSym +} = __nccwpck_require__(23957) +const { noop, genLog } = __nccwpck_require__(51521) -const processFn = (fn, opts) => function () { - const P = opts.promiseModule; - const args = new Array(arguments.length); - - for (let i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - - return new P((resolve, reject) => { - if (opts.errorFirst) { - args.push(function (err, result) { - if (opts.multiArgs) { - const results = new Array(arguments.length - 1); - - for (let i = 1; i < arguments.length; i++) { - results[i - 1] = arguments[i]; - } +const levels = { + trace: 10, + debug: 20, + info: 30, + warn: 40, + error: 50, + fatal: 60 +} +const levelMethods = { + fatal: (hook) => { + const logFatal = genLog(levels.fatal, hook) + return function (...args) { + const stream = this[streamSym] + logFatal.call(this, ...args) + if (typeof stream.flushSync === 'function') { + try { + stream.flushSync() + } catch (e) { + // https://github.com/pinojs/pino/pull/740#discussion_r346788313 + } + } + } + }, + error: (hook) => genLog(levels.error, hook), + warn: (hook) => genLog(levels.warn, hook), + info: (hook) => genLog(levels.info, hook), + debug: (hook) => genLog(levels.debug, hook), + trace: (hook) => genLog(levels.trace, hook) +} - if (err) { - results.unshift(err); - reject(results); - } else { - resolve(results); - } - } else if (err) { - reject(err); - } else { - resolve(result); - } - }); - } else { - args.push(function (result) { - if (opts.multiArgs) { - const results = new Array(arguments.length - 1); +const nums = Object.keys(levels).reduce((o, k) => { + o[levels[k]] = k + return o +}, {}) - for (let i = 0; i < arguments.length; i++) { - results[i] = arguments[i]; - } +const initialLsCache = Object.keys(nums).reduce((o, k) => { + o[k] = flatstr('{"level":' + Number(k)) + return o +}, {}) - resolve(results); - } else { - resolve(result); - } - }); - } +function genLsCache (instance) { + const formatter = instance[formattersSym].level + const { labels } = instance.levels + const cache = {} + for (const label in labels) { + const level = formatter(labels[label], Number(label)) + cache[label] = JSON.stringify(level).slice(0, -1) + } + instance[lsCacheSym] = cache + return instance +} - fn.apply(this, args); - }); -}; +function isStandardLevel (level, useOnlyCustomLevels) { + if (useOnlyCustomLevels) { + return false + } -module.exports = (obj, opts) => { - opts = Object.assign({ - exclude: [/.+(Sync|Stream)$/], - errorFirst: true, - promiseModule: Promise - }, opts); + switch (level) { + case 'fatal': + case 'error': + case 'warn': + case 'info': + case 'debug': + case 'trace': + return true + default: + return false + } +} - const filter = key => { - const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); - return opts.include ? opts.include.some(match) : !opts.exclude.some(match); - }; +function setLevel (level) { + const { labels, values } = this.levels + if (typeof level === 'number') { + if (labels[level] === undefined) throw Error('unknown level value' + level) + level = labels[level] + } + if (values[level] === undefined) throw Error('unknown level ' + level) + const preLevelVal = this[levelValSym] + const levelVal = this[levelValSym] = values[level] + const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym] + const hook = this[hooksSym].logMethod - let ret; - if (typeof obj === 'function') { - ret = function () { - if (opts.excludeMain) { - return obj.apply(this, arguments); - } + for (const key in values) { + if (levelVal > values[key]) { + this[key] = noop + continue + } + this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook) + } - return processFn(obj, opts).apply(this, arguments); - }; - } else { - ret = Object.create(Object.getPrototypeOf(obj)); - } + this.emit( + 'level-change', + level, + levelVal, + labels[preLevelVal], + preLevelVal + ) +} - for (const key in obj) { // eslint-disable-line guard-for-in - const x = obj[key]; - ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; - } +function getLevel (level) { + const { levels, levelVal } = this + // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833) + return (levels && levels.labels) ? levels.labels[levelVal] : '' +} - return ret; -}; +function isLevelEnabled (logLevel) { + const { values } = this.levels + const logLevelVal = values[logLevel] + return logLevelVal !== undefined && (logLevelVal >= this[levelValSym]) +} +function mappings (customLevels = null, useOnlyCustomLevels = false) { + const customNums = customLevels + ? Object.keys(customLevels).reduce((o, k) => { + o[customLevels[k]] = k + return o + }, {}) + : null -/***/ }), + const labels = Object.assign( + Object.create(Object.prototype, { Infinity: { value: 'silent' } }), + useOnlyCustomLevels ? null : nums, + customNums + ) + const values = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : levels, + customLevels + ) + return { labels, values } +} -/***/ 31778: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) { + if (typeof defaultLevel === 'number') { + const values = [].concat( + Object.keys(customLevels || {}).map(key => customLevels[key]), + useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level), + Infinity + ) + if (!values.includes(defaultLevel)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`) + } + return + } -"use strict"; + const labels = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : levels, + customLevels + ) + if (!(defaultLevel in labels)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`) + } +} +function assertNoLevelCollisions (levels, customLevels) { + const { labels, values } = levels + for (const k in customLevels) { + if (k in values) { + throw Error('levels cannot be overridden') + } + if (customLevels[k] in labels) { + throw Error('pre-existing level values cannot be used for new levels') + } + } +} -var pino = __nccwpck_require__(79608) -var serializers = __nccwpck_require__(72571) -var URL = __nccwpck_require__(34578) -var startTime = Symbol('startTime') +module.exports = { + initialLsCache, + genLsCache, + levelMethods, + getLevel, + setLevel, + isLevelEnabled, + mappings, + assertNoLevelCollisions, + assertDefaultLevelFound +} -function pinoLogger (opts, stream) { - if (opts && opts._writableState) { - stream = opts - opts = null - } - opts = Object.assign({}, opts) +/***/ }), - opts.customAttributeKeys = opts.customAttributeKeys || {} - var reqKey = opts.customAttributeKeys.req || 'req' - var resKey = opts.customAttributeKeys.res || 'res' - var errKey = opts.customAttributeKeys.err || 'err' - var responseTimeKey = opts.customAttributeKeys.responseTime || 'responseTime' - delete opts.customAttributeKeys +/***/ 68578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var reqCustomProps = opts.reqCustomProps || {} +"use strict"; - opts.wrapSerializers = 'wrapSerializers' in opts ? opts.wrapSerializers : true - if (opts.wrapSerializers) { - opts.serializers = Object.assign({}, opts.serializers) - var requestSerializer = opts.serializers[reqKey] || opts.serializers.req || serializers.req - var responseSerializer = opts.serializers[resKey] || opts.serializers.res || serializers.res - var errorSerializer = opts.serializers[errKey] || opts.serializers.err || serializers.err - opts.serializers[reqKey] = serializers.wrapRequestSerializer(requestSerializer) - opts.serializers[resKey] = serializers.wrapResponseSerializer(responseSerializer) - opts.serializers[errKey] = serializers.wrapErrorSerializer(errorSerializer) - } - delete opts.wrapSerializers - if (opts.useLevel && opts.customLogLevel) { - throw new Error("You can't pass 'useLevel' and 'customLogLevel' together") - } +const { version } = __nccwpck_require__(59023) - var useLevel = opts.useLevel || 'info' - var customLogLevel = opts.customLogLevel - delete opts.useLevel - delete opts.customLogLevel +module.exports = { version } - var theStream = opts.stream || stream - delete opts.stream - var autoLogging = (opts.autoLogging !== false) - var autoLoggingIgnorePaths = (opts.autoLogging && opts.autoLogging.ignorePaths) ? opts.autoLogging.ignorePaths : [] - var autoLoggingGetPath = opts.autoLogging && opts.autoLogging.getPath ? opts.autoLogging.getPath : null - delete opts.autoLogging +/***/ }), - var successMessage = opts.customSuccessMessage || function () { return 'request completed' } - var errorMessage = opts.customErrorMessage || function () { return 'request errored' } - delete opts.customSuccessfulMessage - delete opts.customErroredMessage +/***/ 26899: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var logger = wrapChild(opts, theStream) - var genReqId = reqIdGenFactory(opts.genReqId) - loggingMiddleware.logger = logger - return loggingMiddleware +"use strict"; - function onResFinished (err) { - this.removeListener('error', onResFinished) - this.removeListener('finish', onResFinished) - var log = this.log - var responseTime = Date.now() - this[startTime] - var level = customLogLevel ? customLogLevel(this, err) : useLevel +/* eslint no-prototype-builtins: 0 */ - if (err || this.err || this.statusCode >= 500) { - var error = err || this.err || new Error('failed with status code ' + this.statusCode) +const { EventEmitter } = __nccwpck_require__(82361) +const SonicBoom = __nccwpck_require__(73460) +const flatstr = __nccwpck_require__(35298) +const { + lsCacheSym, + levelValSym, + setLevelSym, + getLevelSym, + chindingsSym, + parsedChindingsSym, + mixinSym, + asJsonSym, + writeSym, + timeSym, + timeSliceIndexSym, + streamSym, + serializersSym, + formattersSym, + useOnlyCustomLevelsSym, + needsMetadataGsym +} = __nccwpck_require__(23957) +const { + getLevel, + setLevel, + isLevelEnabled, + mappings, + initialLsCache, + genLsCache, + assertNoLevelCollisions +} = __nccwpck_require__(90591) +const { + asChindings, + asJson, + buildFormatters +} = __nccwpck_require__(51521) +const { + version +} = __nccwpck_require__(68578) - log[level]({ - [resKey]: this, - [errKey]: error, - [responseTimeKey]: responseTime - }, errorMessage(error, this)) - return - } +// note: use of class is satirical +// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127 +const constructor = class Pino {} +const prototype = { + constructor, + child, + bindings, + setBindings, + flush, + isLevelEnabled, + version, + get level () { return this[getLevelSym]() }, + set level (lvl) { this[setLevelSym](lvl) }, + get levelVal () { return this[levelValSym] }, + set levelVal (n) { throw Error('levelVal is read-only') }, + [lsCacheSym]: initialLsCache, + [writeSym]: write, + [asJsonSym]: asJson, + [getLevelSym]: getLevel, + [setLevelSym]: setLevel +} - log[level]({ - [resKey]: this, - [responseTimeKey]: responseTime - }, successMessage(this)) - } +Object.setPrototypeOf(prototype, EventEmitter.prototype) - function loggingMiddleware (req, res, next) { - var shouldLogSuccess = true +// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing +module.exports = function () { + return Object.create(prototype) +} - req.id = genReqId(req) +const resetChildingsFormatter = bindings => bindings +function child (bindings) { + if (!bindings) { + throw Error('missing bindings for child Pino') + } + const serializers = this[serializersSym] + const formatters = this[formattersSym] + const instance = Object.create(this) + if (bindings.hasOwnProperty('serializers') === true) { + instance[serializersSym] = Object.create(null) - var log = logger.child({ [reqKey]: req }) + for (const k in serializers) { + instance[serializersSym][k] = serializers[k] + } + const parentSymbols = Object.getOwnPropertySymbols(serializers) + /* eslint no-var: off */ + for (var i = 0; i < parentSymbols.length; i++) { + const ks = parentSymbols[i] + instance[serializersSym][ks] = serializers[ks] + } - if (reqCustomProps) { - var customPropBindings = (typeof reqCustomProps === 'function') ? reqCustomProps(req) : reqCustomProps - log = log.child(customPropBindings) + for (const bk in bindings.serializers) { + instance[serializersSym][bk] = bindings.serializers[bk] } - req.log = res.log = log + const bindingsSymbols = Object.getOwnPropertySymbols(bindings.serializers) + for (var bi = 0; bi < bindingsSymbols.length; bi++) { + const bks = bindingsSymbols[bi] + instance[serializersSym][bks] = bindings.serializers[bks] + } + } else instance[serializersSym] = serializers + if (bindings.hasOwnProperty('formatters')) { + const { level, bindings: chindings, log } = bindings.formatters + instance[formattersSym] = buildFormatters( + level || formatters.level, + chindings || resetChildingsFormatter, + log || formatters.log + ) + } else { + instance[formattersSym] = buildFormatters( + formatters.level, + resetChildingsFormatter, + formatters.log + ) + } + if (bindings.hasOwnProperty('customLevels') === true) { + assertNoLevelCollisions(this.levels, bindings.customLevels) + instance.levels = mappings(bindings.customLevels, instance[useOnlyCustomLevelsSym]) + genLsCache(instance) + } + instance[chindingsSym] = asChindings(instance, bindings) + const childLevel = bindings.level || this.level + instance[setLevelSym](childLevel) - res[startTime] = res[startTime] || Date.now() + return instance +} - if (autoLogging) { - if (autoLoggingIgnorePaths.length) { - var url - if (autoLoggingGetPath) { - url = URL.parse(autoLoggingGetPath(req)) - } else if (req.url) { - url = URL.parse(req.url) - } - if (url && url.pathname) { - shouldLogSuccess = !autoLoggingIgnorePaths.find(ignorePath => { - if (ignorePath instanceof RegExp) { - return ignorePath.test(url.pathname) - } +function bindings () { + const chindings = this[chindingsSym] + const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,"pid":7068,"hostname":"myMac" + const bindingsFromJson = JSON.parse(chindingsJson) + delete bindingsFromJson.pid + delete bindingsFromJson.hostname + return bindingsFromJson +} - return ignorePath === url.pathname - }) - } - } +function setBindings (newBindings) { + const chindings = asChindings(this, newBindings) + this[chindingsSym] = chindings + delete this[parsedChindingsSym] +} - if (shouldLogSuccess) { - res.on('finish', onResFinished) - } +function write (_obj, msg, num) { + const t = this[timeSym]() + const mixin = this[mixinSym] + const objError = _obj instanceof Error + let obj - res.on('error', onResFinished) + if (_obj === undefined || _obj === null) { + obj = mixin ? mixin({}) : {} + } else { + obj = Object.assign(mixin ? mixin(_obj) : {}, _obj) + if (!msg && objError) { + msg = _obj.message } - if (next) { - next() + if (objError) { + obj.stack = _obj.stack + if (!obj.type) { + obj.type = 'Error' + } } } -} - -function wrapChild (opts, stream) { - var prevLogger = opts.logger - var prevGenReqId = opts.genReqId - var logger = null - - if (prevLogger) { - opts.logger = undefined - opts.genReqId = undefined - logger = prevLogger.child(opts) - opts.logger = prevLogger - opts.genReqId = prevGenReqId - } else { - logger = pino(opts, stream) - } - return logger -} + const s = this[asJsonSym](obj, msg, num, t) -function reqIdGenFactory (func) { - if (typeof func === 'function') return func - var maxInt = 2147483647 - var nextReqId = 0 - return function genReqId (req) { - return req.id || (nextReqId = (nextReqId + 1) & maxInt) + const stream = this[streamSym] + if (stream[needsMetadataGsym] === true) { + stream.lastLevel = num + stream.lastObj = obj + stream.lastMsg = msg + stream.lastTime = t.slice(this[timeSliceIndexSym]) + stream.lastLogger = this // for child loggers } + if (stream instanceof SonicBoom) stream.write(s) + else stream.write(flatstr(s)) } -module.exports = pinoLogger -module.exports.stdSerializers = { - err: serializers.err, - req: serializers.req, - res: serializers.res +function flush () { + const stream = this[streamSym] + if ('flush' in stream) stream.flush() } -module.exports.startTime = startTime /***/ }), -/***/ 31691: +/***/ 34219: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const chalk = __nccwpck_require__(78818) -const jmespath = __nccwpck_require__(87783) -const colors = __nccwpck_require__(31297) -const { ERROR_LIKE_KEYS, MESSAGE_KEY, TIMESTAMP_KEY } = __nccwpck_require__(12186) -const { - isObject, - prettifyErrorLog, - prettifyLevel, - prettifyMessage, - prettifyMetadata, - prettifyObject, - prettifyTime -} = __nccwpck_require__(24694) +const fastRedact = __nccwpck_require__(24826) +const { redactFmtSym, wildcardFirstSym } = __nccwpck_require__(23957) +const { rx, validator } = fastRedact -const bourne = __nccwpck_require__(97174) -const jsonParser = input => { - try { - return { value: bourne.parse(input, { protoAction: 'remove' }) } - } catch (err) { - return { err } - } -} +const validate = validator({ + ERR_PATHS_MUST_BE_STRINGS: () => 'pino – redacted paths must be strings', + ERR_INVALID_PATH: (s) => `pino – redact paths array contains an invalid path (${s})` +}) -const defaultOptions = { - colorize: chalk.supportsColor, - crlf: false, - errorLikeObjectKeys: ERROR_LIKE_KEYS, - errorProps: '', - levelFirst: false, - messageKey: MESSAGE_KEY, - messageFormat: false, - timestampKey: TIMESTAMP_KEY, - translateTime: false, - useMetadata: false, - outputStream: process.stdout, - customPrettifiers: {} -} +const CENSOR = '[Redacted]' +const strict = false // TODO should this be configurable? -module.exports = function prettyFactory (options) { - const opts = Object.assign({}, defaultOptions, options) - const EOL = opts.crlf ? '\r\n' : '\n' - const IDENT = ' ' - const messageKey = opts.messageKey - const levelKey = opts.levelKey - const levelLabel = opts.levelLabel - const messageFormat = opts.messageFormat - const timestampKey = opts.timestampKey - const errorLikeObjectKeys = opts.errorLikeObjectKeys - const errorProps = opts.errorProps.split(',') - const customPrettifiers = opts.customPrettifiers - const ignoreKeys = opts.ignore ? new Set(opts.ignore.split(',')) : undefined +function redaction (opts, serialize) { + const { paths, censor } = handle(opts) - const colorizer = colors(opts.colorize) - const search = opts.search + const shape = paths.reduce((o, str) => { + rx.lastIndex = 0 + const first = rx.exec(str) + const next = rx.exec(str) - return pretty + // ns is the top-level path segment, brackets + quoting removed. + let ns = first[1] !== undefined + ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, '$1') + : first[0] - function pretty (inputData) { - let log - if (!isObject(inputData)) { - const parsed = jsonParser(inputData) - if (parsed.err || !isObject(parsed.value)) { - // pass through - return inputData + EOL - } - log = parsed.value - } else { - log = inputData + if (ns === '*') { + ns = wildcardFirstSym } - if (search && !jmespath.search(log, search)) { - return + // top level key: + if (next === null) { + o[ns] = null + return o } - const prettifiedMessage = prettifyMessage({ log, messageKey, colorizer, messageFormat, levelLabel }) - - if (ignoreKeys) { - log = Object.keys(log) - .filter(key => !ignoreKeys.has(key)) - .reduce((res, key) => { - res[key] = log[key] - return res - }, {}) + // path with at least two segments: + // if ns is already redacted at the top level, ignore lower level redactions + if (o[ns] === null) { + return o } - const prettifiedLevel = prettifyLevel({ log, colorizer, levelKey }) - const prettifiedMetadata = prettifyMetadata({ log }) - const prettifiedTime = prettifyTime({ log, translateFormat: opts.translateTime, timestampKey }) - - let line = '' - if (opts.levelFirst && prettifiedLevel) { - line = `${prettifiedLevel}` - } + const { index } = next + const nextPath = `${str.substr(index, str.length - 1)}` - if (prettifiedTime && line === '') { - line = `${prettifiedTime}` - } else if (prettifiedTime) { - line = `${line} ${prettifiedTime}` - } + o[ns] = o[ns] || [] - if (!opts.levelFirst && prettifiedLevel) { - if (line.length > 0) { - line = `${line} ${prettifiedLevel}` - } else { - line = prettifiedLevel - } + // shape is a mix of paths beginning with literal values and wildcard + // paths [ "a.b.c", "*.b.z" ] should reduce to a shape of + // { "a": [ "b.c", "b.z" ], *: [ "b.z" ] } + // note: "b.z" is in both "a" and * arrays because "a" matches the wildcard. + // (* entry has wildcardFirstSym as key) + if (ns !== wildcardFirstSym && o[ns].length === 0) { + // first time ns's get all '*' redactions so far + o[ns].push(...(o[wildcardFirstSym] || [])) } - if (prettifiedMetadata) { - if (line.length > 0) { - line = `${line} ${prettifiedMetadata}:` - } else { - line = prettifiedMetadata - } + if (ns === wildcardFirstSym) { + // new * path gets added to all previously registered literal ns's. + Object.keys(o).forEach(function (k) { + if (o[k]) { + o[k].push(nextPath) + } + }) } - if (line.endsWith(':') === false && line !== '') { - line += ':' - } + o[ns].push(nextPath) + return o + }, {}) - if (prettifiedMessage) { - if (line.length > 0) { - line = `${line} ${prettifiedMessage}` - } else { - line = prettifiedMessage - } - } + // the redactor assigned to the format symbol key + // provides top level redaction for instances where + // an object is interpolated into the msg string + const result = { + [redactFmtSym]: fastRedact({ paths, censor, serialize, strict }) + } - if (line.length > 0) { - line += EOL - } + const topCensor = (...args) => { + return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor) + } - if (log.type === 'Error' && log.stack) { - const prettifiedErrorLog = prettifyErrorLog({ - log, - errorLikeKeys: errorLikeObjectKeys, - errorProperties: errorProps, - ident: IDENT, - eol: EOL - }) - line += prettifiedErrorLog + return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => { + // top level key: + if (shape[k] === null) { + o[k] = (value) => topCensor(value, [k]) } else { - const skipKeys = [messageKey, levelKey, timestampKey].filter(key => typeof log[key] === 'string' || typeof log[key] === 'number') - const prettifiedObject = prettifyObject({ - input: log, - skipKeys, - customPrettifiers, - errorLikeKeys: errorLikeObjectKeys, - eol: EOL, - ident: IDENT + const wrappedCensor = typeof censor === 'function' + ? (value, path) => { + return censor(value, [k, ...path]) + } + : censor + o[k] = fastRedact({ + paths: shape[k], + censor: wrappedCensor, + serialize, + strict }) - line += prettifiedObject } + return o + }, result) +} - return line +function handle (opts) { + if (Array.isArray(opts)) { + opts = { paths: opts, censor: CENSOR } + validate(opts) + return opts } + let { paths, censor = CENSOR, remove } = opts + if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') } + if (remove === true) censor = undefined + validate({ paths, censor }) + + return { paths, censor } } +module.exports = redaction + /***/ }), -/***/ 31297: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 23957: +/***/ ((module) => { "use strict"; -const { LEVELS, LEVEL_NAMES } = __nccwpck_require__(12186) - -const nocolor = input => input -const plain = { - default: nocolor, - 60: nocolor, - 50: nocolor, - 40: nocolor, - 30: nocolor, - 20: nocolor, - 10: nocolor, - message: nocolor -} - -const chalk = __nccwpck_require__(78818) -const ctx = new chalk.Instance({ level: 3 }) -const colored = { - default: ctx.white, - 60: ctx.bgRed, - 50: ctx.red, - 40: ctx.yellow, - 30: ctx.green, - 20: ctx.blue, - 10: ctx.grey, - message: ctx.cyan -} - -function colorizeLevel (level, colorizer) { - if (Number.isInteger(+level)) { - return Object.prototype.hasOwnProperty.call(LEVELS, level) - ? colorizer[level](LEVELS[level]) - : colorizer.default(LEVELS.default) - } - const levelNum = LEVEL_NAMES[level.toLowerCase()] || 'default' - return colorizer[levelNum](LEVELS[levelNum]) -} - -function plainColorizer (level) { - return colorizeLevel(level, plain) -} -plainColorizer.message = plain.message +const setLevelSym = Symbol('pino.setLevel') +const getLevelSym = Symbol('pino.getLevel') +const levelValSym = Symbol('pino.levelVal') +const useLevelLabelsSym = Symbol('pino.useLevelLabels') +const useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels') +const mixinSym = Symbol('pino.mixin') -function coloredColorizer (level) { - return colorizeLevel(level, colored) -} -coloredColorizer.message = colored.message +const lsCacheSym = Symbol('pino.lsCache') +const chindingsSym = Symbol('pino.chindings') +const parsedChindingsSym = Symbol('pino.parsedChindings') -/** - * Factory function get a function to colorized levels. The returned function - * also includes a `.message(str)` method to colorize strings. - * - * @param {bool} [useColors=false] When `true` a function that applies standard - * terminal colors is returned. - * - * @returns {function} `function (level) {}` has a `.message(str)` method to - * apply colorization to a string. The core function accepts either an integer - * `level` or a `string` level. The integer level will map to a known level - * string or to `USERLVL` if not known. The string `level` will map to the same - * colors as the integer `level` and will also default to `USERLVL` if the given - * string is not a recognized level name. - */ -module.exports = function getColorizer (useColors = false) { - return useColors ? coloredColorizer : plainColorizer -} +const asJsonSym = Symbol('pino.asJson') +const writeSym = Symbol('pino.write') +const redactFmtSym = Symbol('pino.redactFmt') +const timeSym = Symbol('pino.time') +const timeSliceIndexSym = Symbol('pino.timeSliceIndex') +const streamSym = Symbol('pino.stream') +const stringifySym = Symbol('pino.stringify') +const stringifiersSym = Symbol('pino.stringifiers') +const endSym = Symbol('pino.end') +const formatOptsSym = Symbol('pino.formatOpts') +const messageKeySym = Symbol('pino.messageKey') +const nestedKeySym = Symbol('pino.nestedKey') -/***/ }), +const wildcardFirstSym = Symbol('pino.wildcardFirst') -/***/ 12186: -/***/ ((module) => { +// public symbols, no need to use the same pino +// version for these +const serializersSym = Symbol.for('pino.serializers') +const formattersSym = Symbol.for('pino.formatters') +const hooksSym = Symbol.for('pino.hooks') +const needsMetadataGsym = Symbol.for('pino.metadata') -"use strict"; +module.exports = { + setLevelSym, + getLevelSym, + levelValSym, + useLevelLabelsSym, + mixinSym, + lsCacheSym, + chindingsSym, + parsedChindingsSym, + asJsonSym, + writeSym, + serializersSym, + redactFmtSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifiersSym, + endSym, + formatOptsSym, + messageKeySym, + nestedKeySym, + wildcardFirstSym, + needsMetadataGsym, + useOnlyCustomLevelsSym, + formattersSym, + hooksSym +} -module.exports = { - DATE_FORMAT: 'yyyy-mm-dd HH:MM:ss.l o', +/***/ }), - ERROR_LIKE_KEYS: ['err', 'error'], +/***/ 61866: +/***/ ((module) => { - MESSAGE_KEY: 'msg', +"use strict"; - LEVEL_KEY: 'level', - LEVEL_LABEL: 'levelLabel', +const nullTime = () => '' - TIMESTAMP_KEY: 'time', +const epochTime = () => `,"time":${Date.now()}` - LEVELS: { - default: 'USERLVL', - 60: 'FATAL', - 50: 'ERROR', - 40: 'WARN', - 30: 'INFO', - 20: 'DEBUG', - 10: 'TRACE' - }, +const unixTime = () => `,"time":${Math.round(Date.now() / 1000.0)}` - LEVEL_NAMES: { - fatal: 60, - error: 50, - warn: 40, - info: 30, - debug: 20, - trace: 10 - }, +const isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"` // using Date.now() for testability - // Object keys that probably came from a logger like Pino or Bunyan. - LOGGER_KEYS: [ - 'pid', - 'hostname', - 'name', - 'level', - 'time', - 'timestamp', - 'caller' - ] -} +module.exports = { nullTime, epochTime, unixTime, isoTime } /***/ }), -/***/ 24694: +/***/ 51521: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const dateformat = __nccwpck_require__(51512) +/* eslint no-prototype-builtins: 0 */ + +const format = __nccwpck_require__(5933) +const { mapHttpRequest, mapHttpResponse } = __nccwpck_require__(73757) +const SonicBoom = __nccwpck_require__(73460) const stringifySafe = __nccwpck_require__(17676) -const defaultColorizer = __nccwpck_require__(31297)() const { - DATE_FORMAT, - ERROR_LIKE_KEYS, - MESSAGE_KEY, - LEVEL_KEY, - LEVEL_LABEL, - TIMESTAMP_KEY, - LOGGER_KEYS, - LEVELS -} = __nccwpck_require__(12186) + lsCacheSym, + chindingsSym, + parsedChindingsSym, + writeSym, + serializersSym, + formatOptsSym, + endSym, + stringifiersSym, + stringifySym, + wildcardFirstSym, + needsMetadataGsym, + redactFmtSym, + streamSym, + nestedKeySym, + formattersSym, + messageKeySym +} = __nccwpck_require__(23957) -module.exports = { - isObject, - prettifyErrorLog, - prettifyLevel, - prettifyMessage, - prettifyMetadata, - prettifyObject, - prettifyTime -} +function noop () {} -module.exports.internals = { - formatTime, - joinLinesWithIndentation -} +function genLog (level, hook) { + if (!hook) return LOG -/** - * Converts a given `epoch` to a desired display format. - * - * @param {number|string} epoch The time to convert. May be any value that is - * valid for `new Date()`. - * @param {bool|string} [translateTime=false] When `false`, the given `epoch` - * will simply be returned. When `true`, the given `epoch` will be converted - * to a string at UTC using the `DATE_FORMAT` constant. If `translateTime` is - * a string, the following rules are available: - * - * - ``: The string is a literal format string. This format - * string will be used to interpret the `epoch` and return a display string - * at UTC. - * - `SYS:STANDARD`: The returned display string will follow the `DATE_FORMAT` - * constant at the system's local timezone. - * - `SYS:`: The returned display string will follow the given - * `` at the system's local timezone. - * - `UTC:`: The returned display string will follow the given - * `` at UTC. - * - * @returns {number|string} The formatted time. - */ -function formatTime (epoch, translateTime = false) { - if (translateTime === false) { - return epoch + return function hookWrappedLog (...args) { + hook.call(this, args, LOG, level) } - const instant = new Date(epoch) - if (translateTime === true) { - return dateformat(instant, 'UTC:' + DATE_FORMAT) + function LOG (o, ...n) { + if (typeof o === 'object') { + let msg = o + if (o !== null) { + if (o.method && o.headers && o.socket) { + o = mapHttpRequest(o) + } else if (typeof o.setHeader === 'function') { + o = mapHttpResponse(o) + } + } + if (this[nestedKeySym]) o = { [this[nestedKeySym]]: o } + let formatParams + if (msg === null && n.length === 0) { + formatParams = [null] + } else { + msg = n.shift() + formatParams = n + } + this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level) + } else { + this[writeSym](null, format(o, n, this[formatOptsSym]), level) + } } +} - const upperFormat = translateTime.toUpperCase() - if (upperFormat === 'SYS:STANDARD') { - return dateformat(instant, DATE_FORMAT) +// magically escape strings for json +// relying on their charCodeAt +// everything below 32 needs JSON.stringify() +// 34 and 92 happens all the time, so we +// have a fast case for them +function asString (str) { + let result = '' + let last = 0 + let found = false + let point = 255 + const l = str.length + if (l > 100) { + return JSON.stringify(str) } - - const prefix = upperFormat.substr(0, 4) - if (prefix === 'SYS:' || prefix === 'UTC:') { - if (prefix === 'UTC:') { - return dateformat(instant, translateTime) + for (var i = 0; i < l && point >= 32; i++) { + point = str.charCodeAt(i) + if (point === 34 || point === 92) { + result += str.slice(last, i) + '\\' + last = i + found = true } - return dateformat(instant, translateTime.slice(4)) } - - return dateformat(instant, `UTC:${translateTime}`) + if (!found) { + result = str + } else { + result += str.slice(last) + } + return point < 32 ? JSON.stringify(str) : '"' + result + '"' } -function isObject (input) { - return Object.prototype.toString.apply(input) === '[object Object]' -} +function asJson (obj, msg, num, time) { + const stringify = this[stringifySym] + const stringifiers = this[stringifiersSym] + const end = this[endSym] + const chindings = this[chindingsSym] + const serializers = this[serializersSym] + const formatters = this[formattersSym] + const messageKey = this[messageKeySym] + let data = this[lsCacheSym][num] + time -/** - * Given a string with line separators, either `\r\n` or `\n`, add indentation - * to all lines subsequent to the first line and rejoin the lines using an - * end of line sequence. - * - * @param {object} input - * @param {string} input.input The string to split and reformat. - * @param {string} [input.ident] The indentation string. Default: ` ` (4 spaces). - * @param {string} [input.eol] The end of line sequence to use when rejoining - * the lines. Default: `'\n'`. - * - * @returns {string} A string with lines subsequent to the first indented - * with the given indentation sequence. - */ -function joinLinesWithIndentation ({ input, ident = ' ', eol = '\n' }) { - const lines = input.split(/\r?\n/) - for (var i = 1; i < lines.length; i += 1) { - lines[i] = ident + lines[i] - } - return lines.join(eol) -} + // we need the child bindings added to the output first so instance logged + // objects can take precedence when JSON.parse-ing the resulting log line + data = data + chindings -/** - * Given a log object that has a `type: 'Error'` key, prettify the object and - * return the result. In other - * - * @param {object} input - * @param {object} input.log The error log to prettify. - * @param {string} [input.messageKey] The name of the key that contains a - * general log message. This is not the error's message property but the logger - * messsage property. Default: `MESSAGE_KEY` constant. - * @param {string} [input.ident] The sequence to use for indentation. Default: `' '`. - * @param {string} [input.eol] The sequence to use for EOL. Default: `'\n'`. - * @param {string[]} [input.errorLikeKeys] A set of keys that should be considered - * to have error objects as values. Default: `ERROR_LIKE_KEYS` constant. - * @param {string[]} [input.errorProperties] A set of specific error object - * properties, that are not the value of `messageKey`, `type`, or `stack`, to - * include in the prettified result. The first entry in the list may be `'*'` - * to indicate that all sibiling properties should be prettified. Default: `[]`. - * - * @returns {string} A sring that represents the prettified error log. - */ -function prettifyErrorLog ({ - log, - messageKey = MESSAGE_KEY, - ident = ' ', - eol = '\n', - errorLikeKeys = ERROR_LIKE_KEYS, - errorProperties = [] -}) { - const stack = log.stack - const joinedLines = joinLinesWithIndentation({ input: stack, ident, eol }) - let result = `${ident}${joinedLines}${eol}` + let value + const notHasOwnProperty = obj.hasOwnProperty === undefined + if (formatters.log) { + obj = formatters.log(obj) + } + if (msg !== undefined) { + obj[messageKey] = msg + } + const wildcardStringifier = stringifiers[wildcardFirstSym] + for (const key in obj) { + value = obj[key] + if ((notHasOwnProperty || obj.hasOwnProperty(key)) && value !== undefined) { + value = serializers[key] ? serializers[key](value) : value - if (errorProperties.length > 0) { - const excludeProperties = LOGGER_KEYS.concat(messageKey, 'type', 'stack') - let propertiesToPrint - if (errorProperties[0] === '*') { - // Print all sibling properties except for the standard exclusions. - propertiesToPrint = Object.keys(log).filter(k => excludeProperties.includes(k) === false) - } else { - // Print only sepcified properties unless the property is a standard exclusion. - propertiesToPrint = errorProperties.filter(k => excludeProperties.includes(k) === false) - } + const stringifier = stringifiers[key] || wildcardStringifier - for (var i = 0; i < propertiesToPrint.length; i += 1) { - const key = propertiesToPrint[i] - if (key in log === false) continue - if (isObject(log[key])) { - // The nested object may have "logger" type keys but since they are not - // at the root level of the object being processed, we want to print them. - // Thus, we invoke with `excludeLoggerKeys: false`. - const prettifiedObject = prettifyObject({ input: log[key], errorLikeKeys, excludeLoggerKeys: false, eol, ident }) - result = `${result}${key}: {${eol}${prettifiedObject}}${eol}` - continue + switch (typeof value) { + case 'undefined': + case 'function': + continue + case 'number': + /* eslint no-fallthrough: "off" */ + if (Number.isFinite(value) === false) { + value = null + } + // this case explicitly falls through to the next one + case 'boolean': + if (stringifier) value = stringifier(value) + break + case 'string': + value = (stringifier || asString)(value) + break + default: + value = (stringifier || stringify)(value) } - result = `${result}${key}: ${log[key]}${eol}` + if (value === undefined) continue + data += ',"' + key + '":' + value } } - return result + return data + end } -/** - * Checks if the passed in log has a `level` value and returns a prettified - * string for that level if so. - * - * @param {object} input - * @param {object} input.log The log object. - * @param {function} [input.colorizer] A colorizer function that accepts a level - * value and returns a colorized string. Default: a no-op colorizer. - * @param {string} [levelKey='level'] The key to find the level under. - * - * @returns {undefined|string} If `log` does not have a `level` property then - * `undefined` will be returned. Otherwise, a string from the specified - * `colorizer` is returned. - */ -function prettifyLevel ({ log, colorizer = defaultColorizer, levelKey = LEVEL_KEY }) { - if (levelKey in log === false) return undefined - return colorizer(log[levelKey]) + '\t' +function asChindings (instance, bindings) { + let value + let data = instance[chindingsSym] + const stringify = instance[stringifySym] + const stringifiers = instance[stringifiersSym] + const wildcardStringifier = stringifiers[wildcardFirstSym] + const serializers = instance[serializersSym] + const formatter = instance[formattersSym].bindings + bindings = formatter(bindings) + + for (const key in bindings) { + value = bindings[key] + const valid = key !== 'level' && + key !== 'serializers' && + key !== 'formatters' && + key !== 'customLevels' && + bindings.hasOwnProperty(key) && + value !== undefined + if (valid === true) { + value = serializers[key] ? serializers[key](value) : value + value = (stringifiers[key] || wildcardStringifier || stringify)(value) + if (value === undefined) continue + data += ',"' + key + '":' + value + } + } + return data } -/** - * Prettifies a message string if the given `log` has a message property. - * - * @param {object} input - * @param {object} input.log The log object with the message to colorize. - * @param {string} [input.messageKey='msg'] The property of the `log` that is the - * message to be prettified. - * @param {string} [input.messageFormat=undefined] A format string that defines how the - * logged message should be formatted, e.g. `'{level} - {pid}'`. - * @param {function} [input.colorizer] A colorizer function that has a - * `.message(str)` method attached to it. This function should return a colorized - * string which will be the "prettified" message. Default: a no-op colorizer. - * - * @returns {undefined|string} If the message key is not found, or the message - * key is not a string, then `undefined` will be returned. Otherwise, a string - * that is the prettified message. - */ -function prettifyMessage ({ log, messageFormat, messageKey = MESSAGE_KEY, colorizer = defaultColorizer, levelLabel = LEVEL_LABEL }) { - if (messageFormat) { - const message = String(messageFormat).replace(/{([^{}]+)}/g, function (match, p1) { - // return log level as string instead of int - if (p1 === levelLabel && log[LEVEL_KEY]) { - return LEVELS[log[LEVEL_KEY]] - } - // Parse nested key access, e.g. `{keyA.subKeyB}`. - return p1.split('.').reduce(function (prev, curr) { - if (prev && prev[curr]) { - return prev[curr] - } - return '' - }, log) - }) - return colorizer.message(message) +function getPrettyStream (opts, prettifier, dest, instance) { + if (prettifier && typeof prettifier === 'function') { + prettifier = prettifier.bind(instance) + return prettifierMetaWrapper(prettifier(opts), dest, opts) + } + try { + const prettyFactory = __nccwpck_require__(31691) + prettyFactory.asMetaWrapper = prettifierMetaWrapper + return prettifierMetaWrapper(prettyFactory(opts), dest, opts) + } catch (e) { + throw Error('Missing `pino-pretty` module: `pino-pretty` must be installed separately') } - if (messageKey in log === false) return undefined - if (typeof log[messageKey] !== 'string') return undefined - return colorizer.message(log[messageKey]) } -/** - * Prettifies metadata that is usually present in a Pino log line. It looks for - * fields `name`, `pid`, `hostname`, and `caller` and returns a formatted string using - * the fields it finds. - * - * @param {object} input - * @param {object} input.log The log that may or may not contain metadata to - * be prettified. - * - * @returns {undefined|string} If no metadata is found then `undefined` is - * returned. Otherwise, a string of prettified metadata is returned. - */ -function prettifyMetadata ({ log }) { - let line = '' +function prettifierMetaWrapper (pretty, dest, opts) { + opts = Object.assign({ suppressFlushSyncWarning: false }, opts) + let warned = false + return { + [needsMetadataGsym]: true, + lastLevel: 0, + lastMsg: null, + lastObj: null, + lastLogger: null, + flushSync () { + if (opts.suppressFlushSyncWarning || warned) { + return + } + warned = true + setMetadataProps(dest, this) + dest.write(pretty(Object.assign({ + level: 40, // warn + msg: 'pino.final with prettyPrint does not support flushing', + time: Date.now() + }, this.chindings()))) + }, + chindings () { + const lastLogger = this.lastLogger + let chindings = null - if (log.name || log.pid || log.hostname) { - line += '(' + // protection against flushSync being called before logging + // anything + if (!lastLogger) { + return null + } - if (log.name) { - line += log.name - } + if (lastLogger.hasOwnProperty(parsedChindingsSym)) { + chindings = lastLogger[parsedChindingsSym] + } else { + chindings = JSON.parse('{' + lastLogger[chindingsSym].substr(1) + '}') + lastLogger[parsedChindingsSym] = chindings + } - if (log.name && log.pid) { - line += '/' + log.pid - } else if (log.pid) { - line += log.pid - } + return chindings + }, + write (chunk) { + const lastLogger = this.lastLogger + const chindings = this.chindings() - if (log.hostname) { - // If `pid` and `name` were in the ignore keys list then we don't need - // the leading space. - line += `${line === '(' ? 'on' : ' on'} ${log.hostname}` - } + let time = this.lastTime - line += ')' - } + if (time.match(/^\d+/)) { + time = parseInt(time) + } else { + time = time.slice(1, -1) + } + + const lastObj = this.lastObj + const lastMsg = this.lastMsg + const errorProps = null + + const formatters = lastLogger[formattersSym] + const formattedObj = formatters.log ? formatters.log(lastObj) : lastObj + + const messageKey = lastLogger[messageKeySym] + if (lastMsg && formattedObj && !formattedObj.hasOwnProperty(messageKey)) { + formattedObj[messageKey] = lastMsg + } + + const obj = Object.assign({ + level: this.lastLevel, + time + }, formattedObj, errorProps) + + const serializers = lastLogger[serializersSym] + const keys = Object.keys(serializers) + + for (var i = 0; i < keys.length; i++) { + const key = keys[i] + if (obj[key] !== undefined) { + obj[key] = serializers[key](obj[key]) + } + } + + for (const key in chindings) { + if (!obj.hasOwnProperty(key)) { + obj[key] = chindings[key] + } + } + + const stringifiers = lastLogger[stringifiersSym] + const redact = stringifiers[redactFmtSym] - if (log.caller) { - line += `${line === '' ? '' : ' '}<${log.caller}>` - } + const formatted = pretty(typeof redact === 'function' ? redact(obj) : obj) + if (formatted === undefined) return - if (line === '') { - return undefined - } else { - return line + setMetadataProps(dest, this) + dest.write(formatted) + } } } -/** - * Prettifies a standard object. Special care is taken when processing the object - * to handle child objects that are attached to keys known to contain error - * objects. - * - * @param {object} input - * @param {object} input.input The object to prettify. - * @param {string} [input.ident] The identation sequence to use. Default: `' '`. - * @param {string} [input.eol] The EOL sequence to use. Default: `'\n'`. - * @param {string[]} [input.skipKeys] A set of object keys to exclude from the - * prettified result. Default: `[]`. - * @param {Object} [input.customPrettifiers] Dictionary of - * custom prettifiers. Default: `{}`. - * @param {string[]} [input.errorLikeKeys] A set of object keys that contain - * error objects. Default: `ERROR_LIKE_KEYS` constant. - * @param {boolean} [input.excludeLoggerKeys] Indicates if known logger specific - * keys should be excluded from prettification. Default: `true`. - * - * @returns {string} The prettified string. This can be as little as `''` if - * there was nothing to prettify. - */ -function prettifyObject ({ - input, - ident = ' ', - eol = '\n', - skipKeys = [], - customPrettifiers = {}, - errorLikeKeys = ERROR_LIKE_KEYS, - excludeLoggerKeys = true -}) { - const objectKeys = Object.keys(input) - const keysToIgnore = [].concat(skipKeys) - - if (excludeLoggerKeys === true) Array.prototype.push.apply(keysToIgnore, LOGGER_KEYS) - - let result = '' - - const keysToIterate = objectKeys.filter(k => keysToIgnore.includes(k) === false) - for (var i = 0; i < objectKeys.length; i += 1) { - const keyName = keysToIterate[i] - const keyValue = input[keyName] +function hasBeenTampered (stream) { + return stream.write !== stream.constructor.prototype.write +} - if (keyValue === undefined) continue +function buildSafeSonicBoom (opts) { + const stream = new SonicBoom(opts) + stream.on('error', filterBrokenPipe) + return stream - let lines - if (typeof customPrettifiers[keyName] === 'function') { - lines = customPrettifiers[keyName](keyValue, keyName, input) - } else { - lines = stringifySafe(keyValue, null, 2) + function filterBrokenPipe (err) { + // TODO verify on Windows + if (err.code === 'EPIPE') { + // If we get EPIPE, we should stop logging here + // however we have no control to the consumer of + // SonicBoom, so we just overwrite the write method + stream.write = noop + stream.end = noop + stream.flushSync = noop + stream.destroy = noop + return } + stream.removeListener('error', filterBrokenPipe) + stream.emit('error', err) + } +} - if (lines === undefined) continue - const joinedLines = joinLinesWithIndentation({ input: lines, ident, eol }) +function createArgsNormalizer (defaultOptions) { + return function normalizeArgs (instance, opts = {}, stream) { + // support stream as a string + if (typeof opts === 'string') { + stream = buildSafeSonicBoom({ dest: opts, sync: true }) + opts = {} + } else if (typeof stream === 'string') { + stream = buildSafeSonicBoom({ dest: stream, sync: true }) + } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) { + stream = opts + opts = null + } + opts = Object.assign({}, defaultOptions, opts) + if ('extreme' in opts) { + throw Error('The extreme option has been removed, use pino.destination({ sync: false }) instead') + } + if ('onTerminated' in opts) { + throw Error('The onTerminated option has been removed, use pino.final instead') + } + if ('changeLevelName' in opts) { + process.emitWarning( + 'The changeLevelName option is deprecated and will be removed in v7. Use levelKey instead.', + { code: 'changeLevelName_deprecation' } + ) + opts.levelKey = opts.changeLevelName + delete opts.changeLevelName + } + const { enabled, prettyPrint, prettifier, messageKey } = opts + if (enabled === false) opts.level = 'silent' + stream = stream || process.stdout + if (stream === process.stdout && stream.fd >= 0 && !hasBeenTampered(stream)) { + stream = buildSafeSonicBoom({ fd: stream.fd, sync: true }) + } + if (prettyPrint) { + const prettyOpts = Object.assign({ messageKey }, prettyPrint) + stream = getPrettyStream(prettyOpts, prettifier, stream, instance) + } + return { opts, stream } + } +} - if (errorLikeKeys.includes(keyName) === true) { - const splitLines = `${ident}${keyName}: ${joinedLines}${eol}`.split(eol) - for (var j = 0; j < splitLines.length; j += 1) { - if (j !== 0) result += eol +function final (logger, handler) { + if (typeof logger === 'undefined' || typeof logger.child !== 'function') { + throw Error('expected a pino logger instance') + } + const hasHandler = (typeof handler !== 'undefined') + if (hasHandler && typeof handler !== 'function') { + throw Error('if supplied, the handler parameter should be a function') + } + const stream = logger[streamSym] + if (typeof stream.flushSync !== 'function') { + throw Error('final requires a stream that has a flushSync method, such as pino.destination') + } - const line = splitLines[j] - if (/^\s*"stack"/.test(line)) { - const matches = /^(\s*"stack":)\s*(".*"),?$/.exec(line) - /* istanbul ignore else */ - if (matches && matches.length === 3) { - const indentSize = /^\s*/.exec(line)[0].length + 4 - const indentation = ' '.repeat(indentSize) - const stackMessage = matches[2] - result += matches[1] + eol + indentation + JSON.parse(stackMessage).replace(/\n/g, eol + indentation) - } - } else { - result += line + const finalLogger = new Proxy(logger, { + get: (logger, key) => { + if (key in logger.levels.values) { + return (...args) => { + logger[key](...args) + stream.flushSync() } } - } else { - result += `${ident}${keyName}: ${joinedLines}${eol}` + return logger[key] } + }) + + if (!hasHandler) { + return finalLogger } - return result + return (err = null, ...args) => { + try { + stream.flushSync() + } catch (e) { + // it's too late to wait for the stream to be ready + // because this is a final tick scenario. + // in practice there shouldn't be a situation where it isn't + // however, swallow the error just in case (and for easier testing) + } + return handler(err, finalLogger, ...args) + } } -/** - * Prettifies a timestamp if the given `log` has either `time`, `timestamp` or custom specified timestamp - * property. - * - * @param {object} input - * @param {object} input.log The log object with the timestamp to be prettified. - * @param {string} [input.timestampKey='time'] The log property that should be used to resolve timestamp value - * @param {bool|string} [input.translateFormat=undefined] When `true` the - * timestamp will be prettified into a string at UTC using the default - * `DATE_FORMAT`. If a string, then `translateFormat` will be used as the format - * string to determine the output; see the `formatTime` function for details. - * - * @returns {undefined|string} If a timestamp property cannot be found then - * `undefined` is returned. Otherwise, the prettified time is returned as a - * string. - */ -function prettifyTime ({ log, timestampKey = TIMESTAMP_KEY, translateFormat = undefined }) { - let time = null +function stringify (obj) { + try { + return JSON.stringify(obj) + } catch (_) { + return stringifySafe(obj) + } +} - if (timestampKey in log) { - time = log[timestampKey] - } else if ('timestamp' in log) { - time = log.timestamp +function buildFormatters (level, bindings, log) { + return { + level, + bindings, + log } +} - if (time === null) return undefined - if (translateFormat) { - return '[' + formatTime(time, translateFormat) + ']' +function setMetadataProps (dest, that) { + if (dest[needsMetadataGsym] === true) { + dest.lastLevel = that.lastLevel + dest.lastMsg = that.lastMsg + dest.lastObj = that.lastObj + dest.lastTime = that.lastTime + dest.lastLogger = that.lastLogger } +} - return `[${time}]` +module.exports = { + noop, + buildSafeSonicBoom, + getPrettyStream, + asChindings, + asJson, + genLog, + createArgsNormalizer, + final, + stringify, + buildFormatters } /***/ }), -/***/ 72571: +/***/ 73757: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var errSerializer = __nccwpck_require__(96522) -var reqSerializers = __nccwpck_require__(75492) -var resSerializers = __nccwpck_require__(9048) +const errSerializer = __nccwpck_require__(79276) +const reqSerializers = __nccwpck_require__(76343) +const resSerializers = __nccwpck_require__(71550) module.exports = { err: errSerializer, @@ -104471,7 +104297,7 @@ module.exports = { /***/ }), -/***/ 96522: +/***/ 79276: /***/ ((module) => { "use strict"; @@ -104479,6 +104305,7 @@ module.exports = { module.exports = errSerializer +const { toString } = Object.prototype const seen = Symbol('circular-ref-tag') const rawSymbol = Symbol('pino-raw-err-ref') const pinoErrProto = Object.create({}, { @@ -104519,13 +104346,16 @@ function errSerializer (err) { err[seen] = undefined // tag to prevent re-looking at this const _err = Object.create(pinoErrProto) - _err.type = err.constructor.name + _err.type = toString.call(err.constructor) === '[object Function]' + ? err.constructor.name + : err.name _err.message = err.message _err.stack = err.stack for (const key in err) { if (_err[key] === undefined) { const val = err[key] if (val instanceof Error) { + /* eslint-disable no-prototype-builtins */ if (!val.hasOwnProperty(seen)) { _err[key] = errSerializer(val) } @@ -104543,7 +104373,7 @@ function errSerializer (err) { /***/ }), -/***/ 75492: +/***/ 76343: /***/ ((module) => { "use strict"; @@ -104554,8 +104384,8 @@ module.exports = { reqSerializer } -var rawSymbol = Symbol('pino-raw-req-ref') -var pinoReqProto = Object.create({}, { +const rawSymbol = Symbol('pino-raw-req-ref') +const pinoReqProto = Object.create({}, { id: { enumerable: true, writable: true, @@ -104571,6 +104401,16 @@ var pinoReqProto = Object.create({}, { writable: true, value: '' }, + query: { + enumerable: true, + writable: true, + value: '' + }, + params: { + enumerable: true, + writable: true, + value: '' + }, headers: { enumerable: true, writable: true, @@ -104603,1887 +104443,2047 @@ Object.defineProperty(pinoReqProto, rawSymbol, { function reqSerializer (req) { // req.info is for hapi compat. - var connection = req.info || req.connection + const connection = req.info || req.socket const _req = Object.create(pinoReqProto) _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined))) _req.method = req.method // req.originalUrl is for expressjs compat. if (req.originalUrl) { _req.url = req.originalUrl + _req.query = req.query + _req.params = req.params } else { // req.url.path is for hapi compat. _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined) } - _req.headers = req.headers - _req.remoteAddress = connection && connection.remoteAddress - _req.remotePort = connection && connection.remotePort - // req.raw is for hapi compat/equivalence - _req.raw = req.raw || req - return _req -} - -function mapHttpRequest (req) { - return { - req: reqSerializer(req) - } -} - - -/***/ }), - -/***/ 9048: -/***/ ((module) => { - -"use strict"; - - -module.exports = { - mapHttpResponse, - resSerializer -} - -var rawSymbol = Symbol('pino-raw-res-ref') -var pinoResProto = Object.create({}, { - statusCode: { - enumerable: true, - writable: true, - value: 0 - }, - headers: { - enumerable: true, - writable: true, - value: '' - }, - raw: { - enumerable: false, - get: function () { - return this[rawSymbol] - }, - set: function (val) { - this[rawSymbol] = val - } - } -}) -Object.defineProperty(pinoResProto, rawSymbol, { - writable: true, - value: {} -}) - -function resSerializer (res) { - const _res = Object.create(pinoResProto) - _res.statusCode = res.statusCode - _res.headers = res.getHeaders ? res.getHeaders() : res._headers - _res.raw = res - return _res -} - -function mapHttpResponse (res) { - return { - res: resSerializer(res) - } -} - - -/***/ }), - -/***/ 90591: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -/* eslint no-prototype-builtins: 0 */ -const flatstr = __nccwpck_require__(35298) -const { - lsCacheSym, - levelValSym, - useOnlyCustomLevelsSym, - streamSym, - formattersSym, - hooksSym -} = __nccwpck_require__(23957) -const { noop, genLog } = __nccwpck_require__(51521) - -const levels = { - trace: 10, - debug: 20, - info: 30, - warn: 40, - error: 50, - fatal: 60 -} -const levelMethods = { - fatal: (hook) => { - const logFatal = genLog(levels.fatal, hook) - return function (...args) { - const stream = this[streamSym] - logFatal.call(this, ...args) - if (typeof stream.flushSync === 'function') { - try { - stream.flushSync() - } catch (e) { - // https://github.com/pinojs/pino/pull/740#discussion_r346788313 - } - } - } - }, - error: (hook) => genLog(levels.error, hook), - warn: (hook) => genLog(levels.warn, hook), - info: (hook) => genLog(levels.info, hook), - debug: (hook) => genLog(levels.debug, hook), - trace: (hook) => genLog(levels.trace, hook) -} - -const nums = Object.keys(levels).reduce((o, k) => { - o[levels[k]] = k - return o -}, {}) - -const initialLsCache = Object.keys(nums).reduce((o, k) => { - o[k] = flatstr('{"level":' + Number(k)) - return o -}, {}) - -function genLsCache (instance) { - const formatter = instance[formattersSym].level - const { labels } = instance.levels - const cache = {} - for (const label in labels) { - const level = formatter(labels[label], Number(label)) - cache[label] = JSON.stringify(level).slice(0, -1) - } - instance[lsCacheSym] = cache - return instance -} - -function isStandardLevel (level, useOnlyCustomLevels) { - if (useOnlyCustomLevels) { - return false - } - - switch (level) { - case 'fatal': - case 'error': - case 'warn': - case 'info': - case 'debug': - case 'trace': - return true - default: - return false - } -} - -function setLevel (level) { - const { labels, values } = this.levels - if (typeof level === 'number') { - if (labels[level] === undefined) throw Error('unknown level value' + level) - level = labels[level] - } - if (values[level] === undefined) throw Error('unknown level ' + level) - const preLevelVal = this[levelValSym] - const levelVal = this[levelValSym] = values[level] - const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym] - const hook = this[hooksSym].logMethod - - for (const key in values) { - if (levelVal > values[key]) { - this[key] = noop - continue - } - this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook) - } - - this.emit( - 'level-change', - level, - levelVal, - labels[preLevelVal], - preLevelVal - ) -} - -function getLevel (level) { - const { levels, levelVal } = this - // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833) - return (levels && levels.labels) ? levels.labels[levelVal] : '' -} - -function isLevelEnabled (logLevel) { - const { values } = this.levels - const logLevelVal = values[logLevel] - return logLevelVal !== undefined && (logLevelVal >= this[levelValSym]) -} - -function mappings (customLevels = null, useOnlyCustomLevels = false) { - const customNums = customLevels - ? Object.keys(customLevels).reduce((o, k) => { - o[customLevels[k]] = k - return o - }, {}) - : null - - const labels = Object.assign( - Object.create(Object.prototype, { Infinity: { value: 'silent' } }), - useOnlyCustomLevels ? null : nums, - customNums - ) - const values = Object.assign( - Object.create(Object.prototype, { silent: { value: Infinity } }), - useOnlyCustomLevels ? null : levels, - customLevels - ) - return { labels, values } -} - -function assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) { - if (typeof defaultLevel === 'number') { - const values = [].concat( - Object.keys(customLevels || {}).map(key => customLevels[key]), - useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level), - Infinity - ) - if (!values.includes(defaultLevel)) { - throw Error(`default level:${defaultLevel} must be included in custom levels`) - } - return - } - - const labels = Object.assign( - Object.create(Object.prototype, { silent: { value: Infinity } }), - useOnlyCustomLevels ? null : levels, - customLevels - ) - if (!(defaultLevel in labels)) { - throw Error(`default level:${defaultLevel} must be included in custom levels`) - } + _req.headers = req.headers + _req.remoteAddress = connection && connection.remoteAddress + _req.remotePort = connection && connection.remotePort + // req.raw is for hapi compat/equivalence + _req.raw = req.raw || req + return _req } -function assertNoLevelCollisions (levels, customLevels) { - const { labels, values } = levels - for (const k in customLevels) { - if (k in values) { - throw Error('levels cannot be overridden') - } - if (customLevels[k] in labels) { - throw Error('pre-existing level values cannot be used for new levels') - } +function mapHttpRequest (req) { + return { + req: reqSerializer(req) } } -module.exports = { - initialLsCache, - genLsCache, - levelMethods, - getLevel, - setLevel, - isLevelEnabled, - mappings, - assertNoLevelCollisions, - assertDefaultLevelFound -} - /***/ }), -/***/ 68578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 71550: +/***/ ((module) => { "use strict"; -const { version } = __nccwpck_require__(59023) +module.exports = { + mapHttpResponse, + resSerializer +} -module.exports = { version } +const rawSymbol = Symbol('pino-raw-res-ref') +const pinoResProto = Object.create({}, { + statusCode: { + enumerable: true, + writable: true, + value: 0 + }, + headers: { + enumerable: true, + writable: true, + value: '' + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val + } + } +}) +Object.defineProperty(pinoResProto, rawSymbol, { + writable: true, + value: {} +}) + +function resSerializer (res) { + const _res = Object.create(pinoResProto) + _res.statusCode = res.statusCode + _res.headers = res.getHeaders ? res.getHeaders() : res._headers + _res.raw = res + return _res +} + +function mapHttpResponse (res) { + return { + res: resSerializer(res) + } +} /***/ }), -/***/ 26899: +/***/ 79608: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - /* eslint no-prototype-builtins: 0 */ - -const { EventEmitter } = __nccwpck_require__(82361) -const SonicBoom = __nccwpck_require__(73460) -const flatstr = __nccwpck_require__(35298) +const os = __nccwpck_require__(22037) +const stdSerializers = __nccwpck_require__(73757) +const redaction = __nccwpck_require__(34219) +const time = __nccwpck_require__(61866) +const proto = __nccwpck_require__(26899) +const symbols = __nccwpck_require__(23957) +const { assertDefaultLevelFound, mappings, genLsCache } = __nccwpck_require__(90591) +const { + createArgsNormalizer, + asChindings, + final, + stringify, + buildSafeSonicBoom, + buildFormatters, + noop +} = __nccwpck_require__(51521) +const { version } = __nccwpck_require__(68578) const { - lsCacheSym, - levelValSym, - setLevelSym, - getLevelSym, chindingsSym, - parsedChindingsSym, - mixinSym, - asJsonSym, - writeSym, + redactFmtSym, + serializersSym, timeSym, timeSliceIndexSym, streamSym, - serializersSym, - formattersSym, + stringifySym, + stringifiersSym, + setLevelSym, + endSym, + formatOptsSym, + messageKeySym, + nestedKeySym, + mixinSym, useOnlyCustomLevelsSym, - needsMetadataGsym -} = __nccwpck_require__(23957) -const { - getLevel, - setLevel, - isLevelEnabled, - mappings, - initialLsCache, - genLsCache, - assertNoLevelCollisions -} = __nccwpck_require__(90591) -const { - asChindings, - asJson, - buildFormatters -} = __nccwpck_require__(51521) -const { - version -} = __nccwpck_require__(68578) - -// note: use of class is satirical -// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127 -const constructor = class Pino {} -const prototype = { - constructor, - child, - bindings, - setBindings, - flush, - isLevelEnabled, - version, - get level () { return this[getLevelSym]() }, - set level (lvl) { this[setLevelSym](lvl) }, - get levelVal () { return this[levelValSym] }, - set levelVal (n) { throw Error('levelVal is read-only') }, - [lsCacheSym]: initialLsCache, - [writeSym]: write, - [asJsonSym]: asJson, - [getLevelSym]: getLevel, - [setLevelSym]: setLevel + formattersSym, + hooksSym +} = symbols +const { epochTime, nullTime } = time +const { pid } = process +const hostname = os.hostname() +const defaultErrorSerializer = stdSerializers.err +const defaultOptions = { + level: 'info', + messageKey: 'msg', + nestedKey: null, + enabled: true, + prettyPrint: false, + base: { pid, hostname }, + serializers: Object.assign(Object.create(null), { + err: defaultErrorSerializer + }), + formatters: Object.assign(Object.create(null), { + bindings (bindings) { + return bindings + }, + level (label, number) { + return { level: number } + } + }), + hooks: { + logMethod: undefined + }, + timestamp: epochTime, + name: undefined, + redact: null, + customLevels: null, + levelKey: undefined, + useOnlyCustomLevels: false } -Object.setPrototypeOf(prototype, EventEmitter.prototype) +const normalize = createArgsNormalizer(defaultOptions) -// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing -module.exports = function () { - return Object.create(prototype) -} +const serializers = Object.assign(Object.create(null), stdSerializers) -const resetChildingsFormatter = bindings => bindings -function child (bindings) { - if (!bindings) { - throw Error('missing bindings for child Pino') +function pino (...args) { + const instance = {} + const { opts, stream } = normalize(instance, ...args) + const { + redact, + crlf, + serializers, + timestamp, + messageKey, + nestedKey, + base, + name, + level, + customLevels, + useLevelLabels, + changeLevelName, + levelKey, + mixin, + useOnlyCustomLevels, + formatters, + hooks + } = opts + + const allFormatters = buildFormatters( + formatters.level, + formatters.bindings, + formatters.log + ) + + if (useLevelLabels && !(changeLevelName || levelKey)) { + process.emitWarning('useLevelLabels is deprecated, use the formatters.level option instead', 'Warning', 'PINODEP001') + allFormatters.level = labelsFormatter + } else if ((changeLevelName || levelKey) && !useLevelLabels) { + process.emitWarning('changeLevelName and levelKey are deprecated, use the formatters.level option instead', 'Warning', 'PINODEP002') + allFormatters.level = levelNameFormatter(changeLevelName || levelKey) + } else if ((changeLevelName || levelKey) && useLevelLabels) { + process.emitWarning('useLevelLabels is deprecated, use the formatters.level option instead', 'Warning', 'PINODEP001') + process.emitWarning('changeLevelName and levelKey are deprecated, use the formatters.level option instead', 'Warning', 'PINODEP002') + allFormatters.level = levelNameLabelFormatter(changeLevelName || levelKey) } - const serializers = this[serializersSym] - const formatters = this[formattersSym] - const instance = Object.create(this) - if (bindings.hasOwnProperty('serializers') === true) { - instance[serializersSym] = Object.create(null) - for (const k in serializers) { - instance[serializersSym][k] = serializers[k] - } - const parentSymbols = Object.getOwnPropertySymbols(serializers) - /* eslint no-var: off */ - for (var i = 0; i < parentSymbols.length; i++) { - const ks = parentSymbols[i] - instance[serializersSym][ks] = serializers[ks] - } + if (serializers[Symbol.for('pino.*')]) { + process.emitWarning('The pino.* serializer is deprecated, use the formatters.log options instead', 'Warning', 'PINODEP003') + allFormatters.log = serializers[Symbol.for('pino.*')] + } - for (const bk in bindings.serializers) { - instance[serializersSym][bk] = bindings.serializers[bk] - } - const bindingsSymbols = Object.getOwnPropertySymbols(bindings.serializers) - for (var bi = 0; bi < bindingsSymbols.length; bi++) { - const bks = bindingsSymbols[bi] - instance[serializersSym][bks] = bindings.serializers[bks] - } - } else instance[serializersSym] = serializers - if (bindings.hasOwnProperty('formatters')) { - const { level, bindings: chindings, log } = bindings.formatters - instance[formattersSym] = buildFormatters( - level || formatters.level, - chindings || resetChildingsFormatter, - log || formatters.log - ) - } else { - instance[formattersSym] = buildFormatters( - formatters.level, - resetChildingsFormatter, - formatters.log - ) + if (!allFormatters.bindings) { + allFormatters.bindings = defaultOptions.formatters.bindings } - if (bindings.hasOwnProperty('customLevels') === true) { - assertNoLevelCollisions(this.levels, bindings.customLevels) - instance.levels = mappings(bindings.customLevels, instance[useOnlyCustomLevelsSym]) - genLsCache(instance) + if (!allFormatters.level) { + allFormatters.level = defaultOptions.formatters.level } - instance[chindingsSym] = asChindings(instance, bindings) - const childLevel = bindings.level || this.level - instance[setLevelSym](childLevel) + + const stringifiers = redact ? redaction(redact, stringify) : {} + const formatOpts = redact + ? { stringify: stringifiers[redactFmtSym] } + : { stringify } + const end = '}' + (crlf ? '\r\n' : '\n') + const coreChindings = asChindings.bind(null, { + [chindingsSym]: '', + [serializersSym]: serializers, + [stringifiersSym]: stringifiers, + [stringifySym]: stringify, + [formattersSym]: allFormatters + }) + + let chindings = '' + if (base !== null) { + if (name === undefined) { + chindings = coreChindings(base) + } else { + chindings = coreChindings(Object.assign({}, base, { name })) + } + } + + const time = (timestamp instanceof Function) + ? timestamp + : (timestamp ? epochTime : nullTime) + const timeSliceIndex = time().indexOf(':') + 1 + + if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true') + if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`) + + assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels) + const levels = mappings(customLevels, useOnlyCustomLevels) + + Object.assign(instance, { + levels, + [useOnlyCustomLevelsSym]: useOnlyCustomLevels, + [streamSym]: stream, + [timeSym]: time, + [timeSliceIndexSym]: timeSliceIndex, + [stringifySym]: stringify, + [stringifiersSym]: stringifiers, + [endSym]: end, + [formatOptsSym]: formatOpts, + [messageKeySym]: messageKey, + [nestedKeySym]: nestedKey, + [serializersSym]: serializers, + [mixinSym]: mixin, + [chindingsSym]: chindings, + [formattersSym]: allFormatters, + [hooksSym]: hooks, + silent: noop + }) + + Object.setPrototypeOf(instance, proto()) + + genLsCache(instance) + + instance[setLevelSym](level) return instance } -function bindings () { - const chindings = this[chindingsSym] - const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,"pid":7068,"hostname":"myMac" - const bindingsFromJson = JSON.parse(chindingsJson) - delete bindingsFromJson.pid - delete bindingsFromJson.hostname - return bindingsFromJson +function labelsFormatter (label, number) { + return { level: label } } -function setBindings (newBindings) { - const chindings = asChindings(this, newBindings) - this[chindingsSym] = chindings - delete this[parsedChindingsSym] +function levelNameFormatter (name) { + return function (label, number) { + return { [name]: number } + } } -function write (_obj, msg, num) { - const t = this[timeSym]() - const mixin = this[mixinSym] - const objError = _obj instanceof Error - let obj - - if (_obj === undefined || _obj === null) { - obj = mixin ? mixin({}) : {} - } else { - obj = Object.assign(mixin ? mixin(_obj) : {}, _obj) - if (!msg && objError) { - msg = _obj.message - } - - if (objError) { - obj.stack = _obj.stack - if (!obj.type) { - obj.type = 'Error' - } - } +function levelNameLabelFormatter (name) { + return function (label, number) { + return { [name]: label } } +} - const s = this[asJsonSym](obj, msg, num, t) +module.exports = pino - const stream = this[streamSym] - if (stream[needsMetadataGsym] === true) { - stream.lastLevel = num - stream.lastObj = obj - stream.lastMsg = msg - stream.lastTime = t.slice(this[timeSliceIndexSym]) - stream.lastLogger = this // for child loggers - } - if (stream instanceof SonicBoom) stream.write(s) - else stream.write(flatstr(s)) +module.exports.extreme = (dest = process.stdout.fd) => { + process.emitWarning( + 'The pino.extreme() option is deprecated and will be removed in v7. Use pino.destination({ sync: false }) instead.', + { code: 'extreme_deprecation' } + ) + return buildSafeSonicBoom({ dest, minLength: 4096, sync: false }) } -function flush () { - const stream = this[streamSym] - if ('flush' in stream) stream.flush() +module.exports.destination = (dest = process.stdout.fd) => { + if (typeof dest === 'object') { + dest.dest = dest.dest || process.stdout.fd + return buildSafeSonicBoom(dest) + } else { + return buildSafeSonicBoom({ dest, minLength: 0, sync: true }) + } } +module.exports.final = final +module.exports.levels = mappings() +module.exports.stdSerializers = serializers +module.exports.stdTimeFunctions = Object.assign({}, time) +module.exports.symbols = symbols +module.exports.version = version + +// Enables default and name export with TypeScript and Babel +module.exports["default"] = pino +module.exports.pino = pino + /***/ }), -/***/ 34219: +/***/ 51235: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const path = __nccwpck_require__(71017); +const findUp = __nccwpck_require__(26428); +const loadJsonFile = __nccwpck_require__(75978); -const fastRedact = __nccwpck_require__(24826) -const { redactFmtSym, wildcardFirstSym } = __nccwpck_require__(23957) -const { rx, validator } = fastRedact +const filepaths = new WeakMap(); +const filepath = conf => filepaths.get(conf); +const findNextCwd = pkgPath => path.resolve(path.dirname(pkgPath), '..'); -const validate = validator({ - ERR_PATHS_MUST_BE_STRINGS: () => 'pino – redacted paths must be strings', - ERR_INVALID_PATH: (s) => `pino – redact paths array contains an invalid path (${s})` -}) +const addFilePath = (object, filePath) => { + filepaths.set(object, filePath); + return object; +}; -const CENSOR = '[Redacted]' -const strict = false // TODO should this be configurable? +const pkgConf = (namespace, options = {}) => { + if (!namespace) { + return Promise.reject(new TypeError('Expected a namespace')); + } -function redaction (opts, serialize) { - const { paths, censor } = handle(opts) + return findUp('package.json', options.cwd ? {cwd: options.cwd} : {}) + .then(filePath => { + if (!filePath) { + return addFilePath(Object.assign({}, options.defaults), filePath); + } - const shape = paths.reduce((o, str) => { - rx.lastIndex = 0 - const first = rx.exec(str) - const next = rx.exec(str) + return loadJsonFile(filePath).then(package_ => { + if (options.skipOnFalse && package_[namespace] === false) { + const newOptions = Object.assign({}, options, {cwd: findNextCwd(filePath)}); + return pkgConf(namespace, newOptions); + } - // ns is the top-level path segment, brackets + quoting removed. - let ns = first[1] !== undefined - ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, '$1') - : first[0] + return addFilePath(Object.assign({}, options.defaults, package_[namespace]), filePath); + }); + }); +}; + +const sync = (namespace, options = {}) => { + if (!namespace) { + throw new TypeError('Expected a namespace'); + } + + const filePath = findUp.sync('package.json', options.cwd ? {cwd: options.cwd} : {}); + + if (!filePath) { + return addFilePath(Object.assign({}, options.defaults), filePath); + } + + const package_ = loadJsonFile.sync(filePath); + + if (options.skipOnFalse && package_[namespace] === false) { + const newOptions = Object.assign({}, options, {cwd: findNextCwd(filePath)}); + return sync(namespace, newOptions); + } + + return addFilePath(Object.assign({}, options.defaults, package_[namespace]), filePath); +}; + +module.exports = pkgConf; +// TODO: Remove this for the next major release +module.exports["default"] = pkgConf; +module.exports.filepath = filepath; +module.exports.sync = sync; - if (ns === '*') { - ns = wildcardFirstSym - } - // top level key: - if (next === null) { - o[ns] = null - return o - } +/***/ }), - // path with at least two segments: - // if ns is already redacted at the top level, ignore lower level redactions - if (o[ns] === null) { - return o - } +/***/ 26428: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const { index } = next - const nextPath = `${str.substr(index, str.length - 1)}` +"use strict"; - o[ns] = o[ns] || [] +const path = __nccwpck_require__(71017); +const locatePath = __nccwpck_require__(47619); - // shape is a mix of paths beginning with literal values and wildcard - // paths [ "a.b.c", "*.b.z" ] should reduce to a shape of - // { "a": [ "b.c", "b.z" ], *: [ "b.z" ] } - // note: "b.z" is in both "a" and * arrays because "a" matches the wildcard. - // (* entry has wildcardFirstSym as key) - if (ns !== wildcardFirstSym && o[ns].length === 0) { - // first time ns's get all '*' redactions so far - o[ns].push(...(o[wildcardFirstSym] || [])) - } +module.exports = (filename, opts = {}) => { + const startDir = path.resolve(opts.cwd || ''); + const {root} = path.parse(startDir); - if (ns === wildcardFirstSym) { - // new * path gets added to all previously registered literal ns's. - Object.keys(o).forEach(function (k) { - if (o[k]) { - o[k].push(nextPath) - } - }) - } + const filenames = [].concat(filename); - o[ns].push(nextPath) - return o - }, {}) + return new Promise(resolve => { + (function find(dir) { + locatePath(filenames, {cwd: dir}).then(file => { + if (file) { + resolve(path.join(dir, file)); + } else if (dir === root) { + resolve(null); + } else { + find(path.dirname(dir)); + } + }); + })(startDir); + }); +}; - // the redactor assigned to the format symbol key - // provides top level redaction for instances where - // an object is interpolated into the msg string - const result = { - [redactFmtSym]: fastRedact({ paths, censor, serialize, strict }) - } +module.exports.sync = (filename, opts = {}) => { + let dir = path.resolve(opts.cwd || ''); + const {root} = path.parse(dir); - const topCensor = (...args) => { - return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor) - } + const filenames = [].concat(filename); - return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => { - // top level key: - if (shape[k] === null) { - o[k] = (value) => topCensor(value, [k]) - } else { - const wrappedCensor = typeof censor === 'function' - ? (value, path) => { - return censor(value, [k, ...path]) - } - : censor - o[k] = fastRedact({ - paths: shape[k], - censor: wrappedCensor, - serialize, - strict - }) - } - return o - }, result) -} + // eslint-disable-next-line no-constant-condition + while (true) { + const file = locatePath.sync(filenames, {cwd: dir}); -function handle (opts) { - if (Array.isArray(opts)) { - opts = { paths: opts, censor: CENSOR } - validate(opts) - return opts - } - let { paths, censor = CENSOR, remove } = opts - if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') } - if (remove === true) censor = undefined - validate({ paths, censor }) + if (file) { + return path.join(dir, file); + } - return { paths, censor } -} + if (dir === root) { + return null; + } -module.exports = redaction + dir = path.dirname(dir); + } +}; /***/ }), -/***/ 23957: -/***/ ((module) => { +/***/ 47619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const path = __nccwpck_require__(71017); +const pathExists = __nccwpck_require__(70652); +const pLocate = __nccwpck_require__(96566); -const setLevelSym = Symbol('pino.setLevel') -const getLevelSym = Symbol('pino.getLevel') -const levelValSym = Symbol('pino.levelVal') -const useLevelLabelsSym = Symbol('pino.useLevelLabels') -const useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels') -const mixinSym = Symbol('pino.mixin') +module.exports = (iterable, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); -const lsCacheSym = Symbol('pino.lsCache') -const chindingsSym = Symbol('pino.chindings') -const parsedChindingsSym = Symbol('pino.parsedChindings') + return pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options); +}; -const asJsonSym = Symbol('pino.asJson') -const writeSym = Symbol('pino.write') -const redactFmtSym = Symbol('pino.redactFmt') +module.exports.sync = (iterable, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); -const timeSym = Symbol('pino.time') -const timeSliceIndexSym = Symbol('pino.timeSliceIndex') -const streamSym = Symbol('pino.stream') -const stringifySym = Symbol('pino.stringify') -const stringifiersSym = Symbol('pino.stringifiers') -const endSym = Symbol('pino.end') -const formatOptsSym = Symbol('pino.formatOpts') -const messageKeySym = Symbol('pino.messageKey') -const nestedKeySym = Symbol('pino.nestedKey') + for (const el of iterable) { + if (pathExists.sync(path.resolve(options.cwd, el))) { + return el; + } + } +}; -const wildcardFirstSym = Symbol('pino.wildcardFirst') -// public symbols, no need to use the same pino -// version for these -const serializersSym = Symbol.for('pino.serializers') -const formattersSym = Symbol.for('pino.formatters') -const hooksSym = Symbol.for('pino.hooks') -const needsMetadataGsym = Symbol.for('pino.metadata') +/***/ }), -module.exports = { - setLevelSym, - getLevelSym, - levelValSym, - useLevelLabelsSym, - mixinSym, - lsCacheSym, - chindingsSym, - parsedChindingsSym, - asJsonSym, - writeSym, - serializersSym, - redactFmtSym, - timeSym, - timeSliceIndexSym, - streamSym, - stringifySym, - stringifiersSym, - endSym, - formatOptsSym, - messageKeySym, - nestedKeySym, - wildcardFirstSym, - needsMetadataGsym, - useOnlyCustomLevelsSym, - formattersSym, - hooksSym -} +/***/ 96566: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -/***/ }), +const pLimit = __nccwpck_require__(57684); -/***/ 61866: -/***/ ((module) => { +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} -"use strict"; +// The input can also be a promise, so we `Promise.resolve()` it +const testElement = (el, tester) => Promise.resolve(el).then(tester); +// The input can also be a promise, so we `Promise.all()` them both +const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0]))); -const nullTime = () => '' +module.exports = (iterable, tester, opts) => { + opts = Object.assign({ + concurrency: Infinity, + preserveOrder: true + }, opts); -const epochTime = () => `,"time":${Date.now()}` + const limit = pLimit(opts.concurrency); -const unixTime = () => `,"time":${Math.round(Date.now() / 1000.0)}` + // Start all the promises concurrently with optional limit + const items = [...iterable].map(el => [el, limit(testElement, el, tester)]); -const isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"` // using Date.now() for testability + // Check the promises either serially or concurrently + const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity); -module.exports = { nullTime, epochTime, unixTime, isoTime } + return Promise.all(items.map(el => checkLimit(finder, el))) + .then(() => {}) + .catch(err => err instanceof EndError ? err.value : Promise.reject(err)); +}; /***/ }), -/***/ 51521: +/***/ 70652: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const fs = __nccwpck_require__(57147); -/* eslint no-prototype-builtins: 0 */ +module.exports = fp => new Promise(resolve => { + fs.access(fp, err => { + resolve(!err); + }); +}); -const format = __nccwpck_require__(5933) -const { mapHttpRequest, mapHttpResponse } = __nccwpck_require__(73757) -const SonicBoom = __nccwpck_require__(73460) -const stringifySafe = __nccwpck_require__(17676) -const { - lsCacheSym, - chindingsSym, - parsedChindingsSym, - writeSym, - serializersSym, - formatOptsSym, - endSym, - stringifiersSym, - stringifySym, - wildcardFirstSym, - needsMetadataGsym, - redactFmtSym, - streamSym, - nestedKeySym, - formattersSym, - messageKeySym -} = __nccwpck_require__(23957) +module.exports.sync = fp => { + try { + fs.accessSync(fp); + return true; + } catch (err) { + return false; + } +}; -function noop () {} -function genLog (level, hook) { - if (!hook) return LOG +/***/ }), - return function hookWrappedLog (...args) { - hook.call(this, args, LOG, level) - } +/***/ 35362: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - function LOG (o, ...n) { - if (typeof o === 'object') { - let msg = o - if (o !== null) { - if (o.method && o.headers && o.socket) { - o = mapHttpRequest(o) - } else if (typeof o.setHeader === 'function') { - o = mapHttpResponse(o) - } - } - if (this[nestedKeySym]) o = { [this[nestedKeySym]]: o } - let formatParams - if (msg === null && n.length === 0) { - formatParams = [null] - } else { - msg = n.shift() - formatParams = n - } - this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level) - } else { - this[writeSym](null, format(o, n, this[formatOptsSym]), level) - } - } -} +"use strict"; -// magically escape strings for json -// relying on their charCodeAt -// everything below 32 needs JSON.stringify() -// 34 and 92 happens all the time, so we -// have a fast case for them -function asString (str) { - let result = '' - let last = 0 - let found = false - let point = 255 - const l = str.length - if (l > 100) { - return JSON.stringify(str) - } - for (var i = 0; i < l && point >= 32; i++) { - point = str.charCodeAt(i) - if (point === 34 || point === 92) { - result += str.slice(last, i) + '\\' - last = i - found = true +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"); } - } - if (!found) { - result = str - } else { - result += str.slice(last) - } - return point < 32 ? JSON.stringify(str) : '"' + result + '"' + 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 -function asJson (obj, msg, num, time) { - const stringify = this[stringifySym] - const stringifiers = this[stringifiersSym] - const end = this[endSym] - const chindings = this[chindingsSym] - const serializers = this[serializersSym] - const formatters = this[formattersSym] - const messageKey = this[messageKeySym] - let data = this[lsCacheSym][num] + time - - // we need the child bindings added to the output first so instance logged - // objects can take precedence when JSON.parse-ing the resulting log line - data = data + chindings +/***/ }), - let value - const notHasOwnProperty = obj.hasOwnProperty === undefined - if (formatters.log) { - obj = formatters.log(obj) - } - if (msg !== undefined) { - obj[messageKey] = msg - } - const wildcardStringifier = stringifiers[wildcardFirstSym] - for (const key in obj) { - value = obj[key] - if ((notHasOwnProperty || obj.hasOwnProperty(key)) && value !== undefined) { - value = serializers[key] ? serializers[key](value) : value +/***/ 31078: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - const stringifier = stringifiers[key] || wildcardStringifier +"use strict"; - switch (typeof value) { - case 'undefined': - case 'function': - continue - case 'number': - /* eslint no-fallthrough: "off" */ - if (Number.isFinite(value) === false) { - value = null - } - // this case explicitly falls through to the next one - case 'boolean': - if (stringifier) value = stringifier(value) - break - case 'string': - value = (stringifier || asString)(value) - break - default: - value = (stringifier || stringify)(value) - } - if (value === undefined) continue - data += ',"' + key + '":' + value +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +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__(59159); +const logging_middleware_1 = __nccwpck_require__(27530); +const is_production_1 = __nccwpck_require__(78079); +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(); } - } - - return data + end -} - -function asChindings (instance, bindings) { - let value - let data = instance[chindingsSym] - const stringify = instance[stringifySym] - const stringifiers = instance[stringifiersSym] - const wildcardStringifier = stringifiers[wildcardFirstSym] - const serializers = instance[serializersSym] - const formatter = instance[formattersSym].bindings - bindings = formatter(bindings) - - for (const key in bindings) { - value = bindings[key] - const valid = key !== 'level' && - key !== 'serializers' && - key !== 'formatters' && - key !== 'customLevels' && - bindings.hasOwnProperty(key) && - value !== undefined - if (valid === true) { - value = serializers[key] ? serializers[key](value) : value - value = (stringifiers[key] || wildcardStringifier || stringify)(value) - if (value === undefined) continue - data += ',"' + key + '":' + value + if (!getRouter) { + throw new Error("getRouter is required to use the setup app"); } - } - return data + 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 getPrettyStream (opts, prettifier, dest, instance) { - if (prettifier && typeof prettifier === 'function') { - prettifier = prettifier.bind(instance) - return prettifierMetaWrapper(prettifier(opts), dest, opts) - } - try { - const prettyFactory = __nccwpck_require__(31691) - prettyFactory.asMetaWrapper = prettifierMetaWrapper - return prettifierMetaWrapper(prettyFactory(opts), dest, opts) - } catch (e) { - throw Error('Missing `pino-pretty` module: `pino-pretty` must be installed separately') - } +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 -function prettifierMetaWrapper (pretty, dest, opts) { - opts = Object.assign({ suppressFlushSyncWarning: false }, opts) - let warned = false - return { - [needsMetadataGsym]: true, - lastLevel: 0, - lastMsg: null, - lastObj: null, - lastLogger: null, - flushSync () { - if (opts.suppressFlushSyncWarning || warned) { - return - } - warned = true - setMetadataProps(dest, this) - dest.write(pretty(Object.assign({ - level: 40, // warn - msg: 'pino.final with prettyPrint does not support flushing', - time: Date.now() - }, this.chindings()))) - }, - chindings () { - const lastLogger = this.lastLogger - let chindings = null - - // protection against flushSync being called before logging - // anything - if (!lastLogger) { - return null - } - - if (lastLogger.hasOwnProperty(parsedChindingsSym)) { - chindings = lastLogger[parsedChindingsSym] - } else { - chindings = JSON.parse('{' + lastLogger[chindingsSym].substr(1) + '}') - lastLogger[parsedChindingsSym] = chindings - } - - return chindings - }, - write (chunk) { - const lastLogger = this.lastLogger - const chindings = this.chindings() - - let time = this.lastTime +/***/ }), - if (time.match(/^\d+/)) { - time = parseInt(time) - } else { - time = time.slice(1, -1) - } +/***/ 23831: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const lastObj = this.lastObj - const lastMsg = this.lastMsg - const errorProps = null +"use strict"; - const formatters = lastLogger[formattersSym] - const formattedObj = formatters.log ? formatters.log(lastObj) : lastObj +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.auth = void 0; +const get_authenticated_octokit_1 = __nccwpck_require__(88916); +/** + * 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 - const messageKey = lastLogger[messageKeySym] - if (lastMsg && formattedObj && !formattedObj.hasOwnProperty(messageKey)) { - formattedObj[messageKey] = lastMsg - } +/***/ }), - const obj = Object.assign({ - level: this.lastLevel, - time - }, formattedObj, errorProps) +/***/ 4015: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - const serializers = lastLogger[serializersSym] - const keys = Object.keys(serializers) +"use strict"; - for (var i = 0; i < keys.length; i++) { - const key = keys[i] - if (obj[key] !== undefined) { - obj[key] = serializers[key](obj[key]) - } - } +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__(61904)); +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 - for (const key in chindings) { - if (!obj.hasOwnProperty(key)) { - obj[key] = chindings[key] - } - } +/***/ }), - const stringifiers = lastLogger[stringifiersSym] - const redact = stringifiers[redactFmtSym] +/***/ 92004: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const formatted = pretty(typeof redact === 'function' ? redact(obj) : obj) - if (formatted === undefined) return +"use strict"; - setMetadataProps(dest, this) - dest.write(formatted) - } - } +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 -function hasBeenTampered (stream) { - return stream.write !== stream.constructor.prototype.write -} +/***/ }), -function buildSafeSonicBoom (opts) { - const stream = new SonicBoom(opts) - stream.on('error', filterBrokenPipe) - return stream +/***/ 94219: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - function filterBrokenPipe (err) { - // TODO verify on Windows - if (err.code === 'EPIPE') { - // If we get EPIPE, we should stop logging here - // however we have no control to the consumer of - // SonicBoom, so we just overwrite the write method - stream.write = noop - stream.end = noop - stream.flushSync = noop - stream.destroy = noop - return - } - stream.removeListener('error', filterBrokenPipe) - stream.emit('error', err) - } -} +"use strict"; -function createArgsNormalizer (defaultOptions) { - return function normalizeArgs (instance, opts = {}, stream) { - // support stream as a string - if (typeof opts === 'string') { - stream = buildSafeSonicBoom({ dest: opts, sync: true }) - opts = {} - } else if (typeof stream === 'string') { - stream = buildSafeSonicBoom({ dest: stream, sync: true }) - } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) { - stream = opts - opts = null - } - opts = Object.assign({}, defaultOptions, opts) - if ('extreme' in opts) { - throw Error('The extreme option has been removed, use pino.destination({ sync: false }) instead') - } - if ('onTerminated' in opts) { - throw Error('The onTerminated option has been removed, use pino.final instead') - } - if ('changeLevelName' in opts) { - process.emitWarning( - 'The changeLevelName option is deprecated and will be removed in v7. Use levelKey instead.', - { code: 'changeLevelName_deprecation' } - ) - opts.levelKey = opts.changeLevelName - delete opts.changeLevelName +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__(95326); +/** + * 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); } - const { enabled, prettyPrint, prettifier, messageKey } = opts - if (enabled === false) opts.level = 'silent' - stream = stream || process.stdout - if (stream === process.stdout && stream.fd >= 0 && !hasBeenTampered(stream)) { - stream = buildSafeSonicBoom({ fd: stream.fd, sync: true }) + /** + * 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); } - if (prettyPrint) { - const prettyOpts = Object.assign({ messageKey }, prettyPrint) - stream = getPrettyStream(prettyOpts, prettifier, stream, instance) + /** + * 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 { opts, stream } - } -} - -function final (logger, handler) { - if (typeof logger === 'undefined' || typeof logger.child !== 'function') { - throw Error('expected a pino logger instance') - } - const hasHandler = (typeof handler !== 'undefined') - if (hasHandler && typeof handler !== 'function') { - throw Error('if supplied, the handler parameter should be a function') - } - const stream = logger[streamSym] - if (typeof stream.flushSync !== 'function') { - throw Error('final requires a stream that has a flushSync method, such as pino.destination') - } - - const finalLogger = new Proxy(logger, { - get: (logger, key) => { - if (key in logger.levels.values) { - return (...args) => { - logger[key](...args) - stream.flushSync() - } - } - return logger[key] + /** + * 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)); } - }) - - if (!hasHandler) { - return finalLogger - } - - return (err = null, ...args) => { - try { - stream.flushSync() - } catch (e) { - // it's too late to wait for the stream to be ready - // because this is a final tick scenario. - // in practice there shouldn't be a situation where it isn't - // however, swallow the error just in case (and for easier testing) + /** + * 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; } - return handler(err, finalLogger, ...args) - } -} - -function stringify (obj) { - try { - return JSON.stringify(obj) - } catch (_) { - return stringifySafe(obj) - } -} - -function buildFormatters (level, bindings, log) { - return { - level, - bindings, - log - } -} - -function setMetadataProps (dest, that) { - if (dest[needsMetadataGsym] === true) { - dest.lastLevel = that.lastLevel - dest.lastMsg = that.lastMsg - dest.lastObj = that.lastObj - dest.lastTime = that.lastTime - dest.lastLogger = that.lastLogger - } -} - -module.exports = { - noop, - buildSafeSonicBoom, - getPrettyStream, - asChindings, - asJson, - genLog, - createArgsNormalizer, - final, - stringify, - buildFormatters } - +exports.Context = Context; +//# sourceMappingURL=context.js.map /***/ }), -/***/ 73757: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 95960: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const errSerializer = __nccwpck_require__(79276) -const reqSerializers = __nccwpck_require__(76343) -const resSerializers = __nccwpck_require__(71550) - -module.exports = { - err: errSerializer, - mapHttpRequest: reqSerializers.mapHttpRequest, - mapHttpResponse: resSerializers.mapHttpResponse, - req: reqSerializers.reqSerializer, - res: resSerializers.resSerializer, - - wrapErrorSerializer: function wrapErrorSerializer (customSerializer) { - if (customSerializer === errSerializer) return customSerializer - return function wrapErrSerializer (err) { - return customSerializer(errSerializer(err)) - } - }, - - wrapRequestSerializer: function wrapRequestSerializer (customSerializer) { - if (customSerializer === reqSerializers.reqSerializer) return customSerializer - return function wrappedReqSerializer (req) { - return customSerializer(reqSerializers.reqSerializer(req)) - } - }, - - wrapResponseSerializer: function wrapResponseSerializer (customSerializer) { - if (customSerializer === resSerializers.resSerializer) return customSerializer - return function wrappedResSerializer (res) { - return customSerializer(resSerializers.resSerializer(res)) - } - } +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 /***/ }), -/***/ 79276: -/***/ ((module) => { +/***/ 82598: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -module.exports = errSerializer - -const { toString } = Object.prototype -const seen = Symbol('circular-ref-tag') -const rawSymbol = Symbol('pino-raw-err-ref') -const pinoErrProto = Object.create({}, { - type: { - enumerable: true, - writable: true, - value: undefined - }, - message: { - enumerable: true, - writable: true, - value: undefined - }, - stack: { - enumerable: true, - writable: true, - value: undefined - }, - raw: { - enumerable: false, - get: function () { - return this[rawSymbol] - }, - set: function (val) { - this[rawSymbol] = val - } - } -}) -Object.defineProperty(pinoErrProto, rawSymbol, { - writable: true, - value: {} -}) - -function errSerializer (err) { - if (!(err instanceof Error)) { - return err - } - - err[seen] = undefined // tag to prevent re-looking at this - const _err = Object.create(pinoErrProto) - _err.type = toString.call(err.constructor) === '[object Function]' - ? err.constructor.name - : err.name - _err.message = err.message - _err.stack = err.stack - for (const key in err) { - if (_err[key] === undefined) { - const val = err[key] - if (val instanceof Error) { - /* eslint-disable no-prototype-builtins */ - if (!val.hasOwnProperty(seen)) { - _err[key] = errSerializer(val) - } - } else { - _err[key] = val - } - } - } - - delete err[seen] // clean up tag in case err is serialized again later - _err.raw = err - return _err +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createProbot = void 0; +const get_private_key_1 = __nccwpck_require__(97743); +const get_log_1 = __nccwpck_require__(75942); +const probot_1 = __nccwpck_require__(87085); +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 /***/ }), -/***/ 76343: -/***/ ((module) => { +/***/ 95326: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -module.exports = { - mapHttpRequest, - reqSerializer -} - -const rawSymbol = Symbol('pino-raw-req-ref') -const pinoReqProto = Object.create({}, { - id: { - enumerable: true, - writable: true, - value: '' - }, - method: { - enumerable: true, - writable: true, - value: '' - }, - url: { - enumerable: true, - writable: true, - value: '' - }, - query: { - enumerable: true, - writable: true, - value: '' - }, - params: { - enumerable: true, - writable: true, - value: '' - }, - headers: { - enumerable: true, - writable: true, - value: {} - }, - remoteAddress: { - enumerable: true, - writable: true, - value: '' - }, - remotePort: { - enumerable: true, - writable: true, - value: '' - }, - raw: { - enumerable: false, - get: function () { - return this[rawSymbol] - }, - set: function (val) { - this[rawSymbol] = val +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); } - } -}) -Object.defineProperty(pinoReqProto, rawSymbol, { - writable: true, - value: {} -}) - -function reqSerializer (req) { - // req.info is for hapi compat. - const connection = req.info || req.socket - const _req = Object.create(pinoReqProto) - _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined))) - _req.method = req.method - // req.originalUrl is for expressjs compat. - if (req.originalUrl) { - _req.url = req.originalUrl - _req.query = req.query - _req.params = req.params - } else { - // req.url.path is for hapi compat. - _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined) - } - _req.headers = req.headers - _req.remoteAddress = connection && connection.remoteAddress - _req.remotePort = connection && connection.remotePort - // req.raw is for hapi compat/equivalence - _req.raw = req.raw || req - return _req -} - -function mapHttpRequest (req) { - return { - req: reqSerializer(req) - } + 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 /***/ }), -/***/ 71550: -/***/ ((module) => { +/***/ 25625: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -module.exports = { - mapHttpResponse, - resSerializer -} - -const rawSymbol = Symbol('pino-raw-res-ref') -const pinoResProto = Object.create({}, { - statusCode: { - enumerable: true, - writable: true, - value: 0 - }, - headers: { - enumerable: true, - writable: true, - value: '' - }, - raw: { - enumerable: false, - get: function () { - return this[rawSymbol] - }, - set: function (val) { - this[rawSymbol] = val - } - } -}) -Object.defineProperty(pinoResProto, rawSymbol, { - writable: true, - value: {} -}) - -function resSerializer (res) { - const _res = Object.create(pinoResProto) - _res.statusCode = res.statusCode - _res.headers = res.getHeaders ? res.getHeaders() : res._headers - _res.raw = res - return _res -} - -function mapHttpResponse (res) { - return { - res: resSerializer(res) - } +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 /***/ }), -/***/ 79608: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 75942: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -/* eslint no-prototype-builtins: 0 */ -const os = __nccwpck_require__(22037) -const stdSerializers = __nccwpck_require__(73757) -const redaction = __nccwpck_require__(34219) -const time = __nccwpck_require__(61866) -const proto = __nccwpck_require__(26899) -const symbols = __nccwpck_require__(23957) -const { assertDefaultLevelFound, mappings, genLsCache } = __nccwpck_require__(90591) -const { - createArgsNormalizer, - asChindings, - final, - stringify, - buildSafeSonicBoom, - buildFormatters, - noop -} = __nccwpck_require__(51521) -const { version } = __nccwpck_require__(68578) -const { - chindingsSym, - redactFmtSym, - serializersSym, - timeSym, - timeSliceIndexSym, - streamSym, - stringifySym, - stringifiersSym, - setLevelSym, - endSym, - formatOptsSym, - messageKeySym, - nestedKeySym, - mixinSym, - useOnlyCustomLevelsSym, - formattersSym, - hooksSym -} = symbols -const { epochTime, nullTime } = time -const { pid } = process -const hostname = os.hostname() -const defaultErrorSerializer = stdSerializers.err -const defaultOptions = { - level: 'info', - messageKey: 'msg', - nestedKey: null, - enabled: true, - prettyPrint: false, - base: { pid, hostname }, - serializers: Object.assign(Object.create(null), { - err: defaultErrorSerializer - }), - formatters: Object.assign(Object.create(null), { - bindings (bindings) { - return bindings - }, - level (label, number) { - return { level: number } - } - }), - hooks: { - logMethod: undefined - }, - timestamp: epochTime, - name: undefined, - redact: null, - customLevels: null, - levelKey: undefined, - useOnlyCustomLevels: false -} - -const normalize = createArgsNormalizer(defaultOptions) - -const serializers = Object.assign(Object.create(null), stdSerializers) - -function pino (...args) { - const instance = {} - const { opts, stream } = normalize(instance, ...args) - const { - redact, - crlf, - serializers, - timestamp, - messageKey, - nestedKey, - base, - name, - level, - customLevels, - useLevelLabels, - changeLevelName, - levelKey, - mixin, - useOnlyCustomLevels, - formatters, - hooks - } = opts +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 - const allFormatters = buildFormatters( - formatters.level, - formatters.bindings, - formatters.log - ) +/***/ }), - if (useLevelLabels && !(changeLevelName || levelKey)) { - process.emitWarning('useLevelLabels is deprecated, use the formatters.level option instead', 'Warning', 'PINODEP001') - allFormatters.level = labelsFormatter - } else if ((changeLevelName || levelKey) && !useLevelLabels) { - process.emitWarning('changeLevelName and levelKey are deprecated, use the formatters.level option instead', 'Warning', 'PINODEP002') - allFormatters.level = levelNameFormatter(changeLevelName || levelKey) - } else if ((changeLevelName || levelKey) && useLevelLabels) { - process.emitWarning('useLevelLabels is deprecated, use the formatters.level option instead', 'Warning', 'PINODEP001') - process.emitWarning('changeLevelName and levelKey are deprecated, use the formatters.level option instead', 'Warning', 'PINODEP002') - allFormatters.level = levelNameLabelFormatter(changeLevelName || levelKey) - } +/***/ 78079: +/***/ ((__unused_webpack_module, exports) => { - if (serializers[Symbol.for('pino.*')]) { - process.emitWarning('The pino.* serializer is deprecated, use the formatters.log options instead', 'Warning', 'PINODEP003') - allFormatters.log = serializers[Symbol.for('pino.*')] - } +"use strict"; - if (!allFormatters.bindings) { - allFormatters.bindings = defaultOptions.formatters.bindings - } - if (!allFormatters.level) { - allFormatters.level = defaultOptions.formatters.level - } +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 - const stringifiers = redact ? redaction(redact, stringify) : {} - const formatOpts = redact - ? { stringify: stringifiers[redactFmtSym] } - : { stringify } - const end = '}' + (crlf ? '\r\n' : '\n') - const coreChindings = asChindings.bind(null, { - [chindingsSym]: '', - [serializersSym]: serializers, - [stringifiersSym]: stringifiers, - [stringifySym]: stringify, - [formattersSym]: allFormatters - }) +/***/ }), - let chindings = '' - if (base !== null) { - if (name === undefined) { - chindings = coreChindings(base) - } else { - chindings = coreChindings(Object.assign({}, base, { name })) - } - } +/***/ 32350: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - const time = (timestamp instanceof Function) - ? timestamp - : (timestamp ? epochTime : nullTime) - const timeSliceIndex = time().indexOf(':') + 1 +"use strict"; - if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true') - if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`) +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 - assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels) - const levels = mappings(customLevels, useOnlyCustomLevels) +/***/ }), - Object.assign(instance, { - levels, - [useOnlyCustomLevelsSym]: useOnlyCustomLevels, - [streamSym]: stream, - [timeSym]: time, - [timeSliceIndexSym]: timeSliceIndex, - [stringifySym]: stringify, - [stringifiersSym]: stringifiers, - [endSym]: end, - [formatOptsSym]: formatOpts, - [messageKeySym]: messageKey, - [nestedKeySym]: nestedKey, - [serializersSym]: serializers, - [mixinSym]: mixin, - [chindingsSym]: chindings, - [formattersSym]: allFormatters, - [hooksSym]: hooks, - silent: noop - }) +/***/ 32415: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Object.setPrototypeOf(instance, proto()) +"use strict"; - genLsCache(instance) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createWebhookProxy = void 0; +const createWebhookProxy = (opts) => { + try { + const SmeeClient = __nccwpck_require__(24807); + 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 - instance[setLevelSym](level) +/***/ }), - return instance -} +/***/ 58930: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function labelsFormatter (label, number) { - return { level: label } -} +"use strict"; -function levelNameFormatter (name) { - return function (label, number) { - return { [name]: number } - } -} +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__(94219); +Object.defineProperty(exports, "Context", ({ enumerable: true, get: function () { return context_1.Context; } })); +const probot_1 = __nccwpck_require__(87085); +Object.defineProperty(exports, "Probot", ({ enumerable: true, get: function () { return probot_1.Probot; } })); +const server_1 = __nccwpck_require__(93772); +Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); +const probot_octokit_1 = __nccwpck_require__(45351); +Object.defineProperty(exports, "ProbotOctokit", ({ enumerable: true, get: function () { return probot_octokit_1.ProbotOctokit; } })); +const run_1 = __nccwpck_require__(75611); +Object.defineProperty(exports, "run", ({ enumerable: true, get: function () { return run_1.run; } })); +const create_node_middleware_1 = __nccwpck_require__(95960); +Object.defineProperty(exports, "createNodeMiddleware", ({ enumerable: true, get: function () { return create_node_middleware_1.createNodeMiddleware; } })); +const create_probot_1 = __nccwpck_require__(82598); +Object.defineProperty(exports, "createProbot", ({ enumerable: true, get: function () { return create_probot_1.createProbot; } })); +//# sourceMappingURL=index.js.map -function levelNameLabelFormatter (name) { - return function (label, number) { - return { [name]: label } - } -} +/***/ }), -module.exports = pino +/***/ 59159: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -module.exports.extreme = (dest = process.stdout.fd) => { - process.emitWarning( - 'The pino.extreme() option is deprecated and will be removed in v7. Use pino.destination({ sync: false }) instead.', - { code: 'extreme_deprecation' } - ) - return buildSafeSonicBoom({ dest, minLength: 4096, sync: false }) -} +"use strict"; -module.exports.destination = (dest = process.stdout.fd) => { - if (typeof dest === 'object') { - dest.dest = dest.dest || process.stdout.fd - return buildSafeSonicBoom(dest) - } else { - return buildSafeSonicBoom({ dest, minLength: 0, sync: true }) - } +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__(45351); +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__(24807); + 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}${process.env.GH_ORG ? "/organizations/".concat(process.env.GH_ORG) : ""}/settings/apps/new`; + } } +exports.ManifestCreation = ManifestCreation; +//# sourceMappingURL=manifest-creation.js.map -module.exports.final = final -module.exports.levels = mappings() -module.exports.stdSerializers = serializers -module.exports.stdTimeFunctions = Object.assign({}, time) -module.exports.symbols = symbols -module.exports.version = version +/***/ }), -// Enables default and name export with TypeScript and Babel -module.exports["default"] = pino -module.exports.pino = pino +/***/ 88916: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +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 /***/ }), -/***/ 51235: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 2286: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -const path = __nccwpck_require__(71017); -const findUp = __nccwpck_require__(26428); -const loadJsonFile = __nccwpck_require__(75978); - -const filepaths = new WeakMap(); -const filepath = conf => filepaths.get(conf); -const findNextCwd = pkgPath => path.resolve(path.dirname(pkgPath), '..'); - -const addFilePath = (object, filePath) => { - filepaths.set(object, filePath); - return object; +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 -const pkgConf = (namespace, options = {}) => { - if (!namespace) { - return Promise.reject(new TypeError('Expected a namespace')); - } +/***/ }), - return findUp('package.json', options.cwd ? {cwd: options.cwd} : {}) - .then(filePath => { - if (!filePath) { - return addFilePath(Object.assign({}, options.defaults), filePath); - } +/***/ 62543: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return loadJsonFile(filePath).then(package_ => { - if (options.skipOnFalse && package_[namespace] === false) { - const newOptions = Object.assign({}, options, {cwd: findNextCwd(filePath)}); - return pkgConf(namespace, newOptions); - } +"use strict"; - return addFilePath(Object.assign({}, options.defaults, package_[namespace]), filePath); - }); - }); -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getProbotOctokitWithDefaults = void 0; +const get_octokit_throttle_options_1 = __nccwpck_require__(2286); +/** + * 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 -const sync = (namespace, options = {}) => { - if (!namespace) { - throw new TypeError('Expected a namespace'); - } +/***/ }), - const filePath = findUp.sync('package.json', options.cwd ? {cwd: options.cwd} : {}); +/***/ 92974: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!filePath) { - return addFilePath(Object.assign({}, options.defaults), filePath); - } +"use strict"; - const package_ = loadJsonFile.sync(filePath); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getWebhooks = void 0; +const webhooks_1 = __nccwpck_require__(18513); +const get_error_handler_1 = __nccwpck_require__(25625); +const octokit_webhooks_transform_1 = __nccwpck_require__(50645); +// 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 - if (options.skipOnFalse && package_[namespace] === false) { - const newOptions = Object.assign({}, options, {cwd: findNextCwd(filePath)}); - return sync(namespace, newOptions); - } +/***/ }), - return addFilePath(Object.assign({}, options.defaults, package_[namespace]), filePath); -}; +/***/ 87517: +/***/ ((__unused_webpack_module, exports) => { -module.exports = pkgConf; -// TODO: Remove this for the next major release -module.exports["default"] = pkgConf; -module.exports.filepath = filepath; -module.exports.sync = sync; +"use strict"; +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 /***/ }), -/***/ 26428: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 50645: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(71017); -const locatePath = __nccwpck_require__(47619); - -module.exports = (filename, opts = {}) => { - const startDir = path.resolve(opts.cwd || ''); - const {root} = path.parse(startDir); - - const filenames = [].concat(filename); - - return new Promise(resolve => { - (function find(dir) { - locatePath(filenames, {cwd: dir}).then(file => { - if (file) { - resolve(path.join(dir, file)); - } else if (dir === root) { - resolve(null); - } else { - find(path.dirname(dir)); - } - }); - })(startDir); - }); -}; - -module.exports.sync = (filename, opts = {}) => { - let dir = path.resolve(opts.cwd || ''); - const {root} = path.parse(dir); - - const filenames = [].concat(filename); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.webhookTransform = void 0; +const context_1 = __nccwpck_require__(94219); +/** + * 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 - // eslint-disable-next-line no-constant-condition - while (true) { - const file = locatePath.sync(filenames, {cwd: dir}); +/***/ }), - if (file) { - return path.join(dir, file); - } +/***/ 45351: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (dir === root) { - return null; - } +"use strict"; - dir = path.dirname(dir); - } +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__(87517); +const version_1 = __nccwpck_require__(23972); +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 /***/ }), -/***/ 47619: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 87085: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -const path = __nccwpck_require__(71017); -const pathExists = __nccwpck_require__(70652); -const pLocate = __nccwpck_require__(96566); +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__(95326); +const auth_1 = __nccwpck_require__(23831); +const get_log_1 = __nccwpck_require__(75942); +const get_probot_octokit_with_defaults_1 = __nccwpck_require__(62543); +const get_webhooks_1 = __nccwpck_require__(92974); +const probot_octokit_1 = __nccwpck_require__(45351); +const version_1 = __nccwpck_require__(23972); +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 -module.exports = (iterable, options) => { - options = Object.assign({ - cwd: process.cwd() - }, options); +/***/ }), - return pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options); -}; +/***/ 75611: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -module.exports.sync = (iterable, options) => { - options = Object.assign({ - cwd: process.cwd() - }, options); +"use strict"; - for (const el of iterable) { - if (pathExists.sync(path.resolve(options.cwd, el))) { - return el; - } - } +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__(58930); +const setup_1 = __nccwpck_require__(31078); +const get_log_1 = __nccwpck_require__(75942); +const read_cli_options_1 = __nccwpck_require__(4015); +const read_env_options_1 = __nccwpck_require__(92004); +const server_1 = __nccwpck_require__(93772); +const default_1 = __nccwpck_require__(35362); +const resolve_app_function_1 = __nccwpck_require__(32350); +const is_production_1 = __nccwpck_require__(78079); +/** + * + * @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 /***/ }), -/***/ 96566: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 27530: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -const pLimit = __nccwpck_require__(57684); - -class EndError extends Error { - constructor(value) { - super(); - this.value = value; - } +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 -// The input can also be a promise, so we `Promise.resolve()` it -const testElement = (el, tester) => Promise.resolve(el).then(tester); - -// The input can also be a promise, so we `Promise.all()` them both -const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0]))); - -module.exports = (iterable, tester, opts) => { - opts = Object.assign({ - concurrency: Infinity, - preserveOrder: true - }, opts); - - const limit = pLimit(opts.concurrency); +/***/ }), - // Start all the promises concurrently with optional limit - const items = [...iterable].map(el => [el, limit(testElement, el, tester)]); +/***/ 93772: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // Check the promises either serially or concurrently - const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity); +"use strict"; - return Promise.all(items.map(el => checkLimit(finder, el))) - .then(() => {}) - .catch(err => err instanceof EndError ? err.value : Promise.reject(err)); +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__(75942); +const logging_middleware_1 = __nccwpck_require__(27530); +const webhook_proxy_1 = __nccwpck_require__(32415); +const version_1 = __nccwpck_require__(23972); +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 /***/ }), -/***/ 70652: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 23972: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -const fs = __nccwpck_require__(57147); - -module.exports = fp => new Promise(resolve => { - fs.access(fp, err => { - resolve(!err); - }); -}); - -module.exports.sync = fp => { - try { - fs.accessSync(fp); - return true; - } catch (err) { - return false; - } -}; - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VERSION = void 0; +// The version is set automatically before publish to npm +exports.VERSION = "12.2.1"; +//# sourceMappingURL=version.js.map /***/ }), @@ -112557,6 +112557,20 @@ var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { } }; +var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); +}; + var getPackageCandidates = function getPackageCandidates(x, start, opts) { var dirs = nodeModulesPaths(start, opts, x); for (var i = 0; i < dirs.length; i++) { @@ -112585,6 +112599,13 @@ module.exports = function resolve(x, options, callback) { var isDirectory = opts.isDirectory || defaultIsDir; var readFile = opts.readFile || fs.readFile; var realpath = opts.realpath || defaultRealpath; + var readPackage = opts.readPackage || defaultReadPackage; + if (opts.readFile && opts.readPackage) { + var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); + return process.nextTick(function () { + cb(conflictErr); + }); + } var packageIterator = opts.packageIterator; var extensions = opts.extensions || ['.js']; @@ -112712,9 +112733,10 @@ module.exports = function resolve(x, options, callback) { // on err, ex is false if (!ex) return loadpkg(path.dirname(dir), cb); - readFile(pkgfile, function (err, body) { + readPackage(readFile, pkgfile, function (err, pkgParam) { if (err) cb(err); - try { var pkg = JSON.parse(body); } catch (jsonErr) {} + + var pkg = pkgParam; if (pkg && opts.packageFilter) { pkg = opts.packageFilter(pkg, pkgfile); @@ -112740,11 +112762,10 @@ module.exports = function resolve(x, options, callback) { if (err) return cb(err); if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); - readFile(pkgfile, function (err, body) { + readPackage(readFile, pkgfile, function (err, pkgParam) { if (err) return cb(err); - try { - var pkg = JSON.parse(body); - } catch (jsonErr) {} + + var pkg = pkgParam; if (pkg && opts.packageFilter) { pkg = opts.packageFilter(pkg, pkgfile); @@ -112851,9 +112872,8 @@ function specifierIncluded(specifier) { return cur < ver; } else if (op === '>=') { return cur >= ver; - } else { - return false; } + return false; } return op === '>='; } @@ -112907,7 +112927,7 @@ module.exports = function isCore(x) { /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var path = __nccwpck_require__(71017); -var parse = path.parse || __nccwpck_require__(5980); +var parse = path.parse || __nccwpck_require__(5980); // eslint-disable-line global-require var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { var prefix = '/'; @@ -112983,22 +113003,22 @@ var realpathFS = fs.realpathSync && typeof fs.realpathSync.native === 'function' var defaultIsFile = function isFile(file) { try { - var stat = fs.statSync(file); + var stat = fs.statSync(file, { throwIfNoEntry: false }); } catch (e) { if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; throw e; } - return stat.isFile() || stat.isFIFO(); + return !!stat && (stat.isFile() || stat.isFIFO()); }; var defaultIsDir = function isDirectory(dir) { try { - var stat = fs.statSync(dir); + var stat = fs.statSync(dir, { throwIfNoEntry: false }); } catch (e) { if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; throw e; } - return stat.isDirectory(); + return !!stat && stat.isDirectory(); }; var defaultRealpathSync = function realpathSync(x) { @@ -113019,6 +113039,14 @@ var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { return x; }; +var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} +}; + var getPackageCandidates = function getPackageCandidates(x, start, opts) { var dirs = nodeModulesPaths(start, opts, x); for (var i = 0; i < dirs.length; i++) { @@ -113037,6 +113065,10 @@ module.exports = function resolveSync(x, options) { var readFileSync = opts.readFileSync || fs.readFileSync; var isDirectory = opts.isDirectory || defaultIsDir; var realpathSync = opts.realpathSync || defaultRealpathSync; + var readPackageSync = opts.readPackageSync || defaultReadPackageSync; + if (opts.readFileSync && opts.readPackageSync) { + throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); + } var packageIterator = opts.packageIterator; var extensions = opts.extensions || ['.js']; @@ -113101,11 +113133,7 @@ module.exports = function resolveSync(x, options) { return loadpkg(path.dirname(dir)); } - var body = readFileSync(pkgfile); - - try { - var pkg = JSON.parse(body); - } catch (jsonErr) {} + var pkg = readPackageSync(readFileSync, pkgfile); if (pkg && opts.packageFilter) { // v2 will pass pkgfile @@ -113119,8 +113147,7 @@ module.exports = function resolveSync(x, options) { var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); if (isFile(pkgfile)) { try { - var body = readFileSync(pkgfile, 'UTF8'); - var pkg = JSON.parse(body); + var pkg = readPackageSync(readFileSync, pkgfile); } catch (e) {} if (pkg && opts.packageFilter) { @@ -123602,7 +123629,7 @@ module.exports = JSON.parse('[["0","\\u0000",128],["a1","。",62],["8140","  /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"assert":true,"assert/strict":">= 15","async_hooks":">= 8","buffer_ieee754":"< 0.9.7","buffer":true,"child_process":true,"cluster":true,"console":true,"constants":true,"crypto":true,"_debug_agent":">= 1 && < 8","_debugger":"< 8","dgram":true,"diagnostics_channel":">= 15.1","dns":true,"dns/promises":">= 15","domain":">= 0.7.12","events":true,"freelist":"< 6","fs":true,"fs/promises":[">= 10 && < 10.1",">= 14"],"_http_agent":">= 0.11.1","_http_client":">= 0.11.1","_http_common":">= 0.11.1","_http_incoming":">= 0.11.1","_http_outgoing":">= 0.11.1","_http_server":">= 0.11.1","http":true,"http2":">= 8.8","https":true,"inspector":">= 8.0.0","_linklist":"< 8","module":true,"net":true,"node-inspect/lib/_inspect":">= 7.6.0 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6.0 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6.0 && < 12","os":true,"path":true,"path/posix":">= 15.3","path/win32":">= 15.3","perf_hooks":">= 8.5","process":">= 1","punycode":true,"querystring":true,"readline":true,"repl":true,"smalloc":">= 0.11.5 && < 3","_stream_duplex":">= 0.9.4","_stream_transform":">= 0.9.4","_stream_wrap":">= 1.4.1","_stream_passthrough":">= 0.9.4","_stream_readable":">= 0.9.4","_stream_writable":">= 0.9.4","stream":true,"stream/promises":">= 15","string_decoder":true,"sys":[">= 0.6 && < 0.7",">= 0.8"],"timers":true,"timers/promises":">= 15","_tls_common":">= 0.11.13","_tls_legacy":">= 0.11.3 && < 10","_tls_wrap":">= 0.11.3","tls":true,"trace_events":">= 10","tty":true,"url":true,"util":true,"util/types":">= 15.3","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/consarray":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/csvparser":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/logreader":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/profile_view":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/splaytree":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8":">= 1","vm":true,"wasi":">= 13.4 && < 13.5","worker_threads":">= 11.7","zlib":true}'); +module.exports = JSON.parse('{"assert":true,"node:assert":[">= 14.18 && < 15",">= 16"],"assert/strict":">= 15","node:assert/strict":">= 16","async_hooks":">= 8","node:async_hooks":[">= 14.18 && < 15",">= 16"],"buffer_ieee754":">= 0.5 && < 0.9.7","buffer":true,"node:buffer":[">= 14.18 && < 15",">= 16"],"child_process":true,"node:child_process":[">= 14.18 && < 15",">= 16"],"cluster":">= 0.5","node:cluster":[">= 14.18 && < 15",">= 16"],"console":true,"node:console":[">= 14.18 && < 15",">= 16"],"constants":true,"node:constants":[">= 14.18 && < 15",">= 16"],"crypto":true,"node:crypto":[">= 14.18 && < 15",">= 16"],"_debug_agent":">= 1 && < 8","_debugger":"< 8","dgram":true,"node:dgram":[">= 14.18 && < 15",">= 16"],"diagnostics_channel":[">= 14.17 && < 15",">= 15.1"],"node:diagnostics_channel":[">= 14.18 && < 15",">= 16"],"dns":true,"node:dns":[">= 14.18 && < 15",">= 16"],"dns/promises":">= 15","node:dns/promises":">= 16","domain":">= 0.7.12","node:domain":[">= 14.18 && < 15",">= 16"],"events":true,"node:events":[">= 14.18 && < 15",">= 16"],"freelist":"< 6","fs":true,"node:fs":[">= 14.18 && < 15",">= 16"],"fs/promises":[">= 10 && < 10.1",">= 14"],"node:fs/promises":[">= 14.18 && < 15",">= 16"],"_http_agent":">= 0.11.1","node:_http_agent":[">= 14.18 && < 15",">= 16"],"_http_client":">= 0.11.1","node:_http_client":[">= 14.18 && < 15",">= 16"],"_http_common":">= 0.11.1","node:_http_common":[">= 14.18 && < 15",">= 16"],"_http_incoming":">= 0.11.1","node:_http_incoming":[">= 14.18 && < 15",">= 16"],"_http_outgoing":">= 0.11.1","node:_http_outgoing":[">= 14.18 && < 15",">= 16"],"_http_server":">= 0.11.1","node:_http_server":[">= 14.18 && < 15",">= 16"],"http":true,"node:http":[">= 14.18 && < 15",">= 16"],"http2":">= 8.8","node:http2":[">= 14.18 && < 15",">= 16"],"https":true,"node:https":[">= 14.18 && < 15",">= 16"],"inspector":">= 8","node:inspector":[">= 14.18 && < 15",">= 16"],"_linklist":"< 8","module":true,"node:module":[">= 14.18 && < 15",">= 16"],"net":true,"node:net":[">= 14.18 && < 15",">= 16"],"node-inspect/lib/_inspect":">= 7.6 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6 && < 12","os":true,"node:os":[">= 14.18 && < 15",">= 16"],"path":true,"node:path":[">= 14.18 && < 15",">= 16"],"path/posix":">= 15.3","node:path/posix":">= 16","path/win32":">= 15.3","node:path/win32":">= 16","perf_hooks":">= 8.5","node:perf_hooks":[">= 14.18 && < 15",">= 16"],"process":">= 1","node:process":[">= 14.18 && < 15",">= 16"],"punycode":">= 0.5","node:punycode":[">= 14.18 && < 15",">= 16"],"querystring":true,"node:querystring":[">= 14.18 && < 15",">= 16"],"readline":true,"node:readline":[">= 14.18 && < 15",">= 16"],"readline/promises":">= 17","node:readline/promises":">= 17","repl":true,"node:repl":[">= 14.18 && < 15",">= 16"],"smalloc":">= 0.11.5 && < 3","_stream_duplex":">= 0.9.4","node:_stream_duplex":[">= 14.18 && < 15",">= 16"],"_stream_transform":">= 0.9.4","node:_stream_transform":[">= 14.18 && < 15",">= 16"],"_stream_wrap":">= 1.4.1","node:_stream_wrap":[">= 14.18 && < 15",">= 16"],"_stream_passthrough":">= 0.9.4","node:_stream_passthrough":[">= 14.18 && < 15",">= 16"],"_stream_readable":">= 0.9.4","node:_stream_readable":[">= 14.18 && < 15",">= 16"],"_stream_writable":">= 0.9.4","node:_stream_writable":[">= 14.18 && < 15",">= 16"],"stream":true,"node:stream":[">= 14.18 && < 15",">= 16"],"stream/consumers":">= 16.7","node:stream/consumers":">= 16.7","stream/promises":">= 15","node:stream/promises":">= 16","stream/web":">= 16.5","node:stream/web":">= 16.5","string_decoder":true,"node:string_decoder":[">= 14.18 && < 15",">= 16"],"sys":[">= 0.4 && < 0.7",">= 0.8"],"node:sys":[">= 14.18 && < 15",">= 16"],"timers":true,"node:timers":[">= 14.18 && < 15",">= 16"],"timers/promises":">= 15","node:timers/promises":">= 16","_tls_common":">= 0.11.13","node:_tls_common":[">= 14.18 && < 15",">= 16"],"_tls_legacy":">= 0.11.3 && < 10","_tls_wrap":">= 0.11.3","node:_tls_wrap":[">= 14.18 && < 15",">= 16"],"tls":true,"node:tls":[">= 14.18 && < 15",">= 16"],"trace_events":">= 10","node:trace_events":[">= 14.18 && < 15",">= 16"],"tty":true,"node:tty":[">= 14.18 && < 15",">= 16"],"url":true,"node:url":[">= 14.18 && < 15",">= 16"],"util":true,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/csvparser":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/logreader":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/profile_view":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/splaytree":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8":">= 1","node:v8":[">= 14.18 && < 15",">= 16"],"vm":true,"node:vm":[">= 14.18 && < 15",">= 16"],"wasi":">= 13.4 && < 13.5","worker_threads":">= 11.7","node:worker_threads":[">= 14.18 && < 15",">= 16"],"zlib":">= 0.5","node:zlib":[">= 14.18 && < 15",">= 16"]}'); /***/ }), @@ -123650,7 +123677,7 @@ module.exports = JSON.parse('{"acl":{"arity":-2,"flags":["admin","noscript","loa /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"assert":true,"assert/strict":">= 15","async_hooks":">= 8","buffer_ieee754":"< 0.9.7","buffer":true,"child_process":true,"cluster":true,"console":true,"constants":true,"crypto":true,"_debug_agent":">= 1 && < 8","_debugger":"< 8","dgram":true,"diagnostics_channel":">= 15.1","dns":true,"dns/promises":">= 15","domain":">= 0.7.12","events":true,"freelist":"< 6","fs":true,"fs/promises":[">= 10 && < 10.1",">= 14"],"_http_agent":">= 0.11.1","_http_client":">= 0.11.1","_http_common":">= 0.11.1","_http_incoming":">= 0.11.1","_http_outgoing":">= 0.11.1","_http_server":">= 0.11.1","http":true,"http2":">= 8.8","https":true,"inspector":">= 8.0.0","_linklist":"< 8","module":true,"net":true,"node-inspect/lib/_inspect":">= 7.6.0 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6.0 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6.0 && < 12","os":true,"path":true,"perf_hooks":">= 8.5","process":">= 1","punycode":true,"querystring":true,"readline":true,"repl":true,"smalloc":">= 0.11.5 && < 3","_stream_duplex":">= 0.9.4","_stream_transform":">= 0.9.4","_stream_wrap":">= 1.4.1","_stream_passthrough":">= 0.9.4","_stream_readable":">= 0.9.4","_stream_writable":">= 0.9.4","stream":true,"stream/promises":">= 15","string_decoder":true,"sys":[">= 0.6 && < 0.7",">= 0.8"],"timers":true,"timers/promises":">= 15","_tls_common":">= 0.11.13","_tls_legacy":">= 0.11.3 && < 10","_tls_wrap":">= 0.11.3","tls":true,"trace_events":">= 10","tty":true,"url":true,"util":true,"v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/consarray":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/csvparser":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/logreader":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/profile_view":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8/tools/splaytree":[">= 4.4.0 && < 5",">= 5.2.0 && < 12"],"v8":">= 1","vm":true,"wasi":">= 13.4 && < 13.5","worker_threads":">= 11.7","zlib":true}'); +module.exports = JSON.parse('{"assert":true,"node:assert":[">= 14.18 && < 15",">= 16"],"assert/strict":">= 15","node:assert/strict":">= 16","async_hooks":">= 8","node:async_hooks":[">= 14.18 && < 15",">= 16"],"buffer_ieee754":"< 0.9.7","buffer":true,"node:buffer":[">= 14.18 && < 15",">= 16"],"child_process":true,"node:child_process":[">= 14.18 && < 15",">= 16"],"cluster":true,"node:cluster":[">= 14.18 && < 15",">= 16"],"console":true,"node:console":[">= 14.18 && < 15",">= 16"],"constants":true,"node:constants":[">= 14.18 && < 15",">= 16"],"crypto":true,"node:crypto":[">= 14.18 && < 15",">= 16"],"_debug_agent":">= 1 && < 8","_debugger":"< 8","dgram":true,"node:dgram":[">= 14.18 && < 15",">= 16"],"diagnostics_channel":[">= 14.17 && < 15",">= 15.1"],"node:diagnostics_channel":[">= 14.18 && < 15",">= 16"],"dns":true,"node:dns":[">= 14.18 && < 15",">= 16"],"dns/promises":">= 15","node:dns/promises":">= 16","domain":">= 0.7.12","node:domain":[">= 14.18 && < 15",">= 16"],"events":true,"node:events":[">= 14.18 && < 15",">= 16"],"freelist":"< 6","fs":true,"node:fs":[">= 14.18 && < 15",">= 16"],"fs/promises":[">= 10 && < 10.1",">= 14"],"node:fs/promises":[">= 14.18 && < 15",">= 16"],"_http_agent":">= 0.11.1","node:_http_agent":[">= 14.18 && < 15",">= 16"],"_http_client":">= 0.11.1","node:_http_client":[">= 14.18 && < 15",">= 16"],"_http_common":">= 0.11.1","node:_http_common":[">= 14.18 && < 15",">= 16"],"_http_incoming":">= 0.11.1","node:_http_incoming":[">= 14.18 && < 15",">= 16"],"_http_outgoing":">= 0.11.1","node:_http_outgoing":[">= 14.18 && < 15",">= 16"],"_http_server":">= 0.11.1","node:_http_server":[">= 14.18 && < 15",">= 16"],"http":true,"node:http":[">= 14.18 && < 15",">= 16"],"http2":">= 8.8","node:http2":[">= 14.18 && < 15",">= 16"],"https":true,"node:https":[">= 14.18 && < 15",">= 16"],"inspector":">= 8","node:inspector":[">= 14.18 && < 15",">= 16"],"_linklist":"< 8","module":true,"node:module":[">= 14.18 && < 15",">= 16"],"net":true,"node:net":[">= 14.18 && < 15",">= 16"],"node-inspect/lib/_inspect":">= 7.6 && < 12","node-inspect/lib/internal/inspect_client":">= 7.6 && < 12","node-inspect/lib/internal/inspect_repl":">= 7.6 && < 12","os":true,"node:os":[">= 14.18 && < 15",">= 16"],"path":true,"node:path":[">= 14.18 && < 15",">= 16"],"path/posix":">= 15.3","node:path/posix":">= 16","path/win32":">= 15.3","node:path/win32":">= 16","perf_hooks":">= 8.5","node:perf_hooks":[">= 14.18 && < 15",">= 16"],"process":">= 1","node:process":[">= 14.18 && < 15",">= 16"],"punycode":true,"node:punycode":[">= 14.18 && < 15",">= 16"],"querystring":true,"node:querystring":[">= 14.18 && < 15",">= 16"],"readline":true,"node:readline":[">= 14.18 && < 15",">= 16"],"readline/promises":">= 17","node:readline/promises":">= 17","repl":true,"node:repl":[">= 14.18 && < 15",">= 16"],"smalloc":">= 0.11.5 && < 3","_stream_duplex":">= 0.9.4","node:_stream_duplex":[">= 14.18 && < 15",">= 16"],"_stream_transform":">= 0.9.4","node:_stream_transform":[">= 14.18 && < 15",">= 16"],"_stream_wrap":">= 1.4.1","node:_stream_wrap":[">= 14.18 && < 15",">= 16"],"_stream_passthrough":">= 0.9.4","node:_stream_passthrough":[">= 14.18 && < 15",">= 16"],"_stream_readable":">= 0.9.4","node:_stream_readable":[">= 14.18 && < 15",">= 16"],"_stream_writable":">= 0.9.4","node:_stream_writable":[">= 14.18 && < 15",">= 16"],"stream":true,"node:stream":[">= 14.18 && < 15",">= 16"],"stream/consumers":">= 16.7","node:stream/consumers":">= 16.7","stream/promises":">= 15","node:stream/promises":">= 16","stream/web":">= 16.5","node:stream/web":">= 16.5","string_decoder":true,"node:string_decoder":[">= 14.18 && < 15",">= 16"],"sys":[">= 0.6 && < 0.7",">= 0.8"],"node:sys":[">= 14.18 && < 15",">= 16"],"timers":true,"node:timers":[">= 14.18 && < 15",">= 16"],"timers/promises":">= 15","node:timers/promises":">= 16","_tls_common":">= 0.11.13","node:_tls_common":[">= 14.18 && < 15",">= 16"],"_tls_legacy":">= 0.11.3 && < 10","_tls_wrap":">= 0.11.3","node:_tls_wrap":[">= 14.18 && < 15",">= 16"],"tls":true,"node:tls":[">= 14.18 && < 15",">= 16"],"trace_events":">= 10","node:trace_events":[">= 14.18 && < 15",">= 16"],"tty":true,"node:tty":[">= 14.18 && < 15",">= 16"],"url":true,"node:url":[">= 14.18 && < 15",">= 16"],"util":true,"node:util":[">= 14.18 && < 15",">= 16"],"util/types":">= 15.3","node:util/types":">= 16","v8/tools/arguments":">= 10 && < 12","v8/tools/codemap":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/consarray":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/csvparser":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/logreader":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/profile_view":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8/tools/splaytree":[">= 4.4 && < 5",">= 5.2 && < 12"],"v8":">= 1","node:v8":[">= 14.18 && < 15",">= 16"],"vm":true,"node:vm":[">= 14.18 && < 15",">= 16"],"wasi":">= 13.4 && < 13.5","worker_threads":">= 11.7","node:worker_threads":[">= 14.18 && < 15",">= 16"],"zlib":true,"node:zlib":[">= 14.18 && < 15",">= 16"]}'); /***/ }), diff --git a/package.json b/package.json index 26add29e4..886a7983a 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "ignore": "5.2.0", "joi": "17.5.0", "lodash": "4.17.21", - "probot": "12.2.0", + "probot": "12.2.1", "regex-parser": "2.2.11", "semver": "7.3.5" }, diff --git a/yarn.lock b/yarn.lock index ecc284a15..ecab14f5d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -770,11 +770,6 @@ resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-11.2.0.tgz#b38d7fc3736d52a1e96b230c1ccd4a58a2f400a6" integrity sha512-PBsVO+15KSlGmiI8QAzaqvsNlZlrDlyAJYcrXBCvVUxCp7VnXjkwPoFHgjEJXx3WF9BAwkA6nfCUA7i9sODzKA== -"@octokit/openapi-types@^2.0.1": - version "2.0.1" - resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-2.0.1.tgz#7453d8281ce66b8ed1607f7ac7d751c3baffd2cc" - integrity sha512-9AuC04PUnZrjoLiw3uPtwGh9FE4Q3rTqs51oNlQ0rkwgE8ftYsOC+lsrQyvCvWm85smBbSc0FNRKKumvGyb44Q== - "@octokit/plugin-enterprise-compatibility@^1.2.8": version "1.2.8" resolved "https://registry.yarnpkg.com/@octokit/plugin-enterprise-compatibility/-/plugin-enterprise-compatibility-1.2.8.tgz#5d63704e9717dac49d363c74dc2dcb6e53933099" @@ -837,15 +832,7 @@ once "^1.4.0" universal-user-agent "^6.0.0" -"@octokit/types@^6.0.0", "@octokit/types@^6.0.1", "@octokit/types@^6.0.3", "@octokit/types@^6.1.1": - version "6.1.2" - resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.1.2.tgz#2b3a6ae0b8b71c27c770b4ff3e9ad8f1f538af58" - integrity sha512-LPCpcLbcky7fWfHCTuc7tMiSHFpFlrThJqVdaHgowBTMS0ijlZFfonQC/C1PrZOjD4xRCYgBqH9yttEATGE/nw== - dependencies: - "@octokit/openapi-types" "^2.0.1" - "@types/node" ">= 8" - -"@octokit/types@^6.34.0": +"@octokit/types@^6.0.0", "@octokit/types@^6.0.1", "@octokit/types@^6.0.3", "@octokit/types@^6.1.1", "@octokit/types@^6.34.0": version "6.34.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.34.0.tgz#c6021333334d1ecfb5d370a8798162ddf1ae8218" integrity sha512-s1zLBjWhdEI2zwaoSgyOFoKSl109CUcVBCc7biPJ3aAf6LGLU6szDvi31JPU7bxfla2lqfhjbbg/5DdFNxOwHw== @@ -1190,11 +1177,6 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.1.tgz#5d93e0a099cd0acd5ef3d5bde3c086e1f49ff68c" integrity sha512-FAYBGwC+W6F9+huFIDtn43cpy7+SzG+atzRiTfdp3inUKL2hXnd4rG8hylJLIh4+hqrQy1P17kvJByE/z825hA== -"@types/node@>= 8": - version "13.1.0" - resolved "https://registry.yarnpkg.com/@types/node/-/node-13.1.0.tgz#225cbaac5fdb2b9ac651b02c070d8aa3c37cc812" - integrity sha512-zwrxviZS08kRX40nqBrmERElF2vpw4IUTd5khkhBTfFH8AOaeoLVx48EC4+ZzS2/Iga7NevncqnsUSYjM4OWYA== - "@types/normalize-package-data@^2.4.0": version "2.4.1" resolved "https://registry.yarnpkg.com/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz#d3357479a0fdfdd5907fe67e17e0a85c906e1301" @@ -2689,13 +2671,6 @@ glob@^7.1.4: once "^1.3.0" path-is-absolute "^1.0.0" -global-dirs@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/global-dirs/-/global-dirs-2.0.1.tgz#acdf3bb6685bcd55cb35e8a052266569e9469201" - integrity sha512-5HqUqdhkEovj2Of/ms3IeS/EekcO54ytHRLV4PEY2rhRwrHXLQjeVEES0Lhka0xwNDtGYn58wyC4s5+MHsOO6A== - dependencies: - ini "^1.3.5" - global-dirs@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/global-dirs/-/global-dirs-3.0.0.tgz#70a76fe84ea315ab37b1f5576cbde7d48ef72686" @@ -2742,10 +2717,10 @@ graceful-fs@^4.2.4: resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== -handlebars@4.7.6: - version "4.7.6" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.7.6.tgz#d4c05c1baf90e9945f77aa68a7a219aa4a7df74e" - integrity sha512-1f2BACcBfiwAfStCKZNrUCgqNZkGsAT7UM3kkYtXuLo0KnaVfjKOyf7PRzB6++aK9STyT1Pd2ZCPe3EGOXleXA== +handlebars@4.7.7: + version "4.7.7" + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.7.7.tgz#9ce33416aad02dbd6c8fafa8240d5d98004945a1" + integrity sha512-aAcXm5OAfE/8IXkcZvCepKU3VzW1/39Fb5ZuqMtgI/hT8X2YgoMvBY5dLhq/cpOvw7Lk1nK/UF71aLG/ZnVYRA== dependencies: minimist "^1.2.5" neo-async "^2.6.0" @@ -2776,13 +2751,13 @@ has@^1.0.3: dependencies: function-bind "^1.1.1" -hbs@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/hbs/-/hbs-4.1.1.tgz#8aab17ca6ae70f9aaa225278bed7af31011254b7" - integrity sha512-6QsbB4RwbpL4cb4DNyjEEPF+suwp+3yZqFVlhILEn92ScC0U4cDCR+FDX53jkfKJPhutcqhAvs+rOLZw5sQrDA== +hbs@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/hbs/-/hbs-4.2.0.tgz#10e40dcc24d5be7342df9636316896617542a32b" + integrity sha512-dQwHnrfWlTk5PvG9+a45GYpg0VpX47ryKF8dULVd6DtwOE6TEcYQXQ5QM6nyOx/h7v3bvEQbdn19EDAcfUAgZg== dependencies: - handlebars "4.7.6" - walk "2.3.14" + handlebars "4.7.7" + walk "2.3.15" hosted-git-info@^2.1.4: version "2.8.9" @@ -2931,7 +2906,7 @@ ini@2.0.0: resolved "https://registry.yarnpkg.com/ini/-/ini-2.0.0.tgz#e5fd556ecdd5726be978fa1001862eacb0a94bc5" integrity sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA== -ini@^1.3.5, ini@~1.3.0: +ini@~1.3.0: version "1.3.8" resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== @@ -2989,13 +2964,6 @@ is-ci@^2.0.0: dependencies: ci-info "^2.0.0" -is-core-module@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.2.0.tgz#97037ef3d52224d85163f5597b2b63d9afed981a" - integrity sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ== - dependencies: - has "^1.0.3" - is-core-module@^2.8.0: version "2.8.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.8.1.tgz#f59fdfca701d5879d0a6b100a40aa1560ce27211" @@ -3035,14 +3003,6 @@ is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3, is-glob@~4.0.1: dependencies: is-extglob "^2.1.1" -is-installed-globally@^0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/is-installed-globally/-/is-installed-globally-0.3.2.tgz#fd3efa79ee670d1187233182d5b0a1dd00313141" - integrity sha512-wZ8x1js7Ia0kecP/CHM/3ABkAmujX7WPvQk6uu3Fly/Mk44pySulQpnHG46OMjHGXApINnV4QhY3SWnECO2z5g== - dependencies: - global-dirs "^2.0.1" - is-path-inside "^3.0.1" - is-installed-globally@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/is-installed-globally/-/is-installed-globally-0.4.0.tgz#9a0fd407949c30f86eb6959ef1b7994ed0b7b520" @@ -3066,11 +3026,6 @@ is-obj@^2.0.0: resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-2.0.0.tgz#473fb05d973705e3fd9620545018ca8e22ef4982" integrity sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w== -is-path-inside@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.2.tgz#f5220fc82a3e233757291dddc9c5877f2a1f3017" - integrity sha512-/2UGPSgmtqwo1ktx8NDHjuPwZWmHhO+gj0f93EkhLB5RgW9RZevWYYlIkS6zePc6U2WpOdQYIwHe9YC4DWEBVg== - is-path-inside@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" @@ -4345,7 +4300,7 @@ path-key@^3.1.0: resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== -path-parse@^1.0.6, path-parse@^1.0.7: +path-parse@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== @@ -4484,51 +4439,10 @@ pretty-format@^27.4.6: ansi-styles "^5.0.0" react-is "^17.0.1" -probot@12.2.0: - version "12.2.0" - resolved "https://registry.yarnpkg.com/probot/-/probot-12.2.0.tgz#9411ec36a96082c6487076366db1e076da1852b8" - integrity sha512-8QO0G82Pf5ksMaT+3sWdiP7C3Gd2H23h+BwkvqHlpVnxRLc96KWdwdjKuergpg3DK4661VLjUQa35uiMGctoZQ== - dependencies: - "@octokit/core" "^3.2.4" - "@octokit/plugin-enterprise-compatibility" "^1.2.8" - "@octokit/plugin-paginate-rest" "^2.6.2" - "@octokit/plugin-rest-endpoint-methods" "^5.0.1" - "@octokit/plugin-retry" "^3.0.6" - "@octokit/plugin-throttling" "^3.3.4" - "@octokit/types" "^6.1.1" - "@octokit/webhooks" "^9.8.4" - "@probot/get-private-key" "^1.1.0" - "@probot/octokit-plugin-config" "^1.0.0" - "@probot/pino" "^2.2.0" - "@types/express" "^4.17.9" - "@types/ioredis" "^4.27.1" - "@types/pino" "^6.3.4" - "@types/pino-http" "^5.0.6" - "@types/update-notifier" "^5.0.0" - commander "^6.2.0" - deepmerge "^4.2.2" - deprecation "^2.3.1" - dotenv "^8.2.0" - eventsource "^1.0.7" - express "^4.17.1" - hbs "^4.1.1" - ioredis "^4.27.8" - js-yaml "^3.14.1" - lru-cache "^6.0.0" - octokit-auth-probot "^1.2.2" - pino "^6.7.0" - pino-http "^5.3.0" - pkg-conf "^3.1.0" - resolve "^1.19.0" - semver "^7.3.4" - update-dotenv "^1.1.1" - update-notifier "^5.0.1" - uuid "^8.3.2" - -probot@^12.1.4: - version "12.1.4" - resolved "https://registry.yarnpkg.com/probot/-/probot-12.1.4.tgz#b5821952961908e5c6419e26f15a186426adf0a5" - integrity sha512-pbvXXeZwIdi/vWk0Xtxe78ElDvczhzEzOjWjfxINyHCAA5cHaXF7+yX/bnDRZ9O0mEJB472H/NcMrT81Uy7kVg== +probot@12.2.1, probot@^12.1.4: + version "12.2.1" + resolved "https://registry.yarnpkg.com/probot/-/probot-12.2.1.tgz#8328b3283957f094bd5f5123c56bbf4cf63d3a20" + integrity sha512-CpqulMQFwfkh/3J+TcizxQgXeTgIVhw8ZpYq4TU4uHoo1iSC8Xmyrfv2BHRNI1OWRQhCnpJXIWh5EzhpX24Fvw== dependencies: "@octokit/core" "^3.2.4" "@octokit/plugin-enterprise-compatibility" "^1.2.8" @@ -4552,7 +4466,7 @@ probot@^12.1.4: dotenv "^8.2.0" eventsource "^1.0.7" express "^4.17.1" - hbs "^4.1.1" + hbs "^4.2.0" ioredis "^4.27.8" js-yaml "^3.14.1" lru-cache "^6.0.0" @@ -4786,7 +4700,7 @@ resolve.exports@^1.1.0: resolved "https://registry.yarnpkg.com/resolve.exports/-/resolve.exports-1.1.0.tgz#5ce842b94b05146c0e03076985d1d0e7e48c90c9" integrity sha512-J1l+Zxxp4XK3LUDZ9m60LRJF/mAe4z6a4xyabPHk7pvK5t35dACV32iIjJDFeWZFfZlO29w6SZ67knR0tHzJtQ== -resolve@^1.10.0, resolve@^1.20.0: +resolve@^1.10.0, resolve@^1.19.0, resolve@^1.20.0, resolve@^1.3.2: version "1.21.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.21.0.tgz#b51adc97f3472e6a5cf4444d34bc9d6b9037591f" integrity sha512-3wCbTpk5WJlyE4mSOtDLhqQmGFi0/TD9VPwmiolnk8U0wRgMEktqCXd3vy5buTO3tljvalNvKrjHEfrd2WpEKA== @@ -4795,14 +4709,6 @@ resolve@^1.10.0, resolve@^1.20.0: path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" -resolve@^1.19.0, resolve@^1.3.2: - version "1.19.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.19.0.tgz#1af5bf630409734a067cae29318aac7fa29a267c" - integrity sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg== - dependencies: - is-core-module "^2.1.0" - path-parse "^1.0.6" - responselike@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/responselike/-/responselike-1.0.2.tgz#918720ef3b631c5642be068f15ade5a46f4ba1e7" @@ -5449,27 +5355,7 @@ update-dotenv@^1.1.1: resolved "https://registry.yarnpkg.com/update-dotenv/-/update-dotenv-1.1.1.tgz#17146f302f216c3c92419d5a327a45be910050ca" integrity sha512-3cIC18In/t0X/yH793c00qqxcKD8jVCgNOPif/fGQkFpYMGecM9YAc+kaAKXuZsM2dE9I9wFI7KvAuNX22SGMQ== -update-notifier@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/update-notifier/-/update-notifier-5.0.1.tgz#1f92d45fb1f70b9e33880a72dd262bc12d22c20d" - integrity sha512-BuVpRdlwxeIOvmc32AGYvO1KVdPlsmqSh8KDDBxS6kDE5VR7R8OMP1d8MdhaVBvxl4H3551k9akXr0Y1iIB2Wg== - dependencies: - boxen "^4.2.0" - chalk "^4.1.0" - configstore "^5.0.1" - has-yarn "^2.1.0" - import-lazy "^2.1.0" - is-ci "^2.0.0" - is-installed-globally "^0.3.2" - is-npm "^5.0.0" - is-yarn-global "^0.3.0" - latest-version "^5.1.0" - pupa "^2.1.1" - semver "^7.3.2" - semver-diff "^3.1.1" - xdg-basedir "^4.0.0" - -update-notifier@^5.1.0: +update-notifier@^5.0.1, update-notifier@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/update-notifier/-/update-notifier-5.1.0.tgz#4ab0d7c7f36a231dd7316cf7729313f0214d9ad9" integrity sha512-ItnICHbeMh9GqUy31hFPrD1kcuZ3rpxDZbf4KUDavXwS0bW5m7SLbDQpGX3UYr072cbrF5hFUs3r5tUsPwjfHw== @@ -5567,10 +5453,10 @@ w3c-xmlserializer@^2.0.0: dependencies: xml-name-validator "^3.0.0" -walk@2.3.14: - version "2.3.14" - resolved "https://registry.yarnpkg.com/walk/-/walk-2.3.14.tgz#60ec8631cfd23276ae1e7363ce11d626452e1ef3" - integrity sha512-5skcWAUmySj6hkBdH6B6+3ddMjVQYH5Qy9QGbPmN8kVmLteXk+yVXg+yfk1nbX30EYakahLrr8iPcCxJQSCBeg== +walk@2.3.15: + version "2.3.15" + resolved "https://registry.yarnpkg.com/walk/-/walk-2.3.15.tgz#1b4611e959d656426bc521e2da5db3acecae2424" + integrity sha512-4eRTBZljBfIISK1Vnt69Gvr2w/wc3U6Vtrw7qiN5iqYJPH7LElcYh/iU4XWhdCy2dZqv1ToMyYlybDylfG/5Vg== dependencies: foreachasync "^3.0.0"