From eb64af9a4655c0a2813a59579ff1f0e75941c696 Mon Sep 17 00:00:00 2001 From: Bastien DUMONT <bdumont@grandlyon.com> Date: Wed, 7 Dec 2022 09:04:12 +0100 Subject: [PATCH] publish: Merge branch 'fix/issue-contract-less-than-6-month' into 'main' generated from commit 803e69ec16b806652f7155fb2279d14ee540cb84 --- index.js | 19950 ++----------------------------------------- manifest.konnector | 2 +- onDeleteAccount.js | 13388 +---------------------------- package.json | 4 +- 4 files changed, 686 insertions(+), 32658 deletions(-) diff --git a/index.js b/index.js index a876db4..ff91813 100644 --- a/index.js +++ b/index.js @@ -15,7 +15,7 @@ const soapRequest = __webpack_require__(1337) const moment = __webpack_require__(1379) __webpack_require__(1516) const xml2js = __webpack_require__(1519) -const { buildAggregatedData } = __webpack_require__(1560) +const { buildAgregatedData } = __webpack_require__(1560) const { parseSgeXmlData, formateDataForDoctype, @@ -39,13 +39,9 @@ const { verifyContract, terminateContract, getContractStartDate, -} = __webpack_require__(1681) -const { getAccount, saveAccountData } = __webpack_require__(1691) -const { isLocal, isDev } = __webpack_require__(1692) -const Sentry = __webpack_require__(1601) -// eslint-disable-next-line -const Tracing = __webpack_require__(1693) // Needed for tracking performance in Sentry -const { version } = __webpack_require__(1730) +} = __webpack_require__(1601) +const { getAccount, saveAccountData } = __webpack_require__(1611) +const { isLocal } = __webpack_require__(1612) moment.locale('fr') // set the language moment.tz.setDefault('Europe/Paris') // set the timezone @@ -64,26 +60,6 @@ const ACCOUNT_ID = isLocal() ? 'default_account_id' : 'enedissgegrandlyon' module.exports = new BaseKonnector(start) -/** - * Sentry - */ -Sentry.init({ - dsn: - 'https://18747a93401447f2a81b83cd8c4bbbdf@grandlyon.errors.cozycloud.cc/5', - - // Set tracesSampleRate to 1.0 to capture 100% - // of transactions for performance monitoring. - // We recommend adjusting this value in production - tracesSampleRate: 1.0, - release: version, - environment: isDev() ? 'development' : 'production', - debug: isDev(), - integrations: [ - // enable HTTP calls tracing - new Sentry.Integrations.Http({ tracing: true }), - ], -}) - /** * The start function is run by the BaseKonnector instance only when it got all the account * information (fields). When you run this connector yourself in "standalone" mode or "dev" mode, @@ -95,11 +71,7 @@ Sentry.init({ */ async function start(fields, cozyParameters) { log('info', 'Konnector configuration ...') - log('info', `isManual execution: ${manualExecution}`) - const transaction = Sentry.startTransaction({ - op: 'konnector', - name: 'SGE Konnector', - }) + log('info', `isManual exectuion: ${manualExecution}`) const pointId = parseInt(fields.pointId) let baseUrl = fields.wso2BaseUrl @@ -127,9 +99,7 @@ async function start(fields, cozyParameters) { !boToken || !boBaseUrl ) { - const errorMessage = 'Missing configuration secrets' - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `Missing configuration secrets`) throw errors.VENDOR_DOWN } @@ -145,7 +115,6 @@ async function start(fields, cozyParameters) { if (isFirstStart(await getAccount(ACCOUNT_ID))) { log('info', 'First start...') - transaction.startChild({ op: 'First start' }) const user = await verifyUserIdentity(fields, baseUrl, apiAuthKey, sgeLogin) let consent = await createBoConsent( @@ -161,15 +130,15 @@ async function start(fields, cozyParameters) { user.hasBeenThroughtSafetyOnBoarding ) - // handle user contract start date in order to properly request data - const userContractStartDate = await getContractStartDate( + // handle user contract start date in order to preperly request data + const userContractstartDate = await getContractStartDate( baseUrl, apiAuthKey, sgeLogin, pointId ) - startDailyDate = moment(userContractStartDate, 'YYYY-MM-DD') + startDailyDate = moment(userContractstartDate, 'YYYY-MM-DD') startDailyDateString = startDailyDate.format('YYYY-MM-DD') const contractStartDate = moment().format('YYYY-MM-DD') @@ -211,10 +180,8 @@ async function start(fields, cozyParameters) { expirationDate: contractEndDate, inseeCode: user.inseeCode, }) - // firstStartTransaction.finish() } else { log('info', 'Alternate start...') - transaction.startChild({ op: 'Alternate start' }) const accountData = await getAccount(ACCOUNT_ID) const userConsent = await getBoConsent( boBaseUrl, @@ -231,9 +198,7 @@ async function start(fields, cozyParameters) { ) if (!userConsent) { - const errorMessage = 'No user consent found' - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', 'No user consent found') throw errors.VENDOR_DOWN } @@ -258,7 +223,6 @@ async function start(fields, cozyParameters) { ) } } - transaction.finish() log('info', 'Successfully logged in') await gatherData(baseUrl, apiAuthKey, sgeLogin, pointId) @@ -300,13 +264,10 @@ async function deleteConsent( ) await deleteBoConsent(boBaseUrl, boToken, userConsent.ID || 0) } else { - const errorMessage = `No service id retrieved from BO` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `No service id retrieved from BO`) throw errors.VENDOR_DOWN } if (isConsentExpired) { - Sentry.captureException('Consent expired') throw errors.USER_ACTION_NEEDED_OAUTH_OUTDATED } throw errors.TERMS_VERSION_MISMATCH @@ -321,14 +282,14 @@ async function deleteConsent( */ async function gatherData(baseUrl, apiAuthKey, sgeLogin, pointId) { log('info', 'Querying data...') - const userContractStartDate = await getContractStartDate( + const userContractstartDate = await getContractStartDate( baseUrl, apiAuthKey, sgeLogin, pointId ) - startDailyDate = moment(userContractStartDate, 'YYYY-MM-DD') + startDailyDate = moment(userContractstartDate, 'YYYY-MM-DD') startDailyDateString = startDailyDate.format('YYYY-MM-DD') await getData( @@ -424,7 +385,6 @@ async function getMaxPowerData(url, apiAuthKey, userLogin, pointId) { }).catch(err => { log('error', 'getMaxPowerData') log('error', err) - Sentry.captureException('getMaxPowerDate') return err }) @@ -479,7 +439,7 @@ async function getDataHalfHour(url, apiAuthKey, userLogin, pointId) { for (var i = 0; i < MAX_HISTO; i++) { log('info', 'launch process with history') - const incrementedStartDateString = moment(startLoadDate) + const increamentedStartDateString = moment(startLoadDate) .subtract(7 * i, 'day') .format('YYYY-MM-DD') const incrementedEndDateString = moment(endDate) @@ -492,7 +452,7 @@ async function getDataHalfHour(url, apiAuthKey, userLogin, pointId) { xml: consultationMesuresDetaillees( pointId, userLogin, - incrementedStartDateString, + increamentedStartDateString, incrementedEndDateString, 'COURBE', 'PA' @@ -500,7 +460,6 @@ async function getDataHalfHour(url, apiAuthKey, userLogin, pointId) { }).catch(err => { log('error', 'consultationMesuresDetaillees half-hour') log('error', err) - Sentry.captureException('consultationMesuresDetaillees half-hour') return err }) @@ -525,7 +484,6 @@ function processData(doctype = 'com.grandlyon.enedis.day') { return async (err, result) => { if (err) { log('error', err) - Sentry.captureException('error while processing daily data') throw err } // Return only needed part of info @@ -541,15 +499,16 @@ function processData(doctype = 'com.grandlyon.enedis.day') { log('info', 'Aggregate enedis daily data for month and year') if (doctype === 'com.grandlyon.enedis.day') { log('info', 'Aggregating...') - await aggregateMonthAndYearData(processedDailyData) + await agregateMonthAndYearData(processedDailyData) } } catch (e) { if (doctype === 'com.grandlyon.enedis.minute') { - const errorMessage = `No half-hour activated. Issue: ${result.Envelope.Body.Fault.faultstring}` - Sentry.captureMessage(errorMessage) - log('warn', errorMessage) + log( + 'warn', + `No half-hour activated. Issue: ${result.Envelope.Body.Fault.faultstring}` + ) } else { - log('warn', `Unknown error ${e}`) + log('warn', `Unkown error ${e}`) } } } @@ -572,9 +531,9 @@ async function storeData(data, doctype, filterKeys) { } /** - * Aggregate data from daily data to monthly and yearly data + * Agregate data from daily data to monthly and yearly data */ -async function aggregateMonthAndYearData(data) { +async function agregateMonthAndYearData(data) { // Sum year and month values into object with year or year-month as keys if (data && data.length > 0) { let monthData = {} @@ -587,21 +546,21 @@ async function aggregateMonthAndYearData(data) { ? (yearData[element.year] += element.load) : (yearData[element.year] = element.load) }) - // Aggregation for Month data - const aggregatedMonthData = await buildAggregatedData( + // Agregation for Month data + const agregatedMonthData = await buildAgregatedData( monthData, 'com.grandlyon.enedis.month' ) - await storeData(aggregatedMonthData, 'com.grandlyon.enedis.month', [ + await storeData(agregatedMonthData, 'com.grandlyon.enedis.month', [ 'year', 'month', ]) - // Aggregation for Year data - const aggregatedYearData = await buildAggregatedData( + // Agregation for Year data + const agregatedYearData = await buildAgregatedData( yearData, 'com.grandlyon.enedis.year' ) - await storeData(aggregatedYearData, 'com.grandlyon.enedis.year', ['year']) + await storeData(agregatedYearData, 'com.grandlyon.enedis.year', ['year']) } } @@ -148409,7 +148368,7 @@ const fs = __webpack_require__(149); const path = __webpack_require__(142); -let manifest = typeof {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos données de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"} === 'undefined' ? {} : {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos données de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"}; +let manifest = typeof {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos donnéees de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"} === 'undefined' ? {} : {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos donnéees de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"}; if (process.env.NODE_ENV !== undefined && process.env.NODE_ENV !== 'none' && process.env.NODE_ENV !== 'production') { try { @@ -223578,18 +223537,18 @@ const { log, cozyClient } = __webpack_require__(1) /** * Retrieve and remove old data for a specific doctype - * Return an Array of aggregated data + * Return an Array of agregated data */ -async function buildAggregatedData(data, doctype) { - let aggregatedData = [] +async function buildAgregatedData(data, doctype) { + let agregatedData = [] // eslint-disable-next-line no-unused-vars for (let [key, value] of Object.entries(data)) { const data = buildDataFromKey(doctype, key, value) const oldValue = await resetInProgressAggregatedData(data, doctype) data.load += oldValue - aggregatedData.push(data) + agregatedData.push(data) } - return aggregatedData + return agregatedData } /** @@ -223677,7 +223636,7 @@ async function resetInProgressAggregatedData(data, doctype) { } module.exports = { - buildAggregatedData, + buildAgregatedData, } @@ -223854,7 +223813,7 @@ function removeMultipleSpaces(str) { * @param {string} str * @returns {string} */ -function removeAddressNumber(str) { +function removeAddressnumber(str) { return str.replace(/\d+ |b |B |T |t |\d+/g, '') } @@ -223870,7 +223829,7 @@ module.exports = { parseUserPdl, parseValue, parseValueHalfHour, - removeAddressNumber, + removeAddressnumber, removeMultipleSpaces, } @@ -224215,7 +224174,6 @@ module.exports = { // @ts-check const { log, errors } = __webpack_require__(1) const { default: axios } = __webpack_require__(1564) -const Sentry = __webpack_require__(1601) /** * @param {number} pointID @@ -224264,9 +224222,7 @@ async function createBoConsent( ) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -224301,9 +224257,7 @@ async function updateBoConsent(url, token, consent, serviceId) { ) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -224323,9 +224277,7 @@ async function getBoConsent(url, token, boId) { const { data } = await axios.get(`${url}/consent/${boId}`, headers) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -224348,9 +224300,7 @@ async function deleteBoConsent(url, token, boId) { const { data } = await axios.delete(`${url}/consent/${boId}`, headers) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -228277,19344 +228227,743 @@ module.exports = function isAxiosError(payload) { /***/ }), /* 1601 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Hub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.Hub), -/* harmony export */ "SDK_VERSION": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_1__.SDK_VERSION), -/* harmony export */ "Scope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.Scope), -/* harmony export */ "addBreadcrumb": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.addBreadcrumb), -/* harmony export */ "addGlobalEventProcessor": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor), -/* harmony export */ "captureEvent": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureEvent), -/* harmony export */ "captureException": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureException), -/* harmony export */ "captureMessage": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureMessage), -/* harmony export */ "configureScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.configureScope), -/* harmony export */ "createTransport": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_4__.createTransport), -/* harmony export */ "getCurrentHub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getHubFromCarrier), -/* harmony export */ "makeMain": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.makeMain), -/* harmony export */ "setContext": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setContext), -/* harmony export */ "setExtra": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtra), -/* harmony export */ "setExtras": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtras), -/* harmony export */ "setTag": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTag), -/* harmony export */ "setTags": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTags), -/* harmony export */ "setUser": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setUser), -/* harmony export */ "startTransaction": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.startTransaction), -/* harmony export */ "withScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.withScope), -/* harmony export */ "NodeClient": () => (/* reexport safe */ _client_js__WEBPACK_IMPORTED_MODULE_5__.NodeClient), -/* harmony export */ "close": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.close), -/* harmony export */ "defaultIntegrations": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultStackParser), -/* harmony export */ "flush": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.flush), -/* harmony export */ "getSentryRelease": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.getSentryRelease), -/* harmony export */ "init": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.init), -/* harmony export */ "lastEventId": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.lastEventId), -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.addRequestDataToEvent), -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.extractRequestData), -/* harmony export */ "deepReadDirSync": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_9__.deepReadDirSync), -/* harmony export */ "Handlers": () => (/* reexport module object */ _handlers_js__WEBPACK_IMPORTED_MODULE_11__), -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _transports_http_js__WEBPACK_IMPORTED_MODULE_13__.makeNodeTransport), -/* harmony export */ "Integrations": () => (/* binding */ INTEGRATIONS) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1680); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1616); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1603); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1617); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1618); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1627); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1635); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1651); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1667); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1676); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1314); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _handlers_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1677); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1652); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1636); - - - - - - - - - - - - - -; -; - -; -; +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const INTEGRATIONS = { - ..._sentry_core__WEBPACK_IMPORTED_MODULE_14__, - ..._integrations_index_js__WEBPACK_IMPORTED_MODULE_12__, -}; +const { activateContract } = __webpack_require__(1602) +const { getContractStartDate } = __webpack_require__(1603) +const { terminateContract } = __webpack_require__(1604) +const { verifyContract } = __webpack_require__(1605) +const { findUserPdl } = __webpack_require__(1607) +const { verifyUserIdentity } = __webpack_require__(1608) +const { findUserAddress } = __webpack_require__(1610) -// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like -// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. -const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getMainCarrier)(); -if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain__WEBPACK_IMPORTED_MODULE_10__; +module.exports = { + activateContract, + getContractStartDate, + terminateContract, + verifyContract, + findUserPdl, + verifyUserIdentity, + findUserAddress, } -//# sourceMappingURL=index.js.map - - /***/ }), /* 1602 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "API_VERSION": () => (/* binding */ API_VERSION), -/* harmony export */ "Hub": () => (/* binding */ Hub), -/* harmony export */ "getCurrentHub": () => (/* binding */ getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* binding */ getHubFromCarrier), -/* harmony export */ "getMainCarrier": () => (/* binding */ getMainCarrier), -/* harmony export */ "makeMain": () => (/* binding */ makeMain), -/* harmony export */ "setHubOnCarrier": () => (/* binding */ setHubOnCarrier) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1606); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1607); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1603); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1604); - - - - -const NIL_EVENT_ID = '00000000000000000000000000000000'; - -/** - * API compatibility version of this hub. - * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. - * - * @hidden - */ -const API_VERSION = 4; - -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -const DEFAULT_BREADCRUMBS = 100; +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * A layer in the process stack. - * @hidden - */ +// @ts-check +const { log, errors } = __webpack_require__(1) +const soapRequest = __webpack_require__(1337) +const { parseTags, parseValue, parseServiceId } = __webpack_require__(1561) +const { commanderCollectePublicationMesures } = __webpack_require__(1562) +const xml2js = __webpack_require__(1519) /** - * @inheritDoc + * @param {string} url + * @param {string} apiAuthKey + * @param {string} appLogin + * @param {string} name + * @param {number} pointId + * @param {string} startDate + * @param {string} endDate + * @return {Promise<number>} User contractId */ -class Hub { - /** Is a {@link Layer}[] containing the client and scope */ - __init() {this._stack = [{}];} - - /** Contains the last event id of a captured event. */ - - /** - * 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. - */ - constructor(client, scope = new _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope(), _version = API_VERSION) {;this._version = _version;Hub.prototype.__init.call(this); - this.getStackTop().scope = scope; - if (client) { - this.bindClient(client); - } - } - - /** - * @inheritDoc - */ - isOlderThan(version) { - return this._version < version; - } - - /** - * @inheritDoc - */ - bindClient(client) { - const top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } - } - - /** - * @inheritDoc - */ - pushScope() { - // We want to clone the content of prev scope - const scope = _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope, - }); - return scope; - } - - /** - * @inheritDoc - */ - popScope() { - if (this.getStack().length <= 1) return false; - return !!this.getStack().pop(); - } - - /** - * @inheritDoc - */ - withScope(callback) { - const scope = this.pushScope(); - try { - callback(scope); - } finally { - this.popScope(); - } - } - - /** - * @inheritDoc - */ - getClient() { - return this.getStackTop().client ; - } - - /** Returns the scope of the top stack. */ - getScope() { - return this.getStackTop().scope; - } - - /** Returns the scope stack for domains or the process. */ - getStack() { - return this._stack; - } - - /** Returns the topmost scope layer in the order domain > local > process. */ - getStackTop() { - return this._stack[this._stack.length - 1]; - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint) { - const syntheticException = new Error('Sentry syntheticException'); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureException( - exception, - { - originalException: exception, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; - } - - /** - * @inheritDoc - */ - captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level, - hint, - ) { - const syntheticException = new Error(message); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureMessage( - message, - level, - { - originalException: message, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; - } - - /** - * @inheritDoc - */ - captureEvent(event, hint) { - const clientId = - this._withClient((client, scope) => { - return client.captureEvent(event, { ...hint }, scope); - }) || NIL_EVENT_ID; - - if (event.type !== 'transaction') { - this._lastEventId = clientId; - } - - return clientId; - } - - /** - * @inheritDoc - */ - lastEventId() { - return this._lastEventId; - } - - /** - * @inheritDoc - */ - addBreadcrumb(breadcrumb, hint) { - const { scope, client } = this.getStackTop(); - - if (!scope || !client) return; - - // eslint-disable-next-line @typescript-eslint/unbound-method - const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = - (client.getOptions && client.getOptions()) || {}; - - if (maxBreadcrumbs <= 0) return; - - const timestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dateTimestampInSeconds)(); - const mergedBreadcrumb = { timestamp, ...breadcrumb }; - const finalBreadcrumb = beforeBreadcrumb - ? ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) - : mergedBreadcrumb; - - if (finalBreadcrumb === null) return; - - scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); - } - - /** - * @inheritDoc - */ - setUser(user) { - const scope = this.getScope(); - if (scope) scope.setUser(user); - } - - /** - * @inheritDoc - */ - setTags(tags) { - const scope = this.getScope(); - if (scope) scope.setTags(tags); - } - - /** - * @inheritDoc - */ - setExtras(extras) { - const scope = this.getScope(); - if (scope) scope.setExtras(extras); - } - - /** - * @inheritDoc - */ - setTag(key, value) { - const scope = this.getScope(); - if (scope) scope.setTag(key, value); - } - - /** - * @inheritDoc - */ - setExtra(key, extra) { - const scope = this.getScope(); - if (scope) scope.setExtra(key, extra); +async function activateContract( + url, + apiAuthKey, + appLogin, + contractId, + name, + pointId, + startDate, + endDate +) { + log('info', 'activateContract') + const sgeHeaders = { + 'Content-Type': 'text/xml;charset=UTF-8', + apikey: apiAuthKey, } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setContext(name, context) { - const scope = this.getScope(); - if (scope) scope.setContext(name, context); - } + const { response } = await soapRequest({ + url: `${url}/enedis_SGE_CommandeCollectePublicationMesures/1.0`, + headers: sgeHeaders, + xml: commanderCollectePublicationMesures( + appLogin, + contractId, + pointId, + name, + startDate, + endDate + ), + }).catch(err => { + log('error', 'commanderCollectePublicationMesures') + log('error', err) + throw errors.LOGIN_FAILED + }) - /** - * @inheritDoc - */ - configureScope(callback) { - const { scope, client } = this.getStackTop(); - if (scope && client) { - callback(scope); - } - } + const parsedReply = await xml2js.parseStringPromise(response.body, { + tagNameProcessors: [parseTags], + valueProcessors: [parseValue], + explicitArray: false, + }) - /** - * @inheritDoc - */ - run(callback) { - const oldHub = makeMain(this); - try { - callback(this); - } finally { - makeMain(oldHub); + try { + return parseServiceId(parsedReply) + } catch (error) { + log('error', 'Error while activating contract: ' + error) + if (parsedReply.Envelope.Body.Fault) { + log( + 'error', + `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` + ) } + //TODO: handle SGT4B8: Il existe déjà plusieurs demandes en cours sur le point ? + throw errors.LOGIN_FAILED } +} - /** - * @inheritDoc - */ - getIntegration(integration) { - const client = this.getClient(); - if (!client) return null; - try { - return client.getIntegration(integration); - } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); - return null; - } - } +module.exports = { activateContract } - /** - * @inheritDoc - */ - startTransaction(context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - } - /** - * @inheritDoc - */ - traceHeaders() { - return this._callExtensionMethod('traceHeaders'); - } +/***/ }), +/* 1603 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /** - * @inheritDoc - */ - captureSession(endSession = false) { - // both send the update and pull the session from the scope - if (endSession) { - return this.endSession(); - } +// @ts-check +const { log, errors } = __webpack_require__(1) +const soapRequest = __webpack_require__(1337) +const { + parseTags, + parseValue, + parseContractStartDate, +} = __webpack_require__(1561) +const xml2js = __webpack_require__(1519) +const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1562) - // only send the update - this._sendSessionUpdate(); +/** + * Get user contract start date + * @param {string} url + * @param {string} apiAuthKey + * @param {string} userLogin + * @param {number} pointId + * @returns {Promise<string>} + */ +async function getContractStartDate(url, apiAuthKey, userLogin, pointId) { + log('info', 'Fetching data start date') + const sgeHeaders = { + 'Content-Type': 'text/xml;charset=UTF-8', + apikey: apiAuthKey, } - /** - * @inheritDoc - */ - endSession() { - const layer = this.getStackTop(); - const scope = layer && layer.scope; - const session = scope && scope.getSession(); - if (session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.closeSession)(session); - } - this._sendSessionUpdate(); + const { response } = await soapRequest({ + url: `${url}/enedis_SGE_ConsultationDonneesTechniquesContractuelles/1.0`, + headers: sgeHeaders, + xml: consulterDonneesTechniquesContractuelles(pointId, userLogin), + }).catch(err => { + log('error', 'Error while fetching contract start date : ' + err) + throw errors.VENDOR_DOWN + }) - // the session is over; take it off of the scope - if (scope) { - scope.setSession(); - } + const result = await xml2js.parseStringPromise(response.body, { + tagNameProcessors: [parseTags], + valueProcessors: [parseValue], + explicitArray: false, + }) + try { + return parseContractStartDate(result) + } catch (error) { + log('error', 'Error while processing contract start date: ' + error) + log( + 'error', + `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}` + ) + throw errors.NOT_EXISTING_DIRECTORY } +} - /** - * @inheritDoc - */ - startSession(context) { - const { scope, client } = this.getStackTop(); - const { release, environment } = (client && client.getOptions()) || {}; - - // Will fetch userAgent if called from browser sdk - const { userAgent } = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.navigator || {}; +module.exports = { getContractStartDate } - const session = (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.makeSession)({ - release, - environment, - ...(scope && { user: scope.getUser() }), - ...(userAgent && { userAgent }), - ...context, - }); - if (scope) { - // End existing session if there's one - const currentSession = scope.getSession && scope.getSession(); - if (currentSession && currentSession.status === 'ok') { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.updateSession)(currentSession, { status: 'exited' }); - } - this.endSession(); +/***/ }), +/* 1604 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - // Afterwards we set the new session on the scope - scope.setSession(session); - } +// @ts-check +const { log, errors } = __webpack_require__(1) +const soapRequest = __webpack_require__(1337) +const { parseTags, parseValue } = __webpack_require__(1561) +const { commanderArretServiceSouscritMesures } = __webpack_require__(1562) +const xml2js = __webpack_require__(1519) - return session; +/** + * @param {string} url + * @param {string} apiAuthKey + * @param {string} appLogin + * @param {number} pointId + * @param {number} serviceId + * @return {Promise<string>} User contractId + */ +async function terminateContract( + url, + apiAuthKey, + appLogin, + contractId, + pointId, + serviceId +) { + log('info', 'terminateContract') + const sgeHeaders = { + 'Content-Type': 'text/xml;charset=UTF-8', + apikey: apiAuthKey, } - /** - * Returns if default PII should be sent to Sentry and propagated in ourgoing requests - * when Tracing is used. - */ - shouldSendDefaultPii() { - const client = this.getClient(); - const options = client && client.getOptions(); - return Boolean(options && options.sendDefaultPii); - } + const { response } = await soapRequest({ + url: `${url}/enedis_SGE_CommandeArretServiceSouscritMesures/1.0`, + headers: sgeHeaders, + xml: commanderArretServiceSouscritMesures( + appLogin, + contractId, + pointId, + serviceId + ), + }).catch(err => { + log('error', 'commanderArretServiceSouscritMesures') + log('error', err) + throw errors.VENDOR_DOWN + }) - /** - * Sends the current Session on the scope - */ - _sendSessionUpdate() { - const { scope, client } = this.getStackTop(); - if (!scope) return; + const parsedReply = await xml2js.parseStringPromise(response.body, { + tagNameProcessors: [parseTags], + valueProcessors: [parseValue], + explicitArray: false, + }) - const session = scope.getSession(); - if (session) { - if (client && client.captureSession) { - client.captureSession(session); - } + try { + // We don't need any action on reply for now + if (parsedReply.Envelope.Body.Fault) { + log( + 'error', + `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` + ) } + return parsedReply + } catch (error) { + log('error', 'Error while parsing user contract termination: ' + error) + log('error', `Enedis issue ${JSON.stringify(parsedReply.Envelope.Body)}`) + throw errors.VENDOR_DOWN } +} - /** - * 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. - */ - _withClient(callback) { - const { scope, client } = this.getStackTop(); - return client && callback(client, scope); - } +module.exports = { terminateContract } - /** - * 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 - _callExtensionMethod(method, ...args) { - const carrier = getMainCarrier(); - const sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); - } -} -/** - * Returns the global shim registry. - * - * FIXME: This function is problematic, because despite always returning a valid Carrier, - * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check - * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. - **/ -function getMainCarrier() { - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ; -} +/***/ }), +/* 1605 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - const registry = getMainCarrier(); - const oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; -} +// @ts-check +const { log, errors } = __webpack_require__(1) +const soapRequest = __webpack_require__(1337) +const { + parseTags, + parseValue, + parseContracts, + checkContractExists, +} = __webpack_require__(1561) +const { rechercherServicesSouscritsMesures } = __webpack_require__(1562) +const xml2js = __webpack_require__(1519) +const { contractState } = __webpack_require__(1606) /** - * 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. + * @param {string} url + * @param {string} apiAuthKey + * @param {string} appLogin + * @param {number} pointId + * @return {Promise<number | null>} User contractId */ -function getCurrentHub() { - // Get main carrier (global for every environment) - const registry = getMainCarrier(); - - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) { - setHubOnCarrier(registry, new Hub()); +async function verifyContract(url, apiAuthKey, appLogin, contractId, pointId) { + log('info', 'verifyContract') + const sgeHeaders = { + 'Content-Type': 'text/xml;charset=UTF-8', + apikey: apiAuthKey, } - // Prefer domains over global if they are there (applicable only to Node environment) - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isNodeEnv)()) { - return getHubFromActiveDomain(registry); - } - // Return hub that lives on a global object - return getHubFromCarrier(registry); -} + const { response } = await soapRequest({ + url: `${url}/enedis_SGE_RechercheServicesMesures/1.0`, + headers: sgeHeaders, + xml: rechercherServicesSouscritsMesures(appLogin, contractId, pointId), + }).catch(err => { + log('error', 'rechercherServicesSouscritsMesures') + log('error', err) + throw errors.LOGIN_FAILED + }) -/** - * 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 { - const sentry = getMainCarrier().__SENTRY__; - const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; + const parsedReply = await xml2js.parseStringPromise(response.body, { + tagNameProcessors: [parseTags], + valueProcessors: [parseValue], + explicitArray: false, + }) - // If there's no active domain, just return global hub - if (!activeDomain) { - return getHubFromCarrier(registry); + try { + if (!checkContractExists(parsedReply)) { + log('error', 'no contract found') + return null } - // If there's no hub on current domain, or it's an old API, assign a new one - if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) { - const registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(registryHubTopStack.scope))); + const currentContracts = parseContracts(parsedReply) + let currentContract = null + if (Array.isArray(currentContracts)) { + currentContract = parseContracts(parsedReply)[0] + } else { + currentContract = currentContracts } - - // Return hub that lives on a domain - return getHubFromCarrier(activeDomain); - } catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); + if ( + currentContract.etatCode === contractState.ACTIF || + currentContract.etatCode === contractState.DEMANDE + ) + return currentContract.serviceSouscritId + return null + } catch (error) { + log('error', 'Error while parsing user contract: ' + error) + if (parsedReply.Envelope.Body.Fault) { + log( + 'error', + `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` + ) + } + log( + 'error', + 'if an error is thrown here, it probably means that the contract has already been open today and that enedis cannot open a second one. Wait until tomorow to try again' + ) + throw errors.LOGIN_FAILED } } -/** - * 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); -} +module.exports = { verifyContract } -/** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object - * @hidden - */ -function getHubFromCarrier(carrier) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.getGlobalSingleton)('hub', () => new Hub(), carrier); -} + +/***/ }), +/* 1606 */ +/***/ ((module) => { /** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - * @returns A boolean indicating success or failure + * Enum for contract-state values. + * @readonly + * @enum {number} */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) return false; - const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); - __SENTRY__.hub = hub; - return true; +const contractState = { + TERMINE: 'TERMINE', + ACTIF: 'ACTIF', + DEMANDE: 'DEMANDE', } - -//# sourceMappingURL=hub.js.map +module.exports = { contractState } /***/ }), -/* 1603 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Scope": () => (/* binding */ Scope), -/* harmony export */ "addGlobalEventProcessor": () => (/* binding */ addGlobalEventProcessor) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1606); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1604); - - +/* 1607 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Default value for maximum number of breadcrumbs added to an event. - */ -const DEFAULT_MAX_BREADCRUMBS = 100; +// @ts-check +const { log, errors } = __webpack_require__(1) +const soapRequest = __webpack_require__(1337) +const { parseUserPdl, parseTags, parseValue } = __webpack_require__(1561) +const { rechercherPoint } = __webpack_require__(1562) +const xml2js = __webpack_require__(1519) /** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. + * @param {string} url + * @param {string} apiAuthKey + * @param {string} appLogin + * @param {string} name + * @param {string} address + * @param {string} postalCode + * @param {string} inseeCode + * @return {Promise<string | null>} User Pdl */ -class Scope { - /** Flag if notifying is happening. */ - - /** Callback for client to receive scope changes. */ - - /** Callback list that will be called after {@link applyToEvent}. */ - - /** Array of breadcrumbs. */ - - /** User */ - - /** Tags */ - - /** Extra */ - - /** Contexts */ - - /** Attachments */ - - /** - * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get - * sent to Sentry - */ - - /** Fingerprint */ - - /** Severity */ - // eslint-disable-next-line deprecation/deprecation - - /** Transaction Name */ - - /** Span */ - - /** Session */ - - /** Request Mode Session Status */ - - // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. - - constructor() { - this._notifyingListeners = false; - this._scopeListeners = []; - this._eventProcessors = []; - this._breadcrumbs = []; - this._attachments = []; - this._user = {}; - this._tags = {}; - this._extra = {}; - this._contexts = {}; - this._sdkProcessingMetadata = {}; - } - - /** - * Inherit values from the parent scope. - * @param scope to clone. - */ - static clone(scope) { - const newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = [...scope._breadcrumbs]; - newScope._tags = { ...scope._tags }; - newScope._extra = { ...scope._extra }; - newScope._contexts = { ...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 = [...scope._eventProcessors]; - newScope._requestSession = scope._requestSession; - newScope._attachments = [...scope._attachments]; - newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata }; - } - return newScope; +async function findUserPdl( + url, + apiAuthKey, + appLogin, + name, + address, + postalCode, + inseeCode, + escalierEtEtageEtAppartement = '' +) { + log('info', 'Fetching user pdl') + const sgeHeaders = { + 'Content-Type': 'text/xml;charset=UTF-8', + apikey: apiAuthKey, } - /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden - */ - addScopeListener(callback) { - this._scopeListeners.push(callback); - } + const { response } = await soapRequest({ + url: url, + headers: sgeHeaders, + xml: rechercherPoint( + appLogin, + name, + postalCode, + inseeCode, + address, + escalierEtEtageEtAppartement + ), + }).catch(err => { + log('error', 'rechercherPointResponse') + log('error', err) + throw errors.LOGIN_FAILED + }) - /** - * @inheritDoc - */ - addEventProcessor(callback) { - this._eventProcessors.push(callback); - return this; - } + const parsedReply = await xml2js.parseStringPromise(response.body, { + tagNameProcessors: [parseTags], + valueProcessors: [parseValue], + explicitArray: false, + }) - /** - * @inheritDoc - */ - setUser(user) { - this._user = user || {}; - if (this._session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_0__.updateSession)(this._session, { user }); + try { + return parseUserPdl(parsedReply) + } catch (error) { + log('warn', 'Error while parsing user PDL: ' + error) + if (parsedReply.Envelope.Body.Fault) { + log( + 'warn', + `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` + ) } - this._notifyScopeListeners(); - return this; + return null } +} - /** - * @inheritDoc - */ - getUser() { - return this._user; - } +module.exports = { findUserPdl } - /** - * @inheritDoc - */ - getRequestSession() { - return this._requestSession; - } - /** - * @inheritDoc - */ - setRequestSession(requestSession) { - this._requestSession = requestSession; - return this; - } +/***/ }), +/* 1608 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /** - * @inheritDoc - */ - setTags(tags) { - this._tags = { - ...this._tags, - ...tags, - }; - this._notifyScopeListeners(); - return this; - } +// @ts-check +const { log, errors } = __webpack_require__(1) +const { findUserPdl } = __webpack_require__(1607) +const { getInseeCode } = __webpack_require__(1609) +const { findUserAddress } = __webpack_require__(1610) +const { + removeMultipleSpaces, + removeAddressnumber, +} = __webpack_require__(1561) - /** - * @inheritDoc - */ - setTag(key, value) { - this._tags = { ...this._tags, [key]: value }; - this._notifyScopeListeners(); - return this; +/** + * Verify user identity + * @param {object} fields + * @param {string} baseUrl + * @param {string} apiAuthKey + * @param {string} loginUtilisateur + * @param {boolean} isAlternateStart + * @returns {Promise<User>} + */ +async function verifyUserIdentity( + fields, + baseUrl, + apiAuthKey, + loginUtilisateur, + isAlternateStart = false, + inseeCode = '' +) { + // If first start get InseeCode + log('debug', 'verifyUserIdentity') + if (!isAlternateStart) { + inseeCode = await getInseeCode(fields.postalCode, fields.city) } - /** - * @inheritDoc - */ - setExtras(extras) { - this._extra = { - ...this._extra, - ...extras, - }; - this._notifyScopeListeners(); - return this; - } + // Store if user is going through safety sge onboarding + let userSafetyOnBoarding = false - /** - * @inheritDoc - */ - setExtra(key, extra) { - this._extra = { ...this._extra, [key]: extra }; - this._notifyScopeListeners(); - return this; - } + // First try with user adresse + let pdl = await findUserPdl( + `${baseUrl}/enedis_SDE_recherche-point/1.0`, + apiAuthKey, + loginUtilisateur, + fields.lastname, + fields.address, + fields.postalCode, + inseeCode + ) - /** - * @inheritDoc - */ - setFingerprint(fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; - } + if (!pdl) { + log('warn', 'Second chance for sge onboarding') + // Set safety onboarding in order to save it inside BO + userSafetyOnBoarding = true + // Backup verification + const userAddress = await findUserAddress( + baseUrl, + apiAuthKey, + loginUtilisateur, + fields.pointId + ) - /** - * @inheritDoc - */ - setLevel( - // eslint-disable-next-line deprecation/deprecation - level, - ) { - this._level = level; - this._notifyScopeListeners(); - return this; - } + const escalierEtEtageEtAppartement = userAddress.escalierEtEtageEtAppartement + ? removeMultipleSpaces(userAddress.escalierEtEtageEtAppartement) + : '' - /** - * @inheritDoc - */ - setTransactionName(name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; - } + pdl = await findUserPdl( + `${baseUrl}/enedis_SDE_recherche-point/1.0`, + apiAuthKey, + loginUtilisateur, + fields.lastname, + removeMultipleSpaces(userAddress.numeroEtNomVoie), + userAddress.codePostal, + userAddress.commune.$.code, + escalierEtEtageEtAppartement + ) - /** - * @inheritDoc - */ - setContext(key, context) { - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } else { - this._contexts[key] = context; + // Third try, remove address number because it's buggy on SGE side + if (!pdl) { + log('warn', 'Third chance onboarding for sge') + pdl = await findUserPdl( + `${baseUrl}/enedis_SDE_recherche-point/1.0`, + apiAuthKey, + loginUtilisateur, + fields.lastname, + removeMultipleSpaces(removeAddressnumber(userAddress.numeroEtNomVoie)), + userAddress.codePostal, + userAddress.commune.$.code + ) } - - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setSpan(span) { - this._span = span; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - getSpan() { - return this._span; - } - - /** - * @inheritDoc - */ - getTransaction() { - // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will - // have a pointer to the currently-active transaction. - const span = this.getSpan(); - return span && span.transaction; - } - - /** - * @inheritDoc - */ - setSession(session) { - if (!session) { - delete this._session; - } else { - this._session = session; + // Third try, remove address number and add escalierEtEtageEtAppartement because it's buggy on SGE side + if (!pdl) { + log('warn', 'Last chance onboarding for sge') + pdl = await findUserPdl( + `${baseUrl}/enedis_SDE_recherche-point/1.0`, + apiAuthKey, + loginUtilisateur, + fields.lastname, + removeMultipleSpaces(removeAddressnumber(userAddress.numeroEtNomVoie)), + userAddress.codePostal, + userAddress.commune.$.code, + escalierEtEtageEtAppartement + ) } - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - getSession() { - return this._session; } - /** - * @inheritDoc - */ - update(captureContext) { - if (!captureContext) { - return this; - } - - if (typeof captureContext === 'function') { - const updatedScope = (captureContext )(this); - return updatedScope instanceof Scope ? updatedScope : this; - } + if (fields.pointId != pdl) { + log('error', 'PointId does not match') - if (captureContext instanceof Scope) { - this._tags = { ...this._tags, ...captureContext._tags }; - this._extra = { ...this._extra, ...captureContext._extra }; - this._contexts = { ...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; - } - if (captureContext._requestSession) { - this._requestSession = captureContext._requestSession; - } - } else if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext ; - this._tags = { ...this._tags, ...captureContext.tags }; - this._extra = { ...this._extra, ...captureContext.extra }; - this._contexts = { ...this._contexts, ...captureContext.contexts }; - if (captureContext.user) { - this._user = captureContext.user; - } - if (captureContext.level) { - this._level = captureContext.level; - } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; - } - if (captureContext.requestSession) { - this._requestSession = captureContext.requestSession; - } + if (isAlternateStart) { + throw errors.TERMS_VERSION_MISMATCH + } else { + throw errors.LOGIN_FAILED } - - return this; } - /** - * @inheritDoc - */ - clear() { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._requestSession = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - this._attachments = []; - return this; + return { + lastname: fields.lastname, + firstname: fields.firstname, + pointId: fields.pointId, + inseeCode, + postalCode: fields.postalCode, + address: fields.address, + hasBeenThroughtSafetyOnBoarding: userSafetyOnBoarding, + city: fields.city, } +} - /** - * @inheritDoc - */ - addBreadcrumb(breadcrumb, maxBreadcrumbs) { - const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; - - // No data has been changed, so don't notify scope listeners - if (maxCrumbs <= 0) { - return this; - } +module.exports = { verifyUserIdentity } - const mergedBreadcrumb = { - timestamp: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dateTimestampInSeconds)(), - ...breadcrumb, - }; - this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs); - this._notifyScopeListeners(); - return this; - } +/***/ }), +/* 1609 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /** - * @inheritDoc - */ - clearBreadcrumbs() { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; - } +// @ts-check +const { default: axios } = __webpack_require__(1564) +const { log, errors } = __webpack_require__(1) - /** - * @inheritDoc - */ - addAttachment(attachment) { - this._attachments.push(attachment); - return this; - } +const API_URL = 'https://apicarto.ign.fr/api/codes-postaux/communes' - /** - * @inheritDoc - */ - getAttachments() { - return this._attachments; - } +/** + * Return inseeCode given a postalCode + * @param {string} postalCode + * @param {string} [city] + * @return {Promise<string>} inseeCode + */ +async function getInseeCode(postalCode, city) { + try { + log('info', `Query getInseeCode for postalCode ${postalCode} / ${city}`) + const response = await axios.get(`${API_URL}/${postalCode}`) - /** - * @inheritDoc - */ - clearAttachments() { - this._attachments = []; - return this; - } + if (response.data.length === 1) { + return response.data[0].codeCommune + } else { + if (!city) throw errors.USER_ACTION_NEEDED - /** - * Applies data from the scope to the event and runs all event processors on it. - * - * @param event Event - * @param hint Object containing additional information about the original exception, for use by the event processors. - * @hidden - */ - applyToEvent(event, hint = {}) { - if (this._extra && Object.keys(this._extra).length) { - event.extra = { ...this._extra, ...event.extra }; - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = { ...this._tags, ...event.tags }; - } - if (this._user && Object.keys(this._user).length) { - event.user = { ...this._user, ...event.user }; - } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = { ...this._contexts, ...event.contexts }; - } - if (this._level) { - event.level = this._level; - } - if (this._transactionName) { - event.transaction = this._transactionName; + const filteredResponse = response.data.filter( + town => town.nomCommune.toLowerCase() === city.toLowerCase() + ) + return filteredResponse[0].codeCommune } + } catch (error) { + log( + 'error', + `Query getInseeCode failed for postalCode ${postalCode} / ${city}` + ) + throw errors.USER_ACTION_NEEDED + } +} - // We want to set the trace context for normal events only if there isn't already - // a trace context on the event. There is a product feature in place where we link - // errors with transaction and it relies on that. - if (this._span) { - event.contexts = { trace: this._span.getTraceContext(), ...event.contexts }; - const transactionName = this._span.transaction && this._span.transaction.name; - if (transactionName) { - event.tags = { transaction: transactionName, ...event.tags }; - } - } +module.exports = { + getInseeCode, +} - this._applyFingerprint(event); - event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs]; - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; +/***/ }), +/* 1610 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata }; +// @ts-check +const { log, errors } = __webpack_require__(1) +const soapRequest = __webpack_require__(1337) +const { + parseTags, + parseValue, + parseUserAddress, +} = __webpack_require__(1561) +const xml2js = __webpack_require__(1519) +const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1562) - return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); +/** + * Get user contract start date + * @param {string} url + * @param {string} apiAuthKey + * @param {string} userLogin + * @param {number} pointId + * @returns {Promise<Address>} + */ +async function findUserAddress(url, apiAuthKey, userLogin, pointId) { + log('info', 'Fetching user address') + const sgeHeaders = { + 'Content-Type': 'text/xml;charset=UTF-8', + apikey: apiAuthKey, } - /** - * Add data which will be accessible during event processing but won't get sent to Sentry - */ - setSDKProcessingMetadata(newData) { - this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; + const { response } = await soapRequest({ + url: `${url}/enedis_SGE_ConsultationDonneesTechniquesContractuelles/1.0`, + headers: sgeHeaders, + xml: consulterDonneesTechniquesContractuelles(pointId, userLogin, false), + }).catch(err => { + log('error', 'Error while fetching user : ' + err) + throw errors.VENDOR_DOWN + }) - return this; + const result = await xml2js.parseStringPromise(response.body, { + tagNameProcessors: [parseTags], + valueProcessors: [parseValue], + explicitArray: false, + }) + + try { + return parseUserAddress(result) + } catch (error) { + log('error', 'Error while processing user address: ' + error) + log( + 'error', + `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}` + ) + throw errors.LOGIN_FAILED } +} - /** - * This will be called after {@link applyToEvent} is finished. - */ - _notifyEventProcessors( - processors, - event, - hint, - index = 0, - ) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.SyncPromise((resolve, reject) => { - const processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } else { - const result = processor({ ...event }, hint) ; +module.exports = { findUserAddress } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - processor.id && - result === null && - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.log(`Event processor "${processor.id}" dropped event`); - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isThenable)(result)) { - void result - .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) - .then(null, reject); - } else { - void this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } - } - }); - } +/***/ }), +/* 1611 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /** - * This will be called on every set call. - */ - _notifyScopeListeners() { - // 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(callback => { - callback(this); - }); - this._notifyingListeners = false; - } - } +const { log, updateOrCreate } = __webpack_require__(1) +const { isLocal } = __webpack_require__(1612) +const cozyClient = __webpack_require__(485) - /** - * 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 - */ - _applyFingerprint(event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.arrayify)(event.fingerprint) : []; +async function saveAccountData(accountId, accountData) { + log('info', `saveAccountData: ${accountId}`) - // If we have something on the scope, then merge it with event - if (this._fingerprint) { - event.fingerprint = event.fingerprint.concat(this._fingerprint); - } + let account = await getAccount(accountId) + log('info', `saveAccountData account: ${JSON.stringify(account)}`) + log( + 'info', + `saveAccountData account: ${JSON.stringify({ + ...account, + data: accountData, + })}` + ) - // If we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; - } - } + log( + 'info', + `saveAccountData account after id: ${JSON.stringify({ + ...account, + data: accountData, + })}` + ) + account = await updateOrCreate( + [{ ...account, data: accountData }], + 'io.cozy.accounts', + ['account_type'] + ) + log('info', `saveAccountData account reply: ${JSON.stringify(account)}`) + return account } /** - * Returns the global event processors. + * Return account + * @param {string} accountId + * @returns {Account} */ -function getGlobalEventProcessors() { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.getGlobalSingleton)('globalEventProcessors', () => []); +async function getAccount(accountId) { + log('info', `getAccount: ${accountId}`) + const accounts = await cozyClient.data.findAll('io.cozy.accounts') + return accounts.filter(account => + isLocal() ? account._id === accountId : account.account_type === accountId + )[0] } -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); -} +async function getAccountForDelete(accountId, accountRev) { + log('info', `getAccountForDelete: ${accountId} ${accountRev}`) + const body = await cozyClient.fetchJSON( + 'GET', + `/data/io.cozy.accounts/${accountId}?rev=${accountRev}` + ) + log('debug', `getAccountForDelete: ${body}`) + return body +} -//# sourceMappingURL=scope.js.map +module.exports = { getAccount, saveAccountData, getAccountForDelete } /***/ }), -/* 1604 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "closeSession": () => (/* binding */ closeSession), -/* harmony export */ "makeSession": () => (/* binding */ makeSession), -/* harmony export */ "updateSession": () => (/* binding */ updateSession) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); - - -/** - * Creates a new `Session` object by setting certain default parameters. If optional @param context - * is passed, the passed properties are applied to the session object. - * - * @param context (optional) additional properties to be applied to the returned session object - * - * @returns a new `Session` object - */ -function makeSession(context) { - // Both timestamp and started are in seconds since the UNIX epoch. - const startingTime = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); - - const session = { - sid: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(), - init: true, - timestamp: startingTime, - started: startingTime, - duration: 0, - status: 'ok', - errors: 0, - ignoreDuration: false, - toJSON: () => sessionToJSON(session), - }; - - if (context) { - updateSession(session, context); - } +/* 1612 */ +/***/ ((module) => { - return session; +function isLocal() { + return ( + process.env.NODE_ENV === 'development' || + process.env.NODE_ENV === 'local' || + process.env.NODE_ENV === 'standalone' + ) } /** - * Updates a session object with the properties passed in the context. - * - * Note that this function mutates the passed object and returns void. - * (Had to do this instead of returning a new and updated session because closing and sending a session - * makes an update to the session after it was passed to the sending logic. - * @see BaseClient.captureSession ) - * - * @param session the `Session` to update - * @param context the `SessionContext` holding the properties that should be updated in @param session + * Verify if it's an alpha URL + * @returns {boolean} */ -// eslint-disable-next-line complexity -function updateSession(session, context = {}) { - if (context.user) { - if (!session.ipAddress && context.user.ip_address) { - session.ipAddress = context.user.ip_address; - } +function isDev() { + return ( + process.env.COZY_URL.includes('alpha') || + process.env.COZY_URL.includes('cozy.tools') + ) +} - if (!session.did && !context.did) { - session.did = context.user.id || context.user.email || context.user.username; - } - } +module.exports = { isLocal, isDev } - session.timestamp = context.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); - - if (context.ignoreDuration) { - session.ignoreDuration = context.ignoreDuration; - } - if (context.sid) { - // Good enough uuid validation. — Kamil - session.sid = context.sid.length === 32 ? context.sid : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(); - } - if (context.init !== undefined) { - session.init = context.init; - } - if (!session.did && context.did) { - session.did = `${context.did}`; - } - if (typeof context.started === 'number') { - session.started = context.started; - } - if (session.ignoreDuration) { - session.duration = undefined; - } else if (typeof context.duration === 'number') { - session.duration = context.duration; - } else { - const duration = session.timestamp - session.started; - session.duration = duration >= 0 ? duration : 0; - } - if (context.release) { - session.release = context.release; - } - if (context.environment) { - session.environment = context.environment; - } - if (!session.ipAddress && context.ipAddress) { - session.ipAddress = context.ipAddress; - } - if (!session.userAgent && context.userAgent) { - session.userAgent = context.userAgent; - } - if (typeof context.errors === 'number') { - session.errors = context.errors; - } - if (context.status) { - session.status = context.status; - } -} - -/** - * Closes a session by setting its status and updating the session object with it. - * Internally calls `updateSession` to update the passed session object. - * - * Note that this function mutates the passed session (@see updateSession for explanation). - * - * @param session the `Session` object to be closed - * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, - * this function will keep the previously set status, unless it was `'ok'` in which case - * it is changed to `'exited'`. - */ -function closeSession(session, status) { - let context = {}; - if (status) { - context = { status }; - } else if (session.status === 'ok') { - context = { status: 'exited' }; - } - - updateSession(session, context); -} - -/** - * Serializes a passed session object to a JSON object with a slightly different structure. - * This is necessary because the Sentry backend requires a slightly different schema of a session - * than the one the JS SDKs use internally. - * - * @param session the session to be converted - * - * @returns a JSON object of the passed session - */ -function sessionToJSON(session) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ - sid: `${session.sid}`, - init: session.init, - // Make sure that sec is converted to ms for date constructor - started: new Date(session.started * 1000).toISOString(), - timestamp: new Date(session.timestamp * 1000).toISOString(), - status: session.status, - errors: session.errors, - did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, - duration: session.duration, - attrs: { - release: session.release, - environment: session.environment, - ip_address: session.ipAddress, - user_agent: session.userAgent, - }, - }); -} - - -//# sourceMappingURL=session.js.map - - -/***/ }), -/* 1605 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_browserPerformanceTimeOriginMode": () => (/* binding */ _browserPerformanceTimeOriginMode), -/* harmony export */ "browserPerformanceTimeOrigin": () => (/* binding */ browserPerformanceTimeOrigin), -/* harmony export */ "dateTimestampInSeconds": () => (/* binding */ dateTimestampInSeconds), -/* harmony export */ "timestampInSeconds": () => (/* binding */ timestampInSeconds), -/* harmony export */ "timestampWithMs": () => (/* binding */ timestampWithMs), -/* harmony export */ "usingPerformanceAPI": () => (/* binding */ usingPerformanceAPI) -/* harmony export */ }); -/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1607); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); -/* module decorator */ module = __webpack_require__.hmd(module); - - - -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - -/** - * An object that can return the current timestamp in seconds since the UNIX epoch. - */ - -/** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. - * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". - */ -const dateTimestampSource = { - nowSeconds: () => Date.now() / 1000, -}; - -/** - * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} - * for accessing a high-resolution monotonic clock. - */ - -/** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. - */ -function getBrowserPerformance() { - const { performance } = WINDOW; - if (!performance || !performance.now) { - return undefined; - } - - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - const timeOrigin = Date.now() - performance.now(); - - return { - now: () => performance.now(), - timeOrigin, - }; -} - -/** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. - */ -function getNodePerformance() { - try { - const perfHooks = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.dynamicRequire)(module, 'perf_hooks') ; - return perfHooks.performance; - } catch (_) { - return undefined; - } -} - -/** - * The Performance API implementation for the current platform, if available. - */ -const platformPerformance = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.isNodeEnv)() ? getNodePerformance() : getBrowserPerformance(); - -const timestampSource = - platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000, - }; - -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. - */ -const dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); - -/** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. - */ -const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); - -// Re-exported with an old name for backwards-compatibility. -const timestampWithMs = timestampInSeconds; - -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -const usingPerformanceAPI = platformPerformance !== undefined; - -/** - * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. - */ -let _browserPerformanceTimeOriginMode; - -/** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. - */ -const browserPerformanceTimeOrigin = (() => { - // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or - // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin - // data as reliable if they are within a reasonable threshold of the current time. - - const { performance } = WINDOW; - if (!performance || !performance.now) { - _browserPerformanceTimeOriginMode = 'none'; - return undefined; - } - - const threshold = 3600 * 1000; - const performanceNow = performance.now(); - const dateNow = Date.now(); - - // if timeOrigin isn't available set delta to threshold so it isn't used - const timeOriginDelta = performance.timeOrigin - ? Math.abs(performance.timeOrigin + performanceNow - dateNow) - : threshold; - const timeOriginIsReliable = timeOriginDelta < threshold; - - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - const navigationStart = performance.timing && performance.timing.navigationStart; - const hasNavigationStart = typeof navigationStart === 'number'; - // if navigationStart isn't available set delta to threshold so it isn't used - const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; - const navigationStartIsReliable = navigationStartDelta < threshold; - - if (timeOriginIsReliable || navigationStartIsReliable) { - // Use the more reliable time origin - if (timeOriginDelta <= navigationStartDelta) { - _browserPerformanceTimeOriginMode = 'timeOrigin'; - return performance.timeOrigin; - } else { - _browserPerformanceTimeOriginMode = 'navigationStart'; - return navigationStart; - } - } - - // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. - _browserPerformanceTimeOriginMode = 'dateNow'; - return dateNow; -})(); - - -//# sourceMappingURL=time.js.map - - -/***/ }), -/* 1606 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "GLOBAL_OBJ": () => (/* binding */ GLOBAL_OBJ), -/* harmony export */ "getGlobalObject": () => (/* binding */ getGlobalObject), -/* harmony export */ "getGlobalSingleton": () => (/* binding */ getGlobalSingleton) -/* harmony export */ }); -/** Internal global with common properties and Sentry extensions */ - -// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification -// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js -// core-js has the following licence: -// -// Copyright (c) 2014-2022 Denis Pushkarev -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -/** Returns 'obj' if it's the global object, otherwise returns undefined */ -function isGlobalObj(obj) { - return obj && obj.Math == Math ? obj : undefined; -} - -/** Get's the global object for the current JavaScript runtime */ -const GLOBAL_OBJ = - (typeof globalThis == 'object' && isGlobalObj(globalThis)) || - // eslint-disable-next-line no-restricted-globals - (typeof window == 'object' && isGlobalObj(window)) || - (typeof self == 'object' && isGlobalObj(self)) || - (typeof global == 'object' && isGlobalObj(global)) || - (function () { - return this; - })() || - {}; - -/** - * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 - */ -function getGlobalObject() { - return GLOBAL_OBJ ; -} - -/** - * Returns a global singleton contained in the global `__SENTRY__` object. - * - * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory - * function and added to the `__SENTRY__` object. - * - * @param name name of the global singleton on __SENTRY__ - * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` - * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value - * @returns the singleton - */ -function getGlobalSingleton(name, creator, obj) { - const gbl = (obj || GLOBAL_OBJ) ; - const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); - const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); - return singleton; -} - - -//# sourceMappingURL=worldwide.js.map - - -/***/ }), -/* 1607 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dynamicRequire": () => (/* binding */ dynamicRequire), -/* harmony export */ "isNodeEnv": () => (/* binding */ isNodeEnv), -/* harmony export */ "loadModule": () => (/* binding */ loadModule) -/* harmony export */ }); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1608); -/* module decorator */ module = __webpack_require__.hmd(module); - - -/** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. - */ - -/** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question - */ -function isNodeEnv() { - // explicitly check for browser bundles as those can be optimized statically - // by terser/rollup. - return ( - !(0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isBrowserBundle)() && - Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' - ); -} - -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); -} - -/** - * Helper for dynamically loading module that should work with linked dependencies. - * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` - * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during - * build time. `require.resolve` is also not available in any other way, so we cannot create, - * a fake helper like we do with `dynamicRequire`. - * - * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. - * That is to mimic the behavior of `require.resolve` exactly. - * - * @param moduleName module name to require - * @returns possibly required module - */ -function loadModule(moduleName) { - let mod; - - try { - mod = dynamicRequire(module, moduleName); - } catch (e) { - // no-empty - } - - try { - const { cwd } = dynamicRequire(module, 'process'); - mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ; - } catch (e) { - // no-empty - } - - return mod; -} - - -//# sourceMappingURL=node.js.map - - -/***/ }), -/* 1608 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isBrowserBundle": () => (/* binding */ isBrowserBundle) -/* harmony export */ }); -/* - * This module exists for optimizations in the build process through rollup and terser. We define some global - * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these - * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will - * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to - * `logger` and preventing node-related code from appearing in browser bundles. - * - * Attention: - * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by - * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack) - * having issues tree-shaking these constants across package boundaries. - * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want - * users to be able to shake away expressions that it guards. - */ - -/** - * Figures out if we're building a browser bundle. - * - * @returns true if this is a browser bundle build. - */ -function isBrowserBundle() { - return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; -} - - -//# sourceMappingURL=env.js.map - - -/***/ }), -/* 1609 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addContextToFrame": () => (/* binding */ addContextToFrame), -/* harmony export */ "addExceptionMechanism": () => (/* binding */ addExceptionMechanism), -/* harmony export */ "addExceptionTypeValue": () => (/* binding */ addExceptionTypeValue), -/* harmony export */ "arrayify": () => (/* binding */ arrayify), -/* harmony export */ "checkOrSetAlreadyCaught": () => (/* binding */ checkOrSetAlreadyCaught), -/* harmony export */ "getEventDescription": () => (/* binding */ getEventDescription), -/* harmony export */ "parseSemver": () => (/* binding */ parseSemver), -/* harmony export */ "uuid4": () => (/* binding */ uuid4) -/* harmony export */ }); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - - - -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -function uuid4() { - const gbl = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; - const crypto = gbl.crypto || gbl.msCrypto; - - if (crypto && crypto.randomUUID) { - return crypto.randomUUID().replace(/-/g, ''); - } - - const getRandomByte = - crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16; - - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - // Concatenating the following numbers as strings results in '10000000100040008000100000000000' - return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => - // eslint-disable-next-line no-bitwise - ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), - ); -} - -function getFirstException(event) { - return event.exception && event.exception.values ? event.exception.values[0] : undefined; -} - -/** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description - */ -function getEventDescription(event) { - const { message, event_id: eventId } = event; - if (message) { - return message; - } - - const firstException = getFirstException(event); - if (firstException) { - if (firstException.type && firstException.value) { - return `${firstException.type}: ${firstException.value}`; - } - return firstException.type || firstException.value || eventId || '<unknown>'; - } - return eventId || '<unknown>'; -} - -/** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden - */ -function addExceptionTypeValue(event, value, type) { - const exception = (event.exception = event.exception || {}); - const values = (exception.values = exception.values || []); - const firstException = (values[0] = values[0] || {}); - if (!firstException.value) { - firstException.value = value || ''; - } - if (!firstException.type) { - firstException.type = type || 'Error'; - } -} - -/** - * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. - * - * @param event The event to modify. - * @param newMechanism Mechanism data to add to the event. - * @hidden - */ -function addExceptionMechanism(event, newMechanism) { - const firstException = getFirstException(event); - if (!firstException) { - return; - } - - const defaultMechanism = { type: 'generic', handled: true }; - const currentMechanism = firstException.mechanism; - firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; - - if (newMechanism && 'data' in newMechanism) { - const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; - firstException.mechanism.data = mergedData; - } -} - -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -const SEMVER_REGEXP = - /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; - -/** - * Represents Semantic Versioning object - */ - -/** - * Parses input into a SemVer interface - * @param input string representation of a semver version - */ -function parseSemver(input) { - const match = input.match(SEMVER_REGEXP) || []; - const major = parseInt(match[1], 10); - const minor = parseInt(match[2], 10); - const patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; -} - -/** - * This function adds context (pre/post/line) lines to the provided frame - * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post - */ -function addContextToFrame(lines, frame, linesOfContext = 5) { - const lineno = frame.lineno || 0; - const maxLines = lines.length; - const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); - - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); - - frame.context_line = (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); - - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); -} - -/** - * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object - * in question), and marks it captured if not. - * - * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and - * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so - * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because - * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not - * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This - * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we - * see it. - * - * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on - * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent - * object wrapper forms so that this check will always work. However, because we need to flag the exact object which - * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification - * must be done before the exception captured. - * - * @param A thrown exception to check or flag as having been seen - * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) - */ -function checkOrSetAlreadyCaught(exception) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (exception && (exception ).__sentry_captured__) { - return true; - } - - try { - // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the - // `ExtraErrorData` integration - (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.addNonEnumerableProperty)(exception , '__sentry_captured__', true); - } catch (err) { - // `exception` is a primitive, so we can't mark it seen - } - - return false; -} - -/** - * Checks whether the given input is already an array, and if it isn't, wraps it in one. - * - * @param maybeArray Input to turn into an array, if necessary - * @returns The input, if already an array, or an array with the input as the only element, if not - */ -function arrayify(maybeArray) { - return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; -} - - -//# sourceMappingURL=misc.js.map - - -/***/ }), -/* 1610 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "escapeStringForRegex": () => (/* binding */ escapeStringForRegex), -/* harmony export */ "isMatchingPattern": () => (/* binding */ isMatchingPattern), -/* harmony export */ "safeJoin": () => (/* binding */ safeJoin), -/* harmony export */ "snipLine": () => (/* binding */ snipLine), -/* harmony export */ "stringMatchesSomePattern": () => (/* binding */ stringMatchesSomePattern), -/* harmony export */ "truncate": () => (/* binding */ truncate) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); - - -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string (0 = unlimited) - * @returns string Encoded - */ -function truncate(str, max = 0) { - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : `${str.substr(0, max)}...`; -} - -/** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function snipLine(line, colno) { - let newLine = line; - const lineLength = newLine.length; - if (lineLength <= 150) { - return newLine; - } - if (colno > lineLength) { - // eslint-disable-next-line no-param-reassign - colno = lineLength; - } - - let start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } - - let end = Math.min(start + 140, lineLength); - if (end > lineLength - 5) { - end = lineLength; - } - if (end === lineLength) { - start = Math.max(end - 140, 0); - } - - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = `'{snip} ${newLine}`; - } - if (end < lineLength) { - newLine += ' {snip}'; - } - - return newLine; -} - -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; - } - - const output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < input.length; i++) { - const value = input[i]; - try { - output.push(String(value)); - } catch (e) { - output.push('[value cannot be serialized]'); - } - } - - return output.join(delimiter); -} - -/** - * Checks if the given value matches a regex or string - * - * @param value The string to test - * @param pattern Either a regex or a string against which `value` will be matched - * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match - * `pattern` if it contains `pattern`. Only applies to string-type patterns. - */ -function isMatchingPattern( - value, - pattern, - requireExactStringMatch = false, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(value)) { - return false; - } - - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern)) { - return pattern.test(value); - } - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(pattern)) { - return requireExactStringMatch ? value === pattern : value.includes(pattern); - } - - return false; -} - -/** - * Test the given string against an array of strings and regexes. By default, string matching is done on a - * substring-inclusion basis rather than a strict equality basis - * - * @param testString The string to test - * @param patterns The patterns against which to test the string - * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to - * count. If false, `testString` will match a string pattern if it contains that pattern. - * @returns - */ -function stringMatchesSomePattern( - testString, - patterns = [], - requireExactStringMatch = false, -) { - return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); -} - -/** - * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to - * `new RegExp()`. - * - * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime - * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node - * 12+). - * - * @param regexString The string to escape - * @returns An version of the string with all special regex characters escaped - */ -function escapeStringForRegex(regexString) { - // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems - // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. - return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); -} - - -//# sourceMappingURL=string.js.map - - -/***/ }), -/* 1611 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isDOMError": () => (/* binding */ isDOMError), -/* harmony export */ "isDOMException": () => (/* binding */ isDOMException), -/* harmony export */ "isElement": () => (/* binding */ isElement), -/* harmony export */ "isError": () => (/* binding */ isError), -/* harmony export */ "isErrorEvent": () => (/* binding */ isErrorEvent), -/* harmony export */ "isEvent": () => (/* binding */ isEvent), -/* harmony export */ "isInstanceOf": () => (/* binding */ isInstanceOf), -/* harmony export */ "isNaN": () => (/* binding */ isNaN), -/* harmony export */ "isPlainObject": () => (/* binding */ isPlainObject), -/* harmony export */ "isPrimitive": () => (/* binding */ isPrimitive), -/* harmony export */ "isRegExp": () => (/* binding */ isRegExp), -/* harmony export */ "isString": () => (/* binding */ isString), -/* harmony export */ "isSyntheticEvent": () => (/* binding */ isSyntheticEvent), -/* harmony export */ "isThenable": () => (/* binding */ isThenable) -/* harmony export */ }); -// eslint-disable-next-line @typescript-eslint/unbound-method -const objectToString = Object.prototype.toString; - -/** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (objectToString.call(wat)) { - case '[object Error]': - case '[object Exception]': - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); - } -} -/** - * Checks whether given value is an instance of the given built-in class. - * - * @param wat The value to be checked - * @param className - * @returns A boolean representing the result. - */ -function isBuiltin(wat, className) { - return objectToString.call(wat) === `[object ${className}]`; -} - -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isErrorEvent(wat) { - return isBuiltin(wat, 'ErrorEvent'); -} - -/** - * Checks whether given value's type is DOMError - * {@link isDOMError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return isBuiltin(wat, 'DOMError'); -} - -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMException(wat) { - return isBuiltin(wat, 'DOMException'); -} - -/** - * Checks whether given value's type is a string - * {@link isString}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return isBuiltin(wat, 'String'); -} - -/** - * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) - * {@link isPrimitive}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); -} - -/** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return isBuiltin(wat, 'Object'); -} - -/** - * Checks whether given value's type is an Event instance - * {@link isEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); -} - -/** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); -} - -/** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isRegExp(wat) { - return isBuiltin(wat, 'RegExp'); -} - -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); -} - -/** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; -} - -/** - * Checks whether given value is NaN - * {@link isNaN}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isNaN(wat) { - return typeof wat === 'number' && wat !== wat; -} - -/** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. - * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. - */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } catch (_e) { - return false; - } -} - - -//# sourceMappingURL=is.js.map - - -/***/ }), -/* 1612 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addNonEnumerableProperty": () => (/* binding */ addNonEnumerableProperty), -/* harmony export */ "convertToPlainObject": () => (/* binding */ convertToPlainObject), -/* harmony export */ "dropUndefinedKeys": () => (/* binding */ dropUndefinedKeys), -/* harmony export */ "extractExceptionKeysForMessage": () => (/* binding */ extractExceptionKeysForMessage), -/* harmony export */ "fill": () => (/* binding */ fill), -/* harmony export */ "getOriginalFunction": () => (/* binding */ getOriginalFunction), -/* harmony export */ "markFunctionWrapped": () => (/* binding */ markFunctionWrapped), -/* harmony export */ "objectify": () => (/* binding */ objectify), -/* harmony export */ "urlEncode": () => (/* binding */ urlEncode) -/* harmony export */ }); -/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1613); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1610); - - - - -/** - * Replace a method in an object with a wrapped version of itself. - * - * @param source An object that contains a method to be wrapped. - * @param name The name of the method to be wrapped. - * @param replacementFactory A higher-order function that takes the original version of the given method and returns a - * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to - * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other - * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. - * @returns void - */ -function fill(source, name, replacementFactory) { - if (!(name in source)) { - return; - } - - const original = source[name] ; - const wrapped = replacementFactory(original) ; - - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - markFunctionWrapped(wrapped, original); - } catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } - } - - source[name] = wrapped; -} - -/** - * Defines a non-enumerable property on the given object. - * - * @param obj The object on which to set the property - * @param name The name of the property to be set - * @param value The value to which to set the property - */ -function addNonEnumerableProperty(obj, name, value) { - Object.defineProperty(obj, name, { - // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it - value: value, - writable: true, - configurable: true, - }); -} - -/** - * Remembers the original function on the wrapped function and - * patches up the prototype. - * - * @param wrapped the wrapper function - * @param original the original function that gets wrapped - */ -function markFunctionWrapped(wrapped, original) { - const proto = original.prototype || {}; - wrapped.prototype = original.prototype = proto; - addNonEnumerableProperty(wrapped, '__sentry_original__', original); -} - -/** - * This extracts the original function if available. See - * `markFunctionWrapped` for more information. - * - * @param func the function to unwrap - * @returns the unwrapped version of the function if available. - */ -function getOriginalFunction(func) { - return func.__sentry_original__; -} - -/** - * Encodes given object into url-friendly format - * - * @param object An object that contains serializable values - * @returns string Encoded - */ -function urlEncode(object) { - return Object.keys(object) - .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) - .join('&'); -} - -/** - * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their - * non-enumerable properties attached. - * - * @param value Initial source that we have to transform in order for it to be usable by the serializer - * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor - * an Error. - */ -function convertToPlainObject( - value, -) - - { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isError)(value)) { - return { - message: value.message, - name: value.name, - stack: value.stack, - ...getOwnProperties(value), - }; - } else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isEvent)(value)) { - const newObj - - = { - type: value.type, - target: serializeEventTarget(value.target), - currentTarget: serializeEventTarget(value.currentTarget), - ...getOwnProperties(value), - }; - - if (typeof CustomEvent !== 'undefined' && (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isInstanceOf)(value, CustomEvent)) { - newObj.detail = value.detail; - } - - return newObj; - } else { - return value; - } -} - -/** Creates a string representation of the target of an `Event` object */ -function serializeEventTarget(target) { - try { - return (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? (0,_browser_js__WEBPACK_IMPORTED_MODULE_1__.htmlTreeAsString)(target) : Object.prototype.toString.call(target); - } catch (_oO) { - return '<unknown>'; - } -} - -/** Filters out all but an object's own properties */ -function getOwnProperties(obj) { - if (typeof obj === 'object' && obj !== null) { - const extractedProps = {}; - for (const property in obj) { - if (Object.prototype.hasOwnProperty.call(obj, property)) { - extractedProps[property] = (obj )[property]; - } - } - return extractedProps; - } else { - return {}; - } -} - -/** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` - */ -function extractExceptionKeysForMessage(exception, maxLength = 40) { - const keys = Object.keys(convertToPlainObject(exception)); - keys.sort(); - - if (!keys.length) { - return '[object has no keys]'; - } - - if (keys[0].length >= maxLength) { - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(keys[0], maxLength); - } - - for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { - const serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; - } - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(serialized, maxLength); - } - - return ''; -} - -/** - * Given any object, return a new object having removed all fields whose value was `undefined`. - * Works recursively on objects and arrays. - * - * Attention: This function keeps circular references in the returned object. - */ -function dropUndefinedKeys(inputValue) { - // This map keeps track of what already visited nodes map to. - // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular - // references as the input object. - const memoizationMap = new Map(); - - // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API - return _dropUndefinedKeys(inputValue, memoizationMap); -} - -function _dropUndefinedKeys(inputValue, memoizationMap) { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(inputValue)) { - // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } - - const returnValue = {}; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); - - for (const key of Object.keys(inputValue)) { - if (typeof inputValue[key] !== 'undefined') { - returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); - } - } - - return returnValue ; - } - - if (Array.isArray(inputValue)) { - // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } - - const returnValue = []; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); - - inputValue.forEach((item) => { - returnValue.push(_dropUndefinedKeys(item, memoizationMap)); - }); - - return returnValue ; - } - - return inputValue; -} - -/** - * Ensure that something is an object. - * - * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper - * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. - * - * @param wat The subject of the objectification - * @returns A version of `wat` which can safely be used with `Object` class methods - */ -function objectify(wat) { - let objectified; - switch (true) { - case wat === undefined || wat === null: - objectified = new String(wat); - break; - - // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason - // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as - // an object in order to wrap it. - case typeof wat === 'symbol' || typeof wat === 'bigint': - objectified = Object(wat); - break; - - // this will catch the remaining primitives: `String`, `Number`, and `Boolean` - case (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPrimitive)(wat): - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - objectified = new (wat ).constructor(wat); - break; - - // by process of elimination, at this point we know that `wat` must already be an object - default: - objectified = wat; - break; - } - return objectified; -} - - -//# sourceMappingURL=object.js.map - - -/***/ }), -/* 1613 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getDomElement": () => (/* binding */ getDomElement), -/* harmony export */ "getLocationHref": () => (/* binding */ getLocationHref), -/* harmony export */ "htmlTreeAsString": () => (/* binding */ htmlTreeAsString) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - - -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - -/** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path - */ -function htmlTreeAsString(elem, keyAttrs) { - - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - let currentElem = elem ; - const MAX_TRAVERSE_HEIGHT = 5; - const MAX_OUTPUT_LEN = 80; - const out = []; - let height = 0; - let len = 0; - const separator = ' > '; - const sepLength = separator.length; - let nextStr; - - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem, keyAttrs); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } - - out.push(nextStr); - - len += nextStr.length; - currentElem = currentElem.parentNode; - } - - return out.reverse().join(separator); - } catch (_oO) { - return '<unknown>'; - } -} - -/** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path - */ -function _htmlElementAsString(el, keyAttrs) { - const elem = el - -; - - const out = []; - let className; - let classes; - let key; - let attr; - let i; - - if (!elem || !elem.tagName) { - return ''; - } - - out.push(elem.tagName.toLowerCase()); - - // Pairs of attribute keys defined in `serializeAttribute` and their values on element. - const keyAttrPairs = - keyAttrs && keyAttrs.length - ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) - : null; - - if (keyAttrPairs && keyAttrPairs.length) { - keyAttrPairs.forEach(keyAttrPair => { - out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); - }); - } else { - if (elem.id) { - out.push(`#${elem.id}`); - } - - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push(`.${classes[i]}`); - } - } - } - const allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push(`[${key}="${attr}"]`); - } - } - return out.join(''); -} - -/** - * A safe form of location.href - */ -function getLocationHref() { - try { - return WINDOW.document.location.href; - } catch (oO) { - return ''; - } -} - -/** - * Gets a DOM element by using document.querySelector. - * - * This wrapper will first check for the existance of the function before - * actually calling it so that we don't have to take care of this check, - * every time we want to access the DOM. - * - * Reason: DOM/querySelector is not available in all environments. - * - * We have to cast to any because utils can be consumed by a variety of environments, - * and we don't want to break TS users. If you know what element will be selected by - * `document.querySelector`, specify it as part of the generic call. For example, - * `const element = getDomElement<Element>('selector');` - * - * @param selector the selector string passed on to document.querySelector - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getDomElement(selector) { - if (WINDOW.document && WINDOW.document.querySelector) { - return WINDOW.document.querySelector(selector) ; - } - return null; -} - - -//# sourceMappingURL=browser.js.map - - -/***/ }), -/* 1614 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SyncPromise": () => (/* binding */ SyncPromise), -/* harmony export */ "rejectedSyncPromise": () => (/* binding */ rejectedSyncPromise), -/* harmony export */ "resolvedSyncPromise": () => (/* binding */ resolvedSyncPromise) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); - - -/* eslint-disable @typescript-eslint/explicit-function-return-type */ - -/** SyncPromise internal states */ -var States; (function (States) { - /** Pending */ - const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; - /** Resolved / OK */ - const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; - /** Rejected / Error */ - const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; -})(States || (States = {})); - -// Overloads so we can call resolvedSyncPromise without arguments and generic argument - -/** - * Creates a resolved sync promise. - * - * @param value the value to resolve the promise with - * @returns the resolved sync promise - */ -function resolvedSyncPromise(value) { - return new SyncPromise(resolve => { - resolve(value); - }); -} - -/** - * Creates a rejected sync promise. - * - * @param value the value to reject the promise with - * @returns the rejected sync promise - */ -function rejectedSyncPromise(reason) { - return new SyncPromise((_, reject) => { - reject(reason); - }); -} - -/** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally - */ -class SyncPromise { - __init() {this._state = States.PENDING;} - __init2() {this._handlers = [];} - - constructor( - executor, - ) {;SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this); - try { - executor(this._resolve, this._reject); - } catch (e) { - this._reject(e); - } - } - - /** JSDoc */ - then( - onfulfilled, - onrejected, - ) { - return new SyncPromise((resolve, reject) => { - this._handlers.push([ - false, - result => { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result ); - } else { - try { - resolve(onfulfilled(result)); - } catch (e) { - reject(e); - } - } - }, - reason => { - if (!onrejected) { - reject(reason); - } else { - try { - resolve(onrejected(reason)); - } catch (e) { - reject(e); - } - } - }, - ]); - this._executeHandlers(); - }); - } - - /** JSDoc */ - catch( - onrejected, - ) { - return this.then(val => val, onrejected); - } - - /** JSDoc */ - finally(onfinally) { - return new SyncPromise((resolve, reject) => { - let val; - let isRejected; - - return this.then( - value => { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, - reason => { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }, - ).then(() => { - if (isRejected) { - reject(val); - return; - } - - resolve(val ); - }); - }); - } - - /** JSDoc */ - __init3() {this._resolve = (value) => { - this._setResult(States.RESOLVED, value); - };} - - /** JSDoc */ - __init4() {this._reject = (reason) => { - this._setResult(States.REJECTED, reason); - };} - - /** JSDoc */ - __init5() {this._setResult = (state, value) => { - if (this._state !== States.PENDING) { - return; - } - - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isThenable)(value)) { - void (value ).then(this._resolve, this._reject); - return; - } - - this._state = state; - this._value = value; - - this._executeHandlers(); - };} - - /** JSDoc */ - __init6() {this._executeHandlers = () => { - if (this._state === States.PENDING) { - return; - } - - const cachedHandlers = this._handlers.slice(); - this._handlers = []; - - cachedHandlers.forEach(handler => { - if (handler[0]) { - return; - } - - if (this._state === States.RESOLVED) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler[1](this._value ); - } - - if (this._state === States.REJECTED) { - handler[2](this._value); - } - - handler[0] = true; - }); - };} -} - - -//# sourceMappingURL=syncpromise.js.map - - -/***/ }), -/* 1615 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CONSOLE_LEVELS": () => (/* binding */ CONSOLE_LEVELS), -/* harmony export */ "consoleSandbox": () => (/* binding */ consoleSandbox), -/* harmony export */ "logger": () => (/* binding */ logger) -/* harmony export */ }); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - -/** Prefix for logging strings */ -const PREFIX = 'Sentry Logger '; - -const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ; - -/** - * Temporarily disable sentry console instrumentations. - * - * @param callback The function to run against the original `console` messages - * @returns The results of the callback - */ -function consoleSandbox(callback) { - if (!('console' in _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ)) { - return callback(); - } - - const originalConsole = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console ; - const wrappedLevels = {}; - - // Restore all wrapped console methods - CONSOLE_LEVELS.forEach(level => { - // TODO(v7): Remove this check as it's only needed for Node 6 - const originalWrappedFunc = - originalConsole[level] && (originalConsole[level] ).__sentry_original__; - if (level in originalConsole && originalWrappedFunc) { - wrappedLevels[level] = originalConsole[level] ; - originalConsole[level] = originalWrappedFunc ; - } - }); - - try { - return callback(); - } finally { - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(level => { - originalConsole[level] = wrappedLevels[level ]; - }); - } -} - -function makeLogger() { - let enabled = false; - const logger = { - enable: () => { - enabled = true; - }, - disable: () => { - enabled = false; - }, - }; - - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - CONSOLE_LEVELS.forEach(name => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - logger[name] = (...args) => { - if (enabled) { - consoleSandbox(() => { - _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); - }); - } - }; - }); - } else { - CONSOLE_LEVELS.forEach(name => { - logger[name] = () => undefined; - }); - } - - return logger ; -} - -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -let logger; -if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - logger = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalSingleton)('logger', makeLogger); -} else { - logger = makeLogger(); -} - - -//# sourceMappingURL=logger.js.map - - -/***/ }), -/* 1616 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SDK_VERSION": () => (/* binding */ SDK_VERSION) -/* harmony export */ }); -const SDK_VERSION = '7.23.0'; - - -//# sourceMappingURL=version.js.map - - -/***/ }), -/* 1617 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addBreadcrumb": () => (/* binding */ addBreadcrumb), -/* harmony export */ "captureEvent": () => (/* binding */ captureEvent), -/* harmony export */ "captureException": () => (/* binding */ captureException), -/* harmony export */ "captureMessage": () => (/* binding */ captureMessage), -/* harmony export */ "configureScope": () => (/* binding */ configureScope), -/* harmony export */ "setContext": () => (/* binding */ setContext), -/* harmony export */ "setExtra": () => (/* binding */ setExtra), -/* harmony export */ "setExtras": () => (/* binding */ setExtras), -/* harmony export */ "setTag": () => (/* binding */ setTag), -/* harmony export */ "setTags": () => (/* binding */ setTags), -/* harmony export */ "setUser": () => (/* binding */ setUser), -/* harmony export */ "startTransaction": () => (/* binding */ startTransaction), -/* harmony export */ "withScope": () => (/* binding */ withScope) -/* harmony export */ }); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); - - -// Note: All functions in this file are typed with a return value of `ReturnType<Hub[HUB_FUNCTION]>`, -// where HUB_FUNCTION is some method on the Hub class. -// -// This is done to make sure the top level SDK methods stay in sync with the hub methods. -// Although every method here has an explicit return type, some of them (that map to void returns) do not -// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable. - -/** - * Captures an exception event and sends it to Sentry. - * - * @param exception An exception-like object. - * @param captureContext Additional scope data to apply to exception event. - * @returns The generated eventId. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureException(exception, { captureContext }); -} - -/** - * Captures a message event and sends it to Sentry. - * - * @param message The message to send to Sentry. - * @param Severity Define the level of the message. - * @returns The generated eventId. - */ -function captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - captureContext, -) { - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - const level = typeof captureContext === 'string' ? captureContext : undefined; - const context = typeof captureContext !== 'string' ? { captureContext } : undefined; - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureMessage(message, level, context); -} - -/** - * 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, hint) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureEvent(event, hint); -} - -/** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. - */ -function configureScope(callback) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().configureScope(callback); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().addBreadcrumb(breadcrumb); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setContext(name, context); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtras(extras); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtra(key, extra); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTags(tags); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTag(key, value); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setUser(user); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().withScope(callback); -} - -/** - * 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. - * - * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call - * `startTransaction` directly on the hub. - * - * @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 (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().startTransaction({ ...context }, customSamplingContext); -} - - -//# sourceMappingURL=exports.js.map - - -/***/ }), -/* 1618 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_TRANSPORT_BUFFER_SIZE": () => (/* binding */ DEFAULT_TRANSPORT_BUFFER_SIZE), -/* harmony export */ "createTransport": () => (/* binding */ createTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1619); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1621); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1626); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1620); - - -const DEFAULT_TRANSPORT_BUFFER_SIZE = 30; - -/** - * Creates an instance of a Sentry `Transport` - * - * @param options - * @param makeRequest - */ -function createTransport( - options, - makeRequest, - buffer = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makePromiseBuffer)(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE), -) { - let rateLimits = {}; - - const flush = (timeout) => buffer.drain(timeout); - - function send(envelope) { - const filteredEnvelopeItems = []; - - // Drop rate limited items from envelope - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(envelope, (item, type) => { - const envelopeItemDataCategory = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type); - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.isRateLimited)(rateLimits, envelopeItemDataCategory)) { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event); - } else { - filteredEnvelopeItems.push(item); - } - }); - - // Skip sending if envelope is empty after filtering out rate limited events - if (filteredEnvelopeItems.length === 0) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const filteredEnvelope = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelope[0], filteredEnvelopeItems ); - - // Creates client report for each item in an envelope - const recordEnvelopeLoss = (reason) => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(filteredEnvelope, (item, type) => { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent(reason, (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type), event); - }); - }; - - const requestTask = () => - makeRequest({ body: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.serializeEnvelope)(filteredEnvelope, options.textEncoder) }).then( - response => { - // We don't want to throw on NOK responses, but we want to at least log them - if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); - } - - rateLimits = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.updateRateLimits)(rateLimits, response); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Failed while sending event:', error); - recordEnvelopeLoss('network_error'); - }, - ); - - return buffer.add(requestTask).then( - result => result, - error => { - if (error instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SentryError) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Skipped sending event because buffer is full.'); - recordEnvelopeLoss('queue_overflow'); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } else { - throw error; - } - }, - ); - } - - return { - send, - flush, - }; -} - -function getEventForEnvelopeItem(item, type) { - if (type !== 'event' && type !== 'transaction') { - return undefined; - } - - return Array.isArray(item) ? (item )[1] : undefined; -} - - -//# sourceMappingURL=base.js.map - - -/***/ }), -/* 1619 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makePromiseBuffer": () => (/* binding */ makePromiseBuffer) -/* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1620); -/* harmony import */ var _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); - - - -/** - * Creates an new PromiseBuffer object with the specified limit - * @param limit max number of promises that can be stored in the buffer - */ -function makePromiseBuffer(limit) { - const buffer = []; - - function isReady() { - return limit === undefined || buffer.length < limit; - } - - /** - * Remove a promise from the queue. - * - * @param task Can be any PromiseLike<T> - * @returns Removed promise. - */ - function remove(task) { - return buffer.splice(buffer.indexOf(task), 1)[0]; - } - - /** - * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. - * - * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: - * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor - * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By - * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer - * limit check. - * @returns The original promise. - */ - function add(taskProducer) { - if (!isReady()) { - return (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.rejectedSyncPromise)(new _error_js__WEBPACK_IMPORTED_MODULE_1__.SentryError('Not adding Promise because buffer limit was reached.')); - } - - // start the task and add its promise to the queue - const task = taskProducer(); - if (buffer.indexOf(task) === -1) { - buffer.push(task); - } - void task - .then(() => remove(task)) - // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` - // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't - // have promises, so TS has to polyfill when down-compiling.) - .then(null, () => - remove(task).then(null, () => { - // We have to add another catch here because `remove()` starts a new promise chain. - }), - ); - return task; - } - - /** - * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or - * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to - * `true`. - * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and - * `false` otherwise - */ - function drain(timeout) { - return new _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.SyncPromise((resolve, reject) => { - let counter = buffer.length; - - if (!counter) { - return resolve(true); - } - - // wait for `timeout` ms and then resolve to `false` (if not cancelled first) - const capturedSetTimeout = setTimeout(() => { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); - - // if all promises resolve in time, cancel the timer and resolve to `true` - buffer.forEach(item => { - void (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.resolvedSyncPromise)(item).then(() => { - if (!--counter) { - clearTimeout(capturedSetTimeout); - resolve(true); - } - }, reject); - }); - }); - } - - return { - $: buffer, - add, - drain, - }; -} - - -//# sourceMappingURL=promisebuffer.js.map - - -/***/ }), -/* 1620 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SentryError": () => (/* binding */ SentryError) -/* harmony export */ }); -/** An error emitted by Sentry SDKs and related utilities. */ -class SentryError extends Error { - /** Display name of this error instance. */ - - constructor( message, logLevel = 'warn') { - super(message);this.message = message;; - - this.name = new.target.prototype.constructor.name; - // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line - // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes - // instances of `SentryError` fail `obj instanceof SentryError` checks. - Object.setPrototypeOf(this, new.target.prototype); - this.logLevel = logLevel; - } -} - - -//# sourceMappingURL=error.js.map - - -/***/ }), -/* 1621 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addItemToEnvelope": () => (/* binding */ addItemToEnvelope), -/* harmony export */ "createAttachmentEnvelopeItem": () => (/* binding */ createAttachmentEnvelopeItem), -/* harmony export */ "createEnvelope": () => (/* binding */ createEnvelope), -/* harmony export */ "envelopeItemTypeToDataCategory": () => (/* binding */ envelopeItemTypeToDataCategory), -/* harmony export */ "forEachEnvelopeItem": () => (/* binding */ forEachEnvelopeItem), -/* harmony export */ "serializeEnvelope": () => (/* binding */ serializeEnvelope) -/* harmony export */ }); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1622); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); - - - -/** - * Creates an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. - */ -function createEnvelope(headers, items = []) { - return [headers, items] ; -} - -/** - * Add an item to an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. - */ -function addItemToEnvelope(envelope, newItem) { - const [headers, items] = envelope; - return [headers, [...items, newItem]] ; -} - -/** - * Convenience function to loop through the items and item types of an envelope. - * (This function was mostly created because working with envelope types is painful at the moment) - */ -function forEachEnvelopeItem( - envelope, - callback, -) { - const envelopeItems = envelope[1]; - envelopeItems.forEach((envelopeItem) => { - const envelopeItemType = envelopeItem[0].type; - callback(envelopeItem, envelopeItemType); - }); -} - -function encodeUTF8(input, textEncoder) { - const utf8 = textEncoder || new TextEncoder(); - return utf8.encode(input); -} - -/** - * Serializes an envelope. - */ -function serializeEnvelope(envelope, textEncoder) { - const [envHeaders, items] = envelope; - - // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data - let parts = JSON.stringify(envHeaders); - - function append(next) { - if (typeof parts === 'string') { - parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; - } else { - parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); - } - } - - for (const item of items) { - const [itemHeaders, payload] = item; - - append(`\n${JSON.stringify(itemHeaders)}\n`); - - if (typeof payload === 'string' || payload instanceof Uint8Array) { - append(payload); - } else { - let stringifiedPayload; - try { - stringifiedPayload = JSON.stringify(payload); - } catch (e) { - // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still - // fails, we try again after normalizing it again with infinite normalization depth. This of course has a - // performance impact but in this case a performance hit is better than throwing. - stringifiedPayload = JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_0__.normalize)(payload)); - } - append(stringifiedPayload); - } - } - - return typeof parts === 'string' ? parts : concatBuffers(parts); -} - -function concatBuffers(buffers) { - const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); - - const merged = new Uint8Array(totalLength); - let offset = 0; - for (const buffer of buffers) { - merged.set(buffer, offset); - offset += buffer.length; - } - - return merged; -} - -/** - * Creates attachment envelope items - */ -function createAttachmentEnvelopeItem( - attachment, - textEncoder, -) { - const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; - - return [ - (0,_object_js__WEBPACK_IMPORTED_MODULE_1__.dropUndefinedKeys)({ - type: 'attachment', - length: buffer.length, - filename: attachment.filename, - content_type: attachment.contentType, - attachment_type: attachment.attachmentType, - }), - buffer, - ]; -} - -const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { - session: 'session', - sessions: 'session', - attachment: 'attachment', - transaction: 'transaction', - event: 'error', - client_report: 'internal', - user_report: 'default', -}; - -/** - * Maps the type of an envelope item to a data category. - */ -function envelopeItemTypeToDataCategory(type) { - return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; -} - - -//# sourceMappingURL=envelope.js.map - - -/***/ }), -/* 1622 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "normalize": () => (/* binding */ normalize), -/* harmony export */ "normalizeToSize": () => (/* binding */ normalizeToSize), -/* harmony export */ "walk": () => (/* binding */ visit) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _memo_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1623); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); -/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1624); - - - - - -/** - * Recursively normalizes the given object. - * - * - Creates a copy to prevent original input mutation - * - Skips non-enumerable properties - * - When stringifying, calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format - * - Translates known global objects/classes to a string representations - * - Takes care of `Error` object serialization - * - Optionally limits depth of final output - * - Optionally limits number of properties/elements included in any single object/array - * - * @param input The object to be normalized. - * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) - * @param maxProperties The max number of elements or properties to be included in any single array or - * object in the normallized output. - * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function normalize(input, depth = +Infinity, maxProperties = +Infinity) { - try { - // since we're at the outermost level, we don't provide a key - return visit('', input, depth, maxProperties); - } catch (err) { - return { ERROR: `**non-serializable** (${err})` }; - } -} - -/** JSDoc */ -function normalizeToSize( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object, - // Default Node.js REPL depth - depth = 3, - // 100kB, as 200kB is max payload size, so half sounds reasonable - maxSize = 100 * 1024, -) { - const normalized = normalize(object, depth); - - if (jsonSize(normalized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } - - return normalized ; -} - -/** - * Visits a node to perform normalization on it - * - * @param key The key corresponding to the given node - * @param value The node to be visited - * @param depth Optional number indicating the maximum recursion depth - * @param maxProperties Optional maximum number of properties/elements included in any single object/array - * @param memo Optional Memo class handling decycling - */ -function visit( - key, - value, - depth = +Infinity, - maxProperties = +Infinity, - memo = (0,_memo_js__WEBPACK_IMPORTED_MODULE_0__.memoBuilder)(), -) { - const [memoize, unmemoize] = memo; - - // Get the simple cases out of the way first - if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isNaN)(value))) { - return value ; - } - - const stringified = stringifyValue(key, value); - - // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. - // Everything else will have already been serialized, so if we don't see that pattern, we're done. - if (!stringified.startsWith('[object ')) { - return stringified; - } - - // From here on, we can assert that `value` is either an object or an array. - - // Do not normalize objects that we know have already been normalized. As a general rule, the - // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that - // have already been normalized. - if ((value )['__sentry_skip_normalization__']) { - return value ; - } - - // We're also done if we've reached the max depth - if (depth === 0) { - // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. - return stringified.replace('object ', ''); - } - - // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. - if (memoize(value)) { - return '[Circular ~]'; - } - - // If the value has a `toJSON` method, we call it to extract more information - const valueWithToJSON = value ; - if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { - try { - const jsonValue = valueWithToJSON.toJSON(); - // We need to normalize the return value of `.toJSON()` in case it has circular references - return visit('', jsonValue, depth - 1, maxProperties, memo); - } catch (err) { - // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) - } - } - - // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse - // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each - // property/entry, and keep track of the number of items we add to it. - const normalized = (Array.isArray(value) ? [] : {}) ; - let numAdded = 0; - - // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant - // properties are non-enumerable and otherwise would get missed. - const visitable = (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.convertToPlainObject)(value ); - - for (const visitKey in visitable) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { - continue; - } - - if (numAdded >= maxProperties) { - normalized[visitKey] = '[MaxProperties ~]'; - break; - } - - // Recursively visit all the child nodes - const visitValue = visitable[visitKey]; - normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo); - - numAdded++; - } - - // Once we've visited all the branches, remove the parent from memo storage - unmemoize(value); - - // Return accumulated values - return normalized; -} - -/** - * Stringify the given value. Handles various known special values and types. - * - * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn - * the number 1231 into "[Object Number]", nor on `null`, as it will throw. - * - * @param value The value to stringify - * @returns A stringified representation of the given value - */ -function stringifyValue( - key, - // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for - // our internal use, it'll do - value, -) { - try { - if (key === 'domain' && value && typeof value === 'object' && (value )._events) { - return '[Domain]'; - } - - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } - - // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first - // which won't throw if they are not present. - - if (typeof global !== 'undefined' && value === global) { - return '[Global]'; - } - - // eslint-disable-next-line no-restricted-globals - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - - // eslint-disable-next-line no-restricted-globals - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } - - // React's SyntheticEvent thingy - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isSyntheticEvent)(value)) { - return '[SyntheticEvent]'; - } - - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } - - // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own) - if (value === void 0) { - return '[undefined]'; - } - - if (typeof value === 'function') { - return `[Function: ${(0,_stacktrace_js__WEBPACK_IMPORTED_MODULE_3__.getFunctionName)(value)}]`; - } - - if (typeof value === 'symbol') { - return `[${String(value)}]`; - } - - // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion - if (typeof value === 'bigint') { - return `[BigInt: ${String(value)}]`; - } - - // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting - // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as - // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), - // we can make sure that only plain objects come out that way. - return `[object ${(Object.getPrototypeOf(value) ).constructor.name}]`; - } catch (err) { - return `**non-serializable** (${err})`; - } -} - -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; -} - -/** Calculates bytes size of input object */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); -} - - -//# sourceMappingURL=normalize.js.map - - -/***/ }), -/* 1623 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "memoBuilder": () => (/* binding */ memoBuilder) -/* harmony export */ }); -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ - -/** - * Helper to decycle json objects - */ -function memoBuilder() { - const hasWeakSet = typeof WeakSet === 'function'; - const inner = hasWeakSet ? new WeakSet() : []; - function memoize(obj) { - if (hasWeakSet) { - if (inner.has(obj)) { - return true; - } - inner.add(obj); - return false; - } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < inner.length; i++) { - const value = inner[i]; - if (value === obj) { - return true; - } - } - inner.push(obj); - return false; - } - - function unmemoize(obj) { - if (hasWeakSet) { - inner.delete(obj); - } else { - for (let i = 0; i < inner.length; i++) { - if (inner[i] === obj) { - inner.splice(i, 1); - break; - } - } - } - } - return [memoize, unmemoize]; -} - - -//# sourceMappingURL=memo.js.map - - -/***/ }), -/* 1624 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createStackParser": () => (/* binding */ createStackParser), -/* harmony export */ "getFunctionName": () => (/* binding */ getFunctionName), -/* harmony export */ "nodeStackLineParser": () => (/* binding */ nodeStackLineParser), -/* harmony export */ "stackParserFromStackParserOptions": () => (/* binding */ stackParserFromStackParserOptions), -/* harmony export */ "stripSentryFramesAndReverse": () => (/* binding */ stripSentryFramesAndReverse) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1625); - - -const STACKTRACE_LIMIT = 50; - -/** - * Creates a stack parser with the supplied line parsers - * - * StackFrames are returned in the correct order for Sentry Exception - * frames and with Sentry SDK internal frames removed from the top and bottom - * - */ -function createStackParser(...parsers) { - const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); - - return (stack, skipFirst = 0) => { - const frames = []; - - for (const line of stack.split('\n').slice(skipFirst)) { - // https://github.com/getsentry/sentry-javascript/issues/5459 - // Remove webpack (error: *) wrappers - const cleanedLine = line.replace(/\(error: (.*)\)/, '$1'); - - for (const parser of sortedParsers) { - const frame = parser(cleanedLine); - - if (frame) { - frames.push(frame); - break; - } - } - } - - return stripSentryFramesAndReverse(frames); - }; -} - -/** - * Gets a stack parser implementation from Options.stackParser - * @see Options - * - * If options contains an array of line parsers, it is converted into a parser - */ -function stackParserFromStackParserOptions(stackParser) { - if (Array.isArray(stackParser)) { - return createStackParser(...stackParser); - } - return stackParser; -} - -/** - * @hidden - */ -function stripSentryFramesAndReverse(stack) { - if (!stack.length) { - return []; - } - - let localStack = stack; - - const firstFrameFunction = localStack[0].function || ''; - const lastFrameFunction = localStack[localStack.length - 1].function || ''; - - // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); - } - - // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) - if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { - localStack = localStack.slice(0, -1); - } - - // The frame where the crash happened, should be the last entry in the array - return localStack - .slice(0, STACKTRACE_LIMIT) - .map(frame => ({ - ...frame, - filename: frame.filename || localStack[0].filename, - function: frame.function || '?', - })) - .reverse(); -} - -const defaultFunctionName = '<anonymous>'; - -/** - * Safely extract function name from itself - */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } -} - -// eslint-disable-next-line complexity -function node(getModule) { - const FILENAME_MATCH = /^\s*[-]{4,}$/; - const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; - - // eslint-disable-next-line complexity - return (line) => { - if (line.match(FILENAME_MATCH)) { - return { - filename: line, - }; - } - - const lineMatch = line.match(FULL_MATCH); - if (!lineMatch) { - return undefined; - } - - let object; - let method; - let functionName; - let typeName; - let methodName; - - if (lineMatch[1]) { - functionName = lineMatch[1]; - - let methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') { - methodStart--; - } - - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - const objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } - } - typeName = undefined; - } - - if (method) { - typeName = object; - methodName = method; - } - - if (method === '<anonymous>') { - methodName = undefined; - functionName = undefined; - } - - if (functionName === undefined) { - methodName = methodName || '<anonymous>'; - functionName = typeName ? `${typeName}.${methodName}` : methodName; - } - - const filename = (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([lineMatch, 'access', _ => _[2], 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3('file://')]) ? lineMatch[2].substr(7) : lineMatch[2]; - const isNative = lineMatch[5] === 'native'; - const isInternal = - isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1); - - // in_app is all that's not an internal Node function or a module within node_modules - // note that isNative appears to return true even for node core libraries - // see https://github.com/getsentry/raven-node/issues/176 - const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/'); - - return { - filename, - module: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([getModule, 'optionalCall', _4 => _4(filename)]), - function: functionName, - lineno: parseInt(lineMatch[3], 10) || undefined, - colno: parseInt(lineMatch[4], 10) || undefined, - in_app, - }; - }; -} - -/** - * Node.js stack line parser - * - * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. - * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain - */ -function nodeStackLineParser(getModule) { - return [90, node(getModule)]; -} - - -//# sourceMappingURL=stacktrace.js.map - - -/***/ }), -/* 1625 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_optionalChain": () => (/* binding */ _optionalChain) -/* harmony export */ }); -/** - * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, - * descriptors, and functions. - * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) - * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 - * - * @param ops Array result of expression conversion - * @returns The value of the expression - */ -function _optionalChain(ops) { - let lastAccessLHS = undefined; - let value = ops[0]; - let i = 1; - while (i < ops.length) { - const op = ops[i] ; - const fn = ops[i + 1] ; - i += 2; - // by checking for loose equality to `null`, we catch both `null` and `undefined` - if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { - // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it - return; - } - if (op === 'access' || op === 'optionalAccess') { - lastAccessLHS = value; - value = fn(value); - } else if (op === 'call' || op === 'optionalCall') { - value = fn((...args) => (value ).call(lastAccessLHS, ...args)); - lastAccessLHS = undefined; - } - } - return value; -} - -// Sucrase version -// function _optionalChain(ops) { -// let lastAccessLHS = undefined; -// let value = ops[0]; -// let i = 1; -// while (i < ops.length) { -// const op = ops[i]; -// const fn = ops[i + 1]; -// i += 2; -// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { -// return undefined; -// } -// if (op === 'access' || op === 'optionalAccess') { -// lastAccessLHS = value; -// value = fn(value); -// } else if (op === 'call' || op === 'optionalCall') { -// value = fn((...args) => value.call(lastAccessLHS, ...args)); -// lastAccessLHS = undefined; -// } -// } -// return value; -// } - - -//# sourceMappingURL=_optionalChain.js.map - - -/***/ }), -/* 1626 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_RETRY_AFTER": () => (/* binding */ DEFAULT_RETRY_AFTER), -/* harmony export */ "disabledUntil": () => (/* binding */ disabledUntil), -/* harmony export */ "isRateLimited": () => (/* binding */ isRateLimited), -/* harmony export */ "parseRetryAfterHeader": () => (/* binding */ parseRetryAfterHeader), -/* harmony export */ "updateRateLimits": () => (/* binding */ updateRateLimits) -/* harmony export */ }); -// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend - -const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds - -/** - * Extracts Retry-After value from the request header or returns default value - * @param header string representation of 'Retry-After' header - * @param now current unix timestamp - * - */ -function parseRetryAfterHeader(header, now = Date.now()) { - const headerDelay = parseInt(`${header}`, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; - } - - const headerDate = Date.parse(`${header}`); - if (!isNaN(headerDate)) { - return headerDate - now; - } - - return DEFAULT_RETRY_AFTER; -} - -/** - * Gets the time that given category is disabled until for rate limiting - */ -function disabledUntil(limits, category) { - return limits[category] || limits.all || 0; -} - -/** - * Checks if a category is rate limited - */ -function isRateLimited(limits, category, now = Date.now()) { - return disabledUntil(limits, category) > now; -} - -/** - * Update ratelimits from incoming headers. - * Returns true if headers contains a non-empty rate limiting header. - */ -function updateRateLimits( - limits, - { statusCode, headers }, - now = Date.now(), -) { - const updatedRateLimits = { - ...limits, - }; - - // "The name is case-insensitive." - // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get - const rateLimitHeader = headers && headers['x-sentry-rate-limits']; - const retryAfterHeader = headers && headers['retry-after']; - - if (rateLimitHeader) { - /** - * rate limit headers are of the form - * <header>,<header>,.. - * where each <header> is of the form - * <retry_after>: <categories>: <scope>: <reason_code> - * where - * <retry_after> is a delay in seconds - * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form - * <category>;<category>;... - * <scope> is what's being limited (org, project, or key) - ignored by SDK - * <reason_code> is an arbitrary string like "org_quota" - ignored by SDK - */ - for (const limit of rateLimitHeader.trim().split(',')) { - const [retryAfter, categories] = limit.split(':', 2); - const headerDelay = parseInt(retryAfter, 10); - const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - if (!categories) { - updatedRateLimits.all = now + delay; - } else { - for (const category of categories.split(';')) { - updatedRateLimits[category] = now + delay; - } - } - } - } else if (retryAfterHeader) { - updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); - } else if (statusCode === 429) { - updatedRateLimits.all = now + 60 * 1000; - } - - return updatedRateLimits; -} - - -//# sourceMappingURL=ratelimit.js.map - - -/***/ }), -/* 1627 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "NodeClient": () => (/* binding */ NodeClient) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1629); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1616); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1634); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1614); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1628); - - - - - - - -/** - * The Sentry Node SDK Client. - * - * @see NodeClientOptions for documentation on configuration options. - * @see SentryClient for usage documentation. - */ -class NodeClient extends _sentry_core__WEBPACK_IMPORTED_MODULE_3__.BaseClient { - - /** - * Creates a new Node SDK instance. - * @param options Configuration options for this SDK. - */ - constructor(options) { - options._metadata = options._metadata || {}; - options._metadata.sdk = options._metadata.sdk || { - name: 'sentry.javascript.node', - packages: [ - { - name: 'npm:@sentry/node', - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }, - ], - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }; - - // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util - options.transportOptions = { - textEncoder: new util__WEBPACK_IMPORTED_MODULE_1__.TextEncoder(), - ...options.transportOptions, - }; - - super(options); - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const requestSession = scope.getRequestSession(); - - // Necessary checks to ensure this is code block is executed only within a request - // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - - return super.captureException(exception, hint, scope); - } - - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const eventType = event.type || 'exception'; - const isException = - eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; - - // If the event is of type Exception, then a request session should be captured - if (isException) { - const requestSession = scope.getRequestSession(); - - // Ensure that this is happening within the bounds of a request, and make sure not to override - // Session Status if Errored / Crashed - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - } - - return super.captureEvent(event, hint, scope); - } - - /** - * - * @inheritdoc - */ - close(timeout) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([this, 'access', _ => _._sessionFlusher, 'optionalAccess', _2 => _2.close, 'call', _3 => _3()]); - return super.close(timeout); - } - - /** Method that initialises an instance of SessionFlusher on Client */ - initSessionFlusher() { - const { release, environment } = this._options; - if (!release) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); - } else { - this._sessionFlusher = new _sentry_core__WEBPACK_IMPORTED_MODULE_7__.SessionFlusher(this, { - release, - environment, - }); - } - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - eventFromException(exception, hint) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)((0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromUnknownInput)(this._options.stackParser, exception, hint)); - } - - /** - * @inheritDoc - */ - eventFromMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - ) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)( - (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromMessage)(this._options.stackParser, message, level, hint, this._options.attachStacktrace), - ); - } - - /** - * @inheritDoc - */ - _prepareEvent(event, hint, scope) { - event.platform = event.platform || 'node'; - event.contexts = { - ...event.contexts, - runtime: (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _4 => _4.contexts, 'optionalAccess', _5 => _5.runtime]) || { - name: 'node', - version: global.process.version, - }, - }; - event.server_name = - event.server_name || this.getOptions().serverName || global.process.env.SENTRY_NAME || os__WEBPACK_IMPORTED_MODULE_0__.hostname(); - return super._prepareEvent(event, hint, scope); - } - - /** - * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment - * appropriate session aggregates bucket - */ - _captureRequestSession() { - if (!this._sessionFlusher) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); - } else { - this._sessionFlusher.incrementSessionStatusCount(); - } - } -} - - -//# sourceMappingURL=client.js.map - - -/***/ }), -/* 1628 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "eventFromMessage": () => (/* binding */ eventFromMessage), -/* harmony export */ "eventFromUnknownInput": () => (/* binding */ eventFromUnknownInput), -/* harmony export */ "exceptionFromError": () => (/* binding */ exceptionFromError), -/* harmony export */ "parseStackFrames": () => (/* binding */ parseStackFrames) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1622); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1609); - - - -/** - * Extracts stack frames from the error.stack string - */ -function parseStackFrames(stackParser, error) { - return stackParser(error.stack || '', 1); -} - -/** - * Extracts stack frames from the error and builds a Sentry Exception - */ -function exceptionFromError(stackParser, error) { - const exception = { - type: error.name || error.constructor.name, - value: error.message, - }; - - const frames = parseStackFrames(stackParser, error); - if (frames.length) { - exception.stacktrace = { frames }; - } - - return exception; -} - -/** - * Builds and Event from a Exception - * @hidden - */ -function eventFromUnknownInput(stackParser, exception, hint) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let ex = exception; - const providedMechanism = - hint && hint.data && (hint.data ).mechanism; - const mechanism = providedMechanism || { - handled: true, - type: 'generic', - }; - - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isError)(exception)) { - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.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 - const message = `Non-Error exception captured with keys: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractExceptionKeysForMessage)(exception)}`; - - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)(); - const client = hub.getClient(); - const normalizeDepth = client && client.getOptions().normalizeDepth; - hub.configureScope(scope => { - scope.setExtra('__serialized__', (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.normalizeToSize)(exception, normalizeDepth)); - }); - - 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; - } - - const event = { - exception: { - values: [exceptionFromError(stackParser, ex )], - }, - }; - - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionTypeValue)(event, undefined, undefined); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionMechanism)(event, mechanism); - - return { - ...event, - event_id: hint && hint.event_id, - }; -} - -/** - * Builds and Event from a Message - * @hidden - */ -function eventFromMessage( - stackParser, - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - attachStacktrace, -) { - const event = { - event_id: hint && hint.event_id, - level, - message, - }; - - if (attachStacktrace && hint && hint.syntheticException) { - const frames = parseStackFrames(stackParser, hint.syntheticException); - if (frames.length) { - event.exception = { - values: [ - { - value: message, - stacktrace: { frames }, - }, - ], - }; - } - } - - return event; -} - - -//# sourceMappingURL=eventbuilder.js.map - - -/***/ }), -/* 1629 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BaseClient": () => (/* binding */ BaseClient) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1630); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1614); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1621); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1622); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1610); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1620); -/* harmony import */ var _api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1631); -/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1633); -/* harmony import */ var _integration_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1632); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1603); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1604); - - - - - - - -const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; - -/** - * Base implementation for all JavaScript SDK clients. - * - * Call the constructor with the corresponding options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. - * - * 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, 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<NodeOptions> { - * public constructor(options: NodeOptions) { - * super(options); - * } - * - * // ... - * } - */ -class BaseClient { - /** Options passed to the SDK. */ - - /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ - - /** Array of set up integrations. */ - __init() {this._integrations = {};} - - /** Indicates whether this client's integrations have been set up. */ - __init2() {this._integrationsInitialized = false;} - - /** Number of calls being processed */ - __init3() {this._numProcessing = 0;} - - /** Holds flushable */ - __init4() {this._outcomes = {};} - - /** - * Initializes this client instance. - * - * @param options Options for the client. - */ - constructor(options) {;BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this); - this._options = options; - if (options.dsn) { - this._dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makeDsn)(options.dsn); - const url = (0,_api_js__WEBPACK_IMPORTED_MODULE_1__.getEnvelopeEndpointWithUrlEncodedAuth)(this._dsn, options); - this._transport = options.transport({ - recordDroppedEvent: this.recordDroppedEvent.bind(this), - ...options.transportOptions, - url, - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('No DSN provided, client will not do anything.'); - } - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // ensure we haven't captured this very object before - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(exception)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; - } - - let eventId; - this._process( - this.eventFromException(exception, hint) - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); - - return eventId; - } - - /** - * @inheritDoc - */ - captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level, - hint, - scope, - ) { - let eventId; - - const promisedEvent = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPrimitive)(message) - ? this.eventFromMessage(String(message), level, hint) - : this.eventFromException(message, hint); - - this._process( - promisedEvent - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); - - return eventId; - } - - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // ensure we haven't captured this very object before - if (hint && hint.originalException && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(hint.originalException)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; - } - - let eventId; - - this._process( - this._captureEvent(event, hint, scope).then(result => { - eventId = result; - }), - ); - - return eventId; - } - - /** - * @inheritDoc - */ - captureSession(session) { - if (!this._isEnabled()) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('SDK not enabled, will not capture session.'); - return; - } - - if (!(typeof session.release === 'string')) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('Discarded session because of missing or non-string release'); - } else { - this.sendSession(session); - // After sending, we set init false to indicate it's not the first occurrence - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { init: false }); - } - } - - /** - * @inheritDoc - */ - getDsn() { - return this._dsn; - } - - /** - * @inheritDoc - */ - getOptions() { - return this._options; - } - - /** - * @inheritDoc - */ - getTransport() { - return this._transport; - } - - /** - * @inheritDoc - */ - flush(timeout) { - const transport = this._transport; - if (transport) { - return this._isClientDoneProcessing(timeout).then(clientFinished => { - return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); - }); - } else { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(true); - } - } - - /** - * @inheritDoc - */ - close(timeout) { - return this.flush(timeout).then(result => { - this.getOptions().enabled = false; - return result; - }); - } - - /** - * Sets up the integrations - */ - setupIntegrations() { - if (this._isEnabled() && !this._integrationsInitialized) { - this._integrations = (0,_integration_js__WEBPACK_IMPORTED_MODULE_7__.setupIntegrations)(this._options.integrations); - this._integrationsInitialized = true; - } - } - - /** - * Gets an installed integration by its `id`. - * - * @returns The installed integration or `undefined` if no integration with that `id` was installed. - */ - getIntegrationById(integrationId) { - return this._integrations[integrationId]; - } - - /** - * @inheritDoc - */ - getIntegration(integration) { - try { - return (this._integrations[integration.id] ) || null; - } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); - return null; - } - } - - /** - * @inheritDoc - */ - sendEvent(event, hint = {}) { - if (this._dsn) { - let env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createEventEnvelope)(event, this._dsn, this._options._metadata, this._options.tunnel); - - for (const attachment of hint.attachments || []) { - env = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.addItemToEnvelope)( - env, - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.createAttachmentEnvelopeItem)( - attachment, - this._options.transportOptions && this._options.transportOptions.textEncoder, - ), - ); - } - - this._sendEnvelope(env); - } - } - - /** - * @inheritDoc - */ - sendSession(session) { - if (this._dsn) { - const env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createSessionEnvelope)(session, this._dsn, this._options._metadata, this._options.tunnel); - this._sendEnvelope(env); - } - } - - /** - * @inheritDoc - */ - recordDroppedEvent(reason, category, _event) { - // Note: we use `event` in replay, where we overwrite this hook. - - if (this._options.sendClientReports) { - // We want to track each category (error, transaction, session) separately - // but still keep the distinction between different type of outcomes. - // We could use nested maps, but it's much easier to read and type this way. - // A correct type for map-based implementation if we want to go that route - // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>` - // With typescript 4.1 we could even use template literal types - const key = `${reason}:${category}`; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(`Adding outcome: "${key}"`); - - // The following works because undefined + 1 === NaN and NaN is falsy - this._outcomes[key] = this._outcomes[key] + 1 || 1; - } - } - - /** Updates existing session based on the provided event */ - _updateSessionFromEvent(session, event) { - let crashed = false; - let errored = false; - const exceptions = event.exception && event.exception.values; - - if (exceptions) { - errored = true; - - for (const ex of exceptions) { - const mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } - } - } - - // A session is updated and that session update is sent in only one of the two following scenarios: - // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update - // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update - const sessionNonTerminal = session.status === 'ok'; - const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); - - if (shouldUpdateAndSend) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { - ...(crashed && { status: 'crashed' }), - errors: session.errors || Number(errored || crashed), - }); - this.captureSession(session); - } - } - - /** - * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying - * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not - * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to - * `true`. - * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and - * `false` otherwise - */ - _isClientDoneProcessing(timeout) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.SyncPromise(resolve => { - let ticked = 0; - const tick = 1; - - const interval = setInterval(() => { - if (this._numProcessing == 0) { - clearInterval(interval); - resolve(true); - } else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); - } - } - }, tick); - }); - } - - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - _isEnabled() { - 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. - */ - _prepareEvent(event, hint, scope) { - const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = this.getOptions(); - const prepared = { - ...event, - event_id: event.event_id || hint.event_id || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.uuid4)(), - timestamp: event.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.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. - let finalScope = scope; - if (hint.captureContext) { - finalScope = _scope_js__WEBPACK_IMPORTED_MODULE_11__.Scope.clone(finalScope).update(hint.captureContext); - } - - // We prepare the result here with a resolved Event. - let result = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(prepared); - - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - // - // We need to check for the existence of `finalScope.getAttachments` - // because `getAttachments` can be undefined if users are using an older version - // of `@sentry/core` that does not have the `getAttachments` method. - // See: https://github.com/getsentry/sentry-javascript/issues/5229 - if (finalScope && finalScope.getAttachments) { - // Collect attachments from the hint and scope - const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()]; - - if (attachments.length) { - hint.attachments = attachments; - } - - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); - } - - return result.then(evt => { - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); - } - 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 - */ - _normalizeEvent(event, depth, maxBreadth) { - if (!event) { - return null; - } - - const normalized = { - ...event, - ...(event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(b => ({ - ...b, - ...(b.data && { - data: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(b.data, depth, maxBreadth), - }), - })), - }), - ...(event.user && { - user: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.user, depth, maxBreadth), - }), - ...(event.contexts && { - contexts: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts, depth, maxBreadth), - }), - ...(event.extra && { - extra: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.extra, depth, maxBreadth), - }), - }; - - // 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 && normalized.contexts) { - normalized.contexts.trace = event.contexts.trace; - - // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it - if (event.contexts.trace.data) { - normalized.contexts.trace.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts.trace.data, depth, maxBreadth); - } - } - - // event.spans[].data may contain circular/dangerous data so we need to normalize it - if (event.spans) { - normalized.spans = event.spans.map(span => { - // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable - if (span.data) { - span.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(span.data, depth, maxBreadth); - } - return span; - }); - } - - 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 - */ - _applyClientOptions(event) { - const options = this.getOptions(); - const { environment, release, dist, maxValueLength = 250 } = options; - - 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 = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(event.message, maxValueLength); - } - - const exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(exception.value, maxValueLength); - } - - const request = event.request; - if (request && request.url) { - request.url = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(request.url, maxValueLength); - } - } - - /** - * This function adds all used integrations to the SDK info in the event. - * @param event The event that will be filled with all integrations. - */ - _applyIntegrationsMetadata(event) { - const integrationsArray = Object.keys(this._integrations); - if (integrationsArray.length > 0) { - event.sdk = event.sdk || {}; - event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray]; - } - } - - /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope - */ - _captureEvent(event, hint = {}, scope) { - return this._processEvent(event, hint, scope).then( - finalEvent => { - return finalEvent.event_id; - }, - reason => { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for - // control flow, log just the message (no stack) as a log-level log. - const sentryError = reason ; - if (sentryError.logLevel === 'log') { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(sentryError.message); - } else { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(sentryError); - } - } - 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. - */ - _processEvent(event, hint, scope) { - const options = this.getOptions(); - const { sampleRate } = options; - - if (!this._isEnabled()) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)(new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('SDK not enabled, will not capture event.', 'log')); - } - - const isTransaction = event.type === 'transaction'; - const beforeSendProcessorName = isTransaction ? 'beforeSendTransaction' : 'beforeSend'; - const beforeSendProcessor = options[beforeSendProcessorName]; - - // 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) { - this.recordDroppedEvent('sample_rate', 'error', event); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)( - new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( - `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, - 'log', - ), - ); - } - - return this._prepareEvent(event, hint, scope) - .then(prepared => { - if (prepared === null) { - this.recordDroppedEvent('event_processor', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('An event processor returned `null`, will not send event.', 'log'); - } - - const isInternalException = hint.data && (hint.data ).__sentry__ === true; - if (isInternalException || !beforeSendProcessor) { - return prepared; - } - - const beforeSendResult = beforeSendProcessor(prepared, hint); - return _validateBeforeSendResult(beforeSendResult, beforeSendProcessorName); - }) - .then(processedEvent => { - if (processedEvent === null) { - this.recordDroppedEvent('before_send', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` returned \`null\`, will not send event.`, 'log'); - } - - const session = scope && scope.getSession(); - if (!isTransaction && session) { - this._updateSessionFromEvent(session, processedEvent); - } - - // None of the Sentry built event processor will update transaction name, - // so if the transaction name has been changed by an event processor, we know - // it has to come from custom event processor added by a user - const transactionInfo = processedEvent.transaction_info; - if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { - const source = 'custom'; - processedEvent.transaction_info = { - ...transactionInfo, - source, - changes: [ - ...transactionInfo.changes, - { - source, - // use the same timestamp as the processed event. - timestamp: processedEvent.timestamp , - propagations: transactionInfo.propagations, - }, - ], - }; - } - - this.sendEvent(processedEvent, hint); - return processedEvent; - }) - .then(null, reason => { - if (reason instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError) { - throw reason; - } - - this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason , - }); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.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 - */ - _process(promise) { - this._numProcessing++; - void promise.then( - value => { - this._numProcessing--; - return value; - }, - reason => { - this._numProcessing--; - return reason; - }, - ); - } - - /** - * @inheritdoc - */ - _sendEnvelope(envelope) { - if (this._transport && this._dsn) { - this._transport.send(envelope).then(null, reason => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Error while sending event:', reason); - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Transport disabled'); - } - } - - /** - * Clears outcomes on this client and returns them. - */ - _clearOutcomes() { - const outcomes = this._outcomes; - this._outcomes = {}; - return Object.keys(outcomes).map(key => { - const [reason, category] = key.split(':') ; - return { - reason, - category, - quantity: outcomes[key], - }; - }); - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - -} - -/** - * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. - */ -function _validateBeforeSendResult( - beforeSendResult, - beforeSendProcessorName, -) { - const invalidValueError = `\`${beforeSendProcessorName}\` must return \`null\` or a valid event.`; - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isThenable)(beforeSendResult)) { - return beforeSendResult.then( - event => { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(event) && event !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); - } - return event; - }, - e => { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` rejected with ${e}`); - }, - ); - } else if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(beforeSendResult) && beforeSendResult !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); - } - return beforeSendResult; -} - - -//# sourceMappingURL=baseclient.js.map - - -/***/ }), -/* 1630 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dsnFromString": () => (/* binding */ dsnFromString), -/* harmony export */ "dsnToString": () => (/* binding */ dsnToString), -/* harmony export */ "makeDsn": () => (/* binding */ makeDsn) -/* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1620); - - -/** Regular expression used to parse a Dsn. */ -const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; - -function isValidProtocol(protocol) { - return protocol === 'http' || protocol === 'https'; -} - -/** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. - */ -function dsnToString(dsn, withPassword = false) { - const { host, path, pass, port, projectId, protocol, publicKey } = dsn; - return ( - `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + - `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` - ); -} - -/** - * Parses a Dsn from a given string. - * - * @param str A Dsn as string - * @returns Dsn as DsnComponents - */ -function dsnFromString(str) { - const match = DSN_REGEX.exec(str); - - if (!match) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${str}`); - } - - const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); - let path = ''; - let projectId = lastPath; - - const split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop() ; - } - - if (projectId) { - const projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } - } - - return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey }); -} - -function dsnFromComponents(components) { - return { - protocol: components.protocol, - publicKey: components.publicKey || '', - pass: components.pass || '', - host: components.host, - port: components.port || '', - path: components.path || '', - projectId: components.projectId, - }; -} - -function validateDsn(dsn) { - if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - return; - } - - const { port, projectId, protocol } = dsn; - - const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; - requiredComponents.forEach(component => { - if (!dsn[component]) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${component} missing`); - } - }); - - if (!projectId.match(/^\d+$/)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); - } - - if (!isValidProtocol(protocol)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); - } - - if (port && isNaN(parseInt(port, 10))) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid port ${port}`); - } - - return true; -} - -/** The Sentry Dsn, identifying a Sentry instance and project. */ -function makeDsn(from) { - const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); - validateDsn(components); - return components; -} - - -//# sourceMappingURL=dsn.js.map - - -/***/ }), -/* 1631 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getEnvelopeEndpointWithUrlEncodedAuth": () => (/* binding */ getEnvelopeEndpointWithUrlEncodedAuth), -/* harmony export */ "getReportDialogEndpoint": () => (/* binding */ getReportDialogEndpoint) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1630); - - -const SENTRY_API_VERSION = '7'; - -/** Returns the prefix to construct Sentry ingestion API endpoints. */ -function getBaseApiEndpoint(dsn) { - const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; - const port = dsn.port ? `:${dsn.port}` : ''; - return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`; -} - -/** Returns the ingest API endpoint for target. */ -function _getIngestEndpoint(dsn) { - return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; -} - -/** Returns a URL-encoded string with auth config suitable for a query string. */ -function _encodedAuth(dsn, sdkInfo) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.urlEncode)({ - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.publicKey, - sentry_version: SENTRY_API_VERSION, - ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.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. - */ -function getEnvelopeEndpointWithUrlEncodedAuth( - dsn, - // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below - // options: ClientOptions = {} as ClientOptions, - tunnelOrOptions = {} , -) { - // TODO (v8): Use this code instead - // const { tunnel, _metadata = {} } = options; - // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; - - const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; - const sdkInfo = - typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; - - return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; -} - -/** Returns the url to the report dialog endpoint. */ -function getReportDialogEndpoint( - dsnLike, - dialogOptions - -, -) { - const dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.makeDsn)(dsnLike); - const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; - - let encodedOptions = `dsn=${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dsnToString)(dsn)}`; - for (const key in dialogOptions) { - if (key === 'dsn') { - continue; - } - - if (key === 'user') { - const user = dialogOptions.user; - if (!user) { - continue; - } - if (user.name) { - encodedOptions += `&name=${encodeURIComponent(user.name)}`; - } - if (user.email) { - encodedOptions += `&email=${encodeURIComponent(user.email)}`; - } - } else { - encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`; - } - } - - return `${endpoint}?${encodedOptions}`; -} - - -//# sourceMappingURL=api.js.map - - -/***/ }), -/* 1632 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getIntegrationsToSetup": () => (/* binding */ getIntegrationsToSetup), -/* harmony export */ "installedIntegrations": () => (/* binding */ installedIntegrations), -/* harmony export */ "setupIntegrations": () => (/* binding */ setupIntegrations) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1615); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1603); - - - - -const installedIntegrations = []; - -/** Map of integrations assigned to a client */ - -/** - * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to - * preseve the order of integrations in the array. - * - * @private - */ -function filterDuplicates(integrations) { - const integrationsByName = {}; - - integrations.forEach(currentInstance => { - const { name } = currentInstance; - - const existingInstance = integrationsByName[name]; - - // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a - // default instance to overwrite an existing user instance - if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { - return; - } - - integrationsByName[name] = currentInstance; - }); - - return Object.values(integrationsByName); -} - -/** Gets integrations to install */ -function getIntegrationsToSetup(options) { - const defaultIntegrations = options.defaultIntegrations || []; - const userIntegrations = options.integrations; - - // We flag default instances, so that later we can tell them apart from any user-created instances of the same class - defaultIntegrations.forEach(integration => { - integration.isDefaultInstance = true; - }); - - let integrations; - - if (Array.isArray(userIntegrations)) { - integrations = [...defaultIntegrations, ...userIntegrations]; - } else if (typeof userIntegrations === 'function') { - integrations = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.arrayify)(userIntegrations(defaultIntegrations)); - } else { - integrations = defaultIntegrations; - } - - const finalIntegrations = filterDuplicates(integrations); - - // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or - // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event - // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore - // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. - const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug'); - if (debugIndex !== -1) { - const [debugInstance] = finalIntegrations.splice(debugIndex, 1); - finalIntegrations.push(debugInstance); - } - - return finalIntegrations; -} - -/** - * 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(integrations) { - const integrationIndex = {}; - - integrations.forEach(integration => { - integrationIndex[integration.name] = integration; - - if (installedIntegrations.indexOf(integration.name) === -1) { - integration.setupOnce(_scope_js__WEBPACK_IMPORTED_MODULE_1__.addGlobalEventProcessor, _hub_js__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub); - installedIntegrations.push(integration.name); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`Integration installed: ${integration.name}`); - } - }); - - return integrationIndex; -} - - -//# sourceMappingURL=integration.js.map - - -/***/ }), -/* 1633 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createEventEnvelope": () => (/* binding */ createEventEnvelope), -/* harmony export */ "createSessionEnvelope": () => (/* binding */ createSessionEnvelope) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1630); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1621); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); - - -/** Extract sdk info from from the API metadata */ -function getSdkMetadataForEnvelopeHeader(metadata) { - if (!metadata || !metadata.sdk) { - return; - } - const { name, version } = metadata.sdk; - return { name, version }; -} - -/** - * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. - * Merge with existing data if any. - **/ -function enhanceEventWithSdkInfo(event, sdkInfo) { - if (!sdkInfo) { - return event; - } - event.sdk = event.sdk || {}; - event.sdk.name = event.sdk.name || sdkInfo.name; - event.sdk.version = event.sdk.version || sdkInfo.version; - event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; - event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; - return event; -} - -/** Creates an envelope from a Session */ -function createSessionEnvelope( - session, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const envelopeHeaders = { - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - }; - - const envelopeItem = - 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session]; - - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [envelopeItem]); -} - -/** - * Create an Envelope from an event. - */ -function createEventEnvelope( - event, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const eventType = event.type || 'event'; - - enhanceEventWithSdkInfo(event, metadata && metadata.sdk); - - const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); - - // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to - // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may - // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid - // of this `delete`, lest we miss putting it back in the next time the property is in use.) - delete event.sdkProcessingMetadata; - - const eventItem = [{ type: eventType }, event]; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [eventItem]); -} - -function createEventEnvelopeHeaders( - event, - sdkInfo, - tunnel, - dsn, -) { - const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; - - return { - event_id: event.event_id , - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - ...(event.type === 'transaction' && - dynamicSamplingContext && { - trace: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ ...dynamicSamplingContext }), - }), - }; -} - - -//# sourceMappingURL=envelope.js.map - - -/***/ }), -/* 1634 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SessionFlusher": () => (/* binding */ SessionFlusher) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1612); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); - - - -/** - * @inheritdoc - */ -class SessionFlusher { - __init() {this.flushTimeout = 60;} - __init2() {this._pendingAggregates = {};} - - __init3() {this._isEnabled = true;} - - constructor(client, attrs) {;SessionFlusher.prototype.__init.call(this);SessionFlusher.prototype.__init2.call(this);SessionFlusher.prototype.__init3.call(this); - this._client = client; - // Call to setInterval, so that flush is called every 60 seconds - this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); - this._sessionAttrs = attrs; - } - - /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ - flush() { - const sessionAggregates = this.getSessionAggregates(); - if (sessionAggregates.aggregates.length === 0) { - return; - } - this._pendingAggregates = {}; - this._client.sendSession(sessionAggregates); - } - - /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ - getSessionAggregates() { - const aggregates = Object.keys(this._pendingAggregates).map((key) => { - return this._pendingAggregates[parseInt(key)]; - }); - - const sessionAggregates = { - attrs: this._sessionAttrs, - aggregates, - }; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dropUndefinedKeys)(sessionAggregates); - } - - /** JSDoc */ - close() { - clearInterval(this._intervalId); - this._isEnabled = false; - this.flush(); - } - - /** - * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then - * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to - * `_incrementSessionStatusCount` along with the start date - */ - incrementSessionStatusCount() { - if (!this._isEnabled) { - return; - } - const scope = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getScope(); - const requestSession = scope && scope.getRequestSession(); - - if (requestSession && requestSession.status) { - this._incrementSessionStatusCount(requestSession.status, new Date()); - // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in - // case captureRequestSession is called more than once to prevent double count - if (scope) { - scope.setRequestSession(undefined); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - } - } - - /** - * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of - * the session received - */ - _incrementSessionStatusCount(status, date) { - // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys - const sessionStartedTrunc = new Date(date).setSeconds(0, 0); - this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; - - // corresponds to aggregated sessions in one specific minute bucket - // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} - const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; - if (!aggregationCounts.started) { - aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); - } - - switch (status) { - case 'errored': - aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; - return aggregationCounts.errored; - case 'ok': - aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; - return aggregationCounts.exited; - default: - aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; - return aggregationCounts.crashed; - } - } -} - - -//# sourceMappingURL=sessionflusher.js.map - - -/***/ }), -/* 1635 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_0__.makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1636); - - -; -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1636 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* binding */ makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1650); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1618); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(stream__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(83); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(zlib__WEBPACK_IMPORTED_MODULE_4__); - - - - - - - - -// Estimated maximum size for reasonable standalone event -const GZIP_THRESHOLD = 1024 * 32; - -/** - * Gets a stream from a Uint8Array or string - * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0 - */ -function streamFromBody(body) { - return new stream__WEBPACK_IMPORTED_MODULE_2__.Readable({ - read() { - this.push(body); - this.push(null); - }, - }); -} - -/** - * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. - */ -function makeNodeTransport(options) { - const urlSegments = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - const isHttps = urlSegments.protocol === 'https:'; - - // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` - // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` - const proxy = applyNoProxyOption( - urlSegments, - options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy, - ); - - const nativeHttpModule = isHttps ? https__WEBPACK_IMPORTED_MODULE_1__ : http__WEBPACK_IMPORTED_MODULE_0__; - const keepAlive = options.keepAlive === undefined ? false : options.keepAlive; - - // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node - // versions(>= 8) as they had memory leaks when using it: #2555 - const agent = proxy - ? (new (__webpack_require__(1637))(proxy) ) - : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 }); - - const requestExecutor = createRequestExecutor(options, (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(options.httpModule, () => ( nativeHttpModule)), agent); - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.createTransport)(options, requestExecutor); -} - -/** - * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. - * - * @param transportUrl The URL the transport intends to send events to. - * @param proxy The client configured proxy. - * @returns A proxy the transport should use. - */ -function applyNoProxyOption(transportUrlSegments, proxy) { - const { no_proxy } = process.env; - - const urlIsExemptFromProxy = - no_proxy && - no_proxy - .split(',') - .some( - exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption), - ); - - if (urlIsExemptFromProxy) { - return undefined; - } else { - return proxy; - } -} - -/** - * Creates a RequestExecutor to be used with `createTransport`. - */ -function createRequestExecutor( - options, - httpModule, - agent, -) { - const { hostname, pathname, port, protocol, search } = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - return function makeRequest(request) { - return new Promise((resolve, reject) => { - let body = streamFromBody(request.body); - - const headers = { ...options.headers }; - - if (request.body.length > GZIP_THRESHOLD) { - headers['content-encoding'] = 'gzip'; - body = body.pipe((0,zlib__WEBPACK_IMPORTED_MODULE_4__.createGzip)()); - } - - const req = httpModule.request( - { - method: 'POST', - agent, - headers, - hostname, - path: `${pathname}${search}`, - port, - protocol, - ca: options.caCerts, - }, - res => { - res.on('data', () => { - // Drain socket - }); - - res.on('end', () => { - // Drain socket - }); - - res.setEncoding('utf8'); - - // "Key-value pairs of header names and values. Header names are lower-cased." - // https://nodejs.org/api/http.html#http_message_headers - const retryAfterHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['retry-after'], () => ( null)); - const rateLimitsHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['x-sentry-rate-limits'], () => ( null)); - - resolve({ - statusCode: res.statusCode, - headers: { - 'retry-after': retryAfterHeader, - 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, - }, - }); - }, - ); - - req.on('error', reject); - body.pipe(req); - }); - }; -} - - -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1637 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const agent_1 = __importDefault(__webpack_require__(1638)); -function createHttpsProxyAgent(opts) { - return new agent_1.default(opts); -} -(function (createHttpsProxyAgent) { - createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent.prototype = agent_1.default.prototype; -})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); -module.exports = createHttpsProxyAgent; -//# sourceMappingURL=index.js.map - -/***/ }), -/* 1638 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __importDefault(__webpack_require__(62)); -const tls_1 = __importDefault(__webpack_require__(145)); -const url_1 = __importDefault(__webpack_require__(63)); -const assert_1 = __importDefault(__webpack_require__(91)); -const debug_1 = __importDefault(__webpack_require__(1639)); -const agent_base_1 = __webpack_require__(1643); -const parse_proxy_response_1 = __importDefault(__webpack_require__(1649)); -const debug = debug_1.default('https-proxy-agent:agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - * - * @api public - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === 'string') { - opts = url_1.default.parse(_opts); - } - else { - opts = _opts; - } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); - } - debug('creating new HttpsProxyAgent instance: %o', opts); - super(opts); - const proxy = Object.assign({}, opts); - // If `true`, then connect to the proxy server over TLS. - // Defaults to `false`. - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - // Prefer `hostname` over `host`, and set the `port` if needed. - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === 'string') { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - // ALPN is supported by Node.js >= v5. - // attempt to negotiate http/1.1 for proxy servers that support http/2 - if (this.secureProxy && !('ALPNProtocols' in proxy)) { - proxy.ALPNProtocols = ['http 1.1']; - } - if (proxy.host && proxy.path) { - // If both a `host` and `path` are specified then it's most likely - // the result of a `url.parse()` call... we need to remove the - // `path` portion so that `net.connect()` doesn't attempt to open - // that as a Unix socket file. - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - * - * @api protected - */ - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - // Create a socket connection to the proxy server. - let socket; - if (secureProxy) { - debug('Creating `tls.Socket`: %o', proxy); - socket = tls_1.default.connect(proxy); - } - else { - debug('Creating `net.Socket`: %o', proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.auth) { - headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; - } - // The `Host` header should only include the port - // number when it is not the default port. - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = 'close'; - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r\n`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - const servername = opts.servername || opts.host; - return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, - servername })); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net_1.default.Socket({ writable: false }); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('replaying proxy buffer for failed request'); - assert_1.default(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); - } -} -exports["default"] = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function isDefaultPort(port, secure) { - return Boolean((!secure && port === 80) || (secure && port === 443)); -} -function isHTTPS(protocol) { - return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=agent.js.map - -/***/ }), -/* 1639 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1640); -} else { - module.exports = __webpack_require__(1642); -} - - -/***/ }), -/* 1640 */ -/***/ ((module, exports, __webpack_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __webpack_require__(1641)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), -/* 1641 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1367); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), -/* 1642 */ -/***/ ((module, exports, __webpack_require__) => { - -/** - * Module dependencies. - */ - -const tty = __webpack_require__(1369); -const util = __webpack_require__(64); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1370); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __webpack_require__(1641)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), -/* 1643 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const events_1 = __webpack_require__(250); -const debug_1 = __importDefault(__webpack_require__(1644)); -const promisify_1 = __importDefault(__webpack_require__(1648)); -const debug = debug_1.default('agent-base'); -function isAgent(v) { - return Boolean(v) && typeof v.addRequest === 'function'; -} -function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); -} -function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); -} -(function (createAgent) { - /** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === 'function') { - this.callback = callback; - } - else if (callback) { - opts = callback; - } - // Timeout for the socket to be returned from the callback - this.timeout = null; - if (opts && typeof opts.timeout === 'number') { - this.timeout = opts.timeout; - } - // These aren't actually used by `agent-base`, but are required - // for the TypeScript definition files in `@types/node` :/ - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === 'number') { - return this.explicitDefaultPort; - } - return isSecureEndpoint() ? 443 : 80; - } - set defaultPort(v) { - this.explicitDefaultPort = v; - } - get protocol() { - if (typeof this.explicitProtocol === 'string') { - return this.explicitProtocol; - } - return isSecureEndpoint() ? 'https:' : 'http:'; - } - set protocol(v) { - this.explicitProtocol = v; - } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); - } - /** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== 'boolean') { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = 'localhost'; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; - } - if (opts.host && opts.path) { - // If both a `host` and `path` are specified then it's most - // likely the result of a `url.parse()` call... we need to - // remove the `path` portion so that `net.connect()` doesn't - // attempt to open that as a unix socket file. - delete opts.path; - } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = 'ETIMEOUT'; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - // `socket` is actually an `http.Agent` instance, so - // relinquish responsibility for this `req` to the Agent - // from here on - debug('Callback returned another Agent instance %o', socket.constructor.name); - socket.addRequest(req, opts); - return; - } - if (socket) { - socket.once('free', () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; - } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== 'function') { - onerror(new Error('`callback` is not defined')); - return; - } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug('Converting legacy callback function to promise'); - this.promisifiedCallback = promisify_1.default(this.callback); - } - else { - this.promisifiedCallback = this.callback; - } - } - if (typeof timeoutMs === 'number' && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ('port' in opts && typeof opts.port !== 'number') { - opts.port = Number(opts.port); - } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } - catch (err) { - Promise.reject(err).catch(callbackError); - } - } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug('Destroying agent %o', this.constructor.name); - } - } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map - -/***/ }), -/* 1644 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1645); -} else { - module.exports = __webpack_require__(1647); -} - - -/***/ }), -/* 1645 */ -/***/ ((module, exports, __webpack_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __webpack_require__(1646)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), -/* 1646 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1367); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), -/* 1647 */ -/***/ ((module, exports, __webpack_require__) => { - -/** - * Module dependencies. - */ - -const tty = __webpack_require__(1369); -const util = __webpack_require__(64); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1370); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __webpack_require__(1646)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), -/* 1648 */ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function promisify(fn) { - return function (req, opts) { - return new Promise((resolve, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } - else { - resolve(rtn); - } - }); - }); - }; -} -exports["default"] = promisify; -//# sourceMappingURL=promisify.js.map - -/***/ }), -/* 1649 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __importDefault(__webpack_require__(1639)); -const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('close', onclose); - socket.removeListener('readable', read); - } - function onclose(err) { - debug('onclose had error %o', err); - } - function onend() { - debug('onend'); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); - const statusCode = +firstLine.split(' ')[1]; - debug('got proxy server response: %o', firstLine); - resolve({ - statusCode, - buffered - }); - } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); -} -exports["default"] = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map - -/***/ }), -/* 1650 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_nullishCoalesce": () => (/* binding */ _nullishCoalesce) -/* harmony export */ }); -/** - * Polyfill for the nullish coalescing operator (`??`). - * - * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the - * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. - * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) - * - * @param lhs The value of the expression to the left of the `??` - * @param rhsFn A function returning the value of the expression to the right of the `??` - * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value - */ -function _nullishCoalesce(lhs, rhsFn) { - // by checking for loose equality to `null`, we catch both `null` and `undefined` - return lhs != null ? lhs : rhsFn(); -} - -// Sucrase version: -// function _nullishCoalesce(lhs, rhsFn) { -// if (lhs != null) { -// return lhs; -// } else { -// return rhsFn(); -// } -// } - - -//# sourceMappingURL=_nullishCoalesce.js.map - - -/***/ }), -/* 1651 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "close": () => (/* binding */ close), -/* harmony export */ "defaultIntegrations": () => (/* binding */ defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* binding */ defaultStackParser), -/* harmony export */ "flush": () => (/* binding */ flush), -/* harmony export */ "getSentryRelease": () => (/* binding */ getSentryRelease), -/* harmony export */ "init": () => (/* binding */ init), -/* harmony export */ "isAutoSessionTrackingEnabled": () => (/* binding */ isAutoSessionTrackingEnabled), -/* harmony export */ "lastEventId": () => (/* binding */ lastEventId) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1673); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(1674); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(1602); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(1632); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1675); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(1624); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(1606); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1314); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1627); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1652); -/* harmony import */ var _module_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1671); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1635); -/* harmony import */ var _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1653); -/* harmony import */ var _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1655); -/* harmony import */ var _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1658); -/* harmony import */ var _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1660); -/* harmony import */ var _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1662); -/* harmony import */ var _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1665); -/* harmony import */ var _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1664); -/* harmony import */ var _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1666); -/* harmony import */ var _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1661); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1636); - - - - - - - - - - - - - - - - - - - -/* eslint-disable max-lines */ - -const defaultIntegrations = [ - // Common - new _sentry_core__WEBPACK_IMPORTED_MODULE_15__.InboundFilters(), - new _sentry_core__WEBPACK_IMPORTED_MODULE_16__.FunctionToString(), - // Native Wrappers - new _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__.Console(), - new _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__.Http(), - // Global Handlers - new _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__.OnUncaughtException(), - new _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__.OnUnhandledRejection(), - // Event Info - new _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__.ContextLines(), - new _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__.Context(), - new _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__.Modules(), - new _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__.RequestData(), - // Misc - new _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__.LinkedErrors(), -]; - -/** - * The Sentry Node SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible in the - * main entry module. To set context information or send manual events, use the - * provided methods. - * - * @example - * ``` - * - * const { init } = require('@sentry/node'); - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const { configureScope } = require('@sentry/node'); - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * const { addBreadcrumb } = require('@sentry/node'); - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const Sentry = require('@sentry/node'); - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` - * - * @see {@link NodeOptions} for documentation on configuration options. - */ -function init(options = {}) { - const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getMainCarrier)(); - const autoloadedIntegrations = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || []; - - options.defaultIntegrations = - options.defaultIntegrations === false - ? [] - : [ - ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations), - ...autoloadedIntegrations, - ]; - - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; - } - - if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { - const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); - if (isFinite(tracesSampleRate)) { - options.tracesSampleRate = tracesSampleRate; - } - } - - if (options.release === undefined) { - const detectedRelease = getSentryRelease(); - if (detectedRelease !== undefined) { - options.release = detectedRelease; - } else { - // If release is not provided, then we should disable autoSessionTracking - options.autoSessionTracking = false; - } - } - - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; - } - - if (options.autoSessionTracking === undefined && options.dsn !== undefined) { - options.autoSessionTracking = true; - } - - if (options.instrumenter === undefined) { - options.instrumenter = 'sentry'; - } - - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain__WEBPACK_IMPORTED_MODULE_0__.active) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.setHubOnCarrier)(carrier, (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)()); - } - - // TODO(v7): Refactor this to reduce the logic above - const clientOptions = { - ...options, - stackParser: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.stackParserFromStackParserOptions)(options.stackParser || defaultStackParser), - integrations: (0,_sentry_core__WEBPACK_IMPORTED_MODULE_20__.getIntegrationsToSetup)(options), - transport: options.transport || _transports_http_js__WEBPACK_IMPORTED_MODULE_14__.makeNodeTransport, - }; - - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_21__.initAndBind)(_client_js__WEBPACK_IMPORTED_MODULE_1__.NodeClient, clientOptions); - - if (options.autoSessionTracking) { - startSessionTracking(); - } -} - -/** - * This is the getter for lastEventId. - * - * @returns The last event id of a captured event. - */ -function lastEventId() { - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().lastEventId(); -} - -/** - * Call `flush()` on the current client, if there is one. See {@link Client.flush}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause - * the client to wait until all events are sent before resolving the promise. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -async function flush(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.flush(timeout); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events. No client defined.'); - return Promise.resolve(false); -} - -/** - * Call `close()` on the current client, if there is one. See {@link Client.close}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this - * parameter will cause the client to wait until all events are sent before disabling itself. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -async function close(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.close(timeout); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events and disable SDK. No client defined.'); - return Promise.resolve(false); -} - -/** - * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client - */ -function isAutoSessionTrackingEnabled(client) { - if (client === undefined) { - return false; - } - const clientOptions = client && client.getOptions(); - if (clientOptions && clientOptions.autoSessionTracking !== undefined) { - return clientOptions.autoSessionTracking; - } - return false; -} - -/** - * Returns a release dynamically from environment variables. - */ -function getSentryRelease(fallback) { - // Always read first as Sentry takes this as precedence - if (process.env.SENTRY_RELEASE) { - return process.env.SENTRY_RELEASE; - } - - // This supports the variable that sentry-webpack-plugin injects - if (_sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE && _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id) { - return _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id; - } - - return ( - // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables - process.env.GITHUB_SHA || - // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata - process.env.COMMIT_REF || - // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables - process.env.VERCEL_GIT_COMMIT_SHA || - process.env.VERCEL_GITHUB_COMMIT_SHA || - process.env.VERCEL_GITLAB_COMMIT_SHA || - process.env.VERCEL_BITBUCKET_COMMIT_SHA || - // Zeit (now known as Vercel) - process.env.ZEIT_GITHUB_COMMIT_SHA || - process.env.ZEIT_GITLAB_COMMIT_SHA || - process.env.ZEIT_BITBUCKET_COMMIT_SHA || - fallback - ); -} - -/** Node.js stack parser */ -const defaultStackParser = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.createStackParser)((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.nodeStackLineParser)(_module_js__WEBPACK_IMPORTED_MODULE_3__.getModule)); - -/** - * Enable automatic Session Tracking for the node process. - */ -function startSessionTracking() { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)(); - hub.startSession(); - // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because - // The 'beforeExit' event is not emitted for conditions causing explicit termination, - // such as calling process.exit() or uncaught exceptions. - // Ref: https://nodejs.org/api/process.html#process_event_beforeexit - process.on('beforeExit', () => { - const session = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([hub, 'access', _3 => _3.getScope, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getSession, 'call', _6 => _6()]); - const terminalStates = ['exited', 'crashed']; - // Only call endSession, if the Session exists on Scope and SessionStatus is not a - // Terminal Status i.e. Exited or Crashed because - // "When a session is moved away from ok it must not be updated anymore." - // Ref: https://develop.sentry.dev/sdk/sessions/ - if (session && !terminalStates.includes(session.status)) hub.endSession(); - }); -} - - -//# sourceMappingURL=sdk.js.map - - -/***/ }), -/* 1652 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* reexport safe */ _console_js__WEBPACK_IMPORTED_MODULE_0__.Console), -/* harmony export */ "Http": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_1__.Http), -/* harmony export */ "OnUncaughtException": () => (/* reexport safe */ _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__.OnUncaughtException), -/* harmony export */ "OnUnhandledRejection": () => (/* reexport safe */ _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__.OnUnhandledRejection), -/* harmony export */ "LinkedErrors": () => (/* reexport safe */ _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__.LinkedErrors), -/* harmony export */ "Modules": () => (/* reexport safe */ _modules_js__WEBPACK_IMPORTED_MODULE_5__.Modules), -/* harmony export */ "ContextLines": () => (/* reexport safe */ _contextlines_js__WEBPACK_IMPORTED_MODULE_6__.ContextLines), -/* harmony export */ "Context": () => (/* reexport safe */ _context_js__WEBPACK_IMPORTED_MODULE_7__.Context), -/* harmony export */ "RequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.RequestData) -/* harmony export */ }); -/* harmony import */ var _console_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1655); -/* harmony import */ var _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1658); -/* harmony import */ var _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1660); -/* harmony import */ var _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1661); -/* harmony import */ var _modules_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1664); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1662); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1665); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1666); - - - - - - - - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1653 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* binding */ Console) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1654); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_0__); - - - - -/** Console module integration */ -class Console {constructor() { Console.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Console';} - - /** - * @inheritDoc - */ - __init() {this.name = Console.id;} - - /** - * @inheritDoc - */ - setupOnce() { - for (const level of ['debug', 'info', 'warn', 'error', 'log']) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.fill)(console, level, createConsoleWrapper(level)); - } - } -} Console.__initStatic(); - -/** - * Wrapper function that'll be used for every console level - */ -function createConsoleWrapper(level) { - return function consoleWrapper(originalConsoleMethod) { - const sentryLevel = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.severityLevelFromString)(level); - - /* eslint-disable prefer-rest-params */ - return function () { - if ((0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(Console)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().addBreadcrumb( - { - category: 'console', - level: sentryLevel, - message: util__WEBPACK_IMPORTED_MODULE_0__.format.apply(undefined, arguments), - }, - { - input: [...arguments], - level, - }, - ); - } - - originalConsoleMethod.apply(this, arguments); - }; - /* eslint-enable prefer-rest-params */ - }; -} - - -//# sourceMappingURL=console.js.map - - -/***/ }), -/* 1654 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "severityFromString": () => (/* binding */ severityFromString), -/* harmony export */ "severityLevelFromString": () => (/* binding */ severityLevelFromString), -/* harmony export */ "validSeverityLevels": () => (/* binding */ validSeverityLevels) -/* harmony export */ }); -// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either -// -// a) moving `validSeverityLevels` to `@sentry/types`, -// b) moving the`SeverityLevel` type here, or -// c) importing `validSeverityLevels` from here into `@sentry/types`. -// -// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would -// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the -// type, reminding anyone who changes it to change this list also, will have to do. - -const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug']; - -/** - * Converts a string-based level into a member of the deprecated {@link Severity} enum. - * - * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead. - * - * @param level String representation of Severity - * @returns Severity - */ -function severityFromString(level) { - return severityLevelFromString(level) ; -} - -/** - * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. - * - * @param level String representation of desired `SeverityLevel`. - * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. - */ -function severityLevelFromString(level) { - return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ; -} - - -//# sourceMappingURL=severity.js.map - - -/***/ }), -/* 1655 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Http": () => (/* binding */ Http) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1610); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1657); -/* harmony import */ var _utils_http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1656); - - - - - -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); - -/** - * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing - * http requests and attaches trace data when tracing is enabled via its `tracing` option. - */ -class Http { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Http';} - - /** - * @inheritDoc - */ - __init() {this.name = Http.id;} - - /** - * @inheritDoc - */ - constructor(options = {}) {;Http.prototype.__init.call(this); - this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; - this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing; - } - - /** - * @inheritDoc - */ - setupOnce( - _addGlobalEventProcessor, - setupOnceGetCurrentHub, - ) { - // No need to instrument if we don't want to track anything - if (!this._breadcrumbs && !this._tracing) { - return; - } - - const clientOptions = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); - - // Do not auto-instrument for other instrumenter - if (clientOptions && clientOptions.instrumenter !== 'sentry') { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('HTTP Integration is skipped because of instrumenter configuration.'); - return; - } - - // TODO (v8): `tracePropagationTargets` and `shouldCreateSpanForRequest` will be removed from clientOptions - // and we will no longer have to do this optional merge, we can just pass `this._tracing` directly. - const tracingOptions = this._tracing ? { ...clientOptions, ...this._tracing } : undefined; - - const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, tracingOptions); - - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpModule = __webpack_require__(80); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'request', wrappedHandlerMaker); - - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // If we do, we'd get double breadcrumbs and double spans for `https` calls. - // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpsModule = __webpack_require__(81); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'request', wrappedHandlerMaker); - } - } -}Http.__initStatic(); - -// for ease of reading below - -/** - * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` - * and `https` modules. (NB: Not a typo - this is a creator^2!) - * - * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs - * @param tracingEnabled Whether or not to record outgoing requests as tracing spans - * - * @returns A function which accepts the exiting handler and returns a wrapped handler - */ -function _createWrappedRequestMethodFactory( - breadcrumbsEnabled, - tracingOptions, -) { - // We're caching results so we don't have to recompute regexp every time we create a request. - const createSpanUrlMap = {}; - const headersUrlMap = {}; - - const shouldCreateSpan = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _6 => _6.shouldCreateSpanForRequest]) === undefined) { - return true; - } - - if (createSpanUrlMap[url]) { - return createSpanUrlMap[url]; - } - - createSpanUrlMap[url] = tracingOptions.shouldCreateSpanForRequest(url); - - return createSpanUrlMap[url]; - }; - - const shouldAttachTraceData = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _7 => _7.tracePropagationTargets]) === undefined) { - return true; - } - - if (headersUrlMap[url]) { - return headersUrlMap[url]; - } - - headersUrlMap[url] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.stringMatchesSomePattern)(url, tracingOptions.tracePropagationTargets); - - return headersUrlMap[url]; - }; - - return function wrappedRequestMethodFactory(originalRequestMethod) { - return function wrappedMethod( ...args) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const httpModule = this; - - const requestArgs = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.normalizeRequestArgs)(this, args); - const requestOptions = requestArgs[0]; - const requestUrl = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.extractUrl)(requestOptions); - - // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method - if ((0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.isSentryRequest)(requestUrl)) { - return originalRequestMethod.apply(httpModule, requestArgs); - } - - let requestSpan; - let parentSpan; - - const scope = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getScope(); - - if (scope && tracingOptions && shouldCreateSpan(requestUrl)) { - parentSpan = scope.getSpan(); - - if (parentSpan) { - requestSpan = parentSpan.startChild({ - description: `${requestOptions.method || 'GET'} ${requestUrl}`, - op: 'http.client', - }); - - if (shouldAttachTraceData(requestUrl)) { - const sentryTraceHeader = requestSpan.toTraceparent(); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `, - ); - - requestOptions.headers = { - ...requestOptions.headers, - 'sentry-trace': sentryTraceHeader, - }; - - if (parentSpan.transaction) { - const dynamicSamplingContext = parentSpan.transaction.getDynamicSamplingContext(); - const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); - - let newBaggageHeaderField; - if (!requestOptions.headers || !requestOptions.headers.baggage) { - newBaggageHeaderField = sentryBaggageHeader; - } else if (!sentryBaggageHeader) { - newBaggageHeaderField = requestOptions.headers.baggage; - } else if (Array.isArray(requestOptions.headers.baggage)) { - newBaggageHeaderField = [...requestOptions.headers.baggage, sentryBaggageHeader]; - } else { - // Type-cast explanation: - // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity - // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this. - newBaggageHeaderField = [requestOptions.headers.baggage, sentryBaggageHeader] ; - } - - requestOptions.headers = { - ...requestOptions.headers, - // Setting a hader to `undefined` will crash in node so we only set the baggage header when it's defined - ...(newBaggageHeaderField && { baggage: newBaggageHeaderField }), - }; - } - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`, - ); - } - - const transaction = parentSpan.transaction; - if (transaction) { - transaction.metadata.propagations++; - } - } - } - - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalRequestMethod - .apply(httpModule, requestArgs) - .once('response', function ( res) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('response', requestUrl, req, res); - } - if (requestSpan) { - if (res.statusCode) { - requestSpan.setHttpStatus(res.statusCode); - } - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }) - .once('error', function () { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; - - if (breadcrumbsEnabled) { - addRequestBreadcrumb('error', requestUrl, req); - } - if (requestSpan) { - requestSpan.setHttpStatus(500); - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }); - }; - }; -} - -/** - * Captures Breadcrumb based on provided request/response pair - */ -function addRequestBreadcrumb(event, url, req, res) { - if (!(0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getIntegration(Http)) { - return; - } - - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().addBreadcrumb( - { - category: 'http', - data: { - method: req.method, - status_code: res && res.statusCode, - url, - }, - type: 'http', - }, - { - event, - request: req, - response: res, - }, - ); -} - - -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1656 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "cleanSpanDescription": () => (/* binding */ cleanSpanDescription), -/* harmony export */ "extractUrl": () => (/* binding */ extractUrl), -/* harmony export */ "isSentryRequest": () => (/* binding */ isSentryRequest), -/* harmony export */ "normalizeRequestArgs": () => (/* binding */ normalizeRequestArgs), -/* harmony export */ "urlToOptions": () => (/* binding */ urlToOptions) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__); - - - - - -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); - -/** - * Checks whether given url points to Sentry server - * @param url url to verify - */ -function isSentryRequest(url) { - const dsn = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getDsn, 'call', _5 => _5()]); - return dsn ? url.includes(dsn.host) : false; -} - -/** - * Assemble a URL to be used for breadcrumbs and spans. - * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL - */ -function extractUrl(requestOptions) { - const protocol = requestOptions.protocol || ''; - const hostname = requestOptions.hostname || requestOptions.host || ''; - // Don't log standard :80 (http) and :443 (https) ports to reduce the noise - const port = - !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`; - const path = requestOptions.path ? requestOptions.path : '/'; - - return `${protocol}//${hostname}${port}${path}`; -} - -/** - * Handle various edge cases in the span description (for spans representing http(s) requests). - * - * @param description current `description` property of the span representing the request - * @param requestOptions Configuration data for the request - * @param Request Request object - * - * @returns The cleaned description - */ -function cleanSpanDescription( - description, - requestOptions, - request, -) { - // nothing to clean - if (!description) { - return description; - } - - // eslint-disable-next-line prefer-const - let [method, requestUrl] = description.split(' '); - - // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, - // we're likely dealing with an internal route and this doesn't apply) - if (requestOptions.host && !requestOptions.protocol) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - requestOptions.protocol = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(request ), 'optionalAccess', _6 => _6.agent, 'optionalAccess', _7 => _7.protocol]); // worst comes to worst, this is undefined and nothing changes - requestUrl = extractUrl(requestOptions); - } - - // internal routes can end up starting with a triple slash rather than a single one - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([requestUrl, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9('///')])) { - requestUrl = requestUrl.slice(2); - } - - return `${method} ${requestUrl}`; -} - -// the node types are missing a few properties which node's `urlToOptions` function spits out - -/** - * Convert a URL object into a RequestOptions object. - * - * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the - * RequestOptions type above. - * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. - */ -function urlToOptions(url) { - const options = { - protocol: url.protocol, - hostname: - typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: `${url.pathname || ''}${url.search || ''}`, - href: url.href, - }; - if (url.port !== '') { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = `${url.username}:${url.password}`; - } - return options; -} - -/** - * Normalize inputs to `http(s).request()` and `http(s).get()`. - * - * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: - * [ RequestOptions | string | URL ], - * [ RequestOptions | string | URL, RequestCallback ], - * [ string | URL, RequestOptions ], and - * [ string | URL, RequestOptions, RequestCallback ]. - * - * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is - * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact - * with the args in a standard way. - * - * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. - * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. - */ -function normalizeRequestArgs( - httpModule, - requestArgs, -) { - let callback, requestOptions; - - // pop off the callback, if there is one - if (typeof requestArgs[requestArgs.length - 1] === 'function') { - callback = requestArgs.pop() ; - } - - // create a RequestOptions object of whatever's at index 0 - if (typeof requestArgs[0] === 'string') { - requestOptions = urlToOptions(new url__WEBPACK_IMPORTED_MODULE_0__.URL(requestArgs[0])); - } else if (requestArgs[0] instanceof url__WEBPACK_IMPORTED_MODULE_0__.URL) { - requestOptions = urlToOptions(requestArgs[0]); - } else { - requestOptions = requestArgs[0]; - } - - // if the options were given separately from the URL, fold them in - if (requestArgs.length === 2) { - requestOptions = { ...requestOptions, ...requestArgs[1] }; - } - - // Figure out the protocol if it's currently missing - if (requestOptions.protocol === undefined) { - // Worst case we end up populating protocol with undefined, which it already is - /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, - // as it will always return `http`, even when using `https` module. - // - // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]); - } else { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - } - - // return args in standardized form - if (callback) { - return [requestOptions, callback]; - } else { - return [requestOptions]; - } -} - - -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1657 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BAGGAGE_HEADER_NAME": () => (/* binding */ BAGGAGE_HEADER_NAME), -/* harmony export */ "MAX_BAGGAGE_STRING_LENGTH": () => (/* binding */ MAX_BAGGAGE_STRING_LENGTH), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX_REGEX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX_REGEX), -/* harmony export */ "baggageHeaderToDynamicSamplingContext": () => (/* binding */ baggageHeaderToDynamicSamplingContext), -/* harmony export */ "dynamicSamplingContextToSentryBaggageHeader": () => (/* binding */ dynamicSamplingContextToSentryBaggageHeader) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); - - - -const BAGGAGE_HEADER_NAME = 'baggage'; - -const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-'; - -const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; - -/** - * Max length of a serialized baggage string - * - * https://www.w3.org/TR/baggage/#limits - */ -const MAX_BAGGAGE_STRING_LENGTH = 8192; - -/** - * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values - * from it. - * - * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. - * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. - */ -function baggageHeaderToDynamicSamplingContext( - // Very liberal definition of what any incoming header might look like - baggageHeader, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(baggageHeader) && !Array.isArray(baggageHeader)) { - return undefined; - } - - // Intermediary object to store baggage key value pairs of incoming baggage headers on. - // It is later used to read Sentry-DSC-values from. - let baggageObject = {}; - - if (Array.isArray(baggageHeader)) { - // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it - baggageObject = baggageHeader.reduce((acc, curr) => { - const currBaggageObject = baggageHeaderToObject(curr); - return { - ...acc, - ...currBaggageObject, - }; - }, {}); - } else { - // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but - // this is how we choose to handle it) - if (!baggageHeader) { - return undefined; - } - - baggageObject = baggageHeaderToObject(baggageHeader); - } - - // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. - const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { - if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { - const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); - acc[nonPrefixedKey] = value; - } - return acc; - }, {}); - - // Only return a dynamic sampling context object if there are keys in it. - // A keyless object means there were no sentry values on the header, which means that there is no DSC. - if (Object.keys(dynamicSamplingContext).length > 0) { - return dynamicSamplingContext ; - } else { - return undefined; - } -} - -/** - * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". - * - * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility - * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is - * `undefined` the function will return `undefined`. - * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` - * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. - */ -function dynamicSamplingContextToSentryBaggageHeader( - // this also takes undefined for convenience and bundle size in other places - dynamicSamplingContext, -) { - // Prefix all DSC keys with "sentry-" and put them into a new object - const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( - (acc, [dscKey, dscValue]) => { - if (dscValue) { - acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; - } - return acc; - }, - {}, - ); - - return objectToBaggageHeader(sentryPrefixedDSC); -} - -/** - * Will parse a baggage header, which is a simple key-value map, into a flat object. - * - * @param baggageHeader The baggage header to parse. - * @returns a flat object containing all the key-value pairs from `baggageHeader`. - */ -function baggageHeaderToObject(baggageHeader) { - return baggageHeader - .split(',') - .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) - .reduce((acc, [key, value]) => { - acc[key] = value; - return acc; - }, {}); -} - -/** - * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. - * - * @param object The object to turn into a baggage header. - * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header - * is not spec compliant. - */ -function objectToBaggageHeader(object) { - if (Object.keys(object).length === 0) { - // An empty baggage header is not spec compliant: We return undefined. - return undefined; - } - - return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { - const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; - const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; - if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn( - `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`, - ); - return baggageHeader; - } else { - return newBaggageHeader; - } - }, ''); -} - - -//# sourceMappingURL=baggage.js.map - - -/***/ }), -/* 1658 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUncaughtException": () => (/* binding */ OnUncaughtException) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1659); - - - - -/** Global Exception handler */ -class OnUncaughtException { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUncaughtException';} - - /** - * @inheritDoc - */ - __init() {this.name = OnUncaughtException.id;} - - /** - * @inheritDoc - */ - __init2() {this.handler = this._makeErrorHandler();} - - // CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts` - - /** - * @inheritDoc - */ - constructor(options = {}) {;OnUncaughtException.prototype.__init.call(this);OnUncaughtException.prototype.__init2.call(this); - this._options = { - exitEvenIfOtherHandlersAreRegistered: true, - ...options, - }; - } - - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('uncaughtException', this.handler); - } - - /** - * @hidden - */ - _makeErrorHandler() { - const timeout = 2000; - let caughtFirstError = false; - let caughtSecondError = false; - let calledFatalError = false; - let firstError; - - return (error) => { - let onFatalError = _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess; - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getClient(); - - if (this._options.onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = this._options.onFatalError; - } else if (client && client.getOptions().onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = client.getOptions().onFatalError ; - } - - // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not - // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust - // exit behaviour of the SDK accordingly: - // - If other listeners are attached, do not exit. - // - If the only listener attached is ours, exit. - const userProvidedListenersCount = global.process - .listeners('uncaughtException') - .reduce((acc, listener) => { - if ( - listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself - listener === this.handler // filter the handler we registered ourselves) - ) { - return acc; - } else { - return acc + 1; - } - }, 0); - - const processWouldExit = userProvidedListenersCount === 0; - const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; - - if (!caughtFirstError) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - - // this is the first uncaught error and the ultimate reason for shutting down - // we want to do absolutely everything possible to ensure it gets captured - // also we want to make sure we don't go recursion crazy if more errors happen after this one - firstError = error; - caughtFirstError = true; - - if (hub.getIntegration(OnUncaughtException)) { - hub.withScope((scope) => { - scope.setLevel('fatal'); - hub.captureException(error, { - originalException: error, - data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, - }); - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - }); - } else { - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - } - } else { - if (shouldApplyFatalHandlingLogic) { - if (calledFatalError) { - // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn( - 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', - ); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(error); - } else if (!caughtSecondError) { - // two cases for how we can hit this branch: - // - capturing of first error blew up and we just caught the exception from that - // - quit trying to capture, proceed with shutdown - // - a second independent error happened while waiting for first error to capture - // - want to avoid causing premature shutdown before first error capture finishes - // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff - // so let's instead just delay a bit before we proceed with our action here - // in case 1, we just wait a bit unnecessarily but ultimately do the same thing - // in case 2, the delay hopefully made us wait long enough for the capture to finish - // two potential nonideal outcomes: - // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError - // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error - // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) - // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish - caughtSecondError = true; - setTimeout(() => { - if (!calledFatalError) { - // it was probably case 1, let's treat err as the sendErr and call onFatalError - calledFatalError = true; - onFatalError(firstError, error); - } else { - // it was probably case 2, our first error finished capturing while we waited, cool, do nothing - } - }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc - } - } - } - }; - } -} OnUncaughtException.__initStatic(); - - -//# sourceMappingURL=onuncaughtexception.js.map - - -/***/ }), -/* 1659 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "logAndExitProcess": () => (/* binding */ logAndExitProcess) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); - - - -const DEFAULT_SHUTDOWN_TIMEOUT = 2000; - -/** - * @hidden - */ -function logAndExitProcess(error) { - // eslint-disable-next-line no-console - console.error(error && error.stack ? error.stack : error); - - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().getClient(); - - if (client === undefined) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('No NodeClient was defined, we are exiting the process now.'); - global.process.exit(1); - } - - const options = client.getOptions(); - const timeout = - (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || - DEFAULT_SHUTDOWN_TIMEOUT; - client.close(timeout).then( - (result) => { - if (!result) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); - } - global.process.exit(1); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error(error); - }, - ); -} - - -//# sourceMappingURL=errorhandling.js.map - - -/***/ }), -/* 1660 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUnhandledRejection": () => (/* binding */ OnUnhandledRejection) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1659); - - - - -/** Global Promise Rejection handler */ -class OnUnhandledRejection { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUnhandledRejection';} - - /** - * @inheritDoc - */ - __init() {this.name = OnUnhandledRejection.id;} - - /** - * @inheritDoc - */ - constructor( - _options - - = { mode: 'warn' }, - ) {;this._options = _options;OnUnhandledRejection.prototype.__init.call(this);} - - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); - } - - /** - * Send an exception with reason - * @param reason string - * @param promise promise - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any - sendUnhandledPromise(reason, promise) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - if (hub.getIntegration(OnUnhandledRejection)) { - hub.withScope((scope) => { - scope.setExtra('unhandledPromiseRejection', true); - hub.captureException(reason, { - originalException: promise, - data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, - }); - }); - } - this._handleRejection(reason); - } - - /** - * Handler for `mode` option - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _handleRejection(reason) { - // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 - const rejectionWarning = - 'This error originated either by ' + - 'throwing inside of an async function without a catch block, ' + - 'or by rejecting a promise which was not handled with .catch().' + - ' The promise rejected with the reason:'; - - /* eslint-disable no-console */ - if (this._options.mode === 'warn') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - console.error(reason && reason.stack ? reason.stack : reason); - }); - } else if (this._options.mode === 'strict') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - }); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(reason); - } - /* eslint-enable no-console */ - } -} OnUnhandledRejection.__initStatic(); - - -//# sourceMappingURL=onunhandledrejection.js.map - - -/***/ }), -/* 1661 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "LinkedErrors": () => (/* binding */ LinkedErrors) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1603); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1614); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1628); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1662); - - - - - - -const DEFAULT_KEY = 'cause'; -const DEFAULT_LIMIT = 5; - -/** Adds SDK info to an event. */ -class LinkedErrors { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'LinkedErrors';} - - /** - * @inheritDoc - */ - __init() {this.name = LinkedErrors.id;} - - /** - * @inheritDoc - */ - - /** - * @inheritDoc - */ - - /** - * @inheritDoc - */ - constructor(options = {}) {;LinkedErrors.prototype.__init.call(this); - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; - } - - /** - * @inheritDoc - */ - setupOnce() { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor)(async (event, hint) => { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)(); - const self = hub.getIntegration(LinkedErrors); - const client = hub.getClient(); - if (client && self && self._handler && typeof self._handler === 'function') { - await self._handler(client.getOptions().stackParser, event, hint); - } - return event; - }); - } - - /** - * @inheritDoc - */ - _handler(stackParser, event, hint) { - if (!event.exception || !event.exception.values || !(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(hint.originalException, Error)) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.resolvedSyncPromise)(event); - } - - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SyncPromise(resolve => { - void this._walkErrorTree(stackParser, hint.originalException , this._key) - .then((linkedErrors) => { - if (event && event.exception && event.exception.values) { - event.exception.values = [...linkedErrors, ...event.exception.values]; - } - resolve(event); - }) - .then(null, () => { - resolve(event); - }); - }); - } - - /** - * @inheritDoc - */ - async _walkErrorTree( - stackParser, - error, - key, - stack = [], - ) { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(error[key], Error) || stack.length + 1 >= this._limit) { - return Promise.resolve(stack); - } - - const exception = (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__.exceptionFromError)(stackParser, error[key]); - - // If the ContextLines integration is enabled, we add source code context to linked errors - // because we can't guarantee the order that integrations are run. - const contextLines = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(_contextlines_js__WEBPACK_IMPORTED_MODULE_1__.ContextLines); - if (contextLines && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__._optionalChain)([exception, 'access', _ => _.stacktrace, 'optionalAccess', _2 => _2.frames])) { - await contextLines.addSourceContextToFrames(exception.stacktrace.frames); - } - - return new Promise((resolve, reject) => { - void this._walkErrorTree(stackParser, error[key], key, [exception, ...stack]) - .then(resolve) - .then(null, () => { - reject(); - }); - }); - } -}LinkedErrors.__initStatic(); - - -//# sourceMappingURL=linkederrors.js.map - - -/***/ }), -/* 1662 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "ContextLines": () => (/* binding */ ContextLines), -/* harmony export */ "resetFileContentCache": () => (/* binding */ resetFileContentCache) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1609); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1663); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lru_map__WEBPACK_IMPORTED_MODULE_1__); - - - - - -const FILE_CONTENT_CACHE = new lru_map__WEBPACK_IMPORTED_MODULE_1__.LRUMap(100); -const DEFAULT_LINES_OF_CONTEXT = 7; - -// TODO: Replace with promisify when minimum supported node >= v8 -function readTextFileAsync(path) { - return new Promise((resolve, reject) => { - (0,fs__WEBPACK_IMPORTED_MODULE_0__.readFile)(path, 'utf8', (err, data) => { - if (err) reject(err); - else resolve(data); - }); - }); -} - -/** - * Resets the file cache. Exists for testing purposes. - * @hidden - */ -function resetFileContentCache() { - FILE_CONTENT_CACHE.clear(); -} - -/** Add node modules / packages to the event */ -class ContextLines { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'ContextLines';} - - /** - * @inheritDoc - */ - __init() {this.name = ContextLines.id;} - - constructor( _options = {}) {;this._options = _options;ContextLines.prototype.__init.call(this);} - - /** Get's the number of context lines to add */ - get _contextLines() { - return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; - } - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addSourceContext(event)); - } - - /** Processes an event and adds context lines */ - async addSourceContext(event) { - if (this._contextLines > 0 && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) { - for (const exception of event.exception.values) { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) { - await this.addSourceContextToFrames(exception.stacktrace.frames); - } - } - } - - return event; - } - - /** Adds context lines to frames */ - async addSourceContextToFrames(frames) { - const contextLines = this._contextLines; - - for (const frame of frames) { - // Only add context if we have a filename and it hasn't already been added - if (frame.filename && frame.context_line === undefined) { - const sourceFile = await _readSourceFile(frame.filename); - - if (sourceFile) { - try { - const lines = sourceFile.split('\n'); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.addContextToFrame)(lines, frame, contextLines); - } catch (e) { - // anomaly, being defensive in case - // unlikely to ever happen in practice but can definitely happen in theory - } - } - } - } - } -}ContextLines.__initStatic(); - -/** - * Reads file contents and caches them in a global LRU cache. - * - * @param filename filepath to read content from. - */ -async function _readSourceFile(filename) { - const cachedFile = FILE_CONTENT_CACHE.get(filename); - // We have a cache hit - if (cachedFile !== undefined) { - return cachedFile; - } - - let content = null; - try { - content = await readTextFileAsync(filename); - } catch (_) { - // - } - - FILE_CONTENT_CACHE.set(filename, content); - return content; -} - - -//# sourceMappingURL=contextlines.js.map - - -/***/ }), -/* 1663 */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/** - * 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 <http://hunch.se/> - * 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 (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } -})(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 <D> 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 <key> 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); - - if (entry) { - // update existing - entry.value = value; - this._markEntryAsUsed(entry); - return this; - } - - // new entry - this._keymap.set(key, (entry = new Entry(key, value))); - - 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; - } - - // 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 <entry> 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]; - } -}; - -// ---------------------------------------------------------------------------- -// Following code is optional and can be removed without breaking the core -// functionality. - -LRUMap.prototype.find = function(key) { - let e = this._keymap.get(key); - return e ? e.value : undefined; -}; - -LRUMap.prototype.has = function(key) { - return this._keymap.has(key); -}; - -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; - } - - this.size--; - return entry.value; -}; - -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(); -}; - - -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 }; - } -}; - - -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 }; - } -}; - -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 }; - } -}; - - -LRUMap.prototype.keys = function() { - return new KeyIterator(this.oldest); -}; - -LRUMap.prototype.values = function() { - return new ValueIterator(this.oldest); -}; - -LRUMap.prototype.entries = function() { - return this; -}; - -LRUMap.prototype[Symbol.iterator] = function() { - return new EntryIterator(this.oldest); -}; - -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]; - } -}; - -/** 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; -}; - -}); - - -/***/ }), -/* 1664 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Modules": () => (/* binding */ Modules) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); - - - -let moduleCache; - -/** Extract information about paths */ -function getPaths() { - try { - return __webpack_require__.c ? Object.keys(__webpack_require__.c ) : []; - } catch (e) { - return []; - } -} - -/** Extract information about package.json modules */ -function collectModules() - - { - const mainPaths = (__webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].paths) || []; - const paths = getPaths(); - const infos - - = {}; - const seen - - = {}; - - paths.forEach(path => { - let dir = path; - - /** Traverse directories upward in the search of package.json file */ - const updir = () => { - const orig = dir; - dir = (0,path__WEBPACK_IMPORTED_MODULE_1__.dirname)(orig); - - if (!dir || orig === dir || seen[orig]) { - return undefined; - } - if (mainPaths.indexOf(dir) < 0) { - return updir(); - } - - const pkgfile = (0,path__WEBPACK_IMPORTED_MODULE_1__.join)(orig, 'package.json'); - seen[orig] = true; - - if (!(0,fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(pkgfile)) { - return updir(); - } - - try { - const info = JSON.parse((0,fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(pkgfile, 'utf8')) - -; - infos[info.name] = info.version; - } catch (_oO) { - // no-empty - } - }; - - updir(); - }); - - return infos; -} - -/** Add node modules / packages to the event */ -class Modules {constructor() { Modules.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Modules';} - - /** - * @inheritDoc - */ - __init() {this.name = Modules.id;} - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - addGlobalEventProcessor(event => { - if (!getCurrentHub().getIntegration(Modules)) { - return event; - } - return { - ...event, - modules: { - ...event.modules, - ...this._getModules(), - }, - }; - }); - } - - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ - _getModules() { - if (!moduleCache) { - moduleCache = collectModules(); - } - return moduleCache; - } -} Modules.__initStatic(); - - -//# sourceMappingURL=modules.js.map - - -/***/ }), -/* 1665 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Context": () => (/* binding */ Context), -/* harmony export */ "getDeviceContext": () => (/* binding */ getDeviceContext), -/* harmony export */ "readDirAsync": () => (/* binding */ readDirAsync), -/* harmony export */ "readFileAsync": () => (/* binding */ readFileAsync) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(828); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); - - - - - - - -// TODO: Required until we drop support for Node v8 -const readFileAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readFile); -const readDirAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readdir); - -/** Add node modules / packages to the event */ -class Context { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Context';} - - /** - * @inheritDoc - */ - __init() {this.name = Context.id;} - - /** - * Caches context so it's only evaluated once - */ - - constructor( _options = { app: true, os: true, device: true, culture: true }) {;this._options = _options;Context.prototype.__init.call(this); - // - } - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addContext(event)); - } - - /** Processes an event and adds context */ - async addContext(event) { - if (this._cachedContext === undefined) { - this._cachedContext = this._getContexts(); - } - - const updatedContext = this._updateContext(await this._cachedContext); - - event.contexts = { - ...event.contexts, - app: { ...updatedContext.app, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) }, - os: { ...updatedContext.os, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) }, - device: { ...updatedContext.device, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) }, - culture: { ...updatedContext.culture, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) }, - }; - - return event; - } - - /** - * Updates the context with dynamic values that can change - */ - _updateContext(contexts) { - // Only update properties if they exist - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _9 => _9.app, 'optionalAccess', _10 => _10.app_memory])) { - contexts.app.app_memory = process.memoryUsage().rss; - } - - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _11 => _11.device, 'optionalAccess', _12 => _12.free_memory])) { - contexts.device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); - } - - return contexts; - } - - /** - * Gets the contexts for the current environment - */ - async _getContexts() { - const contexts = {}; - - if (this._options.os) { - contexts.os = await getOsContext(); - } - - if (this._options.app) { - contexts.app = getAppContext(); - } - - if (this._options.device) { - contexts.device = getDeviceContext(this._options.device); - } - - if (this._options.culture) { - const culture = getCultureContext(); - - if (culture) { - contexts.culture = culture; - } - } - - return contexts; - } -}Context.__initStatic(); - -/** - * Returns the operating system context. - * - * Based on the current platform, this uses a different strategy to provide the - * most accurate OS information. Since this might involve spawning subprocesses - * or accessing the file system, this should only be executed lazily and cached. - * - * - On macOS (Darwin), this will execute the `sw_vers` utility. The context - * has a `name`, `version`, `build` and `kernel_version` set. - * - On Linux, this will try to load a distribution release from `/etc` and set - * the `name`, `version` and `kernel_version` fields. - * - On all other platforms, only a `name` and `version` will be returned. Note - * that `version` might actually be the kernel version. - */ -async function getOsContext() { - const platformId = os__WEBPACK_IMPORTED_MODULE_2__.platform(); - switch (platformId) { - case 'darwin': - return getDarwinInfo(); - case 'linux': - return getLinuxInfo(); - default: - return { - name: PLATFORM_NAMES[platformId] || platformId, - version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - }; - } -} - -function getCultureContext() { - try { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (typeof (process.versions ).icu !== 'string') { - // Node was built without ICU support - return; - } - - // Check that node was built with full Intl support. Its possible it was built without support for non-English - // locales which will make resolvedOptions inaccurate - // - // https://nodejs.org/api/intl.html#detecting-internationalization-support - const january = new Date(9e8); - const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); - if (spanish.format(january) === 'enero') { - const options = Intl.DateTimeFormat().resolvedOptions(); - - return { - locale: options.locale, - timezone: options.timeZone, - }; - } - } catch (err) { - // - } - - return; -} - -function getAppContext() { - const app_memory = process.memoryUsage().rss; - const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); - - return { app_start_time, app_memory }; -} - -/** - * Gets device information from os - */ -function getDeviceContext(deviceOpt) { - const device = {}; - - // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). - // Hence, we only set boot time, if we get a valid uptime value. - // @see https://github.com/getsentry/sentry-javascript/issues/5856 - const uptime = os__WEBPACK_IMPORTED_MODULE_2__.uptime && os__WEBPACK_IMPORTED_MODULE_2__.uptime(); - if (typeof uptime === 'number') { - device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); - } - - device.arch = os__WEBPACK_IMPORTED_MODULE_2__.arch(); - - if (deviceOpt === true || deviceOpt.memory) { - device.memory_size = os__WEBPACK_IMPORTED_MODULE_2__.totalmem(); - device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); - } - - if (deviceOpt === true || deviceOpt.cpu) { - const cpuInfo = os__WEBPACK_IMPORTED_MODULE_2__.cpus(); - if (cpuInfo && cpuInfo.length) { - const firstCpu = cpuInfo[0]; - - device.processor_count = cpuInfo.length; - device.cpu_description = firstCpu.model; - device.processor_frequency = firstCpu.speed; - } - } - - return device; -} - -/** Mapping of Node's platform names to actual OS names. */ -const PLATFORM_NAMES = { - aix: 'IBM AIX', - freebsd: 'FreeBSD', - openbsd: 'OpenBSD', - sunos: 'SunOS', - win32: 'Windows', -}; - -/** Linux version file to check for a distribution. */ - -/** Mapping of linux release files located in /etc to distributions. */ -const LINUX_DISTROS = [ - { name: 'fedora-release', distros: ['Fedora'] }, - { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, - { name: 'redhat_version', distros: ['Red Hat Linux'] }, - { name: 'SuSE-release', distros: ['SUSE Linux'] }, - { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, - { name: 'debian_version', distros: ['Debian'] }, - { name: 'debian_release', distros: ['Debian'] }, - { name: 'arch-release', distros: ['Arch Linux'] }, - { name: 'gentoo-release', distros: ['Gentoo Linux'] }, - { name: 'novell-release', distros: ['SUSE Linux'] }, - { name: 'alpine-release', distros: ['Alpine Linux'] }, -]; - -/** Functions to extract the OS version from Linux release files. */ -const LINUX_VERSIONS - - = { - alpine: content => content, - arch: content => matchFirst(/distrib_release=(.*)/, content), - centos: content => matchFirst(/release ([^ ]+)/, content), - debian: content => content, - fedora: content => matchFirst(/release (..)/, content), - mint: content => matchFirst(/distrib_release=(.*)/, content), - red: content => matchFirst(/release ([^ ]+)/, content), - suse: content => matchFirst(/VERSION = (.*)\n/, content), - ubuntu: content => matchFirst(/distrib_release=(.*)/, content), -}; - -/** - * Executes a regular expression with one capture group. - * - * @param regex A regular expression to execute. - * @param text Content to execute the RegEx on. - * @returns The captured string if matched; otherwise undefined. - */ -function matchFirst(regex, text) { - const match = regex.exec(text); - return match ? match[1] : undefined; -} - -/** Loads the macOS operating system context. */ -async function getDarwinInfo() { - // Default values that will be used in case no operating system information - // can be loaded. The default version is computed via heuristics from the - // kernel version, but the build ID is missing. - const darwinInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Mac OS X', - version: `10.${Number(os__WEBPACK_IMPORTED_MODULE_2__.release().split('.')[0]) - 4}`, - }; - - try { - // We try to load the actual macOS version by executing the `sw_vers` tool. - // This tool should be available on every standard macOS installation. In - // case this fails, we stick with the values computed above. - - const output = await new Promise((resolve, reject) => { - (0,child_process__WEBPACK_IMPORTED_MODULE_0__.execFile)('/usr/bin/sw_vers', (error, stdout) => { - if (error) { - reject(error); - return; - } - resolve(stdout); - }); - }); - - darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); - darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); - darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); - } catch (e) { - // ignore - } - - return darwinInfo; -} - -/** Returns a distribution identifier to look up version callbacks. */ -function getLinuxDistroId(name) { - return name.split(' ')[0].toLowerCase(); -} - -/** Loads the Linux operating system context. */ -async function getLinuxInfo() { - // By default, we cannot assume anything about the distribution or Linux - // version. `os.release()` returns the kernel version and we assume a generic - // "Linux" name, which will be replaced down below. - const linuxInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Linux', - }; - - try { - // We start guessing the distribution by listing files in the /etc - // directory. This is were most Linux distributions (except Knoppix) store - // release files with certain distribution-dependent meta data. We search - // for exactly one known file defined in `LINUX_DISTROS` and exit if none - // are found. In case there are more than one file, we just stick with the - // first one. - const etcFiles = await readDirAsync('/etc'); - const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); - if (!distroFile) { - return linuxInfo; - } - - // Once that file is known, load its contents. To make searching in those - // files easier, we lowercase the file contents. Since these files are - // usually quite small, this should not allocate too much memory and we only - // hold on to it for a very short amount of time. - const distroPath = (0,path__WEBPACK_IMPORTED_MODULE_3__.join)('/etc', distroFile.name); - const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase(); - - // Some Linux distributions store their release information in the same file - // (e.g. RHEL and Centos). In those cases, we scan the file for an - // identifier, that basically consists of the first word of the linux - // distribution name (e.g. "red" for Red Hat). In case there is no match, we - // just assume the first distribution in our list. - const { distros } = distroFile; - linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; - - // Based on the found distribution, we can now compute the actual version - // number. This is different for every distribution, so several strategies - // are computed in `LINUX_VERSIONS`. - const id = getLinuxDistroId(linuxInfo.name); - linuxInfo.version = LINUX_VERSIONS[id](contents); - } catch (e) { - // ignore - } - - return linuxInfo; -} - - -//# sourceMappingURL=context.js.map - - -/***/ }), -/* 1666 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "RequestData": () => (/* binding */ RequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1670); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1667); - - - -const DEFAULT_OPTIONS = { - include: { - cookies: true, - data: true, - headers: true, - ip: false, - query_string: true, - url: true, - user: { - id: true, - username: true, - email: true, - }, - }, - transactionNamingScheme: 'methodPath', -}; - -/** Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` - * so it can be used in cross-platform SDKs like `@sentry/nextjs`. */ -class RequestData { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'RequestData';} - - /** - * @inheritDoc - */ - __init() {this.name = RequestData.id;} - - /** - * Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but - * left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use - * something similar in browser-based SDKs in the future. - */ - - /** - * @inheritDoc - */ - constructor(options = {}) {;RequestData.prototype.__init.call(this); - this._addRequestData = _requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent; - this._options = { - ...DEFAULT_OPTIONS, - ...options, - include: { - // @ts-ignore It's mad because `method` isn't a known `include` key. (It's only here and not set by default in - // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) - method: true, - ...DEFAULT_OPTIONS.include, - ...options.include, - user: - options.include && typeof options.include.user === 'boolean' - ? options.include.user - : { - ...DEFAULT_OPTIONS.include.user, - // Unclear why TS still thinks `options.include.user` could be a boolean at this point - ...((options.include || {}).user ), - }, - }, - }; - } - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - // Note: In the long run, most of the logic here should probably move into the request data utility functions. For - // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. - // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once - // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) - const { transactionNamingScheme } = this._options; - - addGlobalEventProcessor(event => { - const hub = getCurrentHub(); - const self = hub.getIntegration(RequestData); - - const { sdkProcessingMetadata = {} } = event; - const req = sdkProcessingMetadata.request; - - // If the globally installed instance of this integration isn't associated with the current hub, `self` will be - // undefined - if (!self || !req) { - return event; - } - - // The Express request handler takes a similar `include` option to that which can be passed to this integration. - // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this - // integration, so that all of this passing and conversion isn't necessary - const addRequestDataOptions = - sdkProcessingMetadata.requestDataOptionsFromExpressHandler || - sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || - convertReqDataIntegrationOptsToAddReqDataOpts(this._options); - - const processedEvent = this._addRequestData(event, req, addRequestDataOptions); - - // Transaction events already have the right `transaction` value - if (event.type === 'transaction' || transactionNamingScheme === 'handler') { - return processedEvent; - } - - // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` - // value with a high-quality one - const reqWithTransaction = req ; - const transaction = reqWithTransaction._sentryTransaction; - if (transaction) { - // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to - // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential - // to break things like alert rules.) - const shouldIncludeMethodInTransactionName = - getSDKName(hub) === 'sentry.javascript.nextjs' - ? transaction.name.startsWith('/api') - : transactionNamingScheme !== 'path'; - - const [transactionValue] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractPathForTransaction)(req, { - path: true, - method: shouldIncludeMethodInTransactionName, - customRoute: transaction.name, - }); - - processedEvent.transaction = transactionValue; - } - - return processedEvent; - }); - } -} RequestData.__initStatic(); - -/** Convert this integration's options to match what `addRequestDataToEvent` expects */ -/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */ -function convertReqDataIntegrationOptsToAddReqDataOpts( - integrationOptions, -) { - const { - transactionNamingScheme, - include: { ip, user, ...requestOptions }, - } = integrationOptions; - - const requestIncludeKeys = []; - for (const [key, value] of Object.entries(requestOptions)) { - if (value) { - requestIncludeKeys.push(key); - } - } - - let addReqDataUserOpt; - if (user === undefined) { - addReqDataUserOpt = true; - } else if (typeof user === 'boolean') { - addReqDataUserOpt = user; - } else { - const userIncludeKeys = []; - for (const [key, value] of Object.entries(user)) { - if (value) { - userIncludeKeys.push(key); - } - } - addReqDataUserOpt = userIncludeKeys; - } - - return { - include: { - ip, - user: addReqDataUserOpt, - request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, - transaction: transactionNamingScheme, - }, - }; -} - -function getSDKName(hub) { - try { - // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to - // write out a long chain of `a && a.b && a.b.c && ...` - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return hub.getClient().getOptions()._metadata.sdk.name; - } catch (err) { - // In theory we should never get here - return undefined; - } -} - - -//# sourceMappingURL=requestdata.js.map - - -/***/ }), -/* 1667 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* binding */ DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1669); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1622); -/* harmony import */ var cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_1__); - - - - - -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, -}; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; - -/** - * Options deciding what parts of the request to use when enhancing an event - */ - -/** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addRequestDataToTransaction(transaction, req) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); - } - transaction.setData('query', extractQueryParams(req)); -} - -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); - - let path = ''; - let source = 'url'; - - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; - } - - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); - } - - let name = ''; - if (options.method && method) { - name += method; - } - if (options.method && options.path) { - name += ' '; - } - if (options.path && path) { - name += path; - } - - return [name, source]; -} - -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; - } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; - } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; - } - } -} - -/** JSDoc */ -function extractUserData( - user - -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; - - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; - } - }); - - return extractedUser; -} - -/** - * Normalize data from the request object - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies - * - * @returns An object containing normalized request data - */ -function extractRequestData( - req, - options - -, -) { - const { include = DEFAULT_REQUEST_INCLUDES } = options || {}; - const requestData = {}; - - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) - -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; - - // Remove the Cookie header in case cookie data should not be included in the event - if (!include.includes('cookies')) { - delete (requestData.headers ).cookie; - } - - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && cookie__WEBPACK_IMPORTED_MODULE_0__.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isString)(req.body) ? req.body : JSON.stringify((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.normalize)(req.body)); - } - break; - } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; - } - } - } - }); - - return requestData; -} - -/** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included - * - * @returns The mutated `Event` object - */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([options, 'optionalAccess', _ => _.include]), - }; - - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request }) - : extractRequestData(req); - - event.request = { - ...event.request, - ...extractedRequestData, - }; - } - - if (include.user) { - const extractedUser = req.user && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; - - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; - } - } - - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; - } - } - - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); - } - - return event; -} - -function extractQueryParams(req) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; - - if (!originalUrl) { - return; - } - - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; - } - - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - url__WEBPACK_IMPORTED_MODULE_1__.parse(originalUrl).query || - undefined - ); -} - - -//# sourceMappingURL=requestdata.js.map - - -/***/ }), -/* 1668 */ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module exports. - * @public - */ - -exports.parse = parse; -exports.serialize = serialize; - -/** - * Module variables. - * @private - */ - -var decode = decodeURIComponent; -var encode = encodeURIComponent; - -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ - -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; - -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ - -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } - - var obj = {} - var opt = options || {}; - var pairs = str.split(';') - var dec = opt.decode || decode; - - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var index = pair.indexOf('=') - - // skip things that don't look like key=value - if (index < 0) { - continue; - } - - var key = pair.substring(0, index).trim() - - // only assign once - if (undefined == obj[key]) { - var val = pair.substring(index + 1, pair.length).trim() - - // quoted values - if (val[0] === '"') { - val = val.slice(1, -1) - } - - obj[key] = tryDecode(val, dec); - } - } - - return obj; -} - -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ - -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; - - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } - - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } - - var value = enc(val); - - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } - - var str = name + '=' + value; - - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; - - if (isNaN(maxAge) || !isFinite(maxAge)) { - throw new TypeError('option maxAge is invalid') - } - - str += '; Max-Age=' + Math.floor(maxAge); - } - - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } - - str += '; Domain=' + opt.domain; - } - - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } - - str += '; Path=' + opt.path; - } - - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); - } - - str += '; Expires=' + opt.expires.toUTCString(); - } - - if (opt.httpOnly) { - str += '; HttpOnly'; - } - - if (opt.secure) { - str += '; Secure'; - } - - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; - - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } - } - - return str; -} - -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ - -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} - - -/***/ }), -/* 1669 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getNumberOfUrlSegments": () => (/* binding */ getNumberOfUrlSegments), -/* harmony export */ "parseUrl": () => (/* binding */ parseUrl), -/* harmony export */ "stripUrlQueryAndFragment": () => (/* binding */ stripUrlQueryAndFragment) -/* harmony export */ }); -/** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not <a/> href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object - */ -function parseUrl(url) - - { - if (!url) { - return {}; - } - - const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - - if (!match) { - return {}; - } - - // coerce to undefined values to empty string so we don't get 'undefined' - const query = match[6] || ''; - const fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, // everything minus origin - }; -} - -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} - -/** - * Returns number of URL segments of a passed string URL. - */ -function getNumberOfUrlSegments(url) { - // split at '/' or at '\/' to split regex urls correctly - return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length; -} - - -//# sourceMappingURL=url.js.map - - -/***/ }), -/* 1670 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1625); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1622); -/* harmony import */ var _url_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1669); - - - - - -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, -}; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; - -/** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addRequestDataToTransaction( - transaction, - req, - deps, -) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); - } - transaction.setData('query', extractQueryParams(req, deps)); -} - -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); - - let path = ''; - let source = 'url'; - - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; - } - - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_url_js__WEBPACK_IMPORTED_MODULE_0__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); - } - - let name = ''; - if (options.method && method) { - name += method; - } - if (options.method && options.path) { - name += ' '; - } - if (options.path && path) { - name += path; - } - - return [name, source]; -} - -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; - } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; - } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; - } - } -} - -/** JSDoc */ -function extractUserData( - user - -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; - - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; - } - }); - - return extractedUser; -} - -/** - * Normalize data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies - * @returns An object containing normalized request data - */ -function extractRequestData( - req, - options - -, -) { - const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; - const requestData = {}; - - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) - -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && deps && deps.cookie && deps.cookie.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req, deps); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(req.body) ? req.body : JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_2__.normalize)(req.body)); - } - break; - } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; - } - } - } - }); - - return requestData; -} - -/** - * Options deciding what parts of the request to use when enhancing an event - */ - -/** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included - * @param options.deps Injected platform-specific dependencies - * @hidden - */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _ => _.include]), - }; - - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request, deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _2 => _2.deps]) }) - : extractRequestData(req, { deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _3 => _3.deps]) }); - - event.request = { - ...event.request, - ...extractedRequestData, - }; - } - - if (include.user) { - const extractedUser = req.user && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; - - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; - } - } - - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; - } - } - - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); - } - - return event; -} - -function extractQueryParams( - req, - deps, -) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; - - if (!originalUrl) { - return; - } - - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; - } - - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - (deps && deps.url && deps.url.parse(originalUrl).query) || - undefined - ); -} - - -//# sourceMappingURL=requestdata.js.map - - -/***/ }), -/* 1671 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getModule": () => (/* binding */ getModule) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1672); - - -/** normalizes Windows paths */ -function normalizePath(path) { - return path - .replace(/^[A-Z]:/, '') // remove Windows-style prefix - .replace(/\\/g, '/'); // replace all `\` instances with `/` -} - -/** Gets the module from a filename */ -function getModule(filename) { - if (!filename) { - return; - } - - const normalizedFilename = normalizePath(filename); - - // We could use optional chaining here but webpack does like that mixed with require - const base = normalizePath( - `${( true && __webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].filename && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(__webpack_require__.c[__webpack_require__.s].filename)) || global.process.cwd()}/`, - ); - - // It's specifically a module - const file = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.basename)(normalizedFilename, '.js'); - - const path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(normalizedFilename); - let n = path.lastIndexOf('/node_modules/'); - if (n > -1) { - // /node_modules/ is 14 chars - return `${path.substr(n + 14).replace(/\//g, '.')}:${file}`; - } - // Let's see if it's a part of the main module - // To be a part of main module, it has to share the same base - n = `${path}/`.lastIndexOf(base, 0); - - if (n === 0) { - let moduleName = path.substr(base.length).replace(/\//g, '.'); - if (moduleName) { - moduleName += ':'; - } - moduleName += file; - return moduleName; - } - return file; -} - - -//# sourceMappingURL=module.js.map - - -/***/ }), -/* 1672 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "basename": () => (/* binding */ basename), -/* harmony export */ "dirname": () => (/* binding */ dirname), -/* harmony export */ "isAbsolute": () => (/* binding */ isAbsolute), -/* harmony export */ "join": () => (/* binding */ join), -/* harmony export */ "normalizePath": () => (/* binding */ normalizePath), -/* harmony export */ "relative": () => (/* binding */ relative), -/* harmony export */ "resolve": () => (/* binding */ resolve) -/* harmony export */ }); -// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript -// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js - -/** JSDoc */ -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - let up = 0; - for (let i = parts.length - 1; i >= 0; i--) { - const last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; -/** JSDoc */ -function splitPath(filename) { - const parts = splitPathRe.exec(filename); - return parts ? parts.slice(1) : []; -} - -// path.resolve([from ...], to) -// posix version -/** JSDoc */ -function resolve(...args) { - let resolvedPath = ''; - let resolvedAbsolute = false; - - for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - const path = i >= 0 ? args[i] : '/'; - - // Skip empty entries - if (!path) { - continue; - } - - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray( - resolvedPath.split('/').filter(p => !!p), - !resolvedAbsolute, - ).join('/'); - - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; -} - -/** JSDoc */ -function trim(arr) { - let start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') { - break; - } - } - - let end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') { - break; - } - } - - if (start > end) { - return []; - } - return arr.slice(start, end - start + 1); -} - -// path.relative(from, to) -// posix version -/** JSDoc */ -function relative(from, to) { - /* eslint-disable no-param-reassign */ - from = resolve(from).substr(1); - to = resolve(to).substr(1); - /* eslint-enable no-param-reassign */ - - const fromParts = trim(from.split('/')); - const toParts = trim(to.split('/')); - - const length = Math.min(fromParts.length, toParts.length); - let samePartsLength = length; - for (let i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - let outputParts = []; - for (let i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -} - -// path.normalize(path) -// posix version -/** JSDoc */ -function normalizePath(path) { - const isPathAbsolute = isAbsolute(path); - const trailingSlash = path.substr(-1) === '/'; - - // Normalize the path - let normalizedPath = normalizeArray( - path.split('/').filter(p => !!p), - !isPathAbsolute, - ).join('/'); - - if (!normalizedPath && !isPathAbsolute) { - normalizedPath = '.'; - } - if (normalizedPath && trailingSlash) { - normalizedPath += '/'; - } - - return (isPathAbsolute ? '/' : '') + normalizedPath; -} - -// posix version -/** JSDoc */ -function isAbsolute(path) { - return path.charAt(0) === '/'; -} - -// posix version -/** JSDoc */ -function join(...args) { - return normalizePath(args.join('/')); -} - -/** JSDoc */ -function dirname(path) { - const result = splitPath(path); - const root = result[0]; - let dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -} - -/** JSDoc */ -function basename(path, ext) { - let f = splitPath(path)[2]; - if (ext && f.substr(ext.length * -1) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -} - - -//# sourceMappingURL=path.js.map - - -/***/ }), -/* 1673 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "InboundFilters": () => (/* binding */ InboundFilters), -/* harmony export */ "_mergeOptions": () => (/* binding */ _mergeOptions), -/* harmony export */ "_shouldDropEvent": () => (/* binding */ _shouldDropEvent) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1610); - - -// "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. -const DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; - -/** Options for the InboundFilters integration */ - -/** Inbound filters configurable by the user */ -class InboundFilters { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'InboundFilters';} - - /** - * @inheritDoc - */ - __init() {this.name = InboundFilters.id;} - - constructor( _options = {}) {;this._options = _options;InboundFilters.prototype.__init.call(this);} - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - const eventProcess = (event) => { - const hub = getCurrentHub(); - if (hub) { - const self = hub.getIntegration(InboundFilters); - if (self) { - const client = hub.getClient(); - const clientOptions = client ? client.getOptions() : {}; - const options = _mergeOptions(self._options, clientOptions); - return _shouldDropEvent(event, options) ? null : event; - } - } - return event; - }; - - eventProcess.id = this.name; - addGlobalEventProcessor(eventProcess); - } -} InboundFilters.__initStatic(); - -/** JSDoc */ -function _mergeOptions( - internalOptions = {}, - clientOptions = {}, -) { - return { - allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], - denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], - ignoreErrors: [ - ...(internalOptions.ignoreErrors || []), - ...(clientOptions.ignoreErrors || []), - ...DEFAULT_IGNORE_ERRORS, - ], - ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, - }; -} - -/** JSDoc */ -function _shouldDropEvent(event, options) { - if (options.ignoreInternal && _isSentryError(event)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return true; - } - if (_isIgnoredError(event, options.ignoreErrors)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`, - ); - return true; - } - if (_isDeniedUrl(event, options.denyUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; - } - if (!_isAllowedUrl(event, options.allowUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; - } - return false; -} - -function _isIgnoredError(event, ignoreErrors) { - if (!ignoreErrors || !ignoreErrors.length) { - return false; - } - - return _getPossibleEventMessages(event).some(message => (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(message, ignoreErrors)); -} - -function _isDeniedUrl(event, denyUrls) { - // TODO: Use Glob instead? - if (!denyUrls || !denyUrls.length) { - return false; - } - const url = _getEventFilterUrl(event); - return !url ? false : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, denyUrls); -} - -function _isAllowedUrl(event, allowUrls) { - // TODO: Use Glob instead? - if (!allowUrls || !allowUrls.length) { - return true; - } - const url = _getEventFilterUrl(event); - return !url ? true : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, allowUrls); -} - -function _getPossibleEventMessages(event) { - if (event.message) { - return [event.message]; - } - if (event.exception) { - try { - const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {}; - return [`${value}`, `${type}: ${value}`]; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract message for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return []; - } - } - return []; -} - -function _isSentryError(event) { - try { - // @ts-ignore can't be a sentry error if undefined - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return event.exception.values[0].type === 'SentryError'; - } catch (e) { - // ignore - } - return false; -} - -function _getLastValidUrl(frames = []) { - for (let i = frames.length - 1; i >= 0; i--) { - const frame = frames[i]; - - if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') { - return frame.filename || null; - } - } - - return null; -} - -function _getEventFilterUrl(event) { - try { - let frames; - try { - // @ts-ignore we only care about frames if the whole thing here is defined - frames = event.exception.values[0].stacktrace.frames; - } catch (e) { - // ignore - } - return frames ? _getLastValidUrl(frames) : null; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract url for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return null; - } -} - - -//# sourceMappingURL=inboundfilters.js.map - - -/***/ }), -/* 1674 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* binding */ FunctionToString) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1612); - - -let originalFunctionToString; - -/** Patch toString calls to return proper name for wrapped functions */ -class FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'FunctionToString';} - - /** - * @inheritDoc - */ - __init() {this.name = FunctionToString.id;} - - /** - * @inheritDoc - */ - setupOnce() { - // 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 ( ...args) { - const context = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.getOriginalFunction)(this) || this; - return originalFunctionToString.apply(context, args); - }; - } -} FunctionToString.__initStatic(); - - -//# sourceMappingURL=functiontostring.js.map - - -/***/ }), -/* 1675 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "initAndBind": () => (/* binding */ initAndBind) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1615); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); - - - -/** A class object that can instantiate Client objects. */ - -/** - * 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) { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.enable(); - } else { - // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped - // eslint-disable-next-line no-console - console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); - } - } - const hub = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - const scope = hub.getScope(); - if (scope) { - scope.update(options.initialScope); - } - - const client = new clientClass(options); - hub.bindClient(client); -} - - -//# sourceMappingURL=sdk.js.map - - -/***/ }), -/* 1676 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "deepReadDirSync": () => (/* binding */ deepReadDirSync) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); - - - -/** - * Recursively read the contents of a directory. - * - * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this - * directory. - * @returns Array holding all relative paths - */ -function deepReadDirSync(targetDir) { - const targetDirAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.resolve(targetDir); - - if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(targetDirAbsPath)) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`); - } - - if (!fs__WEBPACK_IMPORTED_MODULE_0__.statSync(targetDirAbsPath).isDirectory()) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`); - } - - // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it - // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve - // the difference between `targetDirAbsPath` and `currentDirAbsPath`. - const deepReadCurrentDir = (currentDirAbsPath) => { - return fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => { - const itemAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.join(currentDirAbsPath, itemName); - - if (fs__WEBPACK_IMPORTED_MODULE_0__.statSync(itemAbsPath).isDirectory()) { - return [...absPaths, ...deepReadCurrentDir(itemAbsPath)]; - } - - return [...absPaths, itemAbsPath]; - }, []); - }; - - return deepReadCurrentDir(targetDirAbsPath).map(absPath => path__WEBPACK_IMPORTED_MODULE_1__.relative(targetDirAbsPath, absPath)); -} - - -//# sourceMappingURL=utils.js.map - - -/***/ }), -/* 1677 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.extractRequestData), -/* harmony export */ "parseRequest": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.parseRequest), -/* harmony export */ "errorHandler": () => (/* binding */ errorHandler), -/* harmony export */ "requestHandler": () => (/* binding */ requestHandler), -/* harmony export */ "tracingHandler": () => (/* binding */ tracingHandler) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1602); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1617); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1679); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1657); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1670); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1612); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1314); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1667); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1651); -/* harmony import */ var _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1678); - - - - - - - - -/* eslint-disable @typescript-eslint/no-explicit-any */ - -/** - * Express-compatible tracing handler. - * @see Exposed as `Handlers.tracingHandler` - */ -function tracingHandler() - - { - return function sentryTracingMiddleware( - req, - res, - next, - ) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const options = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]); - - if ( - !options || - options.instrumenter !== 'sentry' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _5 => _5.method, 'optionalAccess', _6 => _6.toUpperCase, 'call', _7 => _7()]) === 'OPTIONS' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _8 => _8.method, 'optionalAccess', _9 => _9.toUpperCase, 'call', _10 => _10()]) === 'HEAD' - ) { - return next(); - } - - // TODO: This is the `hasTracingEnabled` check, but we're doing it manually since `@sentry/tracing` isn't a - // dependency of `@sentry/node`. Long term, that function should probably move to `@sentry/hub. - if (!('tracesSampleRate' in options) && !('tracesSampler' in options)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn( - 'Sentry `tracingHandler` is being used, but tracing is disabled. Please enable tracing by setting ' + - 'either `tracesSampleRate` or `tracesSampler` in your `Sentry.init()` options.', - ); - return next(); - } - - // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) - const traceparentData = - req.headers && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.isString)(req.headers['sentry-trace']) && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.extractTraceparentData)(req.headers['sentry-trace']); - const incomingBaggageHeaders = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _11 => _11.headers, 'optionalAccess', _12 => _12.baggage]); - const dynamicSamplingContext = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.baggageHeaderToDynamicSamplingContext)(incomingBaggageHeaders); - - const [name, source] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.extractPathForTransaction)(req, { path: true, method: true }); - const transaction = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.startTransaction)( - { - name, - op: 'http.server', - ...traceparentData, - metadata: { - dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, - // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become - // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the - // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to - // be sure - request: req, - source, - }, - }, - // extra context passed to the tracesSampler - { request: (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_1__.extractRequestData)(req) }, - ); - - // We put the transaction on the scope so users can attach children to it - hub.configureScope(scope => { - scope.setSpan(transaction); - }); - - // We also set __sentry_transaction on the response so people can grab the transaction there to add - // spans to it later. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).__sentry_transaction = transaction; - - res.once('finish', () => { - // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction - // closes - setImmediate(() => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.addRequestDataToTransaction)(transaction, req); - transaction.setHttpStatus(res.statusCode); - transaction.finish(); - }); - }); - - next(); - }; -} - -/** - * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the - * `AddRequestDataToEventOptions` interface. - * - * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`. - */ -function convertReqHandlerOptsToAddReqDataOpts( - reqHandlerOptions = {}, -) { - let addRequestDataOptions; - - if ('include' in reqHandlerOptions) { - addRequestDataOptions = { include: reqHandlerOptions.include }; - } else { - // eslint-disable-next-line deprecation/deprecation - const { ip, request, transaction, user } = reqHandlerOptions ; - - if (ip || request || transaction || user) { - addRequestDataOptions = { include: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.dropUndefinedKeys)({ ip, request, transaction, user }) }; - } - } - - return addRequestDataOptions; -} - -/** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` - */ -function requestHandler( - options, -) { - // TODO (v8): Get rid of this - const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options); - - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const client = currentHub.getClient(); - // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the - // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - client.initSessionFlusher(); - - // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode - const scope = currentHub.getScope(); - if (scope && scope.getSession()) { - scope.setSession(); - } - } - - return function sentryRequestMiddleware( - req, - res, - next, - ) { - if (options && options.flushTimeout && options.flushTimeout > 0) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const _end = res.end; - res.end = function (chunk, encoding, cb) { - void (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.flush)(options.flushTimeout) - .then(() => { - _end.call(this, chunk, encoding, cb); - }) - .then(null, e => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.error(e); - _end.call(this, chunk, encoding, cb); - }); - }; - } - const local = domain__WEBPACK_IMPORTED_MODULE_0__.create(); - local.add(req); - local.add(res); - - local.run(() => { - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - - currentHub.configureScope(scope => { - scope.setSDKProcessingMetadata({ - request: req, - // TODO (v8): Stop passing this - requestDataOptionsFromExpressHandler: requestDataOptions, - }); - - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - const scope = currentHub.getScope(); - if (scope) { - // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope.setRequestSession({ status: 'ok' }); - } - } - }); - - res.once('finish', () => { - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - setImmediate(() => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (client && (client )._captureRequestSession) { - // Calling _captureRequestSession to capture request session at the end of the request by incrementing - // the correct SessionAggregates bucket i.e. crashed, errored or exited - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (client )._captureRequestSession(); - } - }); - } - }); - next(); - }); - }; -} - -/** JSDoc */ - -/** JSDoc */ -function getStatusCodeFromResponse(error) { - const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); - return statusCode ? parseInt(statusCode , 10) : 500; -} - -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error) { - const status = getStatusCodeFromResponse(error); - return status >= 500; -} - -/** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` - */ -function errorHandler(options - -) - - { - return function sentryErrorMiddleware( - error, - _req, - res, - next, - ) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; - - if (shouldHandleError(error)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.withScope)(_scope => { - // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`, - // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't - // hurt to be sure - _scope.setSDKProcessingMetadata({ request: _req }); - - // For some reason we need to set the transaction on the scope again - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const transaction = (res ).__sentry_transaction ; - if (transaction && _scope.getSpan() === undefined) { - _scope.setSpan(transaction); - } - - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)().getClient(); - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the - // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only - // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be - // running in SessionAggregates mode - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const isSessionAggregatesMode = (client )._sessionFlusher !== undefined; - if (isSessionAggregatesMode) { - const requestSession = _scope.getRequestSession(); - // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a - // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within - // the bounds of a request, and if so the status is updated - if (requestSession && requestSession.status !== undefined) { - requestSession.status = 'crashed'; - } - } - } - - const eventId = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.captureException)(error); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).sentry = eventId; - next(error); - }); - - return; - } - - next(error); - }; -} - -// TODO (v8 / #5257): Remove this -// eslint-disable-next-line deprecation/deprecation -; - - -//# sourceMappingURL=handlers.js.map - - -/***/ }), -/* 1678 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData), -/* harmony export */ "parseRequest": () => (/* binding */ parseRequest) -/* harmony export */ }); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1667); - - -/** - * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead. - */ - -/** - * Normalizes data from the request object, accounting for framework differences. - * - * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead. - * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. - * @returns An object containing normalized request data - */ -function extractRequestData(req, keys) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.extractRequestData)(req, { include: keys }); -} - -/** - * Options deciding what parts of the request to use when enhancing an event - * - * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use - * `AddRequestDataToEventOptions` in `@sentry/utils` instead. - */ - -/** - * Enriches passed event with request data. - * - * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead. - * - * @param event Will be mutated and enriched with req data - * @param req Request object - * @param options object containing flags to enable functionality - * @hidden - */ -function parseRequest(event, req, options = {}) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent)(event, req, { include: options }); -} - - -//# sourceMappingURL=requestDataDeprecated.js.map - - -/***/ }), -/* 1679 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "TRACEPARENT_REGEXP": () => (/* binding */ TRACEPARENT_REGEXP), -/* harmony export */ "extractTraceparentData": () => (/* binding */ extractTraceparentData) -/* harmony export */ }); -const TRACEPARENT_REGEXP = new RegExp( - '^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$', // whitespace -); - -/** - * Extract transaction context data from a `sentry-trace` header. - * - * @param traceparent Traceparent string - * - * @returns Object containing data from the header, or undefined if traceparent string is malformed - */ -function extractTraceparentData(traceparent) { - const matches = traceparent.match(TRACEPARENT_REGEXP); - - if (!traceparent || !matches) { - // empty string or no matches is invalid traceparent data - return undefined; - } - - let parentSampled; - if (matches[3] === '1') { - parentSampled = true; - } else if (matches[3] === '0') { - parentSampled = false; - } - - return { - traceId: matches[1], - parentSampled, - parentSpanId: matches[2], - }; -} - - -//# sourceMappingURL=tracing.js.map - - -/***/ }), -/* 1680 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* reexport safe */ _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__.FunctionToString), -/* harmony export */ "InboundFilters": () => (/* reexport safe */ _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__.InboundFilters) -/* harmony export */ }); -/* harmony import */ var _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1674); -/* harmony import */ var _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1673); - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1681 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -const { activateContract } = __webpack_require__(1682) -const { getContractStartDate } = __webpack_require__(1683) -const { terminateContract } = __webpack_require__(1684) -const { verifyContract } = __webpack_require__(1685) -const { findUserPdl } = __webpack_require__(1687) -const { verifyUserIdentity } = __webpack_require__(1688) -const { findUserAddress } = __webpack_require__(1690) - -module.exports = { - activateContract, - getContractStartDate, - terminateContract, - verifyContract, - findUserPdl, - verifyUserIdentity, - findUserAddress, -} - - -/***/ }), -/* 1682 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const soapRequest = __webpack_require__(1337) -const { parseTags, parseValue, parseServiceId } = __webpack_require__(1561) -const { commanderCollectePublicationMesures } = __webpack_require__(1562) -const xml2js = __webpack_require__(1519) -const Sentry = __webpack_require__(1601) - -/** - * @param {string} url - * @param {string} apiAuthKey - * @param {string} appLogin - * @param {string} name - * @param {number} pointId - * @param {string} startDate - * @param {string} endDate - * @return {Promise<number>} User contractId - */ -async function activateContract( - url, - apiAuthKey, - appLogin, - contractId, - name, - pointId, - startDate, - endDate -) { - log('info', 'activateContract') - const sgeHeaders = { - 'Content-Type': 'text/xml;charset=UTF-8', - apikey: apiAuthKey, - } - - const { response } = await soapRequest({ - url: `${url}/enedis_SGE_CommandeCollectePublicationMesures/1.0`, - headers: sgeHeaders, - xml: commanderCollectePublicationMesures( - appLogin, - contractId, - pointId, - name, - startDate, - endDate - ), - }).catch(err => { - log('error', 'commanderCollectePublicationMesures') - log('error', err) - Sentry.captureException('commanderCollectePublicationMesures', err) - throw errors.LOGIN_FAILED - }) - - const parsedReply = await xml2js.parseStringPromise(response.body, { - tagNameProcessors: [parseTags], - valueProcessors: [parseValue], - explicitArray: false, - }) - - try { - return parseServiceId(parsedReply) - } catch (error) { - const errorMessage = 'Error while activating contract: ' + error - log('error', errorMessage) - Sentry.captureException(errorMessage) - if (parsedReply.Envelope.Body.Fault) { - log( - 'error', - `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` - ) - } - //TODO: handle SGT4B8: Il existe déjà plusieurs demandes en cours sur le point ? - throw errors.LOGIN_FAILED - } -} - -module.exports = { activateContract } - - -/***/ }), -/* 1683 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const soapRequest = __webpack_require__(1337) -const { - parseTags, - parseValue, - parseContractStartDate, -} = __webpack_require__(1561) -const xml2js = __webpack_require__(1519) -const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1562) -const Sentry = __webpack_require__(1601) - -/** - * Get user contract start date - * @param {string} url - * @param {string} apiAuthKey - * @param {string} userLogin - * @param {number} pointId - * @returns {Promise<string>} - */ -async function getContractStartDate(url, apiAuthKey, userLogin, pointId) { - log('info', 'Fetching data start date') - const sgeHeaders = { - 'Content-Type': 'text/xml;charset=UTF-8', - apikey: apiAuthKey, - } - - const { response } = await soapRequest({ - url: `${url}/enedis_SGE_ConsultationDonneesTechniquesContractuelles/1.0`, - headers: sgeHeaders, - xml: consulterDonneesTechniquesContractuelles(pointId, userLogin), - }).catch(err => { - const errorMessage = 'Error while fetching contract start date : ' + err - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN - }) - - const result = await xml2js.parseStringPromise(response.body, { - tagNameProcessors: [parseTags], - valueProcessors: [parseValue], - explicitArray: false, - }) - try { - return parseContractStartDate(result) - } catch (error) { - const errorMessage = 'Error while processing contract start date: ' + error - log('error', errorMessage) - Sentry.captureException(errorMessage) - log( - 'error', - `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}` - ) - throw errors.NOT_EXISTING_DIRECTORY - } -} - -module.exports = { getContractStartDate } - - -/***/ }), -/* 1684 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const soapRequest = __webpack_require__(1337) -const { parseTags, parseValue } = __webpack_require__(1561) -const { commanderArretServiceSouscritMesures } = __webpack_require__(1562) -const xml2js = __webpack_require__(1519) -const Sentry = __webpack_require__(1601) - -/** - * @param {string} url - * @param {string} apiAuthKey - * @param {string} appLogin - * @param {number} pointId - * @param {number} serviceId - * @return {Promise<string>} User contractId - */ -async function terminateContract( - url, - apiAuthKey, - appLogin, - contractId, - pointId, - serviceId -) { - log('info', 'terminateContract') - const sgeHeaders = { - 'Content-Type': 'text/xml;charset=UTF-8', - apikey: apiAuthKey, - } - - const { response } = await soapRequest({ - url: `${url}/enedis_SGE_CommandeArretServiceSouscritMesures/1.0`, - headers: sgeHeaders, - xml: commanderArretServiceSouscritMesures( - appLogin, - contractId, - pointId, - serviceId - ), - }).catch(err => { - log('error', 'commanderArretServiceSouscritMesures') - log('error', err) - Sentry.captureException('commanderArretServiceSouscritMesures', err) - throw errors.VENDOR_DOWN - }) - - const parsedReply = await xml2js.parseStringPromise(response.body, { - tagNameProcessors: [parseTags], - valueProcessors: [parseValue], - explicitArray: false, - }) - - try { - // We don't need any action on reply for now - if (parsedReply.Envelope.Body.Fault) { - log( - 'error', - `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` - ) - } - return parsedReply - } catch (error) { - const errorMessage = - 'Error while parsing user contract termination: ' + error - log('error', errorMessage) - log('error', `Enedis issue ${JSON.stringify(parsedReply.Envelope.Body)}`) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN - } -} - -module.exports = { terminateContract } - - -/***/ }), -/* 1685 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const soapRequest = __webpack_require__(1337) -const { - parseTags, - parseValue, - parseContracts, - checkContractExists, -} = __webpack_require__(1561) -const { rechercherServicesSouscritsMesures } = __webpack_require__(1562) -const xml2js = __webpack_require__(1519) -const { contractState } = __webpack_require__(1686) -const Sentry = __webpack_require__(1601) - -/** - * @param {string} url - * @param {string} apiAuthKey - * @param {string} appLogin - * @param {number} pointId - * @return {Promise<number | null>} User contractId - */ -async function verifyContract(url, apiAuthKey, appLogin, contractId, pointId) { - log('info', 'verifyContract') - const sgeHeaders = { - 'Content-Type': 'text/xml;charset=UTF-8', - apikey: apiAuthKey, - } - - const { response } = await soapRequest({ - url: `${url}/enedis_SGE_RechercheServicesMesures/1.0`, - headers: sgeHeaders, - xml: rechercherServicesSouscritsMesures(appLogin, contractId, pointId), - }).catch(err => { - log('error', 'rechercherServicesSouscritsMesures') - log('error', err) - Sentry.captureException('rechercherServicesSouscritsMesures', err) - throw errors.LOGIN_FAILED - }) - - const parsedReply = await xml2js.parseStringPromise(response.body, { - tagNameProcessors: [parseTags], - valueProcessors: [parseValue], - explicitArray: false, - }) - - try { - if (!checkContractExists(parsedReply)) { - log('error', 'no contract found') - Sentry.captureException('no contract found') - return null - } - - const currentContracts = parseContracts(parsedReply) - let currentContract = null - if (Array.isArray(currentContracts)) { - currentContract = parseContracts(parsedReply)[0] - } else { - currentContract = currentContracts - } - if ( - currentContract.etatCode === contractState.ACTIF || - currentContract.etatCode === contractState.DEMANDE - ) - return currentContract.serviceSouscritId - return null - } catch (error) { - const errorMessage = 'Error while parsing user contract: ' + error - log('error', errorMessage) - Sentry.captureException(errorMessage) - if (parsedReply.Envelope.Body.Fault) { - log( - 'error', - `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` - ) - } - log( - 'error', - 'if an error is thrown here, it probably means that the contract has already been open today and that enedis cannot open a second one. Wait until tomorow to try again' - ) - throw errors.LOGIN_FAILED - } -} - -module.exports = { verifyContract } - - -/***/ }), -/* 1686 */ -/***/ ((module) => { - -/** - * Enum for contract-state values. - * @readonly - * @enum {number} - */ -const contractState = { - TERMINE: 'TERMINE', - ACTIF: 'ACTIF', - DEMANDE: 'DEMANDE', -} - -module.exports = { contractState } - - -/***/ }), -/* 1687 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const soapRequest = __webpack_require__(1337) -const { parseUserPdl, parseTags, parseValue } = __webpack_require__(1561) -const { rechercherPoint } = __webpack_require__(1562) -const xml2js = __webpack_require__(1519) -const Sentry = __webpack_require__(1601) - -/** - * @param {string} url - * @param {string} apiAuthKey - * @param {string} appLogin - * @param {string} name - * @param {string} address - * @param {string} postalCode - * @param {string} inseeCode - * @return {Promise<string | null>} User Pdl - */ -async function findUserPdl( - url, - apiAuthKey, - appLogin, - name, - address, - postalCode, - inseeCode, - escalierEtEtageEtAppartement = '' -) { - log('info', 'Fetching user pdl') - const sgeHeaders = { - 'Content-Type': 'text/xml;charset=UTF-8', - apikey: apiAuthKey, - } - - const { response } = await soapRequest({ - url: url, - headers: sgeHeaders, - xml: rechercherPoint( - appLogin, - name, - postalCode, - inseeCode, - address, - escalierEtEtageEtAppartement - ), - }).catch(err => { - log('error', 'rechercherPointResponse') - log('error', err) - Sentry.captureException('rechercherPointResponse', err) - throw errors.LOGIN_FAILED - }) - - const parsedReply = await xml2js.parseStringPromise(response.body, { - tagNameProcessors: [parseTags], - valueProcessors: [parseValue], - explicitArray: false, - }) - - try { - return parseUserPdl(parsedReply) - } catch (error) { - const errorMessage = 'Error while parsing user PDL: ' + error - log('warn', errorMessage) - Sentry.captureException(errorMessage) - if (parsedReply.Envelope.Body.Fault) { - log( - 'warn', - `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}` - ) - } - return null - } -} - -module.exports = { findUserPdl } - - -/***/ }), -/* 1688 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const { findUserPdl } = __webpack_require__(1687) -const { getInseeCode } = __webpack_require__(1689) -const { findUserAddress } = __webpack_require__(1690) -const { - removeMultipleSpaces, - removeAddressNumber, -} = __webpack_require__(1561) -const Sentry = __webpack_require__(1601) - -/** - * Verify user identity - * @param {object} fields - * @param {string} baseUrl - * @param {string} apiAuthKey - * @param {string} loginUtilisateur - * @param {boolean} isAlternateStart - * @returns {Promise<User>} - */ -async function verifyUserIdentity( - fields, - baseUrl, - apiAuthKey, - loginUtilisateur, - isAlternateStart = false, - inseeCode = '' -) { - // If first start get InseeCode - log('debug', 'verifyUserIdentity') - if (!isAlternateStart) { - inseeCode = await getInseeCode(fields.postalCode, fields.city) - } - - // Store if user is going through safety sge onboarding - let userSafetyOnBoarding = false - - // First try with user adresse - let pdl = await findUserPdl( - `${baseUrl}/enedis_SDE_recherche-point/1.0`, - apiAuthKey, - loginUtilisateur, - fields.lastname, - fields.address, - fields.postalCode, - inseeCode - ) - - if (!pdl) { - log('warn', 'Second chance for sge onboarding') - // Set safety onboarding in order to save it inside BO - userSafetyOnBoarding = true - // Backup verification - const userAddress = await findUserAddress( - baseUrl, - apiAuthKey, - loginUtilisateur, - fields.pointId - ) - - const escalierEtEtageEtAppartement = userAddress.escalierEtEtageEtAppartement - ? removeMultipleSpaces(userAddress.escalierEtEtageEtAppartement) - : '' - - pdl = await findUserPdl( - `${baseUrl}/enedis_SDE_recherche-point/1.0`, - apiAuthKey, - loginUtilisateur, - fields.lastname, - removeMultipleSpaces(userAddress.numeroEtNomVoie), - userAddress.codePostal, - userAddress.commune.$.code, - escalierEtEtageEtAppartement - ) - - // Third try, remove address number because it's buggy on SGE side - if (!pdl) { - log('warn', 'Third chance onboarding for sge') - pdl = await findUserPdl( - `${baseUrl}/enedis_SDE_recherche-point/1.0`, - apiAuthKey, - loginUtilisateur, - fields.lastname, - removeMultipleSpaces(removeAddressNumber(userAddress.numeroEtNomVoie)), - userAddress.codePostal, - userAddress.commune.$.code - ) - } - // Third try, remove address number and add escalierEtEtageEtAppartement because it's buggy on SGE side - if (!pdl) { - log('warn', 'Last chance onboarding for sge') - pdl = await findUserPdl( - `${baseUrl}/enedis_SDE_recherche-point/1.0`, - apiAuthKey, - loginUtilisateur, - fields.lastname, - removeMultipleSpaces(removeAddressNumber(userAddress.numeroEtNomVoie)), - userAddress.codePostal, - userAddress.commune.$.code, - escalierEtEtageEtAppartement - ) - } - } - - if (fields.pointId != pdl) { - log('error', 'PointId does not match') - - if (isAlternateStart) { - Sentry.captureException('PointId does not match: Alternate start') - throw errors.TERMS_VERSION_MISMATCH - } else { - Sentry.captureException('PointId does not match') - throw errors.LOGIN_FAILED - } - } - - return { - lastname: fields.lastname, - firstname: fields.firstname, - pointId: fields.pointId, - inseeCode, - postalCode: fields.postalCode, - address: fields.address, - hasBeenThroughtSafetyOnBoarding: userSafetyOnBoarding, - city: fields.city, - } -} - -module.exports = { verifyUserIdentity } - - -/***/ }), -/* 1689 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const Sentry = __webpack_require__(1601) -const { default: axios } = __webpack_require__(1564) -const { log, errors } = __webpack_require__(1) - -const API_URL = 'https://apicarto.ign.fr/api/codes-postaux/communes' - -/** - * Return inseeCode given a postalCode - * @param {string} postalCode - * @param {string} [city] - * @return {Promise<string>} inseeCode - */ -async function getInseeCode(postalCode, city) { - try { - log('info', `Query getInseeCode for postalCode ${postalCode} / ${city}`) - const response = await axios.get(`${API_URL}/${postalCode}`) - - if (response.data.length === 1) { - return response.data[0].codeCommune - } else { - if (!city) throw new Error('No city') - - const filteredResponse = response.data.filter( - town => town.nomCommune.toLowerCase() === city.toLowerCase() - ) - return filteredResponse[0].codeCommune - } - } catch (error) { - const errorMessage = `Query getInseeCode failed for postalCode ${postalCode} / ${city}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.USER_ACTION_NEEDED - } -} - -module.exports = { - getInseeCode, -} - - -/***/ }), -/* 1690 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const soapRequest = __webpack_require__(1337) -const { - parseTags, - parseValue, - parseUserAddress, -} = __webpack_require__(1561) -const xml2js = __webpack_require__(1519) -const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1562) -const Sentry = __webpack_require__(1601) - -/** - * Get user contract start date - * @param {string} url - * @param {string} apiAuthKey - * @param {string} userLogin - * @param {number} pointId - * @returns {Promise<Address>} - */ -async function findUserAddress(url, apiAuthKey, userLogin, pointId) { - log('info', 'Fetching user address') - const sgeHeaders = { - 'Content-Type': 'text/xml;charset=UTF-8', - apikey: apiAuthKey, - } - - const { response } = await soapRequest({ - url: `${url}/enedis_SGE_ConsultationDonneesTechniquesContractuelles/1.0`, - headers: sgeHeaders, - xml: consulterDonneesTechniquesContractuelles(pointId, userLogin, false), - }).catch(err => { - const errorMessage = 'Error while fetching user : ' + err - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN - }) - - const result = await xml2js.parseStringPromise(response.body, { - tagNameProcessors: [parseTags], - valueProcessors: [parseValue], - explicitArray: false, - }) - - try { - return parseUserAddress(result) - } catch (error) { - const errorMessage = 'Error while processing user address: ' + error - log('error', errorMessage) - log( - 'error', - `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}` - ) - Sentry.captureException(errorMessage) - throw errors.LOGIN_FAILED - } finally { - Sentry.captureException('Error while processing user address') - } -} - -module.exports = { findUserAddress } - - -/***/ }), -/* 1691 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -const { log, updateOrCreate } = __webpack_require__(1) -const { isLocal } = __webpack_require__(1692) -const cozyClient = __webpack_require__(485) - -async function saveAccountData(accountId, accountData) { - log('info', `saveAccountData: ${accountId}`) - - let account = await getAccount(accountId) - log('info', `saveAccountData account: ${JSON.stringify(account)}`) - log( - 'info', - `saveAccountData account: ${JSON.stringify({ - ...account, - data: accountData, - })}` - ) - - log( - 'info', - `saveAccountData account after id: ${JSON.stringify({ - ...account, - data: accountData, - })}` - ) - account = await updateOrCreate( - [{ ...account, data: accountData }], - 'io.cozy.accounts', - ['account_type'] - ) - log('info', `saveAccountData account reply: ${JSON.stringify(account)}`) - return account -} - -/** - * Return account - * @param {string} accountId - * @returns {Account} - */ -async function getAccount(accountId) { - log('info', `getAccount: ${accountId}`) - const accounts = await cozyClient.data.findAll('io.cozy.accounts') - return accounts.filter(account => - isLocal() ? account._id === accountId : account.account_type === accountId - )[0] -} - -async function getAccountForDelete(accountId, accountRev) { - log('info', `getAccountForDelete: ${accountId} ${accountRev}`) - const body = await cozyClient.fetchJSON( - 'GET', - `/data/io.cozy.accounts/${accountId}?rev=${accountRev}` - ) - - log('debug', `getAccountForDelete: ${body}`) - return body -} - -module.exports = { getAccount, saveAccountData, getAccountForDelete } - - -/***/ }), -/* 1692 */ -/***/ ((module) => { - -function isLocal() { - return ( - process.env.NODE_ENV === 'development' || - process.env.NODE_ENV === 'local' || - process.env.NODE_ENV === 'standalone' - ) -} - -/** - * Verify if it's an alpha URL - * @returns {boolean} - */ -function isDev() { - return ( - process.env.COZY_URL.includes('alpha') || - process.env.COZY_URL.includes('cozy.tools') - ) -} - -module.exports = { isLocal, isDev } - - -/***/ }), -/* 1693 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addExtensionMethods": () => (/* reexport safe */ _hubextensions_js__WEBPACK_IMPORTED_MODULE_0__.addExtensionMethods), -/* harmony export */ "startIdleTransaction": () => (/* reexport safe */ _hubextensions_js__WEBPACK_IMPORTED_MODULE_0__.startIdleTransaction), -/* harmony export */ "Integrations": () => (/* reexport module object */ _integrations_index_js__WEBPACK_IMPORTED_MODULE_1__), -/* harmony export */ "Span": () => (/* reexport safe */ _span_js__WEBPACK_IMPORTED_MODULE_2__.Span), -/* harmony export */ "spanStatusfromHttpCode": () => (/* reexport safe */ _span_js__WEBPACK_IMPORTED_MODULE_2__.spanStatusfromHttpCode), -/* harmony export */ "SpanStatus": () => (/* reexport safe */ _spanstatus_js__WEBPACK_IMPORTED_MODULE_3__.SpanStatus), -/* harmony export */ "Transaction": () => (/* reexport safe */ _transaction_js__WEBPACK_IMPORTED_MODULE_4__.Transaction), -/* harmony export */ "IdleTransaction": () => (/* reexport safe */ _idletransaction_js__WEBPACK_IMPORTED_MODULE_5__.IdleTransaction), -/* harmony export */ "getActiveTransaction": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.getActiveTransaction), -/* harmony export */ "hasTracingEnabled": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.hasTracingEnabled), -/* harmony export */ "BROWSER_TRACING_INTEGRATION_ID": () => (/* reexport safe */ _browser_browsertracing_js__WEBPACK_IMPORTED_MODULE_7__.BROWSER_TRACING_INTEGRATION_ID), -/* harmony export */ "BrowserTracing": () => (/* reexport safe */ _browser_browsertracing_js__WEBPACK_IMPORTED_MODULE_7__.BrowserTracing), -/* harmony export */ "defaultRequestInstrumentationOptions": () => (/* reexport safe */ _browser_request_js__WEBPACK_IMPORTED_MODULE_8__.defaultRequestInstrumentationOptions), -/* harmony export */ "instrumentOutgoingRequests": () => (/* reexport safe */ _browser_request_js__WEBPACK_IMPORTED_MODULE_8__.instrumentOutgoingRequests), -/* harmony export */ "TRACEPARENT_REGEXP": () => (/* reexport safe */ _sentry_utils__WEBPACK_IMPORTED_MODULE_9__.TRACEPARENT_REGEXP), -/* harmony export */ "extractTraceparentData": () => (/* reexport safe */ _sentry_utils__WEBPACK_IMPORTED_MODULE_9__.extractTraceparentData), -/* harmony export */ "stripUrlQueryAndFragment": () => (/* reexport safe */ _sentry_utils__WEBPACK_IMPORTED_MODULE_10__.stripUrlQueryAndFragment) -/* harmony export */ }); -/* harmony import */ var _hubextensions_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1694); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1702); -/* harmony import */ var _span_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1697); -/* harmony import */ var _spanstatus_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1729); -/* harmony import */ var _transaction_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1696); -/* harmony import */ var _idletransaction_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1698); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1695); -/* harmony import */ var _browser_browsertracing_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1711); -/* harmony import */ var _browser_request_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1714); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1679); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1669); - - - - - - - - - - - - - - -; -; - -// Treeshakable guard to remove all code related to tracing - -// Guard for tree -if (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) { - // We are patching the global object with our hub extension methods - (0,_hubextensions_js__WEBPACK_IMPORTED_MODULE_0__.addExtensionMethods)(); -} -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1694 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_addTracingExtensions": () => (/* binding */ _addTracingExtensions), -/* harmony export */ "addExtensionMethods": () => (/* binding */ addExtensionMethods), -/* harmony export */ "startIdleTransaction": () => (/* binding */ startIdleTransaction) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1607); -/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1699); -/* harmony import */ var _idletransaction_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1698); -/* harmony import */ var _transaction_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1696); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1695); -/* module decorator */ module = __webpack_require__.hmd(module); - - - - - - - -/** Returns all trace headers that are currently on the top scope. */ -function traceHeaders() { - const scope = this.getScope(); - if (scope) { - const span = scope.getSpan(); - if (span) { - return { - 'sentry-trace': span.toTraceparent(), - }; - } - } - return {}; -} - -/** - * Makes a sampling decision for the given transaction and stores it on the transaction. - * - * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be - * sent to Sentry. - * - * @param transaction: The transaction needing a sampling decision - * @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler` - * @param samplingContext: Default and user-provided data which may be used to help make the decision - * - * @returns The given transaction with its `sampled` value set - */ -function sample( - transaction, - options, - samplingContext, -) { - // nothing to do if tracing is not enabled - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.hasTracingEnabled)(options)) { - transaction.sampled = false; - return transaction; - } - - // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that - if (transaction.sampled !== undefined) { - transaction.setMetadata({ - sampleRate: Number(transaction.sampled), - }); - return transaction; - } - - // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should - // work; prefer the hook if so - let sampleRate; - if (typeof options.tracesSampler === 'function') { - sampleRate = options.tracesSampler(samplingContext); - transaction.setMetadata({ - sampleRate: Number(sampleRate), - }); - } else if (samplingContext.parentSampled !== undefined) { - sampleRate = samplingContext.parentSampled; - } else { - sampleRate = options.tracesSampleRate; - transaction.setMetadata({ - sampleRate: Number(sampleRate), - }); - } - - // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The - // only valid values are booleans or numbers between 0 and 1.) - if (!isValidSampleRate(sampleRate)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('[Tracing] Discarding transaction because of invalid sample rate.'); - transaction.sampled = false; - return transaction; - } - - // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped - if (!sampleRate) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log( - `[Tracing] Discarding transaction because ${ - typeof options.tracesSampler === 'function' - ? 'tracesSampler returned 0 or false' - : 'a negative sampling decision was inherited or tracesSampleRate is set to 0' - }`, - ); - transaction.sampled = false; - return transaction; - } - - // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is - // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. - transaction.sampled = Math.random() < (sampleRate ); - - // if we're not going to keep it, we're done - if (!transaction.sampled) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log( - `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number( - sampleRate, - )})`, - ); - return transaction; - } - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`); - return transaction; -} - -/** - * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). - */ -function isValidSampleRate(rate) { - // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.isNaN)(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn( - `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify( - rate, - )} of type ${JSON.stringify(typeof rate)}.`, - ); - return false; - } - - // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false - if (rate < 0 || rate > 1) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`); - return false; - } - return true; -} - -/** - * Creates a new transaction and adds a sampling decision if it doesn't yet have one. - * - * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if - * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an - * "extension method." - * - * @param this: The Hub starting the transaction - * @param transactionContext: Data used to configure the transaction - * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any) - * - * @returns The new transaction - * - * @see {@link Hub.startTransaction} - */ -function _startTransaction( - - transactionContext, - customSamplingContext, -) { - const client = this.getClient(); - const options = (client && client.getOptions()) || {}; - - const configInstrumenter = options.instrumenter || 'sentry'; - const transactionInstrumenter = transactionContext.instrumenter || 'sentry'; - - if (configInstrumenter !== transactionInstrumenter) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error( - `A transaction was started with instrumenter=\`${transactionInstrumenter}\`, but the SDK is configured with the \`${configInstrumenter}\` instrumenter. -The transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`, - ); - - transactionContext.sampled = false; - } - - let transaction = new _transaction_js__WEBPACK_IMPORTED_MODULE_3__.Transaction(transactionContext, this); - transaction = sample(transaction, options, { - parentSampled: transactionContext.parentSampled, - transactionContext, - ...customSamplingContext, - }); - if (transaction.sampled) { - transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans )); - } - return transaction; -} - -/** - * Create new idle transaction. - */ -function startIdleTransaction( - hub, - transactionContext, - idleTimeout, - finalTimeout, - onScope, - customSamplingContext, - heartbeatInterval, -) { - const client = hub.getClient(); - const options = (client && client.getOptions()) || {}; - - let transaction = new _idletransaction_js__WEBPACK_IMPORTED_MODULE_4__.IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope); - transaction = sample(transaction, options, { - parentSampled: transactionContext.parentSampled, - transactionContext, - ...customSamplingContext, - }); - if (transaction.sampled) { - transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans )); - } - return transaction; -} - -/** - * @private - */ -function _addTracingExtensions() { - const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_5__.getMainCarrier)(); - if (!carrier.__SENTRY__) { - return; - } - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - if (!carrier.__SENTRY__.extensions.startTransaction) { - carrier.__SENTRY__.extensions.startTransaction = _startTransaction; - } - if (!carrier.__SENTRY__.extensions.traceHeaders) { - carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; - } -} - -/** - * @private - */ -function _autoloadDatabaseIntegrations() { - const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_5__.getMainCarrier)(); - if (!carrier.__SENTRY__) { - return; - } - - const packageToIntegrationMapping = { - mongodb() { - const integration = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.dynamicRequire)(module, './integrations/node/mongo') - -; - return new integration.Mongo(); - }, - mongoose() { - const integration = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.dynamicRequire)(module, './integrations/node/mongo') - -; - return new integration.Mongo({ mongoose: true }); - }, - mysql() { - const integration = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.dynamicRequire)(module, './integrations/node/mysql') - -; - return new integration.Mysql(); - }, - pg() { - const integration = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.dynamicRequire)(module, './integrations/node/postgres') - -; - return new integration.Postgres(); - }, - }; - - const mappedPackages = Object.keys(packageToIntegrationMapping) - .filter(moduleName => !!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.loadModule)(moduleName)) - .map(pkg => { - try { - return packageToIntegrationMapping[pkg](); - } catch (e) { - return undefined; - } - }) - .filter(p => p) ; - - if (mappedPackages.length > 0) { - carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages]; - } -} - -/** - * This patches the global object and injects the Tracing extensions methods - */ -function addExtensionMethods() { - _addTracingExtensions(); - - // Detect and automatically load specified integrations. - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.isNodeEnv)()) { - _autoloadDatabaseIntegrations(); - } - - // If an error happens globally, we should make sure transaction status is set to error. - (0,_errors_js__WEBPACK_IMPORTED_MODULE_7__.registerErrorInstrumentation)(); -} - - -//# sourceMappingURL=hubextensions.js.map - - -/***/ }), -/* 1695 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "TRACEPARENT_REGEXP": () => (/* reexport safe */ _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.TRACEPARENT_REGEXP), -/* harmony export */ "extractTraceparentData": () => (/* reexport safe */ _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.extractTraceparentData), -/* harmony export */ "stripUrlQueryAndFragment": () => (/* reexport safe */ _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.stripUrlQueryAndFragment), -/* harmony export */ "getActiveTransaction": () => (/* binding */ getActiveTransaction), -/* harmony export */ "hasTracingEnabled": () => (/* binding */ hasTracingEnabled), -/* harmony export */ "msToSec": () => (/* binding */ msToSec), -/* harmony export */ "secToMs": () => (/* binding */ secToMs) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1679); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1669); - - - -/** - * Determines if tracing is currently enabled. - * - * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. - */ -function hasTracingEnabled( - maybeOptions, -) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)().getClient(); - const options = maybeOptions || (client && client.getOptions()); - return !!options && ('tracesSampleRate' in options || 'tracesSampler' in options); -} - -/** Grabs active transaction off scope, if any */ -function getActiveTransaction(maybeHub) { - const hub = maybeHub || (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)(); - const scope = hub.getScope(); - return scope && (scope.getTransaction() ); -} - -/** - * Converts from milliseconds to seconds - * @param time time in ms - */ -function msToSec(time) { - return time / 1000; -} - -/** - * Converts from seconds to milliseconds - * @param time time in seconds - */ -function secToMs(time) { - return time * 1000; -} - - -//# sourceMappingURL=utils.js.map - - -/***/ }), -/* 1696 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Transaction": () => (/* binding */ Transaction) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1650); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1612); -/* harmony import */ var _span_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1697); - - - - - -/** JSDoc */ -class Transaction extends _span_js__WEBPACK_IMPORTED_MODULE_0__.Span { - - /** - * The reference to the current hub. - */ - - __init() {this._measurements = {};} - - __init2() {this._contexts = {};} - - __init3() {this._frozenDynamicSamplingContext = undefined;} - - /** - * This constructor should never be called manually. Those instrumenting tracing should use - * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. - * @internal - * @hideconstructor - * @hidden - */ - constructor(transactionContext, hub) { - super(transactionContext);Transaction.prototype.__init.call(this);Transaction.prototype.__init2.call(this);Transaction.prototype.__init3.call(this);; - - this._hub = hub || (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - - this._name = transactionContext.name || ''; - - this.metadata = { - source: 'custom', - ...transactionContext.metadata, - spanMetadata: {}, - changes: [], - propagations: 0, - }; - - this._trimEnd = transactionContext.trimEnd; - - // this is because transactions are also spans, and spans have a transaction pointer - this.transaction = this; - - // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means - // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means) - const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext; - if (incomingDynamicSamplingContext) { - // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext` - this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext }; - } - } - - /** Getter for `name` property */ - get name() { - return this._name; - } - - /** Setter for `name` property, which also sets `source` as custom */ - set name(newName) { - this.setName(newName); - } - - /** - * JSDoc - */ - setName(name, source = 'custom') { - // `source` could change without the name changing if we discover that an unparameterized route is actually - // parameterized by virtue of having no parameters in its path - if (name !== this.name || source !== this.metadata.source) { - this.metadata.changes.push({ - // log previous source - source: this.metadata.source, - timestamp: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.timestampInSeconds)(), - propagations: this.metadata.propagations, - }); - } - - this._name = name; - this.metadata.source = source; - } - - /** - * Attaches SpanRecorder to the span itself - * @param maxlen maximum number of spans that can be recorded - */ - initSpanRecorder(maxlen = 1000) { - if (!this.spanRecorder) { - this.spanRecorder = new _span_js__WEBPACK_IMPORTED_MODULE_0__.SpanRecorder(maxlen); - } - this.spanRecorder.add(this); - } - - /** - * @inheritDoc - */ - setContext(key, context) { - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } else { - this._contexts[key] = context; - } - } - - /** - * @inheritDoc - */ - setMeasurement(name, value, unit = '') { - this._measurements[name] = { value, unit }; - } - - /** - * @inheritDoc - */ - setMetadata(newMetadata) { - this.metadata = { ...this.metadata, ...newMetadata }; - } - - /** - * @inheritDoc - */ - finish(endTimestamp) { - // This transaction is already finished, so we should not flush it again. - if (this.endTimestamp !== undefined) { - return undefined; - } - - if (!this.name) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.'); - this.name = '<unlabeled transaction>'; - } - - // just sets the end timestamp - super.finish(endTimestamp); - - if (this.sampled !== true) { - // At this point if `sampled !== true` we want to discard the transaction. - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); - - const client = this._hub.getClient(); - if (client) { - client.recordDroppedEvent('sample_rate', 'transaction'); - } - - return undefined; - } - - const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : []; - - if (this._trimEnd && finishedSpans.length > 0) { - this.endTimestamp = finishedSpans.reduce((prev, current) => { - if (prev.endTimestamp && current.endTimestamp) { - return prev.endTimestamp > current.endTimestamp ? prev : current; - } - return prev; - }).endTimestamp; - } - - const metadata = this.metadata; - - const transaction = { - contexts: { - ...this._contexts, - // We don't want to override trace context - trace: this.getTraceContext(), - }, - spans: finishedSpans, - start_timestamp: this.startTimestamp, - tags: this.tags, - timestamp: this.endTimestamp, - transaction: this.name, - type: 'transaction', - sdkProcessingMetadata: { - ...metadata, - dynamicSamplingContext: this.getDynamicSamplingContext(), - }, - ...(metadata.source && { - transaction_info: { - source: metadata.source, - changes: metadata.changes, - propagations: metadata.propagations, - }, - }), - }; - - const hasMeasurements = Object.keys(this._measurements).length > 0; - - if (hasMeasurements) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - '[Measurements] Adding measurements to transaction', - JSON.stringify(this._measurements, undefined, 2), - ); - transaction.measurements = this._measurements; - } - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`); - - return this._hub.captureEvent(transaction); - } - - /** - * @inheritDoc - */ - toContext() { - const spanContext = super.toContext(); - - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.dropUndefinedKeys)({ - ...spanContext, - name: this.name, - trimEnd: this._trimEnd, - }); - } - - /** - * @inheritDoc - */ - updateWithContext(transactionContext) { - super.updateWithContext(transactionContext); - - this.name = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(transactionContext.name, () => ( '')); - - this._trimEnd = transactionContext.trimEnd; - - return this; - } - - /** - * @inheritdoc - * - * @experimental - */ - getDynamicSamplingContext() { - if (this._frozenDynamicSamplingContext) { - return this._frozenDynamicSamplingContext; - } - - const hub = this._hub || (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - const client = hub && hub.getClient(); - - if (!client) return {}; - - const { environment, release } = client.getOptions() || {}; - const { publicKey: public_key } = client.getDsn() || {}; - - const maybeSampleRate = this.metadata.sampleRate; - const sample_rate = maybeSampleRate !== undefined ? maybeSampleRate.toString() : undefined; - - const scope = hub.getScope(); - const { segment: user_segment } = (scope && scope.getUser()) || {}; - - const source = this.metadata.source; - - // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII - const transaction = source && source !== 'url' ? this.name : undefined; - - const dsc = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.dropUndefinedKeys)({ - environment, - release, - transaction, - user_segment, - public_key, - trace_id: this.traceId, - sample_rate, - }); - - // Uncomment if we want to make DSC immutable - // this._frozenDynamicSamplingContext = dsc; - - return dsc; - } -} - - -//# sourceMappingURL=transaction.js.map - - -/***/ }), -/* 1697 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Span": () => (/* binding */ Span), -/* harmony export */ "SpanRecorder": () => (/* binding */ SpanRecorder), -/* harmony export */ "spanStatusfromHttpCode": () => (/* binding */ spanStatusfromHttpCode) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1612); - - - -/** - * Keeps track of finished spans for a given transaction - * @internal - * @hideconstructor - * @hidden - */ -class SpanRecorder { - __init() {this.spans = [];} - - constructor(maxlen = 1000) {;SpanRecorder.prototype.__init.call(this); - this._maxlen = maxlen; - } - - /** - * This is just so that we don't run out of memory while recording a lot - * of spans. At some point we just stop and flush out the start of the - * trace tree (i.e.the first n spans with the smallest - * start_timestamp). - */ - add(span) { - if (this.spans.length > this._maxlen) { - span.spanRecorder = undefined; - } else { - this.spans.push(span); - } - } -} - -/** - * Span contains all data about a span - */ -class Span { - /** - * @inheritDoc - */ - __init2() {this.traceId = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.uuid4)();} - - /** - * @inheritDoc - */ - __init3() {this.spanId = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.uuid4)().substring(16);} - - /** - * @inheritDoc - */ - - /** - * Internal keeper of the status - */ - - /** - * @inheritDoc - */ - - /** - * Timestamp in seconds when the span was created. - */ - __init4() {this.startTimestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.timestampWithMs)();} - - /** - * Timestamp in seconds when the span ended. - */ - - /** - * @inheritDoc - */ - - /** - * @inheritDoc - */ - - /** - * @inheritDoc - */ - __init5() {this.tags = {};} - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - __init6() {this.data = {};} - - /** - * List of spans that were finalized - */ - - /** - * @inheritDoc - */ - - /** - * The instrumenter that created this span. - */ - __init7() {this.instrumenter = 'sentry';} - - /** - * You should never call the constructor manually, always use `Sentry.startTransaction()` - * or call `startChild()` on an existing span. - * @internal - * @hideconstructor - * @hidden - */ - constructor(spanContext) {;Span.prototype.__init2.call(this);Span.prototype.__init3.call(this);Span.prototype.__init4.call(this);Span.prototype.__init5.call(this);Span.prototype.__init6.call(this);Span.prototype.__init7.call(this); - if (!spanContext) { - return this; - } - if (spanContext.traceId) { - this.traceId = spanContext.traceId; - } - if (spanContext.spanId) { - this.spanId = spanContext.spanId; - } - if (spanContext.parentSpanId) { - this.parentSpanId = spanContext.parentSpanId; - } - // We want to include booleans as well here - if ('sampled' in spanContext) { - this.sampled = spanContext.sampled; - } - if (spanContext.op) { - this.op = spanContext.op; - } - if (spanContext.description) { - this.description = spanContext.description; - } - if (spanContext.data) { - this.data = spanContext.data; - } - if (spanContext.tags) { - this.tags = spanContext.tags; - } - if (spanContext.status) { - this.status = spanContext.status; - } - if (spanContext.startTimestamp) { - this.startTimestamp = spanContext.startTimestamp; - } - if (spanContext.endTimestamp) { - this.endTimestamp = spanContext.endTimestamp; - } - if (spanContext.instrumenter) { - this.instrumenter = spanContext.instrumenter; - } - } - - /** - * @inheritDoc - */ - startChild( - spanContext, - ) { - const childSpan = new Span({ - ...spanContext, - parentSpanId: this.spanId, - sampled: this.sampled, - traceId: this.traceId, - }); - - childSpan.spanRecorder = this.spanRecorder; - if (childSpan.spanRecorder) { - childSpan.spanRecorder.add(childSpan); - } - - childSpan.transaction = this.transaction; - - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && childSpan.transaction) { - const opStr = (spanContext && spanContext.op) || '< unknown op >'; - const nameStr = childSpan.transaction.name || '< unknown name >'; - const idStr = childSpan.transaction.spanId; - - const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`; - childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage }; - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(logMessage); - } - - return childSpan; - } - - /** - * @inheritDoc - */ - setTag(key, value) { - this.tags = { ...this.tags, [key]: value }; - return this; - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - setData(key, value) { - this.data = { ...this.data, [key]: value }; - return this; - } - - /** - * @inheritDoc - */ - setStatus(value) { - this.status = value; - return this; - } - - /** - * @inheritDoc - */ - setHttpStatus(httpStatus) { - this.setTag('http.status_code', String(httpStatus)); - const spanStatus = spanStatusfromHttpCode(httpStatus); - if (spanStatus !== 'unknown_error') { - this.setStatus(spanStatus); - } - return this; - } - - /** - * @inheritDoc - */ - isSuccess() { - return this.status === 'ok'; - } - - /** - * @inheritDoc - */ - finish(endTimestamp) { - if ( - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - // Don't call this for transactions - this.transaction && - this.transaction.spanId !== this.spanId - ) { - const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId]; - if (logMessage) { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log((logMessage ).replace('Starting', 'Finishing')); - } - } - - this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.timestampWithMs)(); - } - - /** - * @inheritDoc - */ - toTraceparent() { - let sampledString = ''; - if (this.sampled !== undefined) { - sampledString = this.sampled ? '-1' : '-0'; - } - return `${this.traceId}-${this.spanId}${sampledString}`; - } - - /** - * @inheritDoc - */ - toContext() { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.dropUndefinedKeys)({ - data: this.data, - description: this.description, - endTimestamp: this.endTimestamp, - op: this.op, - parentSpanId: this.parentSpanId, - sampled: this.sampled, - spanId: this.spanId, - startTimestamp: this.startTimestamp, - status: this.status, - tags: this.tags, - traceId: this.traceId, - }); - } - - /** - * @inheritDoc - */ - updateWithContext(spanContext) { - this.data = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._nullishCoalesce)(spanContext.data, () => ( {})); - this.description = spanContext.description; - this.endTimestamp = spanContext.endTimestamp; - this.op = spanContext.op; - this.parentSpanId = spanContext.parentSpanId; - this.sampled = spanContext.sampled; - this.spanId = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._nullishCoalesce)(spanContext.spanId, () => ( this.spanId)); - this.startTimestamp = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._nullishCoalesce)(spanContext.startTimestamp, () => ( this.startTimestamp)); - this.status = spanContext.status; - this.tags = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._nullishCoalesce)(spanContext.tags, () => ( {})); - this.traceId = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._nullishCoalesce)(spanContext.traceId, () => ( this.traceId)); - - return this; - } - - /** - * @inheritDoc - */ - getTraceContext() - - { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.dropUndefinedKeys)({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - trace_id: this.traceId, - }); - } - - /** - * @inheritDoc - */ - toJSON() - - { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.dropUndefinedKeys)({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - start_timestamp: this.startTimestamp, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - timestamp: this.endTimestamp, - trace_id: this.traceId, - }); - } -} - -/** - * Converts a HTTP status code into a {@link SpanStatusType}. - * - * @param httpStatus The HTTP response status code. - * @returns The span status or unknown_error. - */ -function spanStatusfromHttpCode(httpStatus) { - if (httpStatus < 400 && httpStatus >= 100) { - return 'ok'; - } - - if (httpStatus >= 400 && httpStatus < 500) { - switch (httpStatus) { - case 401: - return 'unauthenticated'; - case 403: - return 'permission_denied'; - case 404: - return 'not_found'; - case 409: - return 'already_exists'; - case 413: - return 'failed_precondition'; - case 429: - return 'resource_exhausted'; - default: - return 'invalid_argument'; - } - } - - if (httpStatus >= 500 && httpStatus < 600) { - switch (httpStatus) { - case 501: - return 'unimplemented'; - case 503: - return 'unavailable'; - case 504: - return 'deadline_exceeded'; - default: - return 'internal_error'; - } - } - - return 'unknown_error'; -} - - -//# sourceMappingURL=span.js.map - - -/***/ }), -/* 1698 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_FINAL_TIMEOUT": () => (/* binding */ DEFAULT_FINAL_TIMEOUT), -/* harmony export */ "DEFAULT_HEARTBEAT_INTERVAL": () => (/* binding */ DEFAULT_HEARTBEAT_INTERVAL), -/* harmony export */ "DEFAULT_IDLE_TIMEOUT": () => (/* binding */ DEFAULT_IDLE_TIMEOUT), -/* harmony export */ "IdleTransaction": () => (/* binding */ IdleTransaction), -/* harmony export */ "IdleTransactionSpanRecorder": () => (/* binding */ IdleTransactionSpanRecorder) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1615); -/* harmony import */ var _span_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1697); -/* harmony import */ var _transaction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1696); - - - - -const DEFAULT_IDLE_TIMEOUT = 1000; -const DEFAULT_FINAL_TIMEOUT = 30000; -const DEFAULT_HEARTBEAT_INTERVAL = 5000; - -/** - * @inheritDoc - */ -class IdleTransactionSpanRecorder extends _span_js__WEBPACK_IMPORTED_MODULE_0__.SpanRecorder { - constructor( - _pushActivity, - _popActivity, - transactionSpanId, - maxlen, - ) { - super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId;; - } - - /** - * @inheritDoc - */ - add(span) { - // We should make sure we do not push and pop activities for - // the transaction that this span recorder belongs to. - if (span.spanId !== this.transactionSpanId) { - // We patch span.finish() to pop an activity after setting an endTimestamp. - span.finish = (endTimestamp) => { - span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.timestampWithMs)(); - this._popActivity(span.spanId); - }; - - // We should only push new activities if the span does not have an end timestamp. - if (span.endTimestamp === undefined) { - this._pushActivity(span.spanId); - } - } - - super.add(span); - } -} - -/** - * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities. - * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will - * put itself on the scope on creation. - */ -class IdleTransaction extends _transaction_js__WEBPACK_IMPORTED_MODULE_2__.Transaction { - // Activities store a list of active spans - __init() {this.activities = {};} - - // Track state of activities in previous heartbeat - - // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats. - __init2() {this._heartbeatCounter = 0;} - - // We should not use heartbeat if we finished a transaction - __init3() {this._finished = false;} - - __init4() {this._beforeFinishCallbacks = [];} - - /** - * Timer that tracks Transaction idleTimeout - */ - - constructor( - transactionContext, - _idleHub, - /** - * The time to wait in ms until the idle transaction will be finished. This timer is started each time - * there are no active spans on this transaction. - */ - _idleTimeout = DEFAULT_IDLE_TIMEOUT, - /** - * The final value in ms that a transaction cannot exceed - */ - _finalTimeout = DEFAULT_FINAL_TIMEOUT, - _heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL, - // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends - _onScope = false, - ) { - super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope;IdleTransaction.prototype.__init.call(this);IdleTransaction.prototype.__init2.call(this);IdleTransaction.prototype.__init3.call(this);IdleTransaction.prototype.__init4.call(this);; - - if (_onScope) { - // There should only be one active transaction on the scope - clearActiveTransaction(_idleHub); - - // We set the transaction here on the scope so error events pick up the trace - // context and attach it to the error. - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`); - _idleHub.configureScope(scope => scope.setSpan(this)); - } - - this._startIdleTimeout(); - setTimeout(() => { - if (!this._finished) { - this.setStatus('deadline_exceeded'); - this.finish(); - } - }, this._finalTimeout); - } - - /** {@inheritDoc} */ - finish(endTimestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.timestampWithMs)()) { - this._finished = true; - this.activities = {}; - - if (this.spanRecorder) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); - - for (const callback of this._beforeFinishCallbacks) { - callback(this, endTimestamp); - } - - this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => { - // If we are dealing with the transaction itself, we just return it - if (span.spanId === this.spanId) { - return true; - } - - // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early - if (!span.endTimestamp) { - span.endTimestamp = endTimestamp; - span.setStatus('cancelled'); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); - } - - const keepSpan = span.startTimestamp < endTimestamp; - if (!keepSpan) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - '[Tracing] discarding Span since it happened after Transaction was finished', - JSON.stringify(span, undefined, 2), - ); - } - return keepSpan; - }); - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] flushing IdleTransaction'); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] No active IdleTransaction'); - } - - // if `this._onScope` is `true`, the transaction put itself on the scope when it started - if (this._onScope) { - clearActiveTransaction(this._idleHub); - } - - return super.finish(endTimestamp); - } - - /** - * Register a callback function that gets excecuted before the transaction finishes. - * Useful for cleanup or if you want to add any additional spans based on current context. - * - * This is exposed because users have no other way of running something before an idle transaction - * finishes. - */ - registerBeforeFinishCallback(callback) { - this._beforeFinishCallbacks.push(callback); - } - - /** - * @inheritDoc - */ - initSpanRecorder(maxlen) { - if (!this.spanRecorder) { - const pushActivity = (id) => { - if (this._finished) { - return; - } - this._pushActivity(id); - }; - const popActivity = (id) => { - if (this._finished) { - return; - } - this._popActivity(id); - }; - - this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen); - - // Start heartbeat so that transactions do not run forever. - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('Starting heartbeat'); - this._pingHeartbeat(); - } - this.spanRecorder.add(this); - } - - /** - * Cancels the existing idletimeout, if there is one - */ - _cancelIdleTimeout() { - if (this._idleTimeoutID) { - clearTimeout(this._idleTimeoutID); - this._idleTimeoutID = undefined; - } - } - - /** - * Creates an idletimeout - */ - _startIdleTimeout(endTimestamp) { - this._cancelIdleTimeout(); - this._idleTimeoutID = setTimeout(() => { - if (!this._finished && Object.keys(this.activities).length === 0) { - this.finish(endTimestamp); - } - }, this._idleTimeout); - } - - /** - * Start tracking a specific activity. - * @param spanId The span id that represents the activity - */ - _pushActivity(spanId) { - this._cancelIdleTimeout(); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`[Tracing] pushActivity: ${spanId}`); - this.activities[spanId] = true; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); - } - - /** - * Remove an activity from usage - * @param spanId The span id that represents the activity - */ - _popActivity(spanId) { - if (this.activities[spanId]) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`[Tracing] popActivity ${spanId}`); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this.activities[spanId]; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); - } - - if (Object.keys(this.activities).length === 0) { - // We need to add the timeout here to have the real endtimestamp of the transaction - // Remember timestampWithMs is in seconds, timeout is in ms - const endTimestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.timestampWithMs)() + this._idleTimeout / 1000; - this._startIdleTimeout(endTimestamp); - } - } - - /** - * Checks when entries of this.activities are not changing for 3 beats. - * If this occurs we finish the transaction. - */ - _beat() { - // We should not be running heartbeat if the idle transaction is finished. - if (this._finished) { - return; - } - - const heartbeatString = Object.keys(this.activities).join(''); - - if (heartbeatString === this._prevHeartbeatString) { - this._heartbeatCounter++; - } else { - this._heartbeatCounter = 1; - } - - this._prevHeartbeatString = heartbeatString; - - if (this._heartbeatCounter >= 3) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('[Tracing] Transaction finished because of no change for 3 heart beats'); - this.setStatus('deadline_exceeded'); - this.finish(); - } else { - this._pingHeartbeat(); - } - } - - /** - * Pings the heartbeat - */ - _pingHeartbeat() { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`); - setTimeout(() => { - this._beat(); - }, this._heartbeatInterval); - } -} - -/** - * Reset transaction on scope to `undefined` - */ -function clearActiveTransaction(hub) { - const scope = hub.getScope(); - if (scope) { - const transaction = scope.getTransaction(); - if (transaction) { - scope.setSpan(undefined); - } - } -} - - -//# sourceMappingURL=idletransaction.js.map - - -/***/ }), -/* 1699 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "registerErrorInstrumentation": () => (/* binding */ registerErrorInstrumentation) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1700); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1695); - - - -/** - * Configures global error listeners - */ -function registerErrorInstrumentation() { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.addInstrumentationHandler)('error', errorCallback); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.addInstrumentationHandler)('unhandledrejection', errorCallback); -} - -/** - * If an error or unhandled promise occurs, we mark the active transaction as failed - */ -function errorCallback() { - const activeTransaction = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.getActiveTransaction)(); - if (activeTransaction) { - const status = 'internal_error'; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(`[Tracing] Transaction: ${status} -> Global error occured`); - activeTransaction.setStatus(status); - } -} - - -//# sourceMappingURL=errors.js.map - - -/***/ }), -/* 1700 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addInstrumentationHandler": () => (/* binding */ addInstrumentationHandler) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1611); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1612); -/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); -/* harmony import */ var _supports_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1701); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - - - - - - -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - -/** - * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc. - * - Console API - * - Fetch API - * - XHR API - * - History API - * - DOM API (click/typing) - * - Error API - * - UnhandledRejection API - */ - -const handlers = {}; -const instrumented = {}; - -/** Instruments given API */ -function instrument(type) { - if (instrumented[type]) { - return; - } - - instrumented[type] = true; - - switch (type) { - case 'console': - instrumentConsole(); - break; - case 'dom': - instrumentDOM(); - break; - case 'xhr': - instrumentXHR(); - break; - case 'fetch': - instrumentFetch(); - break; - case 'history': - instrumentHistory(); - break; - case 'error': - instrumentError(); - break; - case 'unhandledrejection': - instrumentUnhandledRejection(); - break; - default: - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn('unknown instrumentation type:', type); - return; - } -} - -/** - * Add handler that will be called when given type of instrumentation triggers. - * Use at your own risk, this might break without changelog notice, only used internally. - * @hidden - */ -function addInstrumentationHandler(type, callback) { - handlers[type] = handlers[type] || []; - (handlers[type] ).push(callback); - instrument(type); -} - -/** JSDoc */ -function triggerHandlers(type, data) { - if (!type || !handlers[type]) { - return; - } - - for (const handler of handlers[type] || []) { - try { - handler(data); - } catch (e) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.error( - `Error while triggering instrumentation handler.\nType: ${type}\nName: ${(0,_stacktrace_js__WEBPACK_IMPORTED_MODULE_2__.getFunctionName)(handler)}\nError:`, - e, - ); - } - } -} - -/** JSDoc */ -function instrumentConsole() { - if (!('console' in WINDOW)) { - return; - } - - _logger_js__WEBPACK_IMPORTED_MODULE_1__.CONSOLE_LEVELS.forEach(function (level) { - if (!(level in WINDOW.console)) { - return; - } - - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(WINDOW.console, level, function (originalConsoleMethod) { - return function (...args) { - triggerHandlers('console', { args, level }); - - // this fails for some browsers. :( - if (originalConsoleMethod) { - originalConsoleMethod.apply(WINDOW.console, args); - } - }; - }); - }); -} - -/** JSDoc */ -function instrumentFetch() { - if (!(0,_supports_js__WEBPACK_IMPORTED_MODULE_4__.supportsNativeFetch)()) { - return; - } - - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(WINDOW, 'fetch', function (originalFetch) { - return function (...args) { - const handlerData = { - args, - fetchData: { - method: getFetchMethod(args), - url: getFetchUrl(args), - }, - startTimestamp: Date.now(), - }; - - triggerHandlers('fetch', { - ...handlerData, - }); - - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalFetch.apply(WINDOW, args).then( - (response) => { - triggerHandlers('fetch', { - ...handlerData, - endTimestamp: Date.now(), - response, - }); - return response; - }, - (error) => { - triggerHandlers('fetch', { - ...handlerData, - endTimestamp: Date.now(), - error, - }); - // NOTE: If you are a Sentry user, and you are seeing this stack frame, - // it means the sentry.javascript SDK caught an error invoking your application code. - // This is expected behavior and NOT indicative of a bug with sentry.javascript. - throw error; - }, - ); - }; - }); -} - -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/** Extract `method` from fetch call arguments */ -function getFetchMethod(fetchArgs = []) { - if ('Request' in WINDOW && (0,_is_js__WEBPACK_IMPORTED_MODULE_5__.isInstanceOf)(fetchArgs[0], Request) && fetchArgs[0].method) { - return String(fetchArgs[0].method).toUpperCase(); - } - if (fetchArgs[1] && fetchArgs[1].method) { - return String(fetchArgs[1].method).toUpperCase(); - } - return 'GET'; -} - -/** Extract `url` from fetch call arguments */ -function getFetchUrl(fetchArgs = []) { - if (typeof fetchArgs[0] === 'string') { - return fetchArgs[0]; - } - if ('Request' in WINDOW && (0,_is_js__WEBPACK_IMPORTED_MODULE_5__.isInstanceOf)(fetchArgs[0], Request)) { - return fetchArgs[0].url; - } - return String(fetchArgs[0]); -} -/* eslint-enable @typescript-eslint/no-unsafe-member-access */ - -/** JSDoc */ -function instrumentXHR() { - if (!('XMLHttpRequest' in WINDOW)) { - return; - } - - const xhrproto = XMLHttpRequest.prototype; - - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(xhrproto, 'open', function (originalOpen) { - return function ( ...args) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const xhr = this; - const url = args[1]; - const xhrInfo = (xhr.__sentry_xhr__ = { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - method: (0,_is_js__WEBPACK_IMPORTED_MODULE_5__.isString)(args[0]) ? args[0].toUpperCase() : args[0], - url: args[1], - }); - - // if Sentry key appears in URL, don't capture it as a request - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_5__.isString)(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) { - xhr.__sentry_own_request__ = true; - } - - const onreadystatechangeHandler = function () { - if (xhr.readyState === 4) { - try { - // touching statusCode in some platforms throws - // an exception - xhrInfo.status_code = xhr.status; - } catch (e) { - /* do nothing */ - } - - triggerHandlers('xhr', { - args, - endTimestamp: Date.now(), - startTimestamp: Date.now(), - xhr, - }); - } - }; - - if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') { - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(xhr, 'onreadystatechange', function (original) { - return function (...readyStateArgs) { - onreadystatechangeHandler(); - return original.apply(xhr, readyStateArgs); - }; - }); - } else { - xhr.addEventListener('readystatechange', onreadystatechangeHandler); - } - - return originalOpen.apply(xhr, args); - }; - }); - - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(xhrproto, 'send', function (originalSend) { - return function ( ...args) { - if (this.__sentry_xhr__ && args[0] !== undefined) { - this.__sentry_xhr__.body = args[0]; - } - - triggerHandlers('xhr', { - args, - startTimestamp: Date.now(), - xhr: this, - }); - - return originalSend.apply(this, args); - }; - }); -} - -let lastHref; - -/** JSDoc */ -function instrumentHistory() { - if (!(0,_supports_js__WEBPACK_IMPORTED_MODULE_4__.supportsHistory)()) { - return; - } - - const oldOnPopState = WINDOW.onpopstate; - WINDOW.onpopstate = function ( ...args) { - const to = WINDOW.location.href; - // keep track of the current URL state, as we always receive only the updated state - const from = lastHref; - lastHref = to; - triggerHandlers('history', { - from, - to, - }); - if (oldOnPopState) { - // Apparently this can throw in Firefox when incorrectly implemented plugin is installed. - // https://github.com/getsentry/sentry-javascript/issues/3344 - // https://github.com/bugsnag/bugsnag-js/issues/469 - try { - return oldOnPopState.apply(this, args); - } catch (_oO) { - // no-empty - } - } - }; - - /** @hidden */ - function historyReplacementFunction(originalHistoryFunction) { - return function ( ...args) { - const url = args.length > 2 ? args[2] : undefined; - if (url) { - // coerce to string (this is what pushState does) - const from = lastHref; - const to = String(url); - // keep track of the current URL state, as we always receive only the updated state - lastHref = to; - triggerHandlers('history', { - from, - to, - }); - } - return originalHistoryFunction.apply(this, args); - }; - } - - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(WINDOW.history, 'pushState', historyReplacementFunction); - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(WINDOW.history, 'replaceState', historyReplacementFunction); -} - -const debounceDuration = 1000; -let debounceTimerID; -let lastCapturedEvent; - -/** - * Decide whether the current event should finish the debounce of previously captured one. - * @param previous previously captured event - * @param current event to be captured - */ -function shouldShortcircuitPreviousDebounce(previous, current) { - // If there was no previous event, it should always be swapped for the new one. - if (!previous) { - return true; - } - - // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress. - if (previous.type !== current.type) { - return true; - } - - try { - // If both events have the same type, it's still possible that actions were performed on different targets. - // e.g. 2 clicks on different buttons. - if (previous.target !== current.target) { - return true; - } - } catch (e) { - // just accessing `target` property can throw an exception in some rare circumstances - // see: https://github.com/getsentry/sentry-javascript/issues/838 - } - - // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_ - // to which an event listener was attached), we treat them as the same action, as we want to capture - // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box. - return false; -} - -/** - * Decide whether an event should be captured. - * @param event event to be captured - */ -function shouldSkipDOMEvent(event) { - // We are only interested in filtering `keypress` events for now. - if (event.type !== 'keypress') { - return false; - } - - try { - const target = event.target ; - - if (!target || !target.tagName) { - return true; - } - - // Only consider keypress events on actual input elements. This will disregard keypresses targeting body - // e.g.tabbing through elements, hotkeys, etc. - if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { - return false; - } - } catch (e) { - // just accessing `target` property can throw an exception in some rare circumstances - // see: https://github.com/getsentry/sentry-javascript/issues/838 - } - - return true; -} - -/** - * Wraps addEventListener to capture UI breadcrumbs - * @param handler function that will be triggered - * @param globalListener indicates whether event was captured by the global event listener - * @returns wrapped breadcrumb events handler - * @hidden - */ -function makeDOMEventHandler(handler, globalListener = false) { - return (event) => { - // It's possible this handler might trigger multiple times for the same - // event (e.g. event propagation through node ancestors). - // Ignore if we've already captured that event. - if (!event || lastCapturedEvent === event) { - return; - } - - // We always want to skip _some_ events. - if (shouldSkipDOMEvent(event)) { - return; - } - - const name = event.type === 'keypress' ? 'input' : event.type; - - // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons. - if (debounceTimerID === undefined) { - handler({ - event: event, - name, - global: globalListener, - }); - lastCapturedEvent = event; - } - // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one. - // If that's the case, emit the previous event and store locally the newly-captured DOM event. - else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) { - handler({ - event: event, - name, - global: globalListener, - }); - lastCapturedEvent = event; - } - - // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together. - clearTimeout(debounceTimerID); - debounceTimerID = WINDOW.setTimeout(() => { - debounceTimerID = undefined; - }, debounceDuration); - }; -} - -/** JSDoc */ -function instrumentDOM() { - if (!('document' in WINDOW)) { - return; - } - - // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom - // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before - // we instrument `addEventListener` so that we don't end up attaching this handler twice. - const triggerDOMHandler = triggerHandlers.bind(null, 'dom'); - const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); - WINDOW.document.addEventListener('click', globalDOMEventHandler, false); - WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false); - - // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled - // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That - // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler - // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still - // guaranteed to fire at least once.) - ['EventTarget', 'Node'].forEach((target) => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const proto = (WINDOW )[target] && (WINDOW )[target].prototype; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins - if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { - return; - } - - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)(proto, 'addEventListener', function (originalAddEventListener) { - return function ( - - type, - listener, - options, - ) { - if (type === 'click' || type == 'keypress') { - try { - const el = this ; - const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); - const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 }); - - if (!handlerForType.handler) { - const handler = makeDOMEventHandler(triggerDOMHandler); - handlerForType.handler = handler; - originalAddEventListener.call(this, type, handler, options); - } - - handlerForType.refCount++; - } catch (e) { - // Accessing dom properties is always fragile. - // Also allows us to skip `addEventListenrs` calls with no proper `this` context. - } - } - - return originalAddEventListener.call(this, type, listener, options); - }; - }); - - (0,_object_js__WEBPACK_IMPORTED_MODULE_3__.fill)( - proto, - 'removeEventListener', - function (originalRemoveEventListener) { - return function ( - - type, - listener, - options, - ) { - if (type === 'click' || type == 'keypress') { - try { - const el = this ; - const handlers = el.__sentry_instrumentation_handlers__ || {}; - const handlerForType = handlers[type]; - - if (handlerForType) { - handlerForType.refCount--; - // If there are no longer any custom handlers of the current type on this element, we can remove ours, too. - if (handlerForType.refCount <= 0) { - originalRemoveEventListener.call(this, type, handlerForType.handler, options); - handlerForType.handler = undefined; - delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete - } - - // If there are no longer any custom handlers of any type on this element, cleanup everything. - if (Object.keys(handlers).length === 0) { - delete el.__sentry_instrumentation_handlers__; - } - } - } catch (e) { - // Accessing dom properties is always fragile. - // Also allows us to skip `addEventListenrs` calls with no proper `this` context. - } - } - - return originalRemoveEventListener.call(this, type, listener, options); - }; - }, - ); - }); -} - -let _oldOnErrorHandler = null; -/** JSDoc */ -function instrumentError() { - _oldOnErrorHandler = WINDOW.onerror; - - WINDOW.onerror = function (msg, url, line, column, error) { - triggerHandlers('error', { - column, - error, - line, - msg, - url, - }); - - if (_oldOnErrorHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnErrorHandler.apply(this, arguments); - } - - return false; - }; -} - -let _oldOnUnhandledRejectionHandler = null; -/** JSDoc */ -function instrumentUnhandledRejection() { - _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection; - - WINDOW.onunhandledrejection = function (e) { - triggerHandlers('unhandledrejection', e); - - if (_oldOnUnhandledRejectionHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnUnhandledRejectionHandler.apply(this, arguments); - } - - return true; - }; -} - - -//# sourceMappingURL=instrument.js.map - - -/***/ }), -/* 1701 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isNativeFetch": () => (/* binding */ isNativeFetch), -/* harmony export */ "supportsDOMError": () => (/* binding */ supportsDOMError), -/* harmony export */ "supportsDOMException": () => (/* binding */ supportsDOMException), -/* harmony export */ "supportsErrorEvent": () => (/* binding */ supportsErrorEvent), -/* harmony export */ "supportsFetch": () => (/* binding */ supportsFetch), -/* harmony export */ "supportsHistory": () => (/* binding */ supportsHistory), -/* harmony export */ "supportsNativeFetch": () => (/* binding */ supportsNativeFetch), -/* harmony export */ "supportsReferrerPolicy": () => (/* binding */ supportsReferrerPolicy), -/* harmony export */ "supportsReportingObserver": () => (/* binding */ supportsReportingObserver) -/* harmony export */ }); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - - -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - -/** - * Tells whether current environment supports ErrorEvent objects - * {@link supportsErrorEvent}. - * - * @returns Answer to the given question. - */ -function supportsErrorEvent() { - try { - new ErrorEvent(''); - return true; - } catch (e) { - return false; - } -} - -/** - * Tells whether current environment supports DOMError objects - * {@link supportsDOMError}. - * - * @returns Answer to the given question. - */ -function supportsDOMError() { - try { - // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': - // 1 argument required, but only 0 present. - // @ts-ignore It really needs 1 argument, not 0. - new DOMError(''); - return true; - } catch (e) { - return false; - } -} - -/** - * Tells whether current environment supports DOMException objects - * {@link supportsDOMException}. - * - * @returns Answer to the given question. - */ -function supportsDOMException() { - try { - new DOMException(''); - return true; - } catch (e) { - return false; - } -} - -/** - * Tells whether current environment supports Fetch API - * {@link supportsFetch}. - * - * @returns Answer to the given question. - */ -function supportsFetch() { - if (!('fetch' in WINDOW)) { - return false; - } - - try { - new Headers(); - new Request('http://www.example.com'); - new Response(); - return true; - } catch (e) { - return false; - } -} -/** - * isNativeFetch checks if the given function is a native implementation of fetch() - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function isNativeFetch(func) { - return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); -} - -/** - * Tells whether current environment supports Fetch API natively - * {@link supportsNativeFetch}. - * - * @returns true if `window.fetch` is natively implemented, false otherwise - */ -function supportsNativeFetch() { - if (!supportsFetch()) { - return false; - } - - // Fast path to avoid DOM I/O - // eslint-disable-next-line @typescript-eslint/unbound-method - if (isNativeFetch(WINDOW.fetch)) { - return true; - } - - // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) - // so create a "pure" iframe to see if that has native fetch - let result = false; - const doc = WINDOW.document; - // eslint-disable-next-line deprecation/deprecation - if (doc && typeof (doc.createElement ) === 'function') { - try { - const sandbox = doc.createElement('iframe'); - sandbox.hidden = true; - doc.head.appendChild(sandbox); - if (sandbox.contentWindow && sandbox.contentWindow.fetch) { - // eslint-disable-next-line @typescript-eslint/unbound-method - result = isNativeFetch(sandbox.contentWindow.fetch); - } - doc.head.removeChild(sandbox); - } catch (err) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); - } - } - - return result; -} - -/** - * Tells whether current environment supports ReportingObserver API - * {@link supportsReportingObserver}. - * - * @returns Answer to the given question. - */ -function supportsReportingObserver() { - return 'ReportingObserver' in WINDOW; -} - -/** - * Tells whether current environment supports Referrer Policy API - * {@link supportsReferrerPolicy}. - * - * @returns Answer to the given question. - */ -function supportsReferrerPolicy() { - // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default' - // (see https://caniuse.com/#feat=referrer-policy), - // it doesn't. And it throws an exception instead of ignoring this parameter... - // REF: https://github.com/getsentry/raven-js/issues/1233 - - if (!supportsFetch()) { - return false; - } - - try { - new Request('_', { - referrerPolicy: 'origin' , - }); - return true; - } catch (e) { - return false; - } -} - -/** - * Tells whether current environment supports History API - * {@link supportsHistory}. - * - * @returns Answer to the given question. - */ -function supportsHistory() { - // NOTE: in Chrome App environment, touching history.pushState, *even inside - // a try/catch block*, will cause Chrome to output an error to console.error - // borrowed from: https://github.com/angular/angular.js/pull/13945/files - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const chrome = (WINDOW ).chrome; - const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState; - - return !isChromePackagedApp && hasHistoryApi; -} - - -//# sourceMappingURL=supports.js.map - - -/***/ }), -/* 1702 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Express": () => (/* reexport safe */ _node_express_js__WEBPACK_IMPORTED_MODULE_0__.Express), -/* harmony export */ "Postgres": () => (/* reexport safe */ _node_postgres_js__WEBPACK_IMPORTED_MODULE_1__.Postgres), -/* harmony export */ "Mysql": () => (/* reexport safe */ _node_mysql_js__WEBPACK_IMPORTED_MODULE_2__.Mysql), -/* harmony export */ "Mongo": () => (/* reexport safe */ _node_mongo_js__WEBPACK_IMPORTED_MODULE_3__.Mongo), -/* harmony export */ "Prisma": () => (/* reexport safe */ _node_prisma_js__WEBPACK_IMPORTED_MODULE_4__.Prisma), -/* harmony export */ "GraphQL": () => (/* reexport safe */ _node_graphql_js__WEBPACK_IMPORTED_MODULE_5__.GraphQL), -/* harmony export */ "Apollo": () => (/* reexport safe */ _node_apollo_js__WEBPACK_IMPORTED_MODULE_6__.Apollo), -/* harmony export */ "BrowserTracing": () => (/* reexport safe */ _browser_browsertracing_js__WEBPACK_IMPORTED_MODULE_7__.BrowserTracing) -/* harmony export */ }); -/* harmony import */ var _node_express_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1703); -/* harmony import */ var _node_postgres_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1705); -/* harmony import */ var _node_mysql_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1706); -/* harmony import */ var _node_mongo_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1707); -/* harmony import */ var _node_prisma_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1708); -/* harmony import */ var _node_graphql_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1709); -/* harmony import */ var _node_apollo_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1710); -/* harmony import */ var _browser_browsertracing_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1711); - - - - - - - - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1703 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Express": () => (/* binding */ Express) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1669); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1670); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1611); -/* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1704); - - - - -/** - * Express integration - * - * Provides an request and error handler for Express framework as well as tracing capabilities - */ -class Express { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Express';} - - /** - * @inheritDoc - */ - __init() {this.name = Express.id;} - - /** - * Express App instance - */ - - /** - * @inheritDoc - */ - constructor(options = {}) {;Express.prototype.__init.call(this); - this._router = options.router || options.app; - this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use'); - } - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - if (!this._router) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error('ExpressIntegration is missing an Express instance'); - return; - } - - if ((0,_utils_node_utils_js__WEBPACK_IMPORTED_MODULE_1__.shouldDisableAutoInstrumentation)(getCurrentHub)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.log('Express Integration is skipped because of instrumenter configuration.'); - return; - } - - instrumentMiddlewares(this._router, this._methods); - instrumentRouter(this._router ); - } -}Express.__initStatic(); - -/** - * Wraps original middleware function in a tracing call, which stores the info about the call as a span, - * and finishes it once the middleware is done invoking. - * - * Express middlewares have 3 various forms, thus we have to take care of all of them: - * // sync - * app.use(function (req, res) { ... }) - * // async - * app.use(function (req, res, next) { ... }) - * // error handler - * app.use(function (err, req, res, next) { ... }) - * - * They all internally delegate to the `router[method]` of the given application instance. - */ -// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any -function wrap(fn, method) { - const arity = fn.length; - - switch (arity) { - case 2: { - return function ( req, res) { - const transaction = res.__sentry_transaction; - if (transaction) { - const span = transaction.startChild({ - description: fn.name, - op: `middleware.express.${method}`, - }); - res.once('finish', () => { - span.finish(); - }); - } - return fn.call(this, req, res); - }; - } - case 3: { - return function ( - - req, - res, - next, - ) { - const transaction = res.__sentry_transaction; - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([transaction, 'optionalAccess', _2 => _2.startChild, 'call', _3 => _3({ - description: fn.name, - op: `middleware.express.${method}`, - })]); - fn.call(this, req, res, function ( ...args) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([span, 'optionalAccess', _4 => _4.finish, 'call', _5 => _5()]); - next.call(this, ...args); - }); - }; - } - case 4: { - return function ( - - err, - req, - res, - next, - ) { - const transaction = res.__sentry_transaction; - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([transaction, 'optionalAccess', _6 => _6.startChild, 'call', _7 => _7({ - description: fn.name, - op: `middleware.express.${method}`, - })]); - fn.call(this, err, req, res, function ( ...args) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]); - next.call(this, ...args); - }); - }; - } - default: { - throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`); - } - } -} - -/** - * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use` - * and wraps every function, as well as array of functions with a call to our `wrap` method. - * We have to take care of the arrays as well as iterate over all of the arguments, - * as `app.use` can accept middlewares in few various forms. - * - * app.use([<path>], <fn>) - * app.use([<path>], <fn>, ...<fn>) - * app.use([<path>], ...<fn>[]) - */ -function wrapMiddlewareArgs(args, method) { - return args.map((arg) => { - if (typeof arg === 'function') { - return wrap(arg, method); - } - - if (Array.isArray(arg)) { - return arg.map((a) => { - if (typeof a === 'function') { - return wrap(a, method); - } - return a; - }); - } - - return arg; - }); -} - -/** - * Patches original router to utilize our tracing functionality - */ -function patchMiddleware(router, method) { - const originalCallback = router[method]; - - router[method] = function (...args) { - return originalCallback.call(this, ...wrapMiddlewareArgs(args, method)); - }; - - return router; -} - -/** - * Patches original router methods - */ -function instrumentMiddlewares(router, methods = []) { - methods.forEach((method) => patchMiddleware(router, method)); -} - -/** - * Patches the prototype of Express.Router to accumulate the resolved route - * if a layer instance's `match` function was called and it returned a successful match. - * - * @see https://github.com/expressjs/express/blob/master/lib/router/index.js - * - * @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router. - */ -function instrumentRouter(appOrRouter) { - // This is how we can distinguish between app and routers - const isApp = 'settings' in appOrRouter; - - // In case the app's top-level router hasn't been initialized yet, we have to do it now - if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) { - appOrRouter.lazyrouter(); - } - - const router = isApp ? appOrRouter._router : appOrRouter; - - if (!router) { - /* - If we end up here, this means likely that this integration is used with Express 3 or Express 5. - For now, we don't support these versions (3 is very old and 5 is still in beta). To support Express 5, - we'd need to make more changes to the routing instrumentation because the router is no longer part of - the Express core package but maintained in its own package. The new router has different function - signatures and works slightly differently, demanding more changes than just taking the router from - `app.router` instead of `app._router`. - @see https://github.com/pillarjs/router - - TODO: Proper Express 5 support - */ - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.debug('Cannot instrument router for URL Parameterization (did not find a valid router).'); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.debug('Routing instrumentation is currently only supported in Express 4.'); - return; - } - - const routerProto = Object.getPrototypeOf(router) ; - - const originalProcessParams = routerProto.process_params; - routerProto.process_params = function process_params( - layer, - called, - req, - res, - done, - ) { - // Base case: We're in the first part of the URL (thus we start with the root '/') - if (!req._reconstructedRoute) { - req._reconstructedRoute = ''; - } - - // If the layer's partial route has params, is a regex or an array, the route is stored in layer.route. - const { layerRoutePath, isRegex, isArray, numExtraSegments } = getLayerRoutePathInfo(layer); - - if (layerRoutePath || isRegex || isArray) { - req._hasParameters = true; - } - - // Otherwise, the hardcoded path (i.e. a partial route without params) is stored in layer.path - const partialRoute = layerRoutePath || layer.path || ''; - - // Normalize the partial route so that it doesn't contain leading or trailing slashes - // and exclude empty or '*' wildcard routes. - // The exclusion of '*' routes is our best effort to not "pollute" the transaction name - // with interim handlers (e.g. ones that check authentication or do other middleware stuff). - // We want to end up with the parameterized URL of the incoming request without any extraneous path segments. - const finalPartialRoute = partialRoute - .split('/') - .filter(segment => segment.length > 0 && (isRegex || isArray || !segment.includes('*'))) - .join('/'); - - // If we found a valid partial URL, we append it to the reconstructed route - if (finalPartialRoute && finalPartialRoute.length > 0) { - // If the partial route is from a regex route, we append a '/' to close the regex - req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? '/' : ''}`; - } - - // Now we check if we are in the "last" part of the route. We determine this by comparing the - // number of URL segments from the original URL to that of our reconstructed parameterized URL. - // If we've reached our final destination, we update the transaction name. - const urlLength = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.getNumberOfUrlSegments)(req.originalUrl || '') + numExtraSegments; - const routeLength = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.getNumberOfUrlSegments)(req._reconstructedRoute); - - if (urlLength === routeLength) { - if (!req._hasParameters) { - if (req._reconstructedRoute !== req.originalUrl) { - req._reconstructedRoute = req.originalUrl; - } - } - - const transaction = res.__sentry_transaction; - if (transaction && transaction.metadata.source !== 'custom') { - // If the request URL is '/' or empty, the reconstructed route will be empty. - // Therefore, we fall back to setting the final route to '/' in this case. - const finalRoute = req._reconstructedRoute || '/'; - - transaction.setName(...(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.extractPathForTransaction)(req, { path: true, method: true, customRoute: finalRoute })); - } - } - - return originalProcessParams.call(this, layer, called, req, res, done); - }; -} - -/** - * Extracts and stringifies the layer's route which can either be a string with parameters (`users/:id`), - * a RegEx (`/test/`) or an array of strings and regexes (`['/path1', /\/path[2-5]/, /path/:id]`). Additionally - * returns extra information about the route, such as if the route is defined as regex or as an array. - * - * @param layer the layer to extract the stringified route from - * - * @returns an object containing the stringified route, a flag determining if the route was a regex - * and the number of extra segments to the matched path that are additionally in the route, - * if the route was an array (defaults to 0). - */ -function getLayerRoutePathInfo(layer) { - const lrp = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([layer, 'access', _10 => _10.route, 'optionalAccess', _11 => _11.path]); - - const isRegex = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isRegExp)(lrp); - const isArray = Array.isArray(lrp); - - if (!lrp) { - return { isRegex, isArray, numExtraSegments: 0 }; - } - - const numExtraSegments = isArray - ? Math.max(getNumberOfArrayUrlSegments(lrp ) - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.getNumberOfUrlSegments)(layer.path || ''), 0) - : 0; - - const layerRoutePath = getLayerRoutePathString(isArray, lrp); - - return { layerRoutePath, isRegex, isArray, numExtraSegments }; -} - -/** - * Returns the number of URL segments in an array of routes - * - * Example: ['/api/test', /\/api\/post[0-9]/, '/users/:id/details`] -> 7 - */ -function getNumberOfArrayUrlSegments(routesArray) { - return routesArray.reduce((accNumSegments, currentRoute) => { - // array members can be a RegEx -> convert them toString - return accNumSegments + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.getNumberOfUrlSegments)(currentRoute.toString()); - }, 0); -} - -/** - * Extracts and returns the stringified version of the layers route path - * Handles route arrays (by joining the paths together) as well as RegExp and normal - * string values (in the latter case the toString conversion is technically unnecessary but - * it doesn't hurt us either). - */ -function getLayerRoutePathString(isArray, lrp) { - if (isArray) { - return (lrp ).map(r => r.toString()).join(','); - } - return lrp && lrp.toString(); -} - - -//# sourceMappingURL=express.js.map - - -/***/ }), -/* 1704 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "shouldDisableAutoInstrumentation": () => (/* binding */ shouldDisableAutoInstrumentation) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1625); - - -/** - * Check if Sentry auto-instrumentation should be disabled. - * - * @param getCurrentHub A method to fetch the current hub - * @returns boolean - */ -function shouldDisableAutoInstrumentation(getCurrentHub) { - const clientOptions = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); - const instrumenter = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([clientOptions, 'optionalAccess', _6 => _6.instrumenter]) || 'sentry'; - - return instrumenter !== 'sentry'; -} - - -//# sourceMappingURL=node-utils.js.map - - -/***/ }), -/* 1705 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Postgres": () => (/* binding */ Postgres) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1607); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1611); -/* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1704); - - - - -/** Tracing integration for node-postgres package */ -class Postgres { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Postgres';} - - /** - * @inheritDoc - */ - __init() {this.name = Postgres.id;} - - constructor(options = {}) {;Postgres.prototype.__init.call(this); - this._usePgNative = !!options.usePgNative; - } - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - const pkg = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.loadModule)('pg'); - - if (!pkg) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error('Postgres Integration was unable to require `pg` package.'); - return; - } - - if ((0,_utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__.shouldDisableAutoInstrumentation)(getCurrentHub)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log('Postgres Integration is skipped because of instrumenter configuration.'); - return; - } - - if (this._usePgNative && !(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([pkg, 'access', _2 => _2.native, 'optionalAccess', _3 => _3.Client])) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error("Postgres Integration was unable to access 'pg-native' bindings."); - return; - } - - const { Client } = this._usePgNative ? pkg.native : pkg; - - /** - * function (query, callback) => void - * function (query, params, callback) => void - * function (query) => Promise - * function (query, params) => Promise - * function (pg.Cursor) => pg.Cursor - */ - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(Client.prototype, 'query', function (orig) { - return function ( config, values, callback) { - const scope = getCurrentHub().getScope(); - const parentSpan = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([scope, 'optionalAccess', _4 => _4.getSpan, 'call', _5 => _5()]); - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([parentSpan, 'optionalAccess', _6 => _6.startChild, 'call', _7 => _7({ - description: typeof config === 'string' ? config : (config ).text, - op: 'db', - })]); - - if (typeof callback === 'function') { - return orig.call(this, config, values, function (err, result) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]); - callback(err, result); - }); - } - - if (typeof values === 'function') { - return orig.call(this, config, function (err, result) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([span, 'optionalAccess', _10 => _10.finish, 'call', _11 => _11()]); - values(err, result); - }); - } - - const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config); - - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isThenable)(rv)) { - return rv.then((res) => { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([span, 'optionalAccess', _12 => _12.finish, 'call', _13 => _13()]); - return res; - }); - } - - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([span, 'optionalAccess', _14 => _14.finish, 'call', _15 => _15()]); - return rv; - }; - }); - } -}Postgres.__initStatic(); - - -//# sourceMappingURL=postgres.js.map - - -/***/ }), -/* 1706 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Mysql": () => (/* binding */ Mysql) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1607); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1612); -/* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1704); - - - - -/** Tracing integration for node-mysql package */ -class Mysql {constructor() { Mysql.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Mysql';} - - /** - * @inheritDoc - */ - __init() {this.name = Mysql.id;} - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - const pkg = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.loadModule)('mysql/lib/Connection.js'); - - if (!pkg) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error('Mysql Integration was unable to require `mysql` package.'); - return; - } - - if ((0,_utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__.shouldDisableAutoInstrumentation)(getCurrentHub)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log('Mysql Integration is skipped because of instrumenter configuration.'); - return; - } - - // The original function will have one of these signatures: - // function (callback) => void - // function (options, callback) => void - // function (options, values, callback) => void - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.fill)(pkg, 'createQuery', function (orig) { - return function ( options, values, callback) { - const scope = getCurrentHub().getScope(); - const parentSpan = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]); - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({ - description: typeof options === 'string' ? options : (options ).sql, - op: 'db', - })]); - - if (typeof callback === 'function') { - return orig.call(this, options, values, function (err, result, fields) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]); - callback(err, result, fields); - }); - } - - if (typeof values === 'function') { - return orig.call(this, options, function (err, result, fields) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]); - values(err, result, fields); - }); - } - - return orig.call(this, options, values, callback); - }; - }); - } -}Mysql.__initStatic(); - - -//# sourceMappingURL=mysql.js.map - - -/***/ }), -/* 1707 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Mongo": () => (/* binding */ Mongo) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1607); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1611); -/* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1704); - - - - -// This allows us to use the same array for both defaults options and the type itself. -// (note `as const` at the end to make it a union of string literal types (i.e. "a" | "b" | ... ) -// and not just a string[]) - -const OPERATIONS = [ - 'aggregate', // aggregate(pipeline, options, callback) - 'bulkWrite', // bulkWrite(operations, options, callback) - 'countDocuments', // countDocuments(query, options, callback) - 'createIndex', // createIndex(fieldOrSpec, options, callback) - 'createIndexes', // createIndexes(indexSpecs, options, callback) - 'deleteMany', // deleteMany(filter, options, callback) - 'deleteOne', // deleteOne(filter, options, callback) - 'distinct', // distinct(key, query, options, callback) - 'drop', // drop(options, callback) - 'dropIndex', // dropIndex(indexName, options, callback) - 'dropIndexes', // dropIndexes(options, callback) - 'estimatedDocumentCount', // estimatedDocumentCount(options, callback) - 'find', // find(query, options, callback) - 'findOne', // findOne(query, options, callback) - 'findOneAndDelete', // findOneAndDelete(filter, options, callback) - 'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback) - 'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback) - 'indexes', // indexes(options, callback) - 'indexExists', // indexExists(indexes, options, callback) - 'indexInformation', // indexInformation(options, callback) - 'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback) - 'insertMany', // insertMany(docs, options, callback) - 'insertOne', // insertOne(doc, options, callback) - 'isCapped', // isCapped(options, callback) - 'mapReduce', // mapReduce(map, reduce, options, callback) - 'options', // options(options, callback) - 'parallelCollectionScan', // parallelCollectionScan(options, callback) - 'rename', // rename(newName, options, callback) - 'replaceOne', // replaceOne(filter, doc, options, callback) - 'stats', // stats(options, callback) - 'updateMany', // updateMany(filter, update, options, callback) - 'updateOne', // updateOne(filter, update, options, callback) -] ; - -// All of the operations above take `options` and `callback` as their final parameters, but some of them -// take additional parameters as well. For those operations, this is a map of -// { <operation name>: [<names of additional parameters>] }, as a way to know what to call the operation's -// positional arguments when we add them to the span's `data` object later -const OPERATION_SIGNATURES - - = { - // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well - // see https://github.com/getsentry/sentry-javascript/pull/3102 - bulkWrite: ['operations'], - countDocuments: ['query'], - createIndex: ['fieldOrSpec'], - createIndexes: ['indexSpecs'], - deleteMany: ['filter'], - deleteOne: ['filter'], - distinct: ['key', 'query'], - dropIndex: ['indexName'], - find: ['query'], - findOne: ['query'], - findOneAndDelete: ['filter'], - findOneAndReplace: ['filter', 'replacement'], - findOneAndUpdate: ['filter', 'update'], - indexExists: ['indexes'], - insertMany: ['docs'], - insertOne: ['doc'], - mapReduce: ['map', 'reduce'], - rename: ['newName'], - replaceOne: ['filter', 'doc'], - updateMany: ['filter', 'update'], - updateOne: ['filter', 'update'], -}; - -/** Tracing integration for mongo package */ -class Mongo { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Mongo';} - - /** - * @inheritDoc - */ - __init() {this.name = Mongo.id;} - - /** - * @inheritDoc - */ - constructor(options = {}) {;Mongo.prototype.__init.call(this); - this._operations = Array.isArray(options.operations) ? options.operations : (OPERATIONS ); - this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; - this._useMongoose = !!options.useMongoose; - } - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - const moduleName = this._useMongoose ? 'mongoose' : 'mongodb'; - const pkg = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.loadModule)(moduleName); - - if (!pkg) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error(`Mongo Integration was unable to require \`${moduleName}\` package.`); - return; - } - - if ((0,_utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__.shouldDisableAutoInstrumentation)(getCurrentHub)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log('Mongo Integration is skipped because of instrumenter configuration.'); - return; - } - - this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub); - } - - /** - * Patches original collection methods - */ - _instrumentOperations(collection, operations, getCurrentHub) { - operations.forEach((operation) => this._patchOperation(collection, operation, getCurrentHub)); - } - - /** - * Patches original collection to utilize our tracing functionality - */ - _patchOperation(collection, operation, getCurrentHub) { - if (!(operation in collection.prototype)) return; - - const getSpanContext = this._getSpanContextFromOperationArguments.bind(this); - - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.fill)(collection.prototype, operation, function (orig) { - return function ( ...args) { - const lastArg = args[args.length - 1]; - const scope = getCurrentHub().getScope(); - const parentSpan = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]); - - // Check if the operation was passed a callback. (mapReduce requires a different check, as - // its (non-callback) arguments can also be functions.) - if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) { - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5(getSpanContext(this, operation, args))]); - const maybePromise = orig.call(this, ...args) ; - - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isThenable)(maybePromise)) { - return maybePromise.then((res) => { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]); - return res; - }); - } else { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]); - return maybePromise; - } - } - - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([parentSpan, 'optionalAccess', _10 => _10.startChild, 'call', _11 => _11(getSpanContext(this, operation, args.slice(0, -1)))]); - return orig.call(this, ...args.slice(0, -1), function (err, result) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([span, 'optionalAccess', _12 => _12.finish, 'call', _13 => _13()]); - lastArg(err, result); - }); - }; - }); - } - - /** - * Form a SpanContext based on the user input to a given operation. - */ - _getSpanContextFromOperationArguments( - collection, - operation, - args, - ) { - const data = { - collectionName: collection.collectionName, - dbName: collection.dbName, - namespace: collection.namespace, - }; - const spanContext = { - op: 'db', - description: operation, - data, - }; - - // If the operation takes no arguments besides `options` and `callback`, or if argument - // collection is disabled for this operation, just return early. - const signature = OPERATION_SIGNATURES[operation]; - const shouldDescribe = Array.isArray(this._describeOperations) - ? this._describeOperations.includes(operation) - : this._describeOperations; - - if (!signature || !shouldDescribe) { - return spanContext; - } - - try { - // Special case for `mapReduce`, as the only one accepting functions as arguments. - if (operation === 'mapReduce') { - const [map, reduce] = args ; - data[signature[0]] = typeof map === 'string' ? map : map.name || '<anonymous>'; - data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '<anonymous>'; - } else { - for (let i = 0; i < signature.length; i++) { - data[signature[i]] = JSON.stringify(args[i]); - } - } - } catch (_oO) { - // no-empty - } - - return spanContext; - } -}Mongo.__initStatic(); - - -//# sourceMappingURL=mongo.js.map - - -/***/ }), -/* 1708 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Prisma": () => (/* binding */ Prisma) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); -/* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1704); - - - - -function isValidPrismaClient(possibleClient) { - return possibleClient && !!(possibleClient )['$use']; -} - -/** Tracing integration for @prisma/client package */ -class Prisma { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Prisma';} - - /** - * @inheritDoc - */ - __init() {this.name = Prisma.id;} - - /** - * Prisma ORM Client Instance - */ - - /** - * @inheritDoc - */ - constructor(options = {}) {;Prisma.prototype.__init.call(this); - if (isValidPrismaClient(options.client)) { - this._client = options.client; - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Unsupported Prisma client provided to PrismaIntegration. Provided client: ${JSON.stringify(options.client)}`, - ); - } - } - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - if (!this._client) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error('PrismaIntegration is missing a Prisma Client Instance'); - return; - } - - if ((0,_utils_node_utils_js__WEBPACK_IMPORTED_MODULE_1__.shouldDisableAutoInstrumentation)(getCurrentHub)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.log('Prisma Integration is skipped because of instrumenter configuration.'); - return; - } - - this._client.$use((params, next) => { - const scope = getCurrentHub().getScope(); - const parentSpan = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]); - - const action = params.action; - const model = params.model; - - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({ - description: model ? `${model} ${action}` : action, - op: 'db.sql.prisma', - })]); - - const rv = next(params); - - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isThenable)(rv)) { - return rv.then((res) => { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]); - return res; - }); - } - - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]); - return rv; - }); - } -}Prisma.__initStatic(); - - -//# sourceMappingURL=prisma.js.map - - -/***/ }), -/* 1709 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "GraphQL": () => (/* binding */ GraphQL) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1607); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1611); -/* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1704); - - - - -/** Tracing integration for graphql package */ -class GraphQL {constructor() { GraphQL.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'GraphQL';} - - /** - * @inheritDoc - */ - __init() {this.name = GraphQL.id;} - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - const pkg = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.loadModule) - -('graphql/execution/execute.js'); - - if (!pkg) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error('GraphQL Integration was unable to require graphql/execution package.'); - return; - } - - if ((0,_utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__.shouldDisableAutoInstrumentation)(getCurrentHub)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log('GraphQL Integration is skipped because of instrumenter configuration.'); - return; - } - - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.fill)(pkg, 'execute', function (orig) { - return function ( ...args) { - const scope = getCurrentHub().getScope(); - const parentSpan = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]); - - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({ - description: 'execute', - op: 'graphql.execute', - })]); - - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([scope, 'optionalAccess', _6 => _6.setSpan, 'call', _7 => _7(span)]); - - const rv = orig.call(this, ...args); - - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isThenable)(rv)) { - return rv.then((res) => { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]); - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([scope, 'optionalAccess', _10 => _10.setSpan, 'call', _11 => _11(parentSpan)]); - - return res; - }); - } - - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([span, 'optionalAccess', _12 => _12.finish, 'call', _13 => _13()]); - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([scope, 'optionalAccess', _14 => _14.setSpan, 'call', _15 => _15(parentSpan)]); - return rv; - }; - }); - } -}GraphQL.__initStatic(); - - -//# sourceMappingURL=graphql.js.map - - -/***/ }), -/* 1710 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Apollo": () => (/* binding */ Apollo) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1607); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1611); -/* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1704); - - - - -/** Tracing integration for Apollo */ -class Apollo {constructor() { Apollo.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Apollo';} - - /** - * @inheritDoc - */ - __init() {this.name = Apollo.id;} - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - const pkg = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.loadModule) - -('apollo-server-core'); - - if (!pkg) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error('Apollo Integration was unable to require apollo-server-core package.'); - return; - } - - if ((0,_utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__.shouldDisableAutoInstrumentation)(getCurrentHub)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log('Apollo Integration is skipped because of instrumenter configuration.'); - return; - } - - /** - * Iterate over resolvers of the ApolloServer instance before schemas are constructed. - */ - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.fill)(pkg.ApolloServerBase.prototype, 'constructSchema', function (orig) { - return function () { - if (!this.config.resolvers) { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - if (this.config.schema) { - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn( - 'Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.', - ); - } else if (this.config.modules) { - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn( - 'Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property.', - ); - } - - _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error('Skipping tracing as no resolvers found on the `ApolloServer` instance.'); - } - - return orig.call(this); - } - - const resolvers = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.arrayify)(this.config.resolvers); - - this.config.resolvers = resolvers.map(model => { - Object.keys(model).forEach(resolverGroupName => { - Object.keys(model[resolverGroupName]).forEach(resolverName => { - if (typeof model[resolverGroupName][resolverName] !== 'function') { - return; - } - - wrapResolver(model, resolverGroupName, resolverName, getCurrentHub); - }); - }); - - return model; - }); - - return orig.call(this); - }; - }); - } -}Apollo.__initStatic(); - -/** - * Wrap a single resolver which can be a parent of other resolvers and/or db operations. - */ -function wrapResolver( - model, - resolverGroupName, - resolverName, - getCurrentHub, -) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.fill)(model[resolverGroupName], resolverName, function (orig) { - return function ( ...args) { - const scope = getCurrentHub().getScope(); - const parentSpan = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([scope, 'optionalAccess', _2 => _2.getSpan, 'call', _3 => _3()]); - const span = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({ - description: `${resolverGroupName}.${resolverName}`, - op: 'graphql.resolve', - })]); - - const rv = orig.call(this, ...args); - - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.isThenable)(rv)) { - return rv.then((res) => { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([span, 'optionalAccess', _6 => _6.finish, 'call', _7 => _7()]); - return res; - }); - } - - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([span, 'optionalAccess', _8 => _8.finish, 'call', _9 => _9()]); - - return rv; - }; - }); -} - - -//# sourceMappingURL=apollo.js.map - - -/***/ }), -/* 1711 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BROWSER_TRACING_INTEGRATION_ID": () => (/* binding */ BROWSER_TRACING_INTEGRATION_ID), -/* harmony export */ "BrowserTracing": () => (/* binding */ BrowserTracing), -/* harmony export */ "getMetaContent": () => (/* binding */ getMetaContent) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1679); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1657); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1613); -/* harmony import */ var _hubextensions_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1694); -/* harmony import */ var _idletransaction_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1698); -/* harmony import */ var _backgroundtab_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1728); -/* harmony import */ var _metrics_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1715); -/* harmony import */ var _request_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1714); -/* harmony import */ var _router_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1712); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1713); - - - - - - - - - - - -const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing'; - -/** Options for Browser Tracing integration */ - -const DEFAULT_BROWSER_TRACING_OPTIONS = { - idleTimeout: _idletransaction_js__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_IDLE_TIMEOUT, - finalTimeout: _idletransaction_js__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_FINAL_TIMEOUT, - heartbeatInterval: _idletransaction_js__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_HEARTBEAT_INTERVAL, - markBackgroundTransactions: true, - routingInstrumentation: _router_js__WEBPACK_IMPORTED_MODULE_1__.instrumentRoutingWithDefaults, - startTransactionOnLocationChange: true, - startTransactionOnPageLoad: true, - _experiments: { enableLongTask: true }, - ..._request_js__WEBPACK_IMPORTED_MODULE_2__.defaultRequestInstrumentationOptions, -}; - -/** - * The Browser Tracing integration automatically instruments browser pageload/navigation - * actions as transactions, and captures requests, metrics and errors as spans. - * - * The integration can be configured with a variety of options, and can be extended to use - * any routing library. This integration uses {@see IdleTransaction} to create transactions. - */ -class BrowserTracing { - // This class currently doesn't have a static `id` field like the other integration classes, because it prevented - // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects. - // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all - // integrations. - - /** Browser Tracing integration options */ - - /** - * @inheritDoc - */ - __init() {this.name = BROWSER_TRACING_INTEGRATION_ID;} - - constructor(_options) {;BrowserTracing.prototype.__init.call(this); - this.options = { - ...DEFAULT_BROWSER_TRACING_OPTIONS, - ..._options, - }; - - // TODO (v8): remove this block after tracingOrigins is removed - // Set tracePropagationTargets to tracingOrigins if specified by the user - // In case both are specified, tracePropagationTargets takes precedence - // eslint-disable-next-line deprecation/deprecation - if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) { - // eslint-disable-next-line deprecation/deprecation - this.options.tracePropagationTargets = _options.tracingOrigins; - } - - const { _metricOptions } = this.options; - (0,_metrics_index_js__WEBPACK_IMPORTED_MODULE_3__.startTrackingWebVitals)(_metricOptions && _metricOptions._reportAllChanges); - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__._optionalChain)([this, 'access', _2 => _2.options, 'access', _3 => _3._experiments, 'optionalAccess', _4 => _4.enableLongTask])) { - (0,_metrics_index_js__WEBPACK_IMPORTED_MODULE_3__.startTrackingLongTasks)(); - } - } - - /** - * @inheritDoc - */ - setupOnce(_, getCurrentHub) { - this._getCurrentHub = getCurrentHub; - - // eslint-disable-next-line @typescript-eslint/unbound-method - const { - routingInstrumentation: instrumentRouting, - startTransactionOnLocationChange, - startTransactionOnPageLoad, - markBackgroundTransactions, - traceFetch, - traceXHR, - tracePropagationTargets, - shouldCreateSpanForRequest, - } = this.options; - - instrumentRouting( - (context) => this._createRouteTransaction(context), - startTransactionOnPageLoad, - startTransactionOnLocationChange, - ); - - if (markBackgroundTransactions) { - (0,_backgroundtab_js__WEBPACK_IMPORTED_MODULE_5__.registerBackgroundTabDetection)(); - } - - (0,_request_js__WEBPACK_IMPORTED_MODULE_2__.instrumentOutgoingRequests)({ - traceFetch, - traceXHR, - tracePropagationTargets, - shouldCreateSpanForRequest, - }); - } - - /** Create routing idle transaction. */ - _createRouteTransaction(context) { - if (!this._getCurrentHub) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`); - return undefined; - } - - // eslint-disable-next-line @typescript-eslint/unbound-method - const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options; - - const isPageloadTransaction = context.op === 'pageload'; - - const sentryTraceMetaTagValue = isPageloadTransaction ? getMetaContent('sentry-trace') : null; - const baggageMetaTagValue = isPageloadTransaction ? getMetaContent('baggage') : null; - - const traceParentData = sentryTraceMetaTagValue ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.extractTraceparentData)(sentryTraceMetaTagValue) : undefined; - const dynamicSamplingContext = baggageMetaTagValue - ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.baggageHeaderToDynamicSamplingContext)(baggageMetaTagValue) - : undefined; - - const expandedContext = { - ...context, - ...traceParentData, - metadata: { - ...context.metadata, - dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, - }, - trimEnd: true, - }; - - const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext; - - // For backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction (prevent it - // from being sent to Sentry). - const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext; - - // If `beforeNavigate` set a custom name, record that fact - finalContext.metadata = - finalContext.name !== expandedContext.name - ? { ...finalContext.metadata, source: 'custom' } - : finalContext.metadata; - - if (finalContext.sampled === false) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`); - } - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`); - - const hub = this._getCurrentHub(); - const { location } = _types_js__WEBPACK_IMPORTED_MODULE_9__.WINDOW; - - const idleTransaction = (0,_hubextensions_js__WEBPACK_IMPORTED_MODULE_10__.startIdleTransaction)( - hub, - finalContext, - idleTimeout, - finalTimeout, - true, - { location }, // for use in the tracesSampler - heartbeatInterval, - ); - idleTransaction.registerBeforeFinishCallback(transaction => { - (0,_metrics_index_js__WEBPACK_IMPORTED_MODULE_3__.addPerformanceEntries)(transaction); - }); - - return idleTransaction ; - } -} - -/** Returns the value of a meta tag */ -function getMetaContent(metaName) { - // Can't specify generic to `getDomElement` because tracing can be used - // in a variety of environments, have to disable `no-unsafe-member-access` - // as a result. - const metaTag = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_11__.getDomElement)(`meta[name=${metaName}]`); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return metaTag ? metaTag.getAttribute('content') : null; -} - - -//# sourceMappingURL=browsertracing.js.map - - -/***/ }), -/* 1712 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "instrumentRoutingWithDefaults": () => (/* binding */ instrumentRoutingWithDefaults) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1700); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1713); - - - -/** - * Default function implementing pageload and navigation transactions - */ -function instrumentRoutingWithDefaults( - customStartTransaction, - startTransactionOnPageLoad = true, - startTransactionOnLocationChange = true, -) { - if (!_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW || !_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.location) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('Could not initialize routing instrumentation due to invalid location'); - return; - } - - let startingUrl = _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.location.href; - - let activeTransaction; - if (startTransactionOnPageLoad) { - activeTransaction = customStartTransaction({ - name: _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.location.pathname, - op: 'pageload', - metadata: { source: 'url' }, - }); - } - - if (startTransactionOnLocationChange) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.addInstrumentationHandler)('history', ({ to, from }) => { - /** - * This early return is there to account for some cases where a navigation transaction starts right after - * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't - * create an uneccessary navigation transaction. - * - * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also - * only be caused in certain development environments where the usage of a hot module reloader is causing - * errors. - */ - if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { - startingUrl = undefined; - return; - } - - if (from !== to) { - startingUrl = undefined; - if (activeTransaction) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`); - // If there's an open transaction on the scope, we need to finish it before creating an new one. - activeTransaction.finish(); - } - activeTransaction = customStartTransaction({ - name: _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.location.pathname, - op: 'navigation', - metadata: { source: 'url' }, - }); - } - }); - } -} - - -//# sourceMappingURL=router.js.map - - -/***/ }), -/* 1713 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "WINDOW": () => (/* binding */ WINDOW) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - -const WINDOW = _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; - - -//# sourceMappingURL=types.js.map - - -/***/ }), -/* 1714 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_TRACE_PROPAGATION_TARGETS": () => (/* binding */ DEFAULT_TRACE_PROPAGATION_TARGETS), -/* harmony export */ "defaultRequestInstrumentationOptions": () => (/* binding */ defaultRequestInstrumentationOptions), -/* harmony export */ "fetchCallback": () => (/* binding */ fetchCallback), -/* harmony export */ "instrumentOutgoingRequests": () => (/* binding */ instrumentOutgoingRequests), -/* harmony export */ "shouldAttachHeaders": () => (/* binding */ shouldAttachHeaders), -/* harmony export */ "xhrCallback": () => (/* binding */ xhrCallback) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1700); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1657); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1695); - - - -const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\//]; - -/** Options for Request Instrumentation */ - -const defaultRequestInstrumentationOptions = { - traceFetch: true, - traceXHR: true, - // TODO (v8): Remove this property - tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS, - tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS, -}; - -/** Registers span creators for xhr and fetch requests */ -function instrumentOutgoingRequests(_options) { - // eslint-disable-next-line deprecation/deprecation - const { traceFetch, traceXHR, tracePropagationTargets, tracingOrigins, shouldCreateSpanForRequest } = { - traceFetch: defaultRequestInstrumentationOptions.traceFetch, - traceXHR: defaultRequestInstrumentationOptions.traceXHR, - ..._options, - }; - - const shouldCreateSpan = - typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true; - - // TODO(v8) Remove tracingOrigins here - // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported - // and we don't want to break the API. We can remove it in v8. - const shouldAttachHeadersWithTargets = (url) => - shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins); - - const spans = {}; - - if (traceFetch) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.addInstrumentationHandler)('fetch', (handlerData) => { - fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans); - }); - } - - if (traceXHR) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.addInstrumentationHandler)('xhr', (handlerData) => { - xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans); - }); - } -} - -/** - * A function that determines whether to attach tracing headers to a request. - * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders. - * We only export this fuction for testing purposes. - */ -function shouldAttachHeaders(url, tracePropagationTargets) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.stringMatchesSomePattern)(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS); -} - -/** - * Create and track fetch request spans - */ -function fetchCallback( - handlerData, - shouldCreateSpan, - shouldAttachHeaders, - spans, -) { - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.hasTracingEnabled)() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) { - return; - } - - if (handlerData.endTimestamp) { - const spanId = handlerData.fetchData.__span; - if (!spanId) return; - - const span = spans[spanId]; - if (span) { - if (handlerData.response) { - // TODO (kmclb) remove this once types PR goes through - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - span.setHttpStatus(handlerData.response.status); - } else if (handlerData.error) { - span.setStatus('internal_error'); - } - span.finish(); - - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete spans[spanId]; - } - return; - } - - const activeTransaction = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.getActiveTransaction)(); - if (activeTransaction) { - const span = activeTransaction.startChild({ - data: { - ...handlerData.fetchData, - type: 'fetch', - }, - description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`, - op: 'http.client', - }); - - handlerData.fetchData.__span = span.spanId; - spans[span.spanId] = span; - - const request = handlerData.args[0]; - - // In case the user hasn't set the second argument of a fetch call we default it to `{}`. - handlerData.args[1] = handlerData.args[1] || {}; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const options = handlerData.args[1]; - - if (shouldAttachHeaders(handlerData.fetchData.url)) { - options.headers = addTracingHeadersToFetchRequest( - request, - activeTransaction.getDynamicSamplingContext(), - span, - options, - ); - - activeTransaction.metadata.propagations++; - } - } -} - -function addTracingHeadersToFetchRequest( - request, - dynamicSamplingContext, - span, - options - -, -) { - const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); - const sentryTraceHeader = span.toTraceparent(); - - const headers = - typeof Request !== 'undefined' && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(request, Request) ? (request ).headers : options.headers; - - if (!headers) { - return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader }; - } else if (typeof Headers !== 'undefined' && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(headers, Headers)) { - const newHeaders = new Headers(headers ); - - newHeaders.append('sentry-trace', sentryTraceHeader); - - if (sentryBaggageHeader) { - // If the same header is appended miultiple times the browser will merge the values into a single request header. - // Its therefore safe to simply push a "baggage" entry, even though there might already be another baggage header. - newHeaders.append(_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.BAGGAGE_HEADER_NAME, sentryBaggageHeader); - } - - return newHeaders ; - } else if (Array.isArray(headers)) { - const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]]; - - if (sentryBaggageHeader) { - // If there are multiple entries with the same key, the browser will merge the values into a single request header. - // Its therefore safe to simply push a "baggage" entry, even though there might already be another baggage header. - newHeaders.push([_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.BAGGAGE_HEADER_NAME, sentryBaggageHeader]); - } - - return newHeaders; - } else { - const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined; - const newBaggageHeaders = []; - - if (Array.isArray(existingBaggageHeader)) { - newBaggageHeaders.push(...existingBaggageHeader); - } else if (existingBaggageHeader) { - newBaggageHeaders.push(existingBaggageHeader); - } - - if (sentryBaggageHeader) { - newBaggageHeaders.push(sentryBaggageHeader); - } - - return { - ...(headers ), - 'sentry-trace': sentryTraceHeader, - baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined, - }; - } -} - -/** - * Create and track xhr request spans - */ -function xhrCallback( - handlerData, - shouldCreateSpan, - shouldAttachHeaders, - spans, -) { - if ( - !(0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.hasTracingEnabled)() || - (handlerData.xhr && handlerData.xhr.__sentry_own_request__) || - !(handlerData.xhr && handlerData.xhr.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url)) - ) { - return; - } - - const xhr = handlerData.xhr.__sentry_xhr__; - - // check first if the request has finished and is tracked by an existing span which should now end - if (handlerData.endTimestamp) { - const spanId = handlerData.xhr.__sentry_xhr_span_id__; - if (!spanId) return; - - const span = spans[spanId]; - if (span) { - span.setHttpStatus(xhr.status_code); - span.finish(); - - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete spans[spanId]; - } - return; - } - - // if not, create a new span to track it - const activeTransaction = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.getActiveTransaction)(); - if (activeTransaction) { - const span = activeTransaction.startChild({ - data: { - ...xhr.data, - type: 'xhr', - method: xhr.method, - url: xhr.url, - }, - description: `${xhr.method} ${xhr.url}`, - op: 'http.client', - }); - - handlerData.xhr.__sentry_xhr_span_id__ = span.spanId; - spans[handlerData.xhr.__sentry_xhr_span_id__] = span; - - if (handlerData.xhr.setRequestHeader && shouldAttachHeaders(handlerData.xhr.__sentry_xhr__.url)) { - try { - handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); - - const dynamicSamplingContext = activeTransaction.getDynamicSamplingContext(); - const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); - - if (sentryBaggageHeader) { - // From MDN: "If this method is called several times with the same header, the values are merged into one single request header." - // We can therefore simply set a baggage header without checking what was there before - // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader - handlerData.xhr.setRequestHeader(_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.BAGGAGE_HEADER_NAME, sentryBaggageHeader); - } - - activeTransaction.metadata.propagations++; - } catch (_) { - // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. - } - } - } -} - - -//# sourceMappingURL=request.js.map - - -/***/ }), -/* 1715 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_addMeasureSpans": () => (/* binding */ _addMeasureSpans), -/* harmony export */ "_addResourceSpans": () => (/* binding */ _addResourceSpans), -/* harmony export */ "addPerformanceEntries": () => (/* binding */ addPerformanceEntries), -/* harmony export */ "startTrackingLongTasks": () => (/* binding */ startTrackingLongTasks), -/* harmony export */ "startTrackingWebVitals": () => (/* binding */ startTrackingWebVitals) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1613); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1695); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1713); -/* harmony import */ var _web_vitals_getCLS_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1717); -/* harmony import */ var _web_vitals_getFID_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1726); -/* harmony import */ var _web_vitals_getLCP_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1724); -/* harmony import */ var _web_vitals_lib_getVisibilityWatcher_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1725); -/* harmony import */ var _web_vitals_lib_observe_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1716); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1727); - - - - - - - - - - - -function getBrowserPerformanceAPI() { - return _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW && _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.addEventListener && _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.performance; -} - -let _performanceCursor = 0; - -let _measurements = {}; -let _lcpEntry; -let _clsEntry; - -/** - * Start tracking web vitals - */ -function startTrackingWebVitals(reportAllChanges = false) { - const performance = getBrowserPerformanceAPI(); - if (performance && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.browserPerformanceTimeOrigin) { - if (performance.mark) { - _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.performance.mark('sentry-tracing-init'); - } - _trackCLS(); - _trackLCP(reportAllChanges); - _trackFID(); - } -} - -/** - * Start tracking long tasks. - */ -function startTrackingLongTasks() { - const entryHandler = (entries) => { - for (const entry of entries) { - const transaction = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.getActiveTransaction)() ; - if (!transaction) { - return; - } - const startTime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)((_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.browserPerformanceTimeOrigin ) + entry.startTime); - const duration = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.duration); - - transaction.startChild({ - description: 'Main UI thread blocked', - op: 'ui.long-task', - startTimestamp: startTime, - endTimestamp: startTime + duration, - }); - } - }; - - (0,_web_vitals_lib_observe_js__WEBPACK_IMPORTED_MODULE_3__.observe)('longtask', entryHandler); -} - -/** Starts tracking the Cumulative Layout Shift on the current page. */ -function _trackCLS() { - // See: - // https://web.dev/evolving-cls/ - // https://web.dev/cls-web-tooling/ - (0,_web_vitals_getCLS_js__WEBPACK_IMPORTED_MODULE_4__.onCLS)(metric => { - const entry = metric.entries.pop(); - if (!entry) { - return; - } - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding CLS'); - _measurements['cls'] = { value: metric.value, unit: '' }; - _clsEntry = entry ; - }); -} - -/** Starts tracking the Largest Contentful Paint on the current page. */ -function _trackLCP(reportAllChanges) { - (0,_web_vitals_getLCP_js__WEBPACK_IMPORTED_MODULE_6__.onLCP)( - metric => { - const entry = metric.entries.pop(); - if (!entry) { - return; - } - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding LCP'); - _measurements['lcp'] = { value: metric.value, unit: 'millisecond' }; - _lcpEntry = entry ; - }, - { reportAllChanges }, - ); -} - -/** Starts tracking the First Input Delay on the current page. */ -function _trackFID() { - (0,_web_vitals_getFID_js__WEBPACK_IMPORTED_MODULE_7__.onFID)(metric => { - const entry = metric.entries.pop(); - if (!entry) { - return; - } - - const timeOrigin = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.browserPerformanceTimeOrigin ); - const startTime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.startTime); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding FID'); - _measurements['fid'] = { value: metric.value, unit: 'millisecond' }; - _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' }; - }); -} - -/** Add performance related spans to a transaction */ -function addPerformanceEntries(transaction) { - const performance = getBrowserPerformanceAPI(); - if (!performance || !_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.performance.getEntries || !_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.browserPerformanceTimeOrigin) { - // Gatekeeper if performance API not available - return; - } - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Tracing] Adding & adjusting spans using Performance API'); - const timeOrigin = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.browserPerformanceTimeOrigin); - - const performanceEntries = performance.getEntries(); - - let responseStartTimestamp; - let requestStartTimestamp; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - performanceEntries.slice(_performanceCursor).forEach((entry) => { - const startTime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.startTime); - const duration = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.duration); - - if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) { - return; - } - - switch (entry.entryType) { - case 'navigation': { - _addNavigationSpans(transaction, entry, timeOrigin); - responseStartTimestamp = timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.responseStart); - requestStartTimestamp = timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.requestStart); - break; - } - case 'mark': - case 'paint': - case 'measure': { - _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin); - - // capture web vitals - const firstHidden = (0,_web_vitals_lib_getVisibilityWatcher_js__WEBPACK_IMPORTED_MODULE_8__.getVisibilityWatcher)(); - // Only report if the page wasn't hidden prior to the web vital. - const shouldRecord = entry.startTime < firstHidden.firstHiddenTime; - - if (entry.name === 'first-paint' && shouldRecord) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding FP'); - _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' }; - } - if (entry.name === 'first-contentful-paint' && shouldRecord) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding FCP'); - _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' }; - } - break; - } - case 'resource': { - const resourceName = (entry.name ).replace(_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.location.origin, ''); - _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin); - break; - } - default: - // Ignore other entry types. - } - }); - - _performanceCursor = Math.max(performanceEntries.length - 1, 0); - - _trackNavigator(transaction); - - // Measurements are only available for pageload transactions - if (transaction.op === 'pageload') { - // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the - // start of the response in milliseconds - if (typeof responseStartTimestamp === 'number') { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding TTFB'); - _measurements['ttfb'] = { - value: (responseStartTimestamp - transaction.startTimestamp) * 1000, - unit: 'millisecond', - }; - - if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) { - // Capture the time spent making the request and receiving the first byte of the response. - // This is the time between the start of the request and the start of the response in milliseconds. - _measurements['ttfb.requestTime'] = { - value: (responseStartTimestamp - requestStartTimestamp) * 1000, - unit: 'millisecond', - }; - } - } - - ['fcp', 'fp', 'lcp'].forEach(name => { - if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) { - return; - } - // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin. - // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need - // to be adjusted to be relative to transaction.startTimestamp. - const oldValue = _measurements[name].value; - const measurementTimestamp = timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(oldValue); - - // normalizedValue should be in milliseconds - const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000); - const delta = normalizedValue - oldValue; - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`); - _measurements[name].value = normalizedValue; - }); - - const fidMark = _measurements['mark.fid']; - if (fidMark && _measurements['fid']) { - // create span for FID - (0,_utils_js__WEBPACK_IMPORTED_MODULE_9__._startChild)(transaction, { - description: 'first input delay', - endTimestamp: fidMark.value + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(_measurements['fid'].value), - op: 'ui.action', - startTimestamp: fidMark.value, - }); - - // Delete mark.fid as we don't want it to be part of final payload - delete _measurements['mark.fid']; - } - - // If FCP is not recorded we should not record the cls value - // according to the new definition of CLS. - if (!('fcp' in _measurements)) { - delete _measurements.cls; - } - - Object.keys(_measurements).forEach(measurementName => { - transaction.setMeasurement( - measurementName, - _measurements[measurementName].value, - _measurements[measurementName].unit, - ); - }); - - _tagMetricInfo(transaction); - } - - _lcpEntry = undefined; - _clsEntry = undefined; - _measurements = {}; -} - -/** Create measure related spans */ -function _addMeasureSpans( - transaction, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - entry, - startTime, - duration, - timeOrigin, -) { - const measureStartTimestamp = timeOrigin + startTime; - const measureEndTimestamp = measureStartTimestamp + duration; - - (0,_utils_js__WEBPACK_IMPORTED_MODULE_9__._startChild)(transaction, { - description: entry.name , - endTimestamp: measureEndTimestamp, - op: entry.entryType , - startTimestamp: measureStartTimestamp, - }); - - return measureStartTimestamp; -} - -/** Instrument navigation entries */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _addNavigationSpans(transaction, entry, timeOrigin) { - ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => { - _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin); - }); - _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd'); - _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart'); - _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS'); - _addRequest(transaction, entry, timeOrigin); -} - -/** Create performance navigation related spans */ -function _addPerformanceNavigationTiming( - transaction, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - entry, - event, - timeOrigin, - description, - eventEnd, -) { - const end = eventEnd ? (entry[eventEnd] ) : (entry[`${event}End`] ); - const start = entry[`${event}Start`] ; - if (!start || !end) { - return; - } - (0,_utils_js__WEBPACK_IMPORTED_MODULE_9__._startChild)(transaction, { - op: 'browser', - description: (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_10__._nullishCoalesce)(description, () => ( event)), - startTimestamp: timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(start), - endTimestamp: timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(end), - }); -} - -/** Create request and response related spans */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _addRequest(transaction, entry, timeOrigin) { - (0,_utils_js__WEBPACK_IMPORTED_MODULE_9__._startChild)(transaction, { - op: 'browser', - description: 'request', - startTimestamp: timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.requestStart ), - endTimestamp: timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.responseEnd ), - }); - - (0,_utils_js__WEBPACK_IMPORTED_MODULE_9__._startChild)(transaction, { - op: 'browser', - description: 'response', - startTimestamp: timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.responseStart ), - endTimestamp: timeOrigin + (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.msToSec)(entry.responseEnd ), - }); -} - -/** Create resource-related spans */ -function _addResourceSpans( - transaction, - entry, - resourceName, - startTime, - duration, - timeOrigin, -) { - // we already instrument based on fetch and xhr, so we don't need to - // duplicate spans here. - if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { - return; - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const data = {}; - if ('transferSize' in entry) { - data['Transfer Size'] = entry.transferSize; - } - if ('encodedBodySize' in entry) { - data['Encoded Body Size'] = entry.encodedBodySize; - } - if ('decodedBodySize' in entry) { - data['Decoded Body Size'] = entry.decodedBodySize; - } - - const startTimestamp = timeOrigin + startTime; - const endTimestamp = startTimestamp + duration; - - (0,_utils_js__WEBPACK_IMPORTED_MODULE_9__._startChild)(transaction, { - description: resourceName, - endTimestamp, - op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other', - startTimestamp, - data, - }); -} - -/** - * Capture the information of the user agent. - */ -function _trackNavigator(transaction) { - const navigator = _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.navigator ; - if (!navigator) { - return; - } - - // track network connectivity - const connection = navigator.connection; - if (connection) { - if (connection.effectiveType) { - transaction.setTag('effectiveConnectionType', connection.effectiveType); - } - - if (connection.type) { - transaction.setTag('connectionType', connection.type); - } - - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_9__.isMeasurementValue)(connection.rtt)) { - _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' }; - } - } - - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_9__.isMeasurementValue)(navigator.deviceMemory)) { - transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`); - } - - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_9__.isMeasurementValue)(navigator.hardwareConcurrency)) { - transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency)); - } -} - -/** Add LCP / CLS data to transaction to allow debugging */ -function _tagMetricInfo(transaction) { - if (_lcpEntry) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding LCP Data'); - - // Capture Properties of the LCP element that contributes to the LCP. - - if (_lcpEntry.element) { - transaction.setTag('lcp.element', (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_11__.htmlTreeAsString)(_lcpEntry.element)); - } - - if (_lcpEntry.id) { - transaction.setTag('lcp.id', _lcpEntry.id); - } - - if (_lcpEntry.url) { - // Trim URL to the first 200 characters. - transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200)); - } - - transaction.setTag('lcp.size', _lcpEntry.size); - } - - // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift - if (_clsEntry && _clsEntry.sources) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.logger.log('[Measurements] Adding CLS Data'); - _clsEntry.sources.forEach((source, index) => - transaction.setTag(`cls.source.${index + 1}`, (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_11__.htmlTreeAsString)(source.node)), - ); - } -} - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1716 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "observe": () => (/* binding */ observe) -/* harmony export */ }); -/** - * Takes a performance entry type and a callback function, and creates a - * `PerformanceObserver` instance that will observe the specified entry type - * with buffering enabled and call the callback _for each entry_. - * - * This function also feature-detects entry support and wraps the logic in a - * try/catch to avoid errors in unsupporting browsers. - */ -const observe = ( - type, - callback, - opts, -) => { - try { - if (PerformanceObserver.supportedEntryTypes.includes(type)) { - const po = new PerformanceObserver(list => { - callback(list.getEntries() ); - }); - po.observe( - Object.assign( - { - type, - buffered: true, - }, - opts || {}, - ) , - ); - return po; - } - } catch (e) { - // Do nothing. - } - return; -}; - - -//# sourceMappingURL=observe.js.map - - -/***/ }), -/* 1717 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "onCLS": () => (/* binding */ onCLS) -/* harmony export */ }); -/* harmony import */ var _lib_bindReporter_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1722); -/* harmony import */ var _lib_initMetric_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1718); -/* harmony import */ var _lib_observe_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1716); -/* harmony import */ var _lib_onHidden_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1723); - - - - - -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Calculates the [CLS](https://web.dev/cls/) value for the current page and - * calls the `callback` function once the value is ready to be reported, along - * with all `layout-shift` performance entries that were used in the metric - * value calculation. The reported value is a `double` (corresponding to a - * [layout shift score](https://web.dev/cls/#layout-shift-score)). - * - * If the `reportAllChanges` configuration option is set to `true`, the - * `callback` function will be called as soon as the value is initially - * determined as well as any time the value changes throughout the page - * lifespan. - * - * _**Important:** CLS should be continually monitored for changes throughout - * the entire lifespan of a page—including if the user returns to the page after - * it's been hidden/backgrounded. However, since browsers often [will not fire - * additional callbacks once the user has backgrounded a - * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden), - * `callback` is always called when the page's visibility state changes to - * hidden. As a result, the `callback` function might be called multiple times - * during the same page load._ - */ -const onCLS = (onReport, opts = {}) => { - const metric = (0,_lib_initMetric_js__WEBPACK_IMPORTED_MODULE_0__.initMetric)('CLS', 0); - let report; - - let sessionValue = 0; - let sessionEntries = []; - - // const handleEntries = (entries: Metric['entries']) => { - const handleEntries = (entries) => { - entries.forEach(entry => { - // Only count layout shifts without recent user input. - if (!entry.hadRecentInput) { - const firstSessionEntry = sessionEntries[0]; - const lastSessionEntry = sessionEntries[sessionEntries.length - 1]; - - // If the entry occurred less than 1 second after the previous entry and - // less than 5 seconds after the first entry in the session, include the - // entry in the current session. Otherwise, start a new session. - if ( - sessionValue && - sessionEntries.length !== 0 && - entry.startTime - lastSessionEntry.startTime < 1000 && - entry.startTime - firstSessionEntry.startTime < 5000 - ) { - sessionValue += entry.value; - sessionEntries.push(entry); - } else { - sessionValue = entry.value; - sessionEntries = [entry]; - } - - // If the current session value is larger than the current CLS value, - // update CLS and the entries contributing to it. - if (sessionValue > metric.value) { - metric.value = sessionValue; - metric.entries = sessionEntries; - if (report) { - report(); - } - } - } - }); - }; - - const po = (0,_lib_observe_js__WEBPACK_IMPORTED_MODULE_1__.observe)('layout-shift', handleEntries); - if (po) { - report = (0,_lib_bindReporter_js__WEBPACK_IMPORTED_MODULE_2__.bindReporter)(onReport, metric, opts.reportAllChanges); - - (0,_lib_onHidden_js__WEBPACK_IMPORTED_MODULE_3__.onHidden)(() => { - handleEntries(po.takeRecords() ); - report(true); - }); - } -}; - - -//# sourceMappingURL=getCLS.js.map - - -/***/ }), -/* 1718 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "initMetric": () => (/* binding */ initMetric) -/* harmony export */ }); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1713); -/* harmony import */ var _generateUniqueID_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1721); -/* harmony import */ var _getActivationStart_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1720); -/* harmony import */ var _getNavigationEntry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1719); - - - - - -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const initMetric = (name, value) => { - const navEntry = (0,_getNavigationEntry_js__WEBPACK_IMPORTED_MODULE_0__.getNavigationEntry)(); - let navigationType = 'navigate'; - - if (navEntry) { - if (_types_js__WEBPACK_IMPORTED_MODULE_1__.WINDOW.document.prerendering || (0,_getActivationStart_js__WEBPACK_IMPORTED_MODULE_2__.getActivationStart)() > 0) { - navigationType = 'prerender'; - } else { - navigationType = navEntry.type.replace(/_/g, '-') ; - } - } - - return { - name, - value: typeof value === 'undefined' ? -1 : value, - rating: 'good', // Will be updated if the value changes. - delta: 0, - entries: [], - id: (0,_generateUniqueID_js__WEBPACK_IMPORTED_MODULE_3__.generateUniqueID)(), - navigationType, - }; -}; - - -//# sourceMappingURL=initMetric.js.map - - -/***/ }), -/* 1719 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getNavigationEntry": () => (/* binding */ getNavigationEntry) -/* harmony export */ }); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1713); - - -/* - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const getNavigationEntryFromPerformanceTiming = () => { - // eslint-disable-next-line deprecation/deprecation - const timing = _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.performance.timing; - // eslint-disable-next-line deprecation/deprecation - const type = _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.performance.navigation.type; - - const navigationEntry = { - entryType: 'navigation', - startTime: 0, - type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate', - }; - - for (const key in timing) { - if (key !== 'navigationStart' && key !== 'toJSON') { - navigationEntry[key] = Math.max((timing[key ] ) - timing.navigationStart, 0); - } - } - return navigationEntry ; -}; - -const getNavigationEntry = () => { - if (_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.__WEB_VITALS_POLYFILL__) { - return ( - _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.performance && - ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) || - getNavigationEntryFromPerformanceTiming()) - ); - } else { - return _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0]; - } -}; - - -//# sourceMappingURL=getNavigationEntry.js.map - - -/***/ }), -/* 1720 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getActivationStart": () => (/* binding */ getActivationStart) -/* harmony export */ }); -/* harmony import */ var _getNavigationEntry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1719); - - -/* - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const getActivationStart = () => { - const navEntry = (0,_getNavigationEntry_js__WEBPACK_IMPORTED_MODULE_0__.getNavigationEntry)(); - return (navEntry && navEntry.activationStart) || 0; -}; - - -//# sourceMappingURL=getActivationStart.js.map - - -/***/ }), -/* 1721 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "generateUniqueID": () => (/* binding */ generateUniqueID) -/* harmony export */ }); -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Performantly generate a unique, 30-char string by combining a version - * number, the current timestamp with a 13-digit number integer. - * @return {string} - */ -const generateUniqueID = () => { - return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`; -}; - - -//# sourceMappingURL=generateUniqueID.js.map - - -/***/ }), -/* 1722 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "bindReporter": () => (/* binding */ bindReporter) -/* harmony export */ }); -const bindReporter = ( - callback, - metric, - reportAllChanges, -) => { - let prevValue; - let delta; - return (forceReport) => { - if (metric.value >= 0) { - if (forceReport || reportAllChanges) { - delta = metric.value - (prevValue || 0); - - // Report the metric if there's a non-zero delta or if no previous - // value exists (which can happen in the case of the document becoming - // hidden when the metric value is 0). - // See: https://github.com/GoogleChrome/web-vitals/issues/14 - if (delta || prevValue === undefined) { - prevValue = metric.value; - metric.delta = delta; - callback(metric); - } - } - } - }; -}; - - -//# sourceMappingURL=bindReporter.js.map - - -/***/ }), -/* 1723 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "onHidden": () => (/* binding */ onHidden) -/* harmony export */ }); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1713); - - -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const onHidden = (cb, once) => { - const onHiddenOrPageHide = (event) => { - if (event.type === 'pagehide' || _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.document.visibilityState === 'hidden') { - cb(event); - if (once) { - removeEventListener('visibilitychange', onHiddenOrPageHide, true); - removeEventListener('pagehide', onHiddenOrPageHide, true); - } - } - }; - addEventListener('visibilitychange', onHiddenOrPageHide, true); - // Some browsers have buggy implementations of visibilitychange, - // so we use pagehide in addition, just to be safe. - addEventListener('pagehide', onHiddenOrPageHide, true); -}; - - -//# sourceMappingURL=onHidden.js.map - - -/***/ }), -/* 1724 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "onLCP": () => (/* binding */ onLCP) -/* harmony export */ }); -/* harmony import */ var _lib_bindReporter_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1722); -/* harmony import */ var _lib_getActivationStart_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1720); -/* harmony import */ var _lib_getVisibilityWatcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1725); -/* harmony import */ var _lib_initMetric_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1718); -/* harmony import */ var _lib_observe_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1716); -/* harmony import */ var _lib_onHidden_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1723); - - - - - - - -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const reportedMetricIDs = {}; - -/** - * Calculates the [LCP](https://web.dev/lcp/) value for the current page and - * calls the `callback` function once the value is ready (along with the - * relevant `largest-contentful-paint` performance entry used to determine the - * value). The reported value is a `DOMHighResTimeStamp`. - * - * If the `reportAllChanges` configuration option is set to `true`, the - * `callback` function will be called any time a new `largest-contentful-paint` - * performance entry is dispatched, or once the final value of the metric has - * been determined. - */ -const onLCP = (onReport, opts = {}) => { - const visibilityWatcher = (0,_lib_getVisibilityWatcher_js__WEBPACK_IMPORTED_MODULE_0__.getVisibilityWatcher)(); - const metric = (0,_lib_initMetric_js__WEBPACK_IMPORTED_MODULE_1__.initMetric)('LCP'); - let report; - - const handleEntries = (entries) => { - const lastEntry = entries[entries.length - 1] ; - if (lastEntry) { - // The startTime attribute returns the value of the renderTime if it is - // not 0, and the value of the loadTime otherwise. The activationStart - // reference is used because LCP should be relative to page activation - // rather than navigation start if the page was prerendered. - const value = Math.max(lastEntry.startTime - (0,_lib_getActivationStart_js__WEBPACK_IMPORTED_MODULE_2__.getActivationStart)(), 0); - - // Only report if the page wasn't hidden prior to LCP. - if (value < visibilityWatcher.firstHiddenTime) { - metric.value = value; - metric.entries = [lastEntry]; - report(); - } - } - }; - - const po = (0,_lib_observe_js__WEBPACK_IMPORTED_MODULE_3__.observe)('largest-contentful-paint', handleEntries); - - if (po) { - report = (0,_lib_bindReporter_js__WEBPACK_IMPORTED_MODULE_4__.bindReporter)(onReport, metric, opts.reportAllChanges); - - const stopListening = () => { - if (!reportedMetricIDs[metric.id]) { - handleEntries(po.takeRecords() ); - po.disconnect(); - reportedMetricIDs[metric.id] = true; - report(true); - } - }; - - // Stop listening after input. Note: while scrolling is an input that - // stop LCP observation, it's unreliable since it can be programmatically - // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75 - ['keydown', 'click'].forEach(type => { - addEventListener(type, stopListening, { once: true, capture: true }); - }); - - (0,_lib_onHidden_js__WEBPACK_IMPORTED_MODULE_5__.onHidden)(stopListening, true); - } -}; - - -//# sourceMappingURL=getLCP.js.map - - -/***/ }), -/* 1725 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getVisibilityWatcher": () => (/* binding */ getVisibilityWatcher) -/* harmony export */ }); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1713); -/* harmony import */ var _onHidden_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1723); - - - -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -let firstHiddenTime = -1; - -const initHiddenTime = () => { - // If the document is hidden and not prerendering, assume it was always - // hidden and the page was loaded in the background. - return _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.document.visibilityState === 'hidden' && !_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.document.prerendering ? 0 : Infinity; -}; - -const trackChanges = () => { - // Update the time if/when the document becomes hidden. - (0,_onHidden_js__WEBPACK_IMPORTED_MODULE_1__.onHidden)(({ timeStamp }) => { - firstHiddenTime = timeStamp; - }, true); -}; - -const getVisibilityWatcher = ( - -) => { - if (firstHiddenTime < 0) { - // If the document is hidden when this code runs, assume it was hidden - // since navigation start. This isn't a perfect heuristic, but it's the - // best we can do until an API is available to support querying past - // visibilityState. - firstHiddenTime = initHiddenTime(); - trackChanges(); - } - return { - get firstHiddenTime() { - return firstHiddenTime; - }, - }; -}; - - -//# sourceMappingURL=getVisibilityWatcher.js.map - - -/***/ }), -/* 1726 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "onFID": () => (/* binding */ onFID) -/* harmony export */ }); -/* harmony import */ var _lib_bindReporter_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1722); -/* harmony import */ var _lib_getVisibilityWatcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1725); -/* harmony import */ var _lib_initMetric_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1718); -/* harmony import */ var _lib_observe_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1716); -/* harmony import */ var _lib_onHidden_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1723); - - - - - - -/* - * Copyright 2020 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Calculates the [FID](https://web.dev/fid/) value for the current page and - * calls the `callback` function once the value is ready, along with the - * relevant `first-input` performance entry used to determine the value. The - * reported value is a `DOMHighResTimeStamp`. - * - * _**Important:** since FID is only reported after the user interacts with the - * page, it's possible that it will not be reported for some page loads._ - */ -const onFID = (onReport, opts = {}) => { - const visibilityWatcher = (0,_lib_getVisibilityWatcher_js__WEBPACK_IMPORTED_MODULE_0__.getVisibilityWatcher)(); - const metric = (0,_lib_initMetric_js__WEBPACK_IMPORTED_MODULE_1__.initMetric)('FID'); - // eslint-disable-next-line prefer-const - let report; - - const handleEntry = (entry) => { - // Only report if the page wasn't hidden prior to the first input. - if (entry.startTime < visibilityWatcher.firstHiddenTime) { - metric.value = entry.processingStart - entry.startTime; - metric.entries.push(entry); - report(true); - } - }; - - const handleEntries = (entries) => { - (entries ).forEach(handleEntry); - }; - - const po = (0,_lib_observe_js__WEBPACK_IMPORTED_MODULE_2__.observe)('first-input', handleEntries); - report = (0,_lib_bindReporter_js__WEBPACK_IMPORTED_MODULE_3__.bindReporter)(onReport, metric, opts.reportAllChanges); - - if (po) { - (0,_lib_onHidden_js__WEBPACK_IMPORTED_MODULE_4__.onHidden)(() => { - handleEntries(po.takeRecords() ); - po.disconnect(); - }, true); - } -}; - - -//# sourceMappingURL=getFID.js.map - - -/***/ }), -/* 1727 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_startChild": () => (/* binding */ _startChild), -/* harmony export */ "isMeasurementValue": () => (/* binding */ isMeasurementValue) -/* harmony export */ }); -/** - * Checks if a given value is a valid measurement value. - */ -function isMeasurementValue(value) { - return typeof value === 'number' && isFinite(value); -} - -/** - * Helper function to start child on transactions. This function will make sure that the transaction will - * use the start timestamp of the created child span if it is earlier than the transactions actual - * start timestamp. - */ -function _startChild(transaction, { startTimestamp, ...ctx }) { - if (startTimestamp && transaction.startTimestamp > startTimestamp) { - transaction.startTimestamp = startTimestamp; - } - - return transaction.startChild({ - startTimestamp, - ...ctx, - }); -} - - -//# sourceMappingURL=utils.js.map - - -/***/ }), -/* 1728 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "registerBackgroundTabDetection": () => (/* binding */ registerBackgroundTabDetection) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1695); -/* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1713); - - - - -/** - * Add a listener that cancels and finishes a transaction when the global - * document is hidden. - */ -function registerBackgroundTabDetection() { - if (_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW && _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.document) { - _types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.document.addEventListener('visibilitychange', () => { - const activeTransaction = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.getActiveTransaction)() ; - if (_types_js__WEBPACK_IMPORTED_MODULE_0__.WINDOW.document.hidden && activeTransaction) { - const statusType = 'cancelled'; - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log( - `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`, - ); - // We should not set status if it is already set, this prevent important statuses like - // error or data loss from being overwritten on transaction. - if (!activeTransaction.status) { - activeTransaction.setStatus(statusType); - } - activeTransaction.setTag('visibilitychange', 'document.hidden'); - activeTransaction.finish(); - } - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); - } -} - - -//# sourceMappingURL=backgroundtab.js.map - - -/***/ }), -/* 1729 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SpanStatus": () => (/* binding */ SpanStatus) -/* harmony export */ }); -/** The status of an Span. - * - * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type - */ -// eslint-disable-next-line import/export -var SpanStatus; (function (SpanStatus) { - /** The operation completed successfully. */ - const Ok = 'ok'; SpanStatus["Ok"] = Ok; - /** Deadline expired before operation could complete. */ - const DeadlineExceeded = 'deadline_exceeded'; SpanStatus["DeadlineExceeded"] = DeadlineExceeded; - /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ - const Unauthenticated = 'unauthenticated'; SpanStatus["Unauthenticated"] = Unauthenticated; - /** 403 Forbidden */ - const PermissionDenied = 'permission_denied'; SpanStatus["PermissionDenied"] = PermissionDenied; - /** 404 Not Found. Some requested entity (file or directory) was not found. */ - const NotFound = 'not_found'; SpanStatus["NotFound"] = NotFound; - /** 429 Too Many Requests */ - const ResourceExhausted = 'resource_exhausted'; SpanStatus["ResourceExhausted"] = ResourceExhausted; - /** Client specified an invalid argument. 4xx. */ - const InvalidArgument = 'invalid_argument'; SpanStatus["InvalidArgument"] = InvalidArgument; - /** 501 Not Implemented */ - const Unimplemented = 'unimplemented'; SpanStatus["Unimplemented"] = Unimplemented; - /** 503 Service Unavailable */ - const Unavailable = 'unavailable'; SpanStatus["Unavailable"] = Unavailable; - /** Other/generic 5xx. */ - const InternalError = 'internal_error'; SpanStatus["InternalError"] = InternalError; - /** Unknown. Any non-standard HTTP status code. */ - const UnknownError = 'unknown_error'; SpanStatus["UnknownError"] = UnknownError; - /** The operation was cancelled (typically by the user). */ - const Cancelled = 'cancelled'; SpanStatus["Cancelled"] = Cancelled; - /** Already exists (409) */ - const AlreadyExists = 'already_exists'; SpanStatus["AlreadyExists"] = AlreadyExists; - /** Operation was rejected because the system is not in a state required for the operation's */ - const FailedPrecondition = 'failed_precondition'; SpanStatus["FailedPrecondition"] = FailedPrecondition; - /** The operation was aborted, typically due to a concurrency issue. */ - const Aborted = 'aborted'; SpanStatus["Aborted"] = Aborted; - /** Operation was attempted past the valid range. */ - const OutOfRange = 'out_of_range'; SpanStatus["OutOfRange"] = OutOfRange; - /** Unrecoverable data loss or corruption */ - const DataLoss = 'data_loss'; SpanStatus["DataLoss"] = DataLoss; -})(SpanStatus || (SpanStatus = {})); - - -//# sourceMappingURL=spanstatus.js.map - - -/***/ }), -/* 1730 */ -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"name":"enedissgegrandlyon","version":"1.2.0","description":"","repository":{"type":"https","url":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector"},"keywords":[],"main":"./src/index.js","author":"Cozy Cloud","license":"AGPL-3.0","eslintConfig":{"extends":["cozy-app"]},"eslintIgnore":["build","data"],"husky":{"hooks":{"pre-commit":"yarn lint"}},"jest":{"setupFiles":["./setupTests.js"]},"scripts":{"build":"webpack","clean":"rm -rf ./data","cozyPublish":"cozy-app-publish --token $REGISTRY_TOKEN --build-commit $(git rev-parse ${DEPLOY_BRANCH:-build})","deploy":"git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build}","deploy-dev":"git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build-dev}","dev":"cozy-konnector-dev","lint":"eslint --fix .","onDeleteAccount:standalone":"cozy-konnector-standalone src/onDeleteAccount.js","onDeleteAccount":"cozy-konnector-dev src/onDeleteAccount.js","pretest":"npm run clean","release":"standard-version --no-verify","standalone":"cozy-konnector-standalone","start":"node ./src/index.js","test:cov":"jest --coverage","test":"jest","travisDeployKey":"./bin/generate_travis_deploy_key"},"dependencies":{"@sentry/node":"^7.23.0","@sentry/tracing":"^7.23.0","axios":"^0.27.2","cozy-konnector-libs":"4.55.0","easy-soap-request":"^4.7.0","jest":"^28.1.3","moment":"^2.29.3","moment-timezone":"^0.5.34","xml2js":"^0.4.23"},"devDependencies":{"cozy-jobs-cli":"1.19.1","cozy-konnector-build":"1.3.4","eslint-config-cozy-app":"1.3.3","eslint-plugin-prettier":"^4.0.0","git-directory-deploy":"1.5.1","jest-junit":"^14.0.0","standard-version":"^9.5.0"}}'); /***/ }) /******/ ]); @@ -247674,21 +229023,6 @@ module.exports = JSON.parse('{"name":"enedissgegrandlyon","version":"1.2.0","des /******/ }; /******/ })(); /******/ -/******/ /* webpack/runtime/harmony module decorator */ -/******/ (() => { -/******/ __webpack_require__.hmd = (module) => { -/******/ module = Object.create(module); -/******/ if (!module.children) module.children = []; -/******/ Object.defineProperty(module, 'exports', { -/******/ enumerable: true, -/******/ set: () => { -/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); -/******/ } -/******/ }); -/******/ return module; -/******/ }; -/******/ })(); -/******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) diff --git a/manifest.konnector b/manifest.konnector index 1217cfb..7e9526f 100644 --- a/manifest.konnector +++ b/manifest.konnector @@ -51,7 +51,7 @@ "langs": ["fr"], "locales": { "fr": { - "short_description": "Récupère vos données de courbe de charge depuis l'API Enedis", + "short_description": "Récupère vos donnéees de courbe de charge depuis l'API Enedis", "long_description": "Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky", "permissions": { "enedis data": { diff --git a/onDeleteAccount.js b/onDeleteAccount.js index c8ef3bb..820b7df 100644 --- a/onDeleteAccount.js +++ b/onDeleteAccount.js @@ -147791,7 +147791,7 @@ const fs = __webpack_require__(149); const path = __webpack_require__(142); -let manifest = typeof {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos données de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"} === 'undefined' ? {} : {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos données de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"}; +let manifest = typeof {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos donnéees de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"} === 'undefined' ? {} : {"version":"1.2.0","name":"Enedis SGE","type":"konnector","language":"node","icon":"icon.png","slug":"enedissgegrandlyon","source":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector.git","editor":"Métropole de Lyon","vendor_link":"https://www.enedis.fr/","categories":["energy"],"frequency":"daily","fields":{"firstname":{"type":"string"},"lastname":{"type":"string"},"address":{"type":"string"},"postalCode":{"type":"string"},"city":{"type":"string"},"pointId":{"type":"number"}},"data_types":[],"screenshots":[],"permissions":{"accounts":{"type":"io.cozy.accounts"},"files":{"type":"io.cozy.files"},"enedis data":{"type":"com.grandlyon.enedis.*"}},"developer":{"name":"Métropole de Lyon","url":"https://www.grandlyon.com/"},"langs":["fr"],"locales":{"fr":{"short_description":"Récupère vos donnéees de courbe de charge depuis l'API Enedis","long_description":"Ce connecteur récupère la courbe de charge électrique enregistrée par le compteur Linky","permissions":{"enedis data":{"description":"Requises pour accéder et stocker les données collectées par le compteur Linky et exposées par les API Enedis (consommations d’électricité à la demi-heure, au jour, mois et année). "},"files":{"description":"Cozy files"},"accounts":{"description":"Utilisé pour accéder à vos données de consommation."}}},"en":{"short_description":"Fetches your electricity consumption data from Enedis API","long_description":"This konnector fetches the energy curve of your electricity consumption gathered by your Linky device.","permissions":{"enedis data":{"description":"Required to access and store the data collected by the Linky meter and exposed by Enedis APIs (half-an-hour, daily, monthly and yearly consumption)."},"files":{"description":"Cozy files"},"accounts":{"description":"Used to access your consumption data."}}}},"manifest_version":"2","on_delete_account":"onDeleteAccount.js"}; if (process.env.NODE_ENV !== undefined && process.env.NODE_ENV !== 'none' && process.env.NODE_ENV !== 'production') { try { @@ -223125,7 +223125,7 @@ function removeMultipleSpaces(str) { * @param {string} str * @returns {string} */ -function removeAddressNumber(str) { +function removeAddressnumber(str) { return str.replace(/\d+ |b |B |T |t |\d+/g, '') } @@ -223141,7 +223141,7 @@ module.exports = { parseUserPdl, parseValue, parseValueHalfHour, - removeAddressNumber, + removeAddressnumber, removeMultipleSpaces, } @@ -223486,7 +223486,6 @@ module.exports = { // @ts-check const { log, errors } = __webpack_require__(1) const { default: axios } = __webpack_require__(1564) -const Sentry = __webpack_require__(1601) /** * @param {number} pointID @@ -223535,9 +223534,7 @@ async function createBoConsent( ) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -223572,9 +223569,7 @@ async function updateBoConsent(url, token, consent, serviceId) { ) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -223594,9 +223589,7 @@ async function getBoConsent(url, token, boId) { const { data } = await axios.get(`${url}/consent/${boId}`, headers) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -223619,9 +223612,7 @@ async function deleteBoConsent(url, token, boId) { const { data } = await axios.delete(`${url}/consent/${boId}`, headers) return data } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `BO replied with ${e}`) throw errors.MAINTENANCE } } @@ -227547,13239 +227538,10 @@ module.exports = function isAxiosError(payload) { /***/ }), -/* 1601 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Hub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.Hub), -/* harmony export */ "SDK_VERSION": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_1__.SDK_VERSION), -/* harmony export */ "Scope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.Scope), -/* harmony export */ "addBreadcrumb": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.addBreadcrumb), -/* harmony export */ "addGlobalEventProcessor": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor), -/* harmony export */ "captureEvent": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureEvent), -/* harmony export */ "captureException": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureException), -/* harmony export */ "captureMessage": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureMessage), -/* harmony export */ "configureScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.configureScope), -/* harmony export */ "createTransport": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_4__.createTransport), -/* harmony export */ "getCurrentHub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getHubFromCarrier), -/* harmony export */ "makeMain": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.makeMain), -/* harmony export */ "setContext": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setContext), -/* harmony export */ "setExtra": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtra), -/* harmony export */ "setExtras": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtras), -/* harmony export */ "setTag": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTag), -/* harmony export */ "setTags": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTags), -/* harmony export */ "setUser": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setUser), -/* harmony export */ "startTransaction": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.startTransaction), -/* harmony export */ "withScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.withScope), -/* harmony export */ "NodeClient": () => (/* reexport safe */ _client_js__WEBPACK_IMPORTED_MODULE_5__.NodeClient), -/* harmony export */ "close": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.close), -/* harmony export */ "defaultIntegrations": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultStackParser), -/* harmony export */ "flush": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.flush), -/* harmony export */ "getSentryRelease": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.getSentryRelease), -/* harmony export */ "init": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.init), -/* harmony export */ "lastEventId": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.lastEventId), -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.addRequestDataToEvent), -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.extractRequestData), -/* harmony export */ "deepReadDirSync": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_9__.deepReadDirSync), -/* harmony export */ "Handlers": () => (/* reexport module object */ _handlers_js__WEBPACK_IMPORTED_MODULE_11__), -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _transports_http_js__WEBPACK_IMPORTED_MODULE_13__.makeNodeTransport), -/* harmony export */ "Integrations": () => (/* binding */ INTEGRATIONS) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1680); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1616); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1603); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1617); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1618); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1627); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1635); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1651); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1667); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1676); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1314); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _handlers_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1677); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1652); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1636); - - - - - - - - - - - - - -; -; - -; -; - -const INTEGRATIONS = { - ..._sentry_core__WEBPACK_IMPORTED_MODULE_14__, - ..._integrations_index_js__WEBPACK_IMPORTED_MODULE_12__, -}; - -// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like -// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. -const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getMainCarrier)(); -if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain__WEBPACK_IMPORTED_MODULE_10__; -} - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1602 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "API_VERSION": () => (/* binding */ API_VERSION), -/* harmony export */ "Hub": () => (/* binding */ Hub), -/* harmony export */ "getCurrentHub": () => (/* binding */ getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* binding */ getHubFromCarrier), -/* harmony export */ "getMainCarrier": () => (/* binding */ getMainCarrier), -/* harmony export */ "makeMain": () => (/* binding */ makeMain), -/* harmony export */ "setHubOnCarrier": () => (/* binding */ setHubOnCarrier) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1606); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1607); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1603); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1604); - - - - -const NIL_EVENT_ID = '00000000000000000000000000000000'; - -/** - * API compatibility version of this hub. - * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. - * - * @hidden - */ -const API_VERSION = 4; - -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -const DEFAULT_BREADCRUMBS = 100; - -/** - * A layer in the process stack. - * @hidden - */ - -/** - * @inheritDoc - */ -class Hub { - /** Is a {@link Layer}[] containing the client and scope */ - __init() {this._stack = [{}];} - - /** Contains the last event id of a captured event. */ - - /** - * 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. - */ - constructor(client, scope = new _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope(), _version = API_VERSION) {;this._version = _version;Hub.prototype.__init.call(this); - this.getStackTop().scope = scope; - if (client) { - this.bindClient(client); - } - } - - /** - * @inheritDoc - */ - isOlderThan(version) { - return this._version < version; - } - - /** - * @inheritDoc - */ - bindClient(client) { - const top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } - } - - /** - * @inheritDoc - */ - pushScope() { - // We want to clone the content of prev scope - const scope = _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope, - }); - return scope; - } - - /** - * @inheritDoc - */ - popScope() { - if (this.getStack().length <= 1) return false; - return !!this.getStack().pop(); - } - - /** - * @inheritDoc - */ - withScope(callback) { - const scope = this.pushScope(); - try { - callback(scope); - } finally { - this.popScope(); - } - } - - /** - * @inheritDoc - */ - getClient() { - return this.getStackTop().client ; - } - - /** Returns the scope of the top stack. */ - getScope() { - return this.getStackTop().scope; - } - - /** Returns the scope stack for domains or the process. */ - getStack() { - return this._stack; - } - - /** Returns the topmost scope layer in the order domain > local > process. */ - getStackTop() { - return this._stack[this._stack.length - 1]; - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint) { - const syntheticException = new Error('Sentry syntheticException'); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureException( - exception, - { - originalException: exception, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; - } - - /** - * @inheritDoc - */ - captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level, - hint, - ) { - const syntheticException = new Error(message); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureMessage( - message, - level, - { - originalException: message, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; - } - - /** - * @inheritDoc - */ - captureEvent(event, hint) { - const clientId = - this._withClient((client, scope) => { - return client.captureEvent(event, { ...hint }, scope); - }) || NIL_EVENT_ID; - - if (event.type !== 'transaction') { - this._lastEventId = clientId; - } - - return clientId; - } - - /** - * @inheritDoc - */ - lastEventId() { - return this._lastEventId; - } - - /** - * @inheritDoc - */ - addBreadcrumb(breadcrumb, hint) { - const { scope, client } = this.getStackTop(); - - if (!scope || !client) return; - - // eslint-disable-next-line @typescript-eslint/unbound-method - const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = - (client.getOptions && client.getOptions()) || {}; - - if (maxBreadcrumbs <= 0) return; - - const timestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dateTimestampInSeconds)(); - const mergedBreadcrumb = { timestamp, ...breadcrumb }; - const finalBreadcrumb = beforeBreadcrumb - ? ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) - : mergedBreadcrumb; - - if (finalBreadcrumb === null) return; - - scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); - } - - /** - * @inheritDoc - */ - setUser(user) { - const scope = this.getScope(); - if (scope) scope.setUser(user); - } - - /** - * @inheritDoc - */ - setTags(tags) { - const scope = this.getScope(); - if (scope) scope.setTags(tags); - } - - /** - * @inheritDoc - */ - setExtras(extras) { - const scope = this.getScope(); - if (scope) scope.setExtras(extras); - } - - /** - * @inheritDoc - */ - setTag(key, value) { - const scope = this.getScope(); - if (scope) scope.setTag(key, value); - } - - /** - * @inheritDoc - */ - setExtra(key, extra) { - const scope = this.getScope(); - if (scope) scope.setExtra(key, extra); - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setContext(name, context) { - const scope = this.getScope(); - if (scope) scope.setContext(name, context); - } - - /** - * @inheritDoc - */ - configureScope(callback) { - const { scope, client } = this.getStackTop(); - if (scope && client) { - callback(scope); - } - } - - /** - * @inheritDoc - */ - run(callback) { - const oldHub = makeMain(this); - try { - callback(this); - } finally { - makeMain(oldHub); - } - } - - /** - * @inheritDoc - */ - getIntegration(integration) { - const client = this.getClient(); - if (!client) return null; - try { - return client.getIntegration(integration); - } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); - return null; - } - } - - /** - * @inheritDoc - */ - startTransaction(context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - } - - /** - * @inheritDoc - */ - traceHeaders() { - return this._callExtensionMethod('traceHeaders'); - } - - /** - * @inheritDoc - */ - captureSession(endSession = false) { - // both send the update and pull the session from the scope - if (endSession) { - return this.endSession(); - } - - // only send the update - this._sendSessionUpdate(); - } - - /** - * @inheritDoc - */ - endSession() { - const layer = this.getStackTop(); - const scope = layer && layer.scope; - const session = scope && scope.getSession(); - if (session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.closeSession)(session); - } - this._sendSessionUpdate(); - - // the session is over; take it off of the scope - if (scope) { - scope.setSession(); - } - } - - /** - * @inheritDoc - */ - startSession(context) { - const { scope, client } = this.getStackTop(); - const { release, environment } = (client && client.getOptions()) || {}; - - // Will fetch userAgent if called from browser sdk - const { userAgent } = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.navigator || {}; - - const session = (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.makeSession)({ - release, - environment, - ...(scope && { user: scope.getUser() }), - ...(userAgent && { userAgent }), - ...context, - }); - - if (scope) { - // End existing session if there's one - const currentSession = scope.getSession && scope.getSession(); - if (currentSession && currentSession.status === 'ok') { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.updateSession)(currentSession, { status: 'exited' }); - } - this.endSession(); - - // Afterwards we set the new session on the scope - scope.setSession(session); - } - - return session; - } - - /** - * Returns if default PII should be sent to Sentry and propagated in ourgoing requests - * when Tracing is used. - */ - shouldSendDefaultPii() { - const client = this.getClient(); - const options = client && client.getOptions(); - return Boolean(options && options.sendDefaultPii); - } - - /** - * Sends the current Session on the scope - */ - _sendSessionUpdate() { - const { scope, client } = this.getStackTop(); - if (!scope) return; - - const session = scope.getSession(); - if (session) { - if (client && client.captureSession) { - client.captureSession(session); - } - } - } - - /** - * Internal helper function to call a method on the top client if it exists. - * - * @param method The method to call on the client. - * @param args Arguments to pass to the client function. - */ - _withClient(callback) { - const { scope, client } = this.getStackTop(); - return client && callback(client, scope); - } - - /** - * Calls global extension method and binding current instance to the function call - */ - // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _callExtensionMethod(method, ...args) { - const carrier = getMainCarrier(); - const sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); - } -} - -/** - * Returns the global shim registry. - * - * FIXME: This function is problematic, because despite always returning a valid Carrier, - * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check - * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. - **/ -function getMainCarrier() { - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ; -} - -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - const registry = getMainCarrier(); - const oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; -} - -/** - * 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) - const registry = getMainCarrier(); - - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) { - setHubOnCarrier(registry, new Hub()); - } - - // Prefer domains over global if they are there (applicable only to Node environment) - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isNodeEnv)()) { - return getHubFromActiveDomain(registry); - } - // Return hub that lives on a global object - return getHubFromCarrier(registry); -} - -/** - * 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 { - const sentry = getMainCarrier().__SENTRY__; - const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; - - // 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(API_VERSION)) { - const registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, _scope_js__WEBPACK_IMPORTED_MODULE_0__.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) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.getGlobalSingleton)('hub', () => new Hub(), carrier); -} - -/** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - * @returns A boolean indicating success or failure - */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) return false; - const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); - __SENTRY__.hub = hub; - return true; -} - - -//# sourceMappingURL=hub.js.map - - -/***/ }), -/* 1603 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Scope": () => (/* binding */ Scope), -/* harmony export */ "addGlobalEventProcessor": () => (/* binding */ addGlobalEventProcessor) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1606); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1604); - - - -/** - * Default value for maximum number of breadcrumbs added to an event. - */ -const DEFAULT_MAX_BREADCRUMBS = 100; - -/** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. - */ -class Scope { - /** Flag if notifying is happening. */ - - /** Callback for client to receive scope changes. */ - - /** Callback list that will be called after {@link applyToEvent}. */ - - /** Array of breadcrumbs. */ - - /** User */ - - /** Tags */ - - /** Extra */ - - /** Contexts */ - - /** Attachments */ - - /** - * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get - * sent to Sentry - */ - - /** Fingerprint */ - - /** Severity */ - // eslint-disable-next-line deprecation/deprecation - - /** Transaction Name */ - - /** Span */ - - /** Session */ - - /** Request Mode Session Status */ - - // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. - - constructor() { - this._notifyingListeners = false; - this._scopeListeners = []; - this._eventProcessors = []; - this._breadcrumbs = []; - this._attachments = []; - this._user = {}; - this._tags = {}; - this._extra = {}; - this._contexts = {}; - this._sdkProcessingMetadata = {}; - } - - /** - * Inherit values from the parent scope. - * @param scope to clone. - */ - static clone(scope) { - const newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = [...scope._breadcrumbs]; - newScope._tags = { ...scope._tags }; - newScope._extra = { ...scope._extra }; - newScope._contexts = { ...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 = [...scope._eventProcessors]; - newScope._requestSession = scope._requestSession; - newScope._attachments = [...scope._attachments]; - newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata }; - } - return newScope; - } - - /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden - */ - addScopeListener(callback) { - this._scopeListeners.push(callback); - } - - /** - * @inheritDoc - */ - addEventProcessor(callback) { - this._eventProcessors.push(callback); - return this; - } - - /** - * @inheritDoc - */ - setUser(user) { - this._user = user || {}; - if (this._session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_0__.updateSession)(this._session, { user }); - } - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - getUser() { - return this._user; - } - - /** - * @inheritDoc - */ - getRequestSession() { - return this._requestSession; - } - - /** - * @inheritDoc - */ - setRequestSession(requestSession) { - this._requestSession = requestSession; - return this; - } - - /** - * @inheritDoc - */ - setTags(tags) { - this._tags = { - ...this._tags, - ...tags, - }; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setTag(key, value) { - this._tags = { ...this._tags, [key]: value }; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setExtras(extras) { - this._extra = { - ...this._extra, - ...extras, - }; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setExtra(key, extra) { - this._extra = { ...this._extra, [key]: extra }; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setFingerprint(fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setLevel( - // eslint-disable-next-line deprecation/deprecation - level, - ) { - this._level = level; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setTransactionName(name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setContext(key, context) { - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } else { - this._contexts[key] = context; - } - - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setSpan(span) { - this._span = span; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - getSpan() { - return this._span; - } - - /** - * @inheritDoc - */ - getTransaction() { - // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will - // have a pointer to the currently-active transaction. - const span = this.getSpan(); - return span && span.transaction; - } - - /** - * @inheritDoc - */ - setSession(session) { - if (!session) { - delete this._session; - } else { - this._session = session; - } - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - getSession() { - return this._session; - } - - /** - * @inheritDoc - */ - update(captureContext) { - if (!captureContext) { - return this; - } - - if (typeof captureContext === 'function') { - const updatedScope = (captureContext )(this); - return updatedScope instanceof Scope ? updatedScope : this; - } - - if (captureContext instanceof Scope) { - this._tags = { ...this._tags, ...captureContext._tags }; - this._extra = { ...this._extra, ...captureContext._extra }; - this._contexts = { ...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; - } - if (captureContext._requestSession) { - this._requestSession = captureContext._requestSession; - } - } else if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext ; - this._tags = { ...this._tags, ...captureContext.tags }; - this._extra = { ...this._extra, ...captureContext.extra }; - this._contexts = { ...this._contexts, ...captureContext.contexts }; - if (captureContext.user) { - this._user = captureContext.user; - } - if (captureContext.level) { - this._level = captureContext.level; - } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; - } - if (captureContext.requestSession) { - this._requestSession = captureContext.requestSession; - } - } - - return this; - } - - /** - * @inheritDoc - */ - clear() { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._requestSession = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - this._attachments = []; - return this; - } - - /** - * @inheritDoc - */ - addBreadcrumb(breadcrumb, maxBreadcrumbs) { - const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; - - // No data has been changed, so don't notify scope listeners - if (maxCrumbs <= 0) { - return this; - } - - const mergedBreadcrumb = { - timestamp: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dateTimestampInSeconds)(), - ...breadcrumb, - }; - this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs); - this._notifyScopeListeners(); - - return this; - } - - /** - * @inheritDoc - */ - clearBreadcrumbs() { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - addAttachment(attachment) { - this._attachments.push(attachment); - return this; - } - - /** - * @inheritDoc - */ - getAttachments() { - return this._attachments; - } - - /** - * @inheritDoc - */ - clearAttachments() { - this._attachments = []; - return this; - } - - /** - * Applies data from the scope to the event and runs all event processors on it. - * - * @param event Event - * @param hint Object containing additional information about the original exception, for use by the event processors. - * @hidden - */ - applyToEvent(event, hint = {}) { - if (this._extra && Object.keys(this._extra).length) { - event.extra = { ...this._extra, ...event.extra }; - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = { ...this._tags, ...event.tags }; - } - if (this._user && Object.keys(this._user).length) { - event.user = { ...this._user, ...event.user }; - } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = { ...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 relies on that. - if (this._span) { - event.contexts = { trace: this._span.getTraceContext(), ...event.contexts }; - const transactionName = this._span.transaction && this._span.transaction.name; - if (transactionName) { - event.tags = { transaction: transactionName, ...event.tags }; - } - } - - this._applyFingerprint(event); - - event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs]; - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; - - event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata }; - - return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); - } - - /** - * Add data which will be accessible during event processing but won't get sent to Sentry - */ - setSDKProcessingMetadata(newData) { - this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; - - return this; - } - - /** - * This will be called after {@link applyToEvent} is finished. - */ - _notifyEventProcessors( - processors, - event, - hint, - index = 0, - ) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.SyncPromise((resolve, reject) => { - const processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } else { - const result = processor({ ...event }, hint) ; - - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - processor.id && - result === null && - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.log(`Event processor "${processor.id}" dropped event`); - - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isThenable)(result)) { - void result - .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) - .then(null, reject); - } else { - void this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } - } - }); - } - - /** - * This will be called on every set call. - */ - _notifyScopeListeners() { - // 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(callback => { - callback(this); - }); - this._notifyingListeners = false; - } - } - - /** - * Applies fingerprint from the scope to the event if there's one, - * uses message if there's one instead or get rid of empty fingerprint - */ - _applyFingerprint(event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.arrayify)(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; - } - } -} - -/** - * Returns the global event processors. - */ -function getGlobalEventProcessors() { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.getGlobalSingleton)('globalEventProcessors', () => []); -} - -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); -} - - -//# sourceMappingURL=scope.js.map - - -/***/ }), -/* 1604 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "closeSession": () => (/* binding */ closeSession), -/* harmony export */ "makeSession": () => (/* binding */ makeSession), -/* harmony export */ "updateSession": () => (/* binding */ updateSession) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); - - -/** - * Creates a new `Session` object by setting certain default parameters. If optional @param context - * is passed, the passed properties are applied to the session object. - * - * @param context (optional) additional properties to be applied to the returned session object - * - * @returns a new `Session` object - */ -function makeSession(context) { - // Both timestamp and started are in seconds since the UNIX epoch. - const startingTime = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); - - const session = { - sid: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(), - init: true, - timestamp: startingTime, - started: startingTime, - duration: 0, - status: 'ok', - errors: 0, - ignoreDuration: false, - toJSON: () => sessionToJSON(session), - }; - - if (context) { - updateSession(session, context); - } - - return session; -} - -/** - * Updates a session object with the properties passed in the context. - * - * Note that this function mutates the passed object and returns void. - * (Had to do this instead of returning a new and updated session because closing and sending a session - * makes an update to the session after it was passed to the sending logic. - * @see BaseClient.captureSession ) - * - * @param session the `Session` to update - * @param context the `SessionContext` holding the properties that should be updated in @param session - */ -// eslint-disable-next-line complexity -function updateSession(session, context = {}) { - if (context.user) { - if (!session.ipAddress && context.user.ip_address) { - session.ipAddress = context.user.ip_address; - } - - if (!session.did && !context.did) { - session.did = context.user.id || context.user.email || context.user.username; - } - } - - session.timestamp = context.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); - - if (context.ignoreDuration) { - session.ignoreDuration = context.ignoreDuration; - } - if (context.sid) { - // Good enough uuid validation. — Kamil - session.sid = context.sid.length === 32 ? context.sid : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(); - } - if (context.init !== undefined) { - session.init = context.init; - } - if (!session.did && context.did) { - session.did = `${context.did}`; - } - if (typeof context.started === 'number') { - session.started = context.started; - } - if (session.ignoreDuration) { - session.duration = undefined; - } else if (typeof context.duration === 'number') { - session.duration = context.duration; - } else { - const duration = session.timestamp - session.started; - session.duration = duration >= 0 ? duration : 0; - } - if (context.release) { - session.release = context.release; - } - if (context.environment) { - session.environment = context.environment; - } - if (!session.ipAddress && context.ipAddress) { - session.ipAddress = context.ipAddress; - } - if (!session.userAgent && context.userAgent) { - session.userAgent = context.userAgent; - } - if (typeof context.errors === 'number') { - session.errors = context.errors; - } - if (context.status) { - session.status = context.status; - } -} - -/** - * Closes a session by setting its status and updating the session object with it. - * Internally calls `updateSession` to update the passed session object. - * - * Note that this function mutates the passed session (@see updateSession for explanation). - * - * @param session the `Session` object to be closed - * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, - * this function will keep the previously set status, unless it was `'ok'` in which case - * it is changed to `'exited'`. - */ -function closeSession(session, status) { - let context = {}; - if (status) { - context = { status }; - } else if (session.status === 'ok') { - context = { status: 'exited' }; - } - - updateSession(session, context); -} - -/** - * Serializes a passed session object to a JSON object with a slightly different structure. - * This is necessary because the Sentry backend requires a slightly different schema of a session - * than the one the JS SDKs use internally. - * - * @param session the session to be converted - * - * @returns a JSON object of the passed session - */ -function sessionToJSON(session) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ - sid: `${session.sid}`, - init: session.init, - // Make sure that sec is converted to ms for date constructor - started: new Date(session.started * 1000).toISOString(), - timestamp: new Date(session.timestamp * 1000).toISOString(), - status: session.status, - errors: session.errors, - did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, - duration: session.duration, - attrs: { - release: session.release, - environment: session.environment, - ip_address: session.ipAddress, - user_agent: session.userAgent, - }, - }); -} - - -//# sourceMappingURL=session.js.map - - -/***/ }), -/* 1605 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_browserPerformanceTimeOriginMode": () => (/* binding */ _browserPerformanceTimeOriginMode), -/* harmony export */ "browserPerformanceTimeOrigin": () => (/* binding */ browserPerformanceTimeOrigin), -/* harmony export */ "dateTimestampInSeconds": () => (/* binding */ dateTimestampInSeconds), -/* harmony export */ "timestampInSeconds": () => (/* binding */ timestampInSeconds), -/* harmony export */ "timestampWithMs": () => (/* binding */ timestampWithMs), -/* harmony export */ "usingPerformanceAPI": () => (/* binding */ usingPerformanceAPI) -/* harmony export */ }); -/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1607); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); -/* module decorator */ module = __webpack_require__.hmd(module); - - - -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - -/** - * An object that can return the current timestamp in seconds since the UNIX epoch. - */ - -/** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. - * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". - */ -const dateTimestampSource = { - nowSeconds: () => Date.now() / 1000, -}; - -/** - * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} - * for accessing a high-resolution monotonic clock. - */ - -/** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. - */ -function getBrowserPerformance() { - const { performance } = WINDOW; - if (!performance || !performance.now) { - return undefined; - } - - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - const timeOrigin = Date.now() - performance.now(); - - return { - now: () => performance.now(), - timeOrigin, - }; -} - -/** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. - */ -function getNodePerformance() { - try { - const perfHooks = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.dynamicRequire)(module, 'perf_hooks') ; - return perfHooks.performance; - } catch (_) { - return undefined; - } -} - -/** - * The Performance API implementation for the current platform, if available. - */ -const platformPerformance = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.isNodeEnv)() ? getNodePerformance() : getBrowserPerformance(); - -const timestampSource = - platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000, - }; - -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. - */ -const dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); - -/** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. - */ -const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); - -// Re-exported with an old name for backwards-compatibility. -const timestampWithMs = timestampInSeconds; - -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -const usingPerformanceAPI = platformPerformance !== undefined; - -/** - * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. - */ -let _browserPerformanceTimeOriginMode; - -/** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. - */ -const browserPerformanceTimeOrigin = (() => { - // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or - // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin - // data as reliable if they are within a reasonable threshold of the current time. - - const { performance } = WINDOW; - if (!performance || !performance.now) { - _browserPerformanceTimeOriginMode = 'none'; - return undefined; - } - - const threshold = 3600 * 1000; - const performanceNow = performance.now(); - const dateNow = Date.now(); - - // if timeOrigin isn't available set delta to threshold so it isn't used - const timeOriginDelta = performance.timeOrigin - ? Math.abs(performance.timeOrigin + performanceNow - dateNow) - : threshold; - const timeOriginIsReliable = timeOriginDelta < threshold; - - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - const navigationStart = performance.timing && performance.timing.navigationStart; - const hasNavigationStart = typeof navigationStart === 'number'; - // if navigationStart isn't available set delta to threshold so it isn't used - const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; - const navigationStartIsReliable = navigationStartDelta < threshold; - - if (timeOriginIsReliable || navigationStartIsReliable) { - // Use the more reliable time origin - if (timeOriginDelta <= navigationStartDelta) { - _browserPerformanceTimeOriginMode = 'timeOrigin'; - return performance.timeOrigin; - } else { - _browserPerformanceTimeOriginMode = 'navigationStart'; - return navigationStart; - } - } - - // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. - _browserPerformanceTimeOriginMode = 'dateNow'; - return dateNow; -})(); - - -//# sourceMappingURL=time.js.map - - -/***/ }), -/* 1606 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "GLOBAL_OBJ": () => (/* binding */ GLOBAL_OBJ), -/* harmony export */ "getGlobalObject": () => (/* binding */ getGlobalObject), -/* harmony export */ "getGlobalSingleton": () => (/* binding */ getGlobalSingleton) -/* harmony export */ }); -/** Internal global with common properties and Sentry extensions */ - -// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification -// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js -// core-js has the following licence: -// -// Copyright (c) 2014-2022 Denis Pushkarev -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -/** Returns 'obj' if it's the global object, otherwise returns undefined */ -function isGlobalObj(obj) { - return obj && obj.Math == Math ? obj : undefined; -} - -/** Get's the global object for the current JavaScript runtime */ -const GLOBAL_OBJ = - (typeof globalThis == 'object' && isGlobalObj(globalThis)) || - // eslint-disable-next-line no-restricted-globals - (typeof window == 'object' && isGlobalObj(window)) || - (typeof self == 'object' && isGlobalObj(self)) || - (typeof global == 'object' && isGlobalObj(global)) || - (function () { - return this; - })() || - {}; - -/** - * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 - */ -function getGlobalObject() { - return GLOBAL_OBJ ; -} - -/** - * Returns a global singleton contained in the global `__SENTRY__` object. - * - * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory - * function and added to the `__SENTRY__` object. - * - * @param name name of the global singleton on __SENTRY__ - * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` - * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value - * @returns the singleton - */ -function getGlobalSingleton(name, creator, obj) { - const gbl = (obj || GLOBAL_OBJ) ; - const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); - const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); - return singleton; -} - - -//# sourceMappingURL=worldwide.js.map - - -/***/ }), -/* 1607 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dynamicRequire": () => (/* binding */ dynamicRequire), -/* harmony export */ "isNodeEnv": () => (/* binding */ isNodeEnv), -/* harmony export */ "loadModule": () => (/* binding */ loadModule) -/* harmony export */ }); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1608); -/* module decorator */ module = __webpack_require__.hmd(module); - - -/** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. - */ - -/** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question - */ -function isNodeEnv() { - // explicitly check for browser bundles as those can be optimized statically - // by terser/rollup. - return ( - !(0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isBrowserBundle)() && - Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' - ); -} - -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); -} - -/** - * Helper for dynamically loading module that should work with linked dependencies. - * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` - * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during - * build time. `require.resolve` is also not available in any other way, so we cannot create, - * a fake helper like we do with `dynamicRequire`. - * - * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. - * That is to mimic the behavior of `require.resolve` exactly. - * - * @param moduleName module name to require - * @returns possibly required module - */ -function loadModule(moduleName) { - let mod; - - try { - mod = dynamicRequire(module, moduleName); - } catch (e) { - // no-empty - } - - try { - const { cwd } = dynamicRequire(module, 'process'); - mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ; - } catch (e) { - // no-empty - } - - return mod; -} - - -//# sourceMappingURL=node.js.map - - -/***/ }), -/* 1608 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isBrowserBundle": () => (/* binding */ isBrowserBundle) -/* harmony export */ }); -/* - * This module exists for optimizations in the build process through rollup and terser. We define some global - * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these - * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will - * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to - * `logger` and preventing node-related code from appearing in browser bundles. - * - * Attention: - * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by - * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack) - * having issues tree-shaking these constants across package boundaries. - * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want - * users to be able to shake away expressions that it guards. - */ - -/** - * Figures out if we're building a browser bundle. - * - * @returns true if this is a browser bundle build. - */ -function isBrowserBundle() { - return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; -} - - -//# sourceMappingURL=env.js.map - - -/***/ }), -/* 1609 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addContextToFrame": () => (/* binding */ addContextToFrame), -/* harmony export */ "addExceptionMechanism": () => (/* binding */ addExceptionMechanism), -/* harmony export */ "addExceptionTypeValue": () => (/* binding */ addExceptionTypeValue), -/* harmony export */ "arrayify": () => (/* binding */ arrayify), -/* harmony export */ "checkOrSetAlreadyCaught": () => (/* binding */ checkOrSetAlreadyCaught), -/* harmony export */ "getEventDescription": () => (/* binding */ getEventDescription), -/* harmony export */ "parseSemver": () => (/* binding */ parseSemver), -/* harmony export */ "uuid4": () => (/* binding */ uuid4) -/* harmony export */ }); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - - - -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -function uuid4() { - const gbl = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; - const crypto = gbl.crypto || gbl.msCrypto; - - if (crypto && crypto.randomUUID) { - return crypto.randomUUID().replace(/-/g, ''); - } - - const getRandomByte = - crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16; - - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - // Concatenating the following numbers as strings results in '10000000100040008000100000000000' - return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => - // eslint-disable-next-line no-bitwise - ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), - ); -} - -function getFirstException(event) { - return event.exception && event.exception.values ? event.exception.values[0] : undefined; -} - -/** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description - */ -function getEventDescription(event) { - const { message, event_id: eventId } = event; - if (message) { - return message; - } - - const firstException = getFirstException(event); - if (firstException) { - if (firstException.type && firstException.value) { - return `${firstException.type}: ${firstException.value}`; - } - return firstException.type || firstException.value || eventId || '<unknown>'; - } - return eventId || '<unknown>'; -} - -/** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden - */ -function addExceptionTypeValue(event, value, type) { - const exception = (event.exception = event.exception || {}); - const values = (exception.values = exception.values || []); - const firstException = (values[0] = values[0] || {}); - if (!firstException.value) { - firstException.value = value || ''; - } - if (!firstException.type) { - firstException.type = type || 'Error'; - } -} - -/** - * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. - * - * @param event The event to modify. - * @param newMechanism Mechanism data to add to the event. - * @hidden - */ -function addExceptionMechanism(event, newMechanism) { - const firstException = getFirstException(event); - if (!firstException) { - return; - } - - const defaultMechanism = { type: 'generic', handled: true }; - const currentMechanism = firstException.mechanism; - firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; - - if (newMechanism && 'data' in newMechanism) { - const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; - firstException.mechanism.data = mergedData; - } -} - -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -const SEMVER_REGEXP = - /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; - -/** - * Represents Semantic Versioning object - */ - -/** - * Parses input into a SemVer interface - * @param input string representation of a semver version - */ -function parseSemver(input) { - const match = input.match(SEMVER_REGEXP) || []; - const major = parseInt(match[1], 10); - const minor = parseInt(match[2], 10); - const patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; -} - -/** - * This function adds context (pre/post/line) lines to the provided frame - * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post - */ -function addContextToFrame(lines, frame, linesOfContext = 5) { - const lineno = frame.lineno || 0; - const maxLines = lines.length; - const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); - - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); - - frame.context_line = (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); - - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); -} - -/** - * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object - * in question), and marks it captured if not. - * - * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and - * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so - * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because - * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not - * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This - * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we - * see it. - * - * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on - * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent - * object wrapper forms so that this check will always work. However, because we need to flag the exact object which - * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification - * must be done before the exception captured. - * - * @param A thrown exception to check or flag as having been seen - * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) - */ -function checkOrSetAlreadyCaught(exception) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (exception && (exception ).__sentry_captured__) { - return true; - } - - try { - // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the - // `ExtraErrorData` integration - (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.addNonEnumerableProperty)(exception , '__sentry_captured__', true); - } catch (err) { - // `exception` is a primitive, so we can't mark it seen - } - - return false; -} - -/** - * Checks whether the given input is already an array, and if it isn't, wraps it in one. - * - * @param maybeArray Input to turn into an array, if necessary - * @returns The input, if already an array, or an array with the input as the only element, if not - */ -function arrayify(maybeArray) { - return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; -} - - -//# sourceMappingURL=misc.js.map - - -/***/ }), -/* 1610 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "escapeStringForRegex": () => (/* binding */ escapeStringForRegex), -/* harmony export */ "isMatchingPattern": () => (/* binding */ isMatchingPattern), -/* harmony export */ "safeJoin": () => (/* binding */ safeJoin), -/* harmony export */ "snipLine": () => (/* binding */ snipLine), -/* harmony export */ "stringMatchesSomePattern": () => (/* binding */ stringMatchesSomePattern), -/* harmony export */ "truncate": () => (/* binding */ truncate) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); - - -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string (0 = unlimited) - * @returns string Encoded - */ -function truncate(str, max = 0) { - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : `${str.substr(0, max)}...`; -} - -/** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function snipLine(line, colno) { - let newLine = line; - const lineLength = newLine.length; - if (lineLength <= 150) { - return newLine; - } - if (colno > lineLength) { - // eslint-disable-next-line no-param-reassign - colno = lineLength; - } - - let start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } - - let end = Math.min(start + 140, lineLength); - if (end > lineLength - 5) { - end = lineLength; - } - if (end === lineLength) { - start = Math.max(end - 140, 0); - } - - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = `'{snip} ${newLine}`; - } - if (end < lineLength) { - newLine += ' {snip}'; - } - - return newLine; -} - -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; - } - - const output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < input.length; i++) { - const value = input[i]; - try { - output.push(String(value)); - } catch (e) { - output.push('[value cannot be serialized]'); - } - } - - return output.join(delimiter); -} - -/** - * Checks if the given value matches a regex or string - * - * @param value The string to test - * @param pattern Either a regex or a string against which `value` will be matched - * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match - * `pattern` if it contains `pattern`. Only applies to string-type patterns. - */ -function isMatchingPattern( - value, - pattern, - requireExactStringMatch = false, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(value)) { - return false; - } - - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern)) { - return pattern.test(value); - } - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(pattern)) { - return requireExactStringMatch ? value === pattern : value.includes(pattern); - } - - return false; -} - -/** - * Test the given string against an array of strings and regexes. By default, string matching is done on a - * substring-inclusion basis rather than a strict equality basis - * - * @param testString The string to test - * @param patterns The patterns against which to test the string - * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to - * count. If false, `testString` will match a string pattern if it contains that pattern. - * @returns - */ -function stringMatchesSomePattern( - testString, - patterns = [], - requireExactStringMatch = false, -) { - return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); -} - -/** - * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to - * `new RegExp()`. - * - * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime - * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node - * 12+). - * - * @param regexString The string to escape - * @returns An version of the string with all special regex characters escaped - */ -function escapeStringForRegex(regexString) { - // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems - // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. - return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); -} - - -//# sourceMappingURL=string.js.map - - -/***/ }), -/* 1611 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isDOMError": () => (/* binding */ isDOMError), -/* harmony export */ "isDOMException": () => (/* binding */ isDOMException), -/* harmony export */ "isElement": () => (/* binding */ isElement), -/* harmony export */ "isError": () => (/* binding */ isError), -/* harmony export */ "isErrorEvent": () => (/* binding */ isErrorEvent), -/* harmony export */ "isEvent": () => (/* binding */ isEvent), -/* harmony export */ "isInstanceOf": () => (/* binding */ isInstanceOf), -/* harmony export */ "isNaN": () => (/* binding */ isNaN), -/* harmony export */ "isPlainObject": () => (/* binding */ isPlainObject), -/* harmony export */ "isPrimitive": () => (/* binding */ isPrimitive), -/* harmony export */ "isRegExp": () => (/* binding */ isRegExp), -/* harmony export */ "isString": () => (/* binding */ isString), -/* harmony export */ "isSyntheticEvent": () => (/* binding */ isSyntheticEvent), -/* harmony export */ "isThenable": () => (/* binding */ isThenable) -/* harmony export */ }); -// eslint-disable-next-line @typescript-eslint/unbound-method -const objectToString = Object.prototype.toString; - -/** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (objectToString.call(wat)) { - case '[object Error]': - case '[object Exception]': - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); - } -} -/** - * Checks whether given value is an instance of the given built-in class. - * - * @param wat The value to be checked - * @param className - * @returns A boolean representing the result. - */ -function isBuiltin(wat, className) { - return objectToString.call(wat) === `[object ${className}]`; -} - -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isErrorEvent(wat) { - return isBuiltin(wat, 'ErrorEvent'); -} - -/** - * Checks whether given value's type is DOMError - * {@link isDOMError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return isBuiltin(wat, 'DOMError'); -} - -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMException(wat) { - return isBuiltin(wat, 'DOMException'); -} - -/** - * Checks whether given value's type is a string - * {@link isString}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return isBuiltin(wat, 'String'); -} - -/** - * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) - * {@link isPrimitive}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); -} - -/** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return isBuiltin(wat, 'Object'); -} - -/** - * Checks whether given value's type is an Event instance - * {@link isEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); -} - -/** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); -} - -/** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isRegExp(wat) { - return isBuiltin(wat, 'RegExp'); -} - -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); -} - -/** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; -} - -/** - * Checks whether given value is NaN - * {@link isNaN}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isNaN(wat) { - return typeof wat === 'number' && wat !== wat; -} - -/** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. - * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. - */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } catch (_e) { - return false; - } -} - - -//# sourceMappingURL=is.js.map - - -/***/ }), -/* 1612 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addNonEnumerableProperty": () => (/* binding */ addNonEnumerableProperty), -/* harmony export */ "convertToPlainObject": () => (/* binding */ convertToPlainObject), -/* harmony export */ "dropUndefinedKeys": () => (/* binding */ dropUndefinedKeys), -/* harmony export */ "extractExceptionKeysForMessage": () => (/* binding */ extractExceptionKeysForMessage), -/* harmony export */ "fill": () => (/* binding */ fill), -/* harmony export */ "getOriginalFunction": () => (/* binding */ getOriginalFunction), -/* harmony export */ "markFunctionWrapped": () => (/* binding */ markFunctionWrapped), -/* harmony export */ "objectify": () => (/* binding */ objectify), -/* harmony export */ "urlEncode": () => (/* binding */ urlEncode) -/* harmony export */ }); -/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1613); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1610); - - - - -/** - * Replace a method in an object with a wrapped version of itself. - * - * @param source An object that contains a method to be wrapped. - * @param name The name of the method to be wrapped. - * @param replacementFactory A higher-order function that takes the original version of the given method and returns a - * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to - * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other - * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. - * @returns void - */ -function fill(source, name, replacementFactory) { - if (!(name in source)) { - return; - } - - const original = source[name] ; - const wrapped = replacementFactory(original) ; - - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - markFunctionWrapped(wrapped, original); - } catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } - } - - source[name] = wrapped; -} - -/** - * Defines a non-enumerable property on the given object. - * - * @param obj The object on which to set the property - * @param name The name of the property to be set - * @param value The value to which to set the property - */ -function addNonEnumerableProperty(obj, name, value) { - Object.defineProperty(obj, name, { - // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it - value: value, - writable: true, - configurable: true, - }); -} - -/** - * Remembers the original function on the wrapped function and - * patches up the prototype. - * - * @param wrapped the wrapper function - * @param original the original function that gets wrapped - */ -function markFunctionWrapped(wrapped, original) { - const proto = original.prototype || {}; - wrapped.prototype = original.prototype = proto; - addNonEnumerableProperty(wrapped, '__sentry_original__', original); -} - -/** - * This extracts the original function if available. See - * `markFunctionWrapped` for more information. - * - * @param func the function to unwrap - * @returns the unwrapped version of the function if available. - */ -function getOriginalFunction(func) { - return func.__sentry_original__; -} - -/** - * Encodes given object into url-friendly format - * - * @param object An object that contains serializable values - * @returns string Encoded - */ -function urlEncode(object) { - return Object.keys(object) - .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) - .join('&'); -} - -/** - * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their - * non-enumerable properties attached. - * - * @param value Initial source that we have to transform in order for it to be usable by the serializer - * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor - * an Error. - */ -function convertToPlainObject( - value, -) - - { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isError)(value)) { - return { - message: value.message, - name: value.name, - stack: value.stack, - ...getOwnProperties(value), - }; - } else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isEvent)(value)) { - const newObj - - = { - type: value.type, - target: serializeEventTarget(value.target), - currentTarget: serializeEventTarget(value.currentTarget), - ...getOwnProperties(value), - }; - - if (typeof CustomEvent !== 'undefined' && (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isInstanceOf)(value, CustomEvent)) { - newObj.detail = value.detail; - } - - return newObj; - } else { - return value; - } -} - -/** Creates a string representation of the target of an `Event` object */ -function serializeEventTarget(target) { - try { - return (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? (0,_browser_js__WEBPACK_IMPORTED_MODULE_1__.htmlTreeAsString)(target) : Object.prototype.toString.call(target); - } catch (_oO) { - return '<unknown>'; - } -} - -/** Filters out all but an object's own properties */ -function getOwnProperties(obj) { - if (typeof obj === 'object' && obj !== null) { - const extractedProps = {}; - for (const property in obj) { - if (Object.prototype.hasOwnProperty.call(obj, property)) { - extractedProps[property] = (obj )[property]; - } - } - return extractedProps; - } else { - return {}; - } -} - -/** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` - */ -function extractExceptionKeysForMessage(exception, maxLength = 40) { - const keys = Object.keys(convertToPlainObject(exception)); - keys.sort(); - - if (!keys.length) { - return '[object has no keys]'; - } - - if (keys[0].length >= maxLength) { - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(keys[0], maxLength); - } - - for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { - const serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; - } - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(serialized, maxLength); - } - - return ''; -} - -/** - * Given any object, return a new object having removed all fields whose value was `undefined`. - * Works recursively on objects and arrays. - * - * Attention: This function keeps circular references in the returned object. - */ -function dropUndefinedKeys(inputValue) { - // This map keeps track of what already visited nodes map to. - // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular - // references as the input object. - const memoizationMap = new Map(); - - // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API - return _dropUndefinedKeys(inputValue, memoizationMap); -} - -function _dropUndefinedKeys(inputValue, memoizationMap) { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(inputValue)) { - // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } - - const returnValue = {}; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); - - for (const key of Object.keys(inputValue)) { - if (typeof inputValue[key] !== 'undefined') { - returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); - } - } - - return returnValue ; - } - - if (Array.isArray(inputValue)) { - // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } - - const returnValue = []; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); - - inputValue.forEach((item) => { - returnValue.push(_dropUndefinedKeys(item, memoizationMap)); - }); - - return returnValue ; - } - - return inputValue; -} - -/** - * Ensure that something is an object. - * - * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper - * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. - * - * @param wat The subject of the objectification - * @returns A version of `wat` which can safely be used with `Object` class methods - */ -function objectify(wat) { - let objectified; - switch (true) { - case wat === undefined || wat === null: - objectified = new String(wat); - break; - - // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason - // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as - // an object in order to wrap it. - case typeof wat === 'symbol' || typeof wat === 'bigint': - objectified = Object(wat); - break; - - // this will catch the remaining primitives: `String`, `Number`, and `Boolean` - case (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPrimitive)(wat): - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - objectified = new (wat ).constructor(wat); - break; - - // by process of elimination, at this point we know that `wat` must already be an object - default: - objectified = wat; - break; - } - return objectified; -} - - -//# sourceMappingURL=object.js.map - - -/***/ }), -/* 1613 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getDomElement": () => (/* binding */ getDomElement), -/* harmony export */ "getLocationHref": () => (/* binding */ getLocationHref), -/* harmony export */ "htmlTreeAsString": () => (/* binding */ htmlTreeAsString) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - - -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - -/** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path - */ -function htmlTreeAsString(elem, keyAttrs) { - - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - let currentElem = elem ; - const MAX_TRAVERSE_HEIGHT = 5; - const MAX_OUTPUT_LEN = 80; - const out = []; - let height = 0; - let len = 0; - const separator = ' > '; - const sepLength = separator.length; - let nextStr; - - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem, keyAttrs); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } - - out.push(nextStr); - - len += nextStr.length; - currentElem = currentElem.parentNode; - } - - return out.reverse().join(separator); - } catch (_oO) { - return '<unknown>'; - } -} - -/** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path - */ -function _htmlElementAsString(el, keyAttrs) { - const elem = el - -; - - const out = []; - let className; - let classes; - let key; - let attr; - let i; - - if (!elem || !elem.tagName) { - return ''; - } - - out.push(elem.tagName.toLowerCase()); - - // Pairs of attribute keys defined in `serializeAttribute` and their values on element. - const keyAttrPairs = - keyAttrs && keyAttrs.length - ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) - : null; - - if (keyAttrPairs && keyAttrPairs.length) { - keyAttrPairs.forEach(keyAttrPair => { - out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); - }); - } else { - if (elem.id) { - out.push(`#${elem.id}`); - } - - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push(`.${classes[i]}`); - } - } - } - const allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push(`[${key}="${attr}"]`); - } - } - return out.join(''); -} - -/** - * A safe form of location.href - */ -function getLocationHref() { - try { - return WINDOW.document.location.href; - } catch (oO) { - return ''; - } -} - -/** - * Gets a DOM element by using document.querySelector. - * - * This wrapper will first check for the existance of the function before - * actually calling it so that we don't have to take care of this check, - * every time we want to access the DOM. - * - * Reason: DOM/querySelector is not available in all environments. - * - * We have to cast to any because utils can be consumed by a variety of environments, - * and we don't want to break TS users. If you know what element will be selected by - * `document.querySelector`, specify it as part of the generic call. For example, - * `const element = getDomElement<Element>('selector');` - * - * @param selector the selector string passed on to document.querySelector - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getDomElement(selector) { - if (WINDOW.document && WINDOW.document.querySelector) { - return WINDOW.document.querySelector(selector) ; - } - return null; -} - - -//# sourceMappingURL=browser.js.map - - -/***/ }), -/* 1614 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SyncPromise": () => (/* binding */ SyncPromise), -/* harmony export */ "rejectedSyncPromise": () => (/* binding */ rejectedSyncPromise), -/* harmony export */ "resolvedSyncPromise": () => (/* binding */ resolvedSyncPromise) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); - - -/* eslint-disable @typescript-eslint/explicit-function-return-type */ - -/** SyncPromise internal states */ -var States; (function (States) { - /** Pending */ - const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; - /** Resolved / OK */ - const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; - /** Rejected / Error */ - const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; -})(States || (States = {})); - -// Overloads so we can call resolvedSyncPromise without arguments and generic argument - -/** - * Creates a resolved sync promise. - * - * @param value the value to resolve the promise with - * @returns the resolved sync promise - */ -function resolvedSyncPromise(value) { - return new SyncPromise(resolve => { - resolve(value); - }); -} - -/** - * Creates a rejected sync promise. - * - * @param value the value to reject the promise with - * @returns the rejected sync promise - */ -function rejectedSyncPromise(reason) { - return new SyncPromise((_, reject) => { - reject(reason); - }); -} - -/** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally - */ -class SyncPromise { - __init() {this._state = States.PENDING;} - __init2() {this._handlers = [];} - - constructor( - executor, - ) {;SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this); - try { - executor(this._resolve, this._reject); - } catch (e) { - this._reject(e); - } - } - - /** JSDoc */ - then( - onfulfilled, - onrejected, - ) { - return new SyncPromise((resolve, reject) => { - this._handlers.push([ - false, - result => { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result ); - } else { - try { - resolve(onfulfilled(result)); - } catch (e) { - reject(e); - } - } - }, - reason => { - if (!onrejected) { - reject(reason); - } else { - try { - resolve(onrejected(reason)); - } catch (e) { - reject(e); - } - } - }, - ]); - this._executeHandlers(); - }); - } - - /** JSDoc */ - catch( - onrejected, - ) { - return this.then(val => val, onrejected); - } - - /** JSDoc */ - finally(onfinally) { - return new SyncPromise((resolve, reject) => { - let val; - let isRejected; - - return this.then( - value => { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, - reason => { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }, - ).then(() => { - if (isRejected) { - reject(val); - return; - } - - resolve(val ); - }); - }); - } - - /** JSDoc */ - __init3() {this._resolve = (value) => { - this._setResult(States.RESOLVED, value); - };} - - /** JSDoc */ - __init4() {this._reject = (reason) => { - this._setResult(States.REJECTED, reason); - };} - - /** JSDoc */ - __init5() {this._setResult = (state, value) => { - if (this._state !== States.PENDING) { - return; - } - - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isThenable)(value)) { - void (value ).then(this._resolve, this._reject); - return; - } - - this._state = state; - this._value = value; - - this._executeHandlers(); - };} - - /** JSDoc */ - __init6() {this._executeHandlers = () => { - if (this._state === States.PENDING) { - return; - } - - const cachedHandlers = this._handlers.slice(); - this._handlers = []; - - cachedHandlers.forEach(handler => { - if (handler[0]) { - return; - } - - if (this._state === States.RESOLVED) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler[1](this._value ); - } - - if (this._state === States.REJECTED) { - handler[2](this._value); - } - - handler[0] = true; - }); - };} -} - - -//# sourceMappingURL=syncpromise.js.map - - -/***/ }), -/* 1615 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CONSOLE_LEVELS": () => (/* binding */ CONSOLE_LEVELS), -/* harmony export */ "consoleSandbox": () => (/* binding */ consoleSandbox), -/* harmony export */ "logger": () => (/* binding */ logger) -/* harmony export */ }); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); - - -/** Prefix for logging strings */ -const PREFIX = 'Sentry Logger '; - -const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ; - -/** - * Temporarily disable sentry console instrumentations. - * - * @param callback The function to run against the original `console` messages - * @returns The results of the callback - */ -function consoleSandbox(callback) { - if (!('console' in _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ)) { - return callback(); - } - - const originalConsole = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console ; - const wrappedLevels = {}; - - // Restore all wrapped console methods - CONSOLE_LEVELS.forEach(level => { - // TODO(v7): Remove this check as it's only needed for Node 6 - const originalWrappedFunc = - originalConsole[level] && (originalConsole[level] ).__sentry_original__; - if (level in originalConsole && originalWrappedFunc) { - wrappedLevels[level] = originalConsole[level] ; - originalConsole[level] = originalWrappedFunc ; - } - }); - - try { - return callback(); - } finally { - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(level => { - originalConsole[level] = wrappedLevels[level ]; - }); - } -} - -function makeLogger() { - let enabled = false; - const logger = { - enable: () => { - enabled = true; - }, - disable: () => { - enabled = false; - }, - }; - - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - CONSOLE_LEVELS.forEach(name => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - logger[name] = (...args) => { - if (enabled) { - consoleSandbox(() => { - _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); - }); - } - }; - }); - } else { - CONSOLE_LEVELS.forEach(name => { - logger[name] = () => undefined; - }); - } - - return logger ; -} - -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -let logger; -if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - logger = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalSingleton)('logger', makeLogger); -} else { - logger = makeLogger(); -} - - -//# sourceMappingURL=logger.js.map - - -/***/ }), -/* 1616 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SDK_VERSION": () => (/* binding */ SDK_VERSION) -/* harmony export */ }); -const SDK_VERSION = '7.23.0'; - - -//# sourceMappingURL=version.js.map - - -/***/ }), -/* 1617 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addBreadcrumb": () => (/* binding */ addBreadcrumb), -/* harmony export */ "captureEvent": () => (/* binding */ captureEvent), -/* harmony export */ "captureException": () => (/* binding */ captureException), -/* harmony export */ "captureMessage": () => (/* binding */ captureMessage), -/* harmony export */ "configureScope": () => (/* binding */ configureScope), -/* harmony export */ "setContext": () => (/* binding */ setContext), -/* harmony export */ "setExtra": () => (/* binding */ setExtra), -/* harmony export */ "setExtras": () => (/* binding */ setExtras), -/* harmony export */ "setTag": () => (/* binding */ setTag), -/* harmony export */ "setTags": () => (/* binding */ setTags), -/* harmony export */ "setUser": () => (/* binding */ setUser), -/* harmony export */ "startTransaction": () => (/* binding */ startTransaction), -/* harmony export */ "withScope": () => (/* binding */ withScope) -/* harmony export */ }); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); - - -// Note: All functions in this file are typed with a return value of `ReturnType<Hub[HUB_FUNCTION]>`, -// where HUB_FUNCTION is some method on the Hub class. -// -// This is done to make sure the top level SDK methods stay in sync with the hub methods. -// Although every method here has an explicit return type, some of them (that map to void returns) do not -// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable. - -/** - * Captures an exception event and sends it to Sentry. - * - * @param exception An exception-like object. - * @param captureContext Additional scope data to apply to exception event. - * @returns The generated eventId. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureException(exception, { captureContext }); -} - -/** - * Captures a message event and sends it to Sentry. - * - * @param message The message to send to Sentry. - * @param Severity Define the level of the message. - * @returns The generated eventId. - */ -function captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - captureContext, -) { - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - const level = typeof captureContext === 'string' ? captureContext : undefined; - const context = typeof captureContext !== 'string' ? { captureContext } : undefined; - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureMessage(message, level, context); -} - -/** - * 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, hint) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureEvent(event, hint); -} - -/** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. - */ -function configureScope(callback) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().configureScope(callback); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().addBreadcrumb(breadcrumb); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setContext(name, context); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtras(extras); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtra(key, extra); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTags(tags); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTag(key, value); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setUser(user); -} - -/** - * 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) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().withScope(callback); -} - -/** - * 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. - * - * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call - * `startTransaction` directly on the hub. - * - * @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 (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().startTransaction({ ...context }, customSamplingContext); -} - - -//# sourceMappingURL=exports.js.map - - -/***/ }), -/* 1618 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_TRANSPORT_BUFFER_SIZE": () => (/* binding */ DEFAULT_TRANSPORT_BUFFER_SIZE), -/* harmony export */ "createTransport": () => (/* binding */ createTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1619); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1621); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1626); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1620); - - -const DEFAULT_TRANSPORT_BUFFER_SIZE = 30; - -/** - * Creates an instance of a Sentry `Transport` - * - * @param options - * @param makeRequest - */ -function createTransport( - options, - makeRequest, - buffer = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makePromiseBuffer)(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE), -) { - let rateLimits = {}; - - const flush = (timeout) => buffer.drain(timeout); - - function send(envelope) { - const filteredEnvelopeItems = []; - - // Drop rate limited items from envelope - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(envelope, (item, type) => { - const envelopeItemDataCategory = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type); - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.isRateLimited)(rateLimits, envelopeItemDataCategory)) { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event); - } else { - filteredEnvelopeItems.push(item); - } - }); - - // Skip sending if envelope is empty after filtering out rate limited events - if (filteredEnvelopeItems.length === 0) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const filteredEnvelope = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelope[0], filteredEnvelopeItems ); - - // Creates client report for each item in an envelope - const recordEnvelopeLoss = (reason) => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(filteredEnvelope, (item, type) => { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent(reason, (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type), event); - }); - }; - - const requestTask = () => - makeRequest({ body: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.serializeEnvelope)(filteredEnvelope, options.textEncoder) }).then( - response => { - // We don't want to throw on NOK responses, but we want to at least log them - if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); - } - - rateLimits = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.updateRateLimits)(rateLimits, response); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Failed while sending event:', error); - recordEnvelopeLoss('network_error'); - }, - ); - - return buffer.add(requestTask).then( - result => result, - error => { - if (error instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SentryError) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Skipped sending event because buffer is full.'); - recordEnvelopeLoss('queue_overflow'); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } else { - throw error; - } - }, - ); - } - - return { - send, - flush, - }; -} - -function getEventForEnvelopeItem(item, type) { - if (type !== 'event' && type !== 'transaction') { - return undefined; - } - - return Array.isArray(item) ? (item )[1] : undefined; -} - - -//# sourceMappingURL=base.js.map - - -/***/ }), -/* 1619 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makePromiseBuffer": () => (/* binding */ makePromiseBuffer) -/* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1620); -/* harmony import */ var _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); - - - -/** - * Creates an new PromiseBuffer object with the specified limit - * @param limit max number of promises that can be stored in the buffer - */ -function makePromiseBuffer(limit) { - const buffer = []; - - function isReady() { - return limit === undefined || buffer.length < limit; - } - - /** - * Remove a promise from the queue. - * - * @param task Can be any PromiseLike<T> - * @returns Removed promise. - */ - function remove(task) { - return buffer.splice(buffer.indexOf(task), 1)[0]; - } - - /** - * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. - * - * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: - * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor - * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By - * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer - * limit check. - * @returns The original promise. - */ - function add(taskProducer) { - if (!isReady()) { - return (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.rejectedSyncPromise)(new _error_js__WEBPACK_IMPORTED_MODULE_1__.SentryError('Not adding Promise because buffer limit was reached.')); - } - - // start the task and add its promise to the queue - const task = taskProducer(); - if (buffer.indexOf(task) === -1) { - buffer.push(task); - } - void task - .then(() => remove(task)) - // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` - // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't - // have promises, so TS has to polyfill when down-compiling.) - .then(null, () => - remove(task).then(null, () => { - // We have to add another catch here because `remove()` starts a new promise chain. - }), - ); - return task; - } - - /** - * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or - * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to - * `true`. - * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and - * `false` otherwise - */ - function drain(timeout) { - return new _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.SyncPromise((resolve, reject) => { - let counter = buffer.length; - - if (!counter) { - return resolve(true); - } - - // wait for `timeout` ms and then resolve to `false` (if not cancelled first) - const capturedSetTimeout = setTimeout(() => { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); - - // if all promises resolve in time, cancel the timer and resolve to `true` - buffer.forEach(item => { - void (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.resolvedSyncPromise)(item).then(() => { - if (!--counter) { - clearTimeout(capturedSetTimeout); - resolve(true); - } - }, reject); - }); - }); - } - - return { - $: buffer, - add, - drain, - }; -} - - -//# sourceMappingURL=promisebuffer.js.map - - -/***/ }), -/* 1620 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SentryError": () => (/* binding */ SentryError) -/* harmony export */ }); -/** An error emitted by Sentry SDKs and related utilities. */ -class SentryError extends Error { - /** Display name of this error instance. */ - - constructor( message, logLevel = 'warn') { - super(message);this.message = message;; - - this.name = new.target.prototype.constructor.name; - // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line - // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes - // instances of `SentryError` fail `obj instanceof SentryError` checks. - Object.setPrototypeOf(this, new.target.prototype); - this.logLevel = logLevel; - } -} - - -//# sourceMappingURL=error.js.map - - -/***/ }), -/* 1621 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addItemToEnvelope": () => (/* binding */ addItemToEnvelope), -/* harmony export */ "createAttachmentEnvelopeItem": () => (/* binding */ createAttachmentEnvelopeItem), -/* harmony export */ "createEnvelope": () => (/* binding */ createEnvelope), -/* harmony export */ "envelopeItemTypeToDataCategory": () => (/* binding */ envelopeItemTypeToDataCategory), -/* harmony export */ "forEachEnvelopeItem": () => (/* binding */ forEachEnvelopeItem), -/* harmony export */ "serializeEnvelope": () => (/* binding */ serializeEnvelope) -/* harmony export */ }); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1622); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); - - - -/** - * Creates an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. - */ -function createEnvelope(headers, items = []) { - return [headers, items] ; -} - -/** - * Add an item to an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. - */ -function addItemToEnvelope(envelope, newItem) { - const [headers, items] = envelope; - return [headers, [...items, newItem]] ; -} - -/** - * Convenience function to loop through the items and item types of an envelope. - * (This function was mostly created because working with envelope types is painful at the moment) - */ -function forEachEnvelopeItem( - envelope, - callback, -) { - const envelopeItems = envelope[1]; - envelopeItems.forEach((envelopeItem) => { - const envelopeItemType = envelopeItem[0].type; - callback(envelopeItem, envelopeItemType); - }); -} - -function encodeUTF8(input, textEncoder) { - const utf8 = textEncoder || new TextEncoder(); - return utf8.encode(input); -} - -/** - * Serializes an envelope. - */ -function serializeEnvelope(envelope, textEncoder) { - const [envHeaders, items] = envelope; - - // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data - let parts = JSON.stringify(envHeaders); - - function append(next) { - if (typeof parts === 'string') { - parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; - } else { - parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); - } - } - - for (const item of items) { - const [itemHeaders, payload] = item; - - append(`\n${JSON.stringify(itemHeaders)}\n`); - - if (typeof payload === 'string' || payload instanceof Uint8Array) { - append(payload); - } else { - let stringifiedPayload; - try { - stringifiedPayload = JSON.stringify(payload); - } catch (e) { - // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still - // fails, we try again after normalizing it again with infinite normalization depth. This of course has a - // performance impact but in this case a performance hit is better than throwing. - stringifiedPayload = JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_0__.normalize)(payload)); - } - append(stringifiedPayload); - } - } - - return typeof parts === 'string' ? parts : concatBuffers(parts); -} - -function concatBuffers(buffers) { - const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); - - const merged = new Uint8Array(totalLength); - let offset = 0; - for (const buffer of buffers) { - merged.set(buffer, offset); - offset += buffer.length; - } - - return merged; -} - -/** - * Creates attachment envelope items - */ -function createAttachmentEnvelopeItem( - attachment, - textEncoder, -) { - const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; - - return [ - (0,_object_js__WEBPACK_IMPORTED_MODULE_1__.dropUndefinedKeys)({ - type: 'attachment', - length: buffer.length, - filename: attachment.filename, - content_type: attachment.contentType, - attachment_type: attachment.attachmentType, - }), - buffer, - ]; -} - -const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { - session: 'session', - sessions: 'session', - attachment: 'attachment', - transaction: 'transaction', - event: 'error', - client_report: 'internal', - user_report: 'default', -}; - -/** - * Maps the type of an envelope item to a data category. - */ -function envelopeItemTypeToDataCategory(type) { - return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; -} - - -//# sourceMappingURL=envelope.js.map - - -/***/ }), -/* 1622 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "normalize": () => (/* binding */ normalize), -/* harmony export */ "normalizeToSize": () => (/* binding */ normalizeToSize), -/* harmony export */ "walk": () => (/* binding */ visit) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _memo_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1623); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); -/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1624); - - - - - -/** - * Recursively normalizes the given object. - * - * - Creates a copy to prevent original input mutation - * - Skips non-enumerable properties - * - When stringifying, calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format - * - Translates known global objects/classes to a string representations - * - Takes care of `Error` object serialization - * - Optionally limits depth of final output - * - Optionally limits number of properties/elements included in any single object/array - * - * @param input The object to be normalized. - * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) - * @param maxProperties The max number of elements or properties to be included in any single array or - * object in the normallized output. - * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function normalize(input, depth = +Infinity, maxProperties = +Infinity) { - try { - // since we're at the outermost level, we don't provide a key - return visit('', input, depth, maxProperties); - } catch (err) { - return { ERROR: `**non-serializable** (${err})` }; - } -} - -/** JSDoc */ -function normalizeToSize( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object, - // Default Node.js REPL depth - depth = 3, - // 100kB, as 200kB is max payload size, so half sounds reasonable - maxSize = 100 * 1024, -) { - const normalized = normalize(object, depth); - - if (jsonSize(normalized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } - - return normalized ; -} - -/** - * Visits a node to perform normalization on it - * - * @param key The key corresponding to the given node - * @param value The node to be visited - * @param depth Optional number indicating the maximum recursion depth - * @param maxProperties Optional maximum number of properties/elements included in any single object/array - * @param memo Optional Memo class handling decycling - */ -function visit( - key, - value, - depth = +Infinity, - maxProperties = +Infinity, - memo = (0,_memo_js__WEBPACK_IMPORTED_MODULE_0__.memoBuilder)(), -) { - const [memoize, unmemoize] = memo; - - // Get the simple cases out of the way first - if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isNaN)(value))) { - return value ; - } - - const stringified = stringifyValue(key, value); - - // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. - // Everything else will have already been serialized, so if we don't see that pattern, we're done. - if (!stringified.startsWith('[object ')) { - return stringified; - } - - // From here on, we can assert that `value` is either an object or an array. - - // Do not normalize objects that we know have already been normalized. As a general rule, the - // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that - // have already been normalized. - if ((value )['__sentry_skip_normalization__']) { - return value ; - } - - // We're also done if we've reached the max depth - if (depth === 0) { - // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. - return stringified.replace('object ', ''); - } - - // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. - if (memoize(value)) { - return '[Circular ~]'; - } - - // If the value has a `toJSON` method, we call it to extract more information - const valueWithToJSON = value ; - if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { - try { - const jsonValue = valueWithToJSON.toJSON(); - // We need to normalize the return value of `.toJSON()` in case it has circular references - return visit('', jsonValue, depth - 1, maxProperties, memo); - } catch (err) { - // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) - } - } - - // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse - // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each - // property/entry, and keep track of the number of items we add to it. - const normalized = (Array.isArray(value) ? [] : {}) ; - let numAdded = 0; - - // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant - // properties are non-enumerable and otherwise would get missed. - const visitable = (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.convertToPlainObject)(value ); - - for (const visitKey in visitable) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { - continue; - } - - if (numAdded >= maxProperties) { - normalized[visitKey] = '[MaxProperties ~]'; - break; - } - - // Recursively visit all the child nodes - const visitValue = visitable[visitKey]; - normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo); - - numAdded++; - } - - // Once we've visited all the branches, remove the parent from memo storage - unmemoize(value); - - // Return accumulated values - return normalized; -} - -/** - * Stringify the given value. Handles various known special values and types. - * - * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn - * the number 1231 into "[Object Number]", nor on `null`, as it will throw. - * - * @param value The value to stringify - * @returns A stringified representation of the given value - */ -function stringifyValue( - key, - // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for - // our internal use, it'll do - value, -) { - try { - if (key === 'domain' && value && typeof value === 'object' && (value )._events) { - return '[Domain]'; - } - - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } - - // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first - // which won't throw if they are not present. - - if (typeof global !== 'undefined' && value === global) { - return '[Global]'; - } - - // eslint-disable-next-line no-restricted-globals - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - - // eslint-disable-next-line no-restricted-globals - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } - - // React's SyntheticEvent thingy - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isSyntheticEvent)(value)) { - return '[SyntheticEvent]'; - } - - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } - - // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own) - if (value === void 0) { - return '[undefined]'; - } - - if (typeof value === 'function') { - return `[Function: ${(0,_stacktrace_js__WEBPACK_IMPORTED_MODULE_3__.getFunctionName)(value)}]`; - } - - if (typeof value === 'symbol') { - return `[${String(value)}]`; - } - - // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion - if (typeof value === 'bigint') { - return `[BigInt: ${String(value)}]`; - } - - // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting - // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as - // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), - // we can make sure that only plain objects come out that way. - return `[object ${(Object.getPrototypeOf(value) ).constructor.name}]`; - } catch (err) { - return `**non-serializable** (${err})`; - } -} - -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; -} - -/** Calculates bytes size of input object */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); -} - - -//# sourceMappingURL=normalize.js.map - - -/***/ }), -/* 1623 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "memoBuilder": () => (/* binding */ memoBuilder) -/* harmony export */ }); -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ - -/** - * Helper to decycle json objects - */ -function memoBuilder() { - const hasWeakSet = typeof WeakSet === 'function'; - const inner = hasWeakSet ? new WeakSet() : []; - function memoize(obj) { - if (hasWeakSet) { - if (inner.has(obj)) { - return true; - } - inner.add(obj); - return false; - } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < inner.length; i++) { - const value = inner[i]; - if (value === obj) { - return true; - } - } - inner.push(obj); - return false; - } - - function unmemoize(obj) { - if (hasWeakSet) { - inner.delete(obj); - } else { - for (let i = 0; i < inner.length; i++) { - if (inner[i] === obj) { - inner.splice(i, 1); - break; - } - } - } - } - return [memoize, unmemoize]; -} - - -//# sourceMappingURL=memo.js.map - - -/***/ }), -/* 1624 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createStackParser": () => (/* binding */ createStackParser), -/* harmony export */ "getFunctionName": () => (/* binding */ getFunctionName), -/* harmony export */ "nodeStackLineParser": () => (/* binding */ nodeStackLineParser), -/* harmony export */ "stackParserFromStackParserOptions": () => (/* binding */ stackParserFromStackParserOptions), -/* harmony export */ "stripSentryFramesAndReverse": () => (/* binding */ stripSentryFramesAndReverse) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1625); - - -const STACKTRACE_LIMIT = 50; - -/** - * Creates a stack parser with the supplied line parsers - * - * StackFrames are returned in the correct order for Sentry Exception - * frames and with Sentry SDK internal frames removed from the top and bottom - * - */ -function createStackParser(...parsers) { - const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); - - return (stack, skipFirst = 0) => { - const frames = []; - - for (const line of stack.split('\n').slice(skipFirst)) { - // https://github.com/getsentry/sentry-javascript/issues/5459 - // Remove webpack (error: *) wrappers - const cleanedLine = line.replace(/\(error: (.*)\)/, '$1'); - - for (const parser of sortedParsers) { - const frame = parser(cleanedLine); - - if (frame) { - frames.push(frame); - break; - } - } - } - - return stripSentryFramesAndReverse(frames); - }; -} - -/** - * Gets a stack parser implementation from Options.stackParser - * @see Options - * - * If options contains an array of line parsers, it is converted into a parser - */ -function stackParserFromStackParserOptions(stackParser) { - if (Array.isArray(stackParser)) { - return createStackParser(...stackParser); - } - return stackParser; -} - -/** - * @hidden - */ -function stripSentryFramesAndReverse(stack) { - if (!stack.length) { - return []; - } - - let localStack = stack; - - const firstFrameFunction = localStack[0].function || ''; - const lastFrameFunction = localStack[localStack.length - 1].function || ''; - - // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); - } - - // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) - if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { - localStack = localStack.slice(0, -1); - } - - // The frame where the crash happened, should be the last entry in the array - return localStack - .slice(0, STACKTRACE_LIMIT) - .map(frame => ({ - ...frame, - filename: frame.filename || localStack[0].filename, - function: frame.function || '?', - })) - .reverse(); -} - -const defaultFunctionName = '<anonymous>'; - -/** - * Safely extract function name from itself - */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } -} - -// eslint-disable-next-line complexity -function node(getModule) { - const FILENAME_MATCH = /^\s*[-]{4,}$/; - const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; - - // eslint-disable-next-line complexity - return (line) => { - if (line.match(FILENAME_MATCH)) { - return { - filename: line, - }; - } - - const lineMatch = line.match(FULL_MATCH); - if (!lineMatch) { - return undefined; - } - - let object; - let method; - let functionName; - let typeName; - let methodName; - - if (lineMatch[1]) { - functionName = lineMatch[1]; - - let methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') { - methodStart--; - } - - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - const objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } - } - typeName = undefined; - } - - if (method) { - typeName = object; - methodName = method; - } - - if (method === '<anonymous>') { - methodName = undefined; - functionName = undefined; - } - - if (functionName === undefined) { - methodName = methodName || '<anonymous>'; - functionName = typeName ? `${typeName}.${methodName}` : methodName; - } - - const filename = (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([lineMatch, 'access', _ => _[2], 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3('file://')]) ? lineMatch[2].substr(7) : lineMatch[2]; - const isNative = lineMatch[5] === 'native'; - const isInternal = - isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1); - - // in_app is all that's not an internal Node function or a module within node_modules - // note that isNative appears to return true even for node core libraries - // see https://github.com/getsentry/raven-node/issues/176 - const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/'); - - return { - filename, - module: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([getModule, 'optionalCall', _4 => _4(filename)]), - function: functionName, - lineno: parseInt(lineMatch[3], 10) || undefined, - colno: parseInt(lineMatch[4], 10) || undefined, - in_app, - }; - }; -} - -/** - * Node.js stack line parser - * - * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. - * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain - */ -function nodeStackLineParser(getModule) { - return [90, node(getModule)]; -} - - -//# sourceMappingURL=stacktrace.js.map - - -/***/ }), -/* 1625 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_optionalChain": () => (/* binding */ _optionalChain) -/* harmony export */ }); -/** - * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, - * descriptors, and functions. - * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) - * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 - * - * @param ops Array result of expression conversion - * @returns The value of the expression - */ -function _optionalChain(ops) { - let lastAccessLHS = undefined; - let value = ops[0]; - let i = 1; - while (i < ops.length) { - const op = ops[i] ; - const fn = ops[i + 1] ; - i += 2; - // by checking for loose equality to `null`, we catch both `null` and `undefined` - if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { - // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it - return; - } - if (op === 'access' || op === 'optionalAccess') { - lastAccessLHS = value; - value = fn(value); - } else if (op === 'call' || op === 'optionalCall') { - value = fn((...args) => (value ).call(lastAccessLHS, ...args)); - lastAccessLHS = undefined; - } - } - return value; -} - -// Sucrase version -// function _optionalChain(ops) { -// let lastAccessLHS = undefined; -// let value = ops[0]; -// let i = 1; -// while (i < ops.length) { -// const op = ops[i]; -// const fn = ops[i + 1]; -// i += 2; -// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { -// return undefined; -// } -// if (op === 'access' || op === 'optionalAccess') { -// lastAccessLHS = value; -// value = fn(value); -// } else if (op === 'call' || op === 'optionalCall') { -// value = fn((...args) => value.call(lastAccessLHS, ...args)); -// lastAccessLHS = undefined; -// } -// } -// return value; -// } - - -//# sourceMappingURL=_optionalChain.js.map - - -/***/ }), -/* 1626 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_RETRY_AFTER": () => (/* binding */ DEFAULT_RETRY_AFTER), -/* harmony export */ "disabledUntil": () => (/* binding */ disabledUntil), -/* harmony export */ "isRateLimited": () => (/* binding */ isRateLimited), -/* harmony export */ "parseRetryAfterHeader": () => (/* binding */ parseRetryAfterHeader), -/* harmony export */ "updateRateLimits": () => (/* binding */ updateRateLimits) -/* harmony export */ }); -// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend - -const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds - -/** - * Extracts Retry-After value from the request header or returns default value - * @param header string representation of 'Retry-After' header - * @param now current unix timestamp - * - */ -function parseRetryAfterHeader(header, now = Date.now()) { - const headerDelay = parseInt(`${header}`, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; - } - - const headerDate = Date.parse(`${header}`); - if (!isNaN(headerDate)) { - return headerDate - now; - } - - return DEFAULT_RETRY_AFTER; -} - -/** - * Gets the time that given category is disabled until for rate limiting - */ -function disabledUntil(limits, category) { - return limits[category] || limits.all || 0; -} - -/** - * Checks if a category is rate limited - */ -function isRateLimited(limits, category, now = Date.now()) { - return disabledUntil(limits, category) > now; -} - -/** - * Update ratelimits from incoming headers. - * Returns true if headers contains a non-empty rate limiting header. - */ -function updateRateLimits( - limits, - { statusCode, headers }, - now = Date.now(), -) { - const updatedRateLimits = { - ...limits, - }; - - // "The name is case-insensitive." - // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get - const rateLimitHeader = headers && headers['x-sentry-rate-limits']; - const retryAfterHeader = headers && headers['retry-after']; - - if (rateLimitHeader) { - /** - * rate limit headers are of the form - * <header>,<header>,.. - * where each <header> is of the form - * <retry_after>: <categories>: <scope>: <reason_code> - * where - * <retry_after> is a delay in seconds - * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form - * <category>;<category>;... - * <scope> is what's being limited (org, project, or key) - ignored by SDK - * <reason_code> is an arbitrary string like "org_quota" - ignored by SDK - */ - for (const limit of rateLimitHeader.trim().split(',')) { - const [retryAfter, categories] = limit.split(':', 2); - const headerDelay = parseInt(retryAfter, 10); - const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - if (!categories) { - updatedRateLimits.all = now + delay; - } else { - for (const category of categories.split(';')) { - updatedRateLimits[category] = now + delay; - } - } - } - } else if (retryAfterHeader) { - updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); - } else if (statusCode === 429) { - updatedRateLimits.all = now + 60 * 1000; - } - - return updatedRateLimits; -} - - -//# sourceMappingURL=ratelimit.js.map - - -/***/ }), -/* 1627 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "NodeClient": () => (/* binding */ NodeClient) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1629); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1616); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1634); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1614); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1628); - - - - - - - -/** - * The Sentry Node SDK Client. - * - * @see NodeClientOptions for documentation on configuration options. - * @see SentryClient for usage documentation. - */ -class NodeClient extends _sentry_core__WEBPACK_IMPORTED_MODULE_3__.BaseClient { - - /** - * Creates a new Node SDK instance. - * @param options Configuration options for this SDK. - */ - constructor(options) { - options._metadata = options._metadata || {}; - options._metadata.sdk = options._metadata.sdk || { - name: 'sentry.javascript.node', - packages: [ - { - name: 'npm:@sentry/node', - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }, - ], - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }; - - // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util - options.transportOptions = { - textEncoder: new util__WEBPACK_IMPORTED_MODULE_1__.TextEncoder(), - ...options.transportOptions, - }; - - super(options); - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const requestSession = scope.getRequestSession(); - - // Necessary checks to ensure this is code block is executed only within a request - // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - - return super.captureException(exception, hint, scope); - } - - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const eventType = event.type || 'exception'; - const isException = - eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; - - // If the event is of type Exception, then a request session should be captured - if (isException) { - const requestSession = scope.getRequestSession(); - - // Ensure that this is happening within the bounds of a request, and make sure not to override - // Session Status if Errored / Crashed - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - } - - return super.captureEvent(event, hint, scope); - } - - /** - * - * @inheritdoc - */ - close(timeout) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([this, 'access', _ => _._sessionFlusher, 'optionalAccess', _2 => _2.close, 'call', _3 => _3()]); - return super.close(timeout); - } - - /** Method that initialises an instance of SessionFlusher on Client */ - initSessionFlusher() { - const { release, environment } = this._options; - if (!release) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); - } else { - this._sessionFlusher = new _sentry_core__WEBPACK_IMPORTED_MODULE_7__.SessionFlusher(this, { - release, - environment, - }); - } - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - eventFromException(exception, hint) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)((0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromUnknownInput)(this._options.stackParser, exception, hint)); - } - - /** - * @inheritDoc - */ - eventFromMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - ) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)( - (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromMessage)(this._options.stackParser, message, level, hint, this._options.attachStacktrace), - ); - } - - /** - * @inheritDoc - */ - _prepareEvent(event, hint, scope) { - event.platform = event.platform || 'node'; - event.contexts = { - ...event.contexts, - runtime: (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _4 => _4.contexts, 'optionalAccess', _5 => _5.runtime]) || { - name: 'node', - version: global.process.version, - }, - }; - event.server_name = - event.server_name || this.getOptions().serverName || global.process.env.SENTRY_NAME || os__WEBPACK_IMPORTED_MODULE_0__.hostname(); - return super._prepareEvent(event, hint, scope); - } - - /** - * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment - * appropriate session aggregates bucket - */ - _captureRequestSession() { - if (!this._sessionFlusher) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); - } else { - this._sessionFlusher.incrementSessionStatusCount(); - } - } -} - - -//# sourceMappingURL=client.js.map - - -/***/ }), -/* 1628 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "eventFromMessage": () => (/* binding */ eventFromMessage), -/* harmony export */ "eventFromUnknownInput": () => (/* binding */ eventFromUnknownInput), -/* harmony export */ "exceptionFromError": () => (/* binding */ exceptionFromError), -/* harmony export */ "parseStackFrames": () => (/* binding */ parseStackFrames) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1622); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1609); - - - -/** - * Extracts stack frames from the error.stack string - */ -function parseStackFrames(stackParser, error) { - return stackParser(error.stack || '', 1); -} - -/** - * Extracts stack frames from the error and builds a Sentry Exception - */ -function exceptionFromError(stackParser, error) { - const exception = { - type: error.name || error.constructor.name, - value: error.message, - }; - - const frames = parseStackFrames(stackParser, error); - if (frames.length) { - exception.stacktrace = { frames }; - } - - return exception; -} - -/** - * Builds and Event from a Exception - * @hidden - */ -function eventFromUnknownInput(stackParser, exception, hint) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let ex = exception; - const providedMechanism = - hint && hint.data && (hint.data ).mechanism; - const mechanism = providedMechanism || { - handled: true, - type: 'generic', - }; - - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isError)(exception)) { - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.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 - const message = `Non-Error exception captured with keys: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractExceptionKeysForMessage)(exception)}`; - - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)(); - const client = hub.getClient(); - const normalizeDepth = client && client.getOptions().normalizeDepth; - hub.configureScope(scope => { - scope.setExtra('__serialized__', (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.normalizeToSize)(exception, normalizeDepth)); - }); - - 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; - } - - const event = { - exception: { - values: [exceptionFromError(stackParser, ex )], - }, - }; - - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionTypeValue)(event, undefined, undefined); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionMechanism)(event, mechanism); - - return { - ...event, - event_id: hint && hint.event_id, - }; -} - -/** - * Builds and Event from a Message - * @hidden - */ -function eventFromMessage( - stackParser, - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - attachStacktrace, -) { - const event = { - event_id: hint && hint.event_id, - level, - message, - }; - - if (attachStacktrace && hint && hint.syntheticException) { - const frames = parseStackFrames(stackParser, hint.syntheticException); - if (frames.length) { - event.exception = { - values: [ - { - value: message, - stacktrace: { frames }, - }, - ], - }; - } - } - - return event; -} - - -//# sourceMappingURL=eventbuilder.js.map - - -/***/ }), -/* 1629 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BaseClient": () => (/* binding */ BaseClient) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1630); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1614); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1621); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1605); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1622); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1610); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1620); -/* harmony import */ var _api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1631); -/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1633); -/* harmony import */ var _integration_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1632); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1603); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1604); - - - - - - - -const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; - -/** - * Base implementation for all JavaScript SDK clients. - * - * Call the constructor with the corresponding options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. - * - * 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, 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<NodeOptions> { - * public constructor(options: NodeOptions) { - * super(options); - * } - * - * // ... - * } - */ -class BaseClient { - /** Options passed to the SDK. */ - - /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ - - /** Array of set up integrations. */ - __init() {this._integrations = {};} - - /** Indicates whether this client's integrations have been set up. */ - __init2() {this._integrationsInitialized = false;} - - /** Number of calls being processed */ - __init3() {this._numProcessing = 0;} - - /** Holds flushable */ - __init4() {this._outcomes = {};} - - /** - * Initializes this client instance. - * - * @param options Options for the client. - */ - constructor(options) {;BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this); - this._options = options; - if (options.dsn) { - this._dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makeDsn)(options.dsn); - const url = (0,_api_js__WEBPACK_IMPORTED_MODULE_1__.getEnvelopeEndpointWithUrlEncodedAuth)(this._dsn, options); - this._transport = options.transport({ - recordDroppedEvent: this.recordDroppedEvent.bind(this), - ...options.transportOptions, - url, - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('No DSN provided, client will not do anything.'); - } - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // ensure we haven't captured this very object before - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(exception)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; - } - - let eventId; - this._process( - this.eventFromException(exception, hint) - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); - - return eventId; - } - - /** - * @inheritDoc - */ - captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level, - hint, - scope, - ) { - let eventId; - - const promisedEvent = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPrimitive)(message) - ? this.eventFromMessage(String(message), level, hint) - : this.eventFromException(message, hint); - - this._process( - promisedEvent - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); - - return eventId; - } - - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // ensure we haven't captured this very object before - if (hint && hint.originalException && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(hint.originalException)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; - } - - let eventId; - - this._process( - this._captureEvent(event, hint, scope).then(result => { - eventId = result; - }), - ); - - return eventId; - } - - /** - * @inheritDoc - */ - captureSession(session) { - if (!this._isEnabled()) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('SDK not enabled, will not capture session.'); - return; - } - - if (!(typeof session.release === 'string')) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('Discarded session because of missing or non-string release'); - } else { - this.sendSession(session); - // After sending, we set init false to indicate it's not the first occurrence - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { init: false }); - } - } - - /** - * @inheritDoc - */ - getDsn() { - return this._dsn; - } - - /** - * @inheritDoc - */ - getOptions() { - return this._options; - } - - /** - * @inheritDoc - */ - getTransport() { - return this._transport; - } - - /** - * @inheritDoc - */ - flush(timeout) { - const transport = this._transport; - if (transport) { - return this._isClientDoneProcessing(timeout).then(clientFinished => { - return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); - }); - } else { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(true); - } - } - - /** - * @inheritDoc - */ - close(timeout) { - return this.flush(timeout).then(result => { - this.getOptions().enabled = false; - return result; - }); - } - - /** - * Sets up the integrations - */ - setupIntegrations() { - if (this._isEnabled() && !this._integrationsInitialized) { - this._integrations = (0,_integration_js__WEBPACK_IMPORTED_MODULE_7__.setupIntegrations)(this._options.integrations); - this._integrationsInitialized = true; - } - } - - /** - * Gets an installed integration by its `id`. - * - * @returns The installed integration or `undefined` if no integration with that `id` was installed. - */ - getIntegrationById(integrationId) { - return this._integrations[integrationId]; - } - - /** - * @inheritDoc - */ - getIntegration(integration) { - try { - return (this._integrations[integration.id] ) || null; - } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); - return null; - } - } - - /** - * @inheritDoc - */ - sendEvent(event, hint = {}) { - if (this._dsn) { - let env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createEventEnvelope)(event, this._dsn, this._options._metadata, this._options.tunnel); - - for (const attachment of hint.attachments || []) { - env = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.addItemToEnvelope)( - env, - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.createAttachmentEnvelopeItem)( - attachment, - this._options.transportOptions && this._options.transportOptions.textEncoder, - ), - ); - } - - this._sendEnvelope(env); - } - } - - /** - * @inheritDoc - */ - sendSession(session) { - if (this._dsn) { - const env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createSessionEnvelope)(session, this._dsn, this._options._metadata, this._options.tunnel); - this._sendEnvelope(env); - } - } - - /** - * @inheritDoc - */ - recordDroppedEvent(reason, category, _event) { - // Note: we use `event` in replay, where we overwrite this hook. - - if (this._options.sendClientReports) { - // We want to track each category (error, transaction, session) separately - // but still keep the distinction between different type of outcomes. - // We could use nested maps, but it's much easier to read and type this way. - // A correct type for map-based implementation if we want to go that route - // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>` - // With typescript 4.1 we could even use template literal types - const key = `${reason}:${category}`; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(`Adding outcome: "${key}"`); - - // The following works because undefined + 1 === NaN and NaN is falsy - this._outcomes[key] = this._outcomes[key] + 1 || 1; - } - } - - /** Updates existing session based on the provided event */ - _updateSessionFromEvent(session, event) { - let crashed = false; - let errored = false; - const exceptions = event.exception && event.exception.values; - - if (exceptions) { - errored = true; - - for (const ex of exceptions) { - const mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } - } - } - - // A session is updated and that session update is sent in only one of the two following scenarios: - // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update - // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update - const sessionNonTerminal = session.status === 'ok'; - const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); - - if (shouldUpdateAndSend) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { - ...(crashed && { status: 'crashed' }), - errors: session.errors || Number(errored || crashed), - }); - this.captureSession(session); - } - } - - /** - * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying - * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not - * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to - * `true`. - * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and - * `false` otherwise - */ - _isClientDoneProcessing(timeout) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.SyncPromise(resolve => { - let ticked = 0; - const tick = 1; - - const interval = setInterval(() => { - if (this._numProcessing == 0) { - clearInterval(interval); - resolve(true); - } else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); - } - } - }, tick); - }); - } - - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - _isEnabled() { - 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. - */ - _prepareEvent(event, hint, scope) { - const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = this.getOptions(); - const prepared = { - ...event, - event_id: event.event_id || hint.event_id || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.uuid4)(), - timestamp: event.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.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. - let finalScope = scope; - if (hint.captureContext) { - finalScope = _scope_js__WEBPACK_IMPORTED_MODULE_11__.Scope.clone(finalScope).update(hint.captureContext); - } - - // We prepare the result here with a resolved Event. - let result = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(prepared); - - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - // - // We need to check for the existence of `finalScope.getAttachments` - // because `getAttachments` can be undefined if users are using an older version - // of `@sentry/core` that does not have the `getAttachments` method. - // See: https://github.com/getsentry/sentry-javascript/issues/5229 - if (finalScope && finalScope.getAttachments) { - // Collect attachments from the hint and scope - const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()]; - - if (attachments.length) { - hint.attachments = attachments; - } - - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); - } - - return result.then(evt => { - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); - } - 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 - */ - _normalizeEvent(event, depth, maxBreadth) { - if (!event) { - return null; - } - - const normalized = { - ...event, - ...(event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(b => ({ - ...b, - ...(b.data && { - data: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(b.data, depth, maxBreadth), - }), - })), - }), - ...(event.user && { - user: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.user, depth, maxBreadth), - }), - ...(event.contexts && { - contexts: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts, depth, maxBreadth), - }), - ...(event.extra && { - extra: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.extra, depth, maxBreadth), - }), - }; - - // 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 && normalized.contexts) { - normalized.contexts.trace = event.contexts.trace; - - // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it - if (event.contexts.trace.data) { - normalized.contexts.trace.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts.trace.data, depth, maxBreadth); - } - } - - // event.spans[].data may contain circular/dangerous data so we need to normalize it - if (event.spans) { - normalized.spans = event.spans.map(span => { - // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable - if (span.data) { - span.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(span.data, depth, maxBreadth); - } - return span; - }); - } - - 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 - */ - _applyClientOptions(event) { - const options = this.getOptions(); - const { environment, release, dist, maxValueLength = 250 } = options; - - 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 = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(event.message, maxValueLength); - } - - const exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(exception.value, maxValueLength); - } - - const request = event.request; - if (request && request.url) { - request.url = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(request.url, maxValueLength); - } - } - - /** - * This function adds all used integrations to the SDK info in the event. - * @param event The event that will be filled with all integrations. - */ - _applyIntegrationsMetadata(event) { - const integrationsArray = Object.keys(this._integrations); - if (integrationsArray.length > 0) { - event.sdk = event.sdk || {}; - event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray]; - } - } - - /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope - */ - _captureEvent(event, hint = {}, scope) { - return this._processEvent(event, hint, scope).then( - finalEvent => { - return finalEvent.event_id; - }, - reason => { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for - // control flow, log just the message (no stack) as a log-level log. - const sentryError = reason ; - if (sentryError.logLevel === 'log') { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(sentryError.message); - } else { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(sentryError); - } - } - 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. - */ - _processEvent(event, hint, scope) { - const options = this.getOptions(); - const { sampleRate } = options; - - if (!this._isEnabled()) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)(new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('SDK not enabled, will not capture event.', 'log')); - } - - const isTransaction = event.type === 'transaction'; - const beforeSendProcessorName = isTransaction ? 'beforeSendTransaction' : 'beforeSend'; - const beforeSendProcessor = options[beforeSendProcessorName]; - - // 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) { - this.recordDroppedEvent('sample_rate', 'error', event); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)( - new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( - `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, - 'log', - ), - ); - } - - return this._prepareEvent(event, hint, scope) - .then(prepared => { - if (prepared === null) { - this.recordDroppedEvent('event_processor', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('An event processor returned `null`, will not send event.', 'log'); - } - - const isInternalException = hint.data && (hint.data ).__sentry__ === true; - if (isInternalException || !beforeSendProcessor) { - return prepared; - } - - const beforeSendResult = beforeSendProcessor(prepared, hint); - return _validateBeforeSendResult(beforeSendResult, beforeSendProcessorName); - }) - .then(processedEvent => { - if (processedEvent === null) { - this.recordDroppedEvent('before_send', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` returned \`null\`, will not send event.`, 'log'); - } - - const session = scope && scope.getSession(); - if (!isTransaction && session) { - this._updateSessionFromEvent(session, processedEvent); - } - - // None of the Sentry built event processor will update transaction name, - // so if the transaction name has been changed by an event processor, we know - // it has to come from custom event processor added by a user - const transactionInfo = processedEvent.transaction_info; - if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { - const source = 'custom'; - processedEvent.transaction_info = { - ...transactionInfo, - source, - changes: [ - ...transactionInfo.changes, - { - source, - // use the same timestamp as the processed event. - timestamp: processedEvent.timestamp , - propagations: transactionInfo.propagations, - }, - ], - }; - } - - this.sendEvent(processedEvent, hint); - return processedEvent; - }) - .then(null, reason => { - if (reason instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError) { - throw reason; - } - - this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason , - }); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.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 - */ - _process(promise) { - this._numProcessing++; - void promise.then( - value => { - this._numProcessing--; - return value; - }, - reason => { - this._numProcessing--; - return reason; - }, - ); - } - - /** - * @inheritdoc - */ - _sendEnvelope(envelope) { - if (this._transport && this._dsn) { - this._transport.send(envelope).then(null, reason => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Error while sending event:', reason); - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Transport disabled'); - } - } - - /** - * Clears outcomes on this client and returns them. - */ - _clearOutcomes() { - const outcomes = this._outcomes; - this._outcomes = {}; - return Object.keys(outcomes).map(key => { - const [reason, category] = key.split(':') ; - return { - reason, - category, - quantity: outcomes[key], - }; - }); - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - -} - -/** - * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. - */ -function _validateBeforeSendResult( - beforeSendResult, - beforeSendProcessorName, -) { - const invalidValueError = `\`${beforeSendProcessorName}\` must return \`null\` or a valid event.`; - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isThenable)(beforeSendResult)) { - return beforeSendResult.then( - event => { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(event) && event !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); - } - return event; - }, - e => { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` rejected with ${e}`); - }, - ); - } else if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(beforeSendResult) && beforeSendResult !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); - } - return beforeSendResult; -} - - -//# sourceMappingURL=baseclient.js.map - - -/***/ }), -/* 1630 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dsnFromString": () => (/* binding */ dsnFromString), -/* harmony export */ "dsnToString": () => (/* binding */ dsnToString), -/* harmony export */ "makeDsn": () => (/* binding */ makeDsn) -/* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1620); - - -/** Regular expression used to parse a Dsn. */ -const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; - -function isValidProtocol(protocol) { - return protocol === 'http' || protocol === 'https'; -} - -/** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. - */ -function dsnToString(dsn, withPassword = false) { - const { host, path, pass, port, projectId, protocol, publicKey } = dsn; - return ( - `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + - `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` - ); -} - -/** - * Parses a Dsn from a given string. - * - * @param str A Dsn as string - * @returns Dsn as DsnComponents - */ -function dsnFromString(str) { - const match = DSN_REGEX.exec(str); - - if (!match) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${str}`); - } - - const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); - let path = ''; - let projectId = lastPath; - - const split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop() ; - } - - if (projectId) { - const projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } - } - - return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey }); -} - -function dsnFromComponents(components) { - return { - protocol: components.protocol, - publicKey: components.publicKey || '', - pass: components.pass || '', - host: components.host, - port: components.port || '', - path: components.path || '', - projectId: components.projectId, - }; -} - -function validateDsn(dsn) { - if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - return; - } - - const { port, projectId, protocol } = dsn; - - const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; - requiredComponents.forEach(component => { - if (!dsn[component]) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${component} missing`); - } - }); - - if (!projectId.match(/^\d+$/)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); - } - - if (!isValidProtocol(protocol)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); - } - - if (port && isNaN(parseInt(port, 10))) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid port ${port}`); - } - - return true; -} - -/** The Sentry Dsn, identifying a Sentry instance and project. */ -function makeDsn(from) { - const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); - validateDsn(components); - return components; -} - - -//# sourceMappingURL=dsn.js.map - - -/***/ }), -/* 1631 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getEnvelopeEndpointWithUrlEncodedAuth": () => (/* binding */ getEnvelopeEndpointWithUrlEncodedAuth), -/* harmony export */ "getReportDialogEndpoint": () => (/* binding */ getReportDialogEndpoint) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1630); - - -const SENTRY_API_VERSION = '7'; - -/** Returns the prefix to construct Sentry ingestion API endpoints. */ -function getBaseApiEndpoint(dsn) { - const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; - const port = dsn.port ? `:${dsn.port}` : ''; - return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`; -} - -/** Returns the ingest API endpoint for target. */ -function _getIngestEndpoint(dsn) { - return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; -} - -/** Returns a URL-encoded string with auth config suitable for a query string. */ -function _encodedAuth(dsn, sdkInfo) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.urlEncode)({ - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.publicKey, - sentry_version: SENTRY_API_VERSION, - ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.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. - */ -function getEnvelopeEndpointWithUrlEncodedAuth( - dsn, - // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below - // options: ClientOptions = {} as ClientOptions, - tunnelOrOptions = {} , -) { - // TODO (v8): Use this code instead - // const { tunnel, _metadata = {} } = options; - // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; - - const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; - const sdkInfo = - typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; - - return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; -} - -/** Returns the url to the report dialog endpoint. */ -function getReportDialogEndpoint( - dsnLike, - dialogOptions - -, -) { - const dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.makeDsn)(dsnLike); - const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; - - let encodedOptions = `dsn=${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dsnToString)(dsn)}`; - for (const key in dialogOptions) { - if (key === 'dsn') { - continue; - } - - if (key === 'user') { - const user = dialogOptions.user; - if (!user) { - continue; - } - if (user.name) { - encodedOptions += `&name=${encodeURIComponent(user.name)}`; - } - if (user.email) { - encodedOptions += `&email=${encodeURIComponent(user.email)}`; - } - } else { - encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`; - } - } - - return `${endpoint}?${encodedOptions}`; -} - - -//# sourceMappingURL=api.js.map - - -/***/ }), -/* 1632 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getIntegrationsToSetup": () => (/* binding */ getIntegrationsToSetup), -/* harmony export */ "installedIntegrations": () => (/* binding */ installedIntegrations), -/* harmony export */ "setupIntegrations": () => (/* binding */ setupIntegrations) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1615); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1603); - - - - -const installedIntegrations = []; - -/** Map of integrations assigned to a client */ - -/** - * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to - * preseve the order of integrations in the array. - * - * @private - */ -function filterDuplicates(integrations) { - const integrationsByName = {}; - - integrations.forEach(currentInstance => { - const { name } = currentInstance; - - const existingInstance = integrationsByName[name]; - - // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a - // default instance to overwrite an existing user instance - if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { - return; - } - - integrationsByName[name] = currentInstance; - }); - - return Object.values(integrationsByName); -} - -/** Gets integrations to install */ -function getIntegrationsToSetup(options) { - const defaultIntegrations = options.defaultIntegrations || []; - const userIntegrations = options.integrations; - - // We flag default instances, so that later we can tell them apart from any user-created instances of the same class - defaultIntegrations.forEach(integration => { - integration.isDefaultInstance = true; - }); - - let integrations; - - if (Array.isArray(userIntegrations)) { - integrations = [...defaultIntegrations, ...userIntegrations]; - } else if (typeof userIntegrations === 'function') { - integrations = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.arrayify)(userIntegrations(defaultIntegrations)); - } else { - integrations = defaultIntegrations; - } - - const finalIntegrations = filterDuplicates(integrations); - - // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or - // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event - // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore - // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. - const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug'); - if (debugIndex !== -1) { - const [debugInstance] = finalIntegrations.splice(debugIndex, 1); - finalIntegrations.push(debugInstance); - } - - return finalIntegrations; -} - -/** - * 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(integrations) { - const integrationIndex = {}; - - integrations.forEach(integration => { - integrationIndex[integration.name] = integration; - - if (installedIntegrations.indexOf(integration.name) === -1) { - integration.setupOnce(_scope_js__WEBPACK_IMPORTED_MODULE_1__.addGlobalEventProcessor, _hub_js__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub); - installedIntegrations.push(integration.name); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`Integration installed: ${integration.name}`); - } - }); - - return integrationIndex; -} - - -//# sourceMappingURL=integration.js.map - - -/***/ }), -/* 1633 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createEventEnvelope": () => (/* binding */ createEventEnvelope), -/* harmony export */ "createSessionEnvelope": () => (/* binding */ createSessionEnvelope) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1630); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1621); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1612); - - -/** Extract sdk info from from the API metadata */ -function getSdkMetadataForEnvelopeHeader(metadata) { - if (!metadata || !metadata.sdk) { - return; - } - const { name, version } = metadata.sdk; - return { name, version }; -} - -/** - * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. - * Merge with existing data if any. - **/ -function enhanceEventWithSdkInfo(event, sdkInfo) { - if (!sdkInfo) { - return event; - } - event.sdk = event.sdk || {}; - event.sdk.name = event.sdk.name || sdkInfo.name; - event.sdk.version = event.sdk.version || sdkInfo.version; - event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; - event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; - return event; -} - -/** Creates an envelope from a Session */ -function createSessionEnvelope( - session, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const envelopeHeaders = { - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - }; - - const envelopeItem = - 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session]; - - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [envelopeItem]); -} - -/** - * Create an Envelope from an event. - */ -function createEventEnvelope( - event, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const eventType = event.type || 'event'; - - enhanceEventWithSdkInfo(event, metadata && metadata.sdk); - - const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); - - // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to - // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may - // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid - // of this `delete`, lest we miss putting it back in the next time the property is in use.) - delete event.sdkProcessingMetadata; - - const eventItem = [{ type: eventType }, event]; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [eventItem]); -} - -function createEventEnvelopeHeaders( - event, - sdkInfo, - tunnel, - dsn, -) { - const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; - - return { - event_id: event.event_id , - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - ...(event.type === 'transaction' && - dynamicSamplingContext && { - trace: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ ...dynamicSamplingContext }), - }), - }; -} - - -//# sourceMappingURL=envelope.js.map - - -/***/ }), -/* 1634 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SessionFlusher": () => (/* binding */ SessionFlusher) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1612); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); - - - -/** - * @inheritdoc - */ -class SessionFlusher { - __init() {this.flushTimeout = 60;} - __init2() {this._pendingAggregates = {};} - - __init3() {this._isEnabled = true;} - - constructor(client, attrs) {;SessionFlusher.prototype.__init.call(this);SessionFlusher.prototype.__init2.call(this);SessionFlusher.prototype.__init3.call(this); - this._client = client; - // Call to setInterval, so that flush is called every 60 seconds - this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); - this._sessionAttrs = attrs; - } - - /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ - flush() { - const sessionAggregates = this.getSessionAggregates(); - if (sessionAggregates.aggregates.length === 0) { - return; - } - this._pendingAggregates = {}; - this._client.sendSession(sessionAggregates); - } - - /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ - getSessionAggregates() { - const aggregates = Object.keys(this._pendingAggregates).map((key) => { - return this._pendingAggregates[parseInt(key)]; - }); - - const sessionAggregates = { - attrs: this._sessionAttrs, - aggregates, - }; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dropUndefinedKeys)(sessionAggregates); - } - - /** JSDoc */ - close() { - clearInterval(this._intervalId); - this._isEnabled = false; - this.flush(); - } - - /** - * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then - * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to - * `_incrementSessionStatusCount` along with the start date - */ - incrementSessionStatusCount() { - if (!this._isEnabled) { - return; - } - const scope = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getScope(); - const requestSession = scope && scope.getRequestSession(); - - if (requestSession && requestSession.status) { - this._incrementSessionStatusCount(requestSession.status, new Date()); - // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in - // case captureRequestSession is called more than once to prevent double count - if (scope) { - scope.setRequestSession(undefined); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - } - } - - /** - * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of - * the session received - */ - _incrementSessionStatusCount(status, date) { - // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys - const sessionStartedTrunc = new Date(date).setSeconds(0, 0); - this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; - - // corresponds to aggregated sessions in one specific minute bucket - // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} - const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; - if (!aggregationCounts.started) { - aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); - } - - switch (status) { - case 'errored': - aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; - return aggregationCounts.errored; - case 'ok': - aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; - return aggregationCounts.exited; - default: - aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; - return aggregationCounts.crashed; - } - } -} - - -//# sourceMappingURL=sessionflusher.js.map - - -/***/ }), -/* 1635 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_0__.makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1636); - - -; -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1636 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* binding */ makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1650); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1618); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(stream__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(83); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(zlib__WEBPACK_IMPORTED_MODULE_4__); - - - - - - - - -// Estimated maximum size for reasonable standalone event -const GZIP_THRESHOLD = 1024 * 32; - -/** - * Gets a stream from a Uint8Array or string - * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0 - */ -function streamFromBody(body) { - return new stream__WEBPACK_IMPORTED_MODULE_2__.Readable({ - read() { - this.push(body); - this.push(null); - }, - }); -} - -/** - * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. - */ -function makeNodeTransport(options) { - const urlSegments = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - const isHttps = urlSegments.protocol === 'https:'; - - // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` - // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` - const proxy = applyNoProxyOption( - urlSegments, - options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy, - ); - - const nativeHttpModule = isHttps ? https__WEBPACK_IMPORTED_MODULE_1__ : http__WEBPACK_IMPORTED_MODULE_0__; - const keepAlive = options.keepAlive === undefined ? false : options.keepAlive; - - // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node - // versions(>= 8) as they had memory leaks when using it: #2555 - const agent = proxy - ? (new (__webpack_require__(1637))(proxy) ) - : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 }); - - const requestExecutor = createRequestExecutor(options, (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(options.httpModule, () => ( nativeHttpModule)), agent); - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.createTransport)(options, requestExecutor); -} - -/** - * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. - * - * @param transportUrl The URL the transport intends to send events to. - * @param proxy The client configured proxy. - * @returns A proxy the transport should use. - */ -function applyNoProxyOption(transportUrlSegments, proxy) { - const { no_proxy } = process.env; - - const urlIsExemptFromProxy = - no_proxy && - no_proxy - .split(',') - .some( - exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption), - ); - - if (urlIsExemptFromProxy) { - return undefined; - } else { - return proxy; - } -} - -/** - * Creates a RequestExecutor to be used with `createTransport`. - */ -function createRequestExecutor( - options, - httpModule, - agent, -) { - const { hostname, pathname, port, protocol, search } = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - return function makeRequest(request) { - return new Promise((resolve, reject) => { - let body = streamFromBody(request.body); - - const headers = { ...options.headers }; - - if (request.body.length > GZIP_THRESHOLD) { - headers['content-encoding'] = 'gzip'; - body = body.pipe((0,zlib__WEBPACK_IMPORTED_MODULE_4__.createGzip)()); - } - - const req = httpModule.request( - { - method: 'POST', - agent, - headers, - hostname, - path: `${pathname}${search}`, - port, - protocol, - ca: options.caCerts, - }, - res => { - res.on('data', () => { - // Drain socket - }); - - res.on('end', () => { - // Drain socket - }); - - res.setEncoding('utf8'); - - // "Key-value pairs of header names and values. Header names are lower-cased." - // https://nodejs.org/api/http.html#http_message_headers - const retryAfterHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['retry-after'], () => ( null)); - const rateLimitsHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['x-sentry-rate-limits'], () => ( null)); - - resolve({ - statusCode: res.statusCode, - headers: { - 'retry-after': retryAfterHeader, - 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, - }, - }); - }, - ); - - req.on('error', reject); - body.pipe(req); - }); - }; -} - - -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1637 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const agent_1 = __importDefault(__webpack_require__(1638)); -function createHttpsProxyAgent(opts) { - return new agent_1.default(opts); -} -(function (createHttpsProxyAgent) { - createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent.prototype = agent_1.default.prototype; -})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); -module.exports = createHttpsProxyAgent; -//# sourceMappingURL=index.js.map - -/***/ }), -/* 1638 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __importDefault(__webpack_require__(62)); -const tls_1 = __importDefault(__webpack_require__(145)); -const url_1 = __importDefault(__webpack_require__(63)); -const assert_1 = __importDefault(__webpack_require__(91)); -const debug_1 = __importDefault(__webpack_require__(1639)); -const agent_base_1 = __webpack_require__(1643); -const parse_proxy_response_1 = __importDefault(__webpack_require__(1649)); -const debug = debug_1.default('https-proxy-agent:agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - * - * @api public - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === 'string') { - opts = url_1.default.parse(_opts); - } - else { - opts = _opts; - } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); - } - debug('creating new HttpsProxyAgent instance: %o', opts); - super(opts); - const proxy = Object.assign({}, opts); - // If `true`, then connect to the proxy server over TLS. - // Defaults to `false`. - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - // Prefer `hostname` over `host`, and set the `port` if needed. - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === 'string') { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - // ALPN is supported by Node.js >= v5. - // attempt to negotiate http/1.1 for proxy servers that support http/2 - if (this.secureProxy && !('ALPNProtocols' in proxy)) { - proxy.ALPNProtocols = ['http 1.1']; - } - if (proxy.host && proxy.path) { - // If both a `host` and `path` are specified then it's most likely - // the result of a `url.parse()` call... we need to remove the - // `path` portion so that `net.connect()` doesn't attempt to open - // that as a Unix socket file. - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - * - * @api protected - */ - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - // Create a socket connection to the proxy server. - let socket; - if (secureProxy) { - debug('Creating `tls.Socket`: %o', proxy); - socket = tls_1.default.connect(proxy); - } - else { - debug('Creating `net.Socket`: %o', proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.auth) { - headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; - } - // The `Host` header should only include the port - // number when it is not the default port. - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = 'close'; - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r\n`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - const servername = opts.servername || opts.host; - return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, - servername })); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net_1.default.Socket({ writable: false }); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('replaying proxy buffer for failed request'); - assert_1.default(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); - } -} -exports["default"] = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function isDefaultPort(port, secure) { - return Boolean((!secure && port === 80) || (secure && port === 443)); -} -function isHTTPS(protocol) { - return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=agent.js.map - -/***/ }), -/* 1639 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1640); -} else { - module.exports = __webpack_require__(1642); -} - - -/***/ }), -/* 1640 */ -/***/ ((module, exports, __webpack_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __webpack_require__(1641)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), -/* 1641 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1367); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), -/* 1642 */ -/***/ ((module, exports, __webpack_require__) => { - -/** - * Module dependencies. - */ - -const tty = __webpack_require__(1369); -const util = __webpack_require__(64); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1370); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __webpack_require__(1641)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), -/* 1643 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const events_1 = __webpack_require__(250); -const debug_1 = __importDefault(__webpack_require__(1644)); -const promisify_1 = __importDefault(__webpack_require__(1648)); -const debug = debug_1.default('agent-base'); -function isAgent(v) { - return Boolean(v) && typeof v.addRequest === 'function'; -} -function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); -} -function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); -} -(function (createAgent) { - /** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === 'function') { - this.callback = callback; - } - else if (callback) { - opts = callback; - } - // Timeout for the socket to be returned from the callback - this.timeout = null; - if (opts && typeof opts.timeout === 'number') { - this.timeout = opts.timeout; - } - // These aren't actually used by `agent-base`, but are required - // for the TypeScript definition files in `@types/node` :/ - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === 'number') { - return this.explicitDefaultPort; - } - return isSecureEndpoint() ? 443 : 80; - } - set defaultPort(v) { - this.explicitDefaultPort = v; - } - get protocol() { - if (typeof this.explicitProtocol === 'string') { - return this.explicitProtocol; - } - return isSecureEndpoint() ? 'https:' : 'http:'; - } - set protocol(v) { - this.explicitProtocol = v; - } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); - } - /** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== 'boolean') { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = 'localhost'; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; - } - if (opts.host && opts.path) { - // If both a `host` and `path` are specified then it's most - // likely the result of a `url.parse()` call... we need to - // remove the `path` portion so that `net.connect()` doesn't - // attempt to open that as a unix socket file. - delete opts.path; - } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = 'ETIMEOUT'; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - // `socket` is actually an `http.Agent` instance, so - // relinquish responsibility for this `req` to the Agent - // from here on - debug('Callback returned another Agent instance %o', socket.constructor.name); - socket.addRequest(req, opts); - return; - } - if (socket) { - socket.once('free', () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; - } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== 'function') { - onerror(new Error('`callback` is not defined')); - return; - } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug('Converting legacy callback function to promise'); - this.promisifiedCallback = promisify_1.default(this.callback); - } - else { - this.promisifiedCallback = this.callback; - } - } - if (typeof timeoutMs === 'number' && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ('port' in opts && typeof opts.port !== 'number') { - opts.port = Number(opts.port); - } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } - catch (err) { - Promise.reject(err).catch(callbackError); - } - } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug('Destroying agent %o', this.constructor.name); - } - } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map - -/***/ }), -/* 1644 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1645); -} else { - module.exports = __webpack_require__(1647); -} - - -/***/ }), -/* 1645 */ -/***/ ((module, exports, __webpack_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __webpack_require__(1646)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), -/* 1646 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1367); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), -/* 1647 */ -/***/ ((module, exports, __webpack_require__) => { - -/** - * Module dependencies. - */ - -const tty = __webpack_require__(1369); -const util = __webpack_require__(64); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1370); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __webpack_require__(1646)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), -/* 1648 */ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -function promisify(fn) { - return function (req, opts) { - return new Promise((resolve, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } - else { - resolve(rtn); - } - }); - }); - }; -} -exports["default"] = promisify; -//# sourceMappingURL=promisify.js.map - -/***/ }), -/* 1649 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __importDefault(__webpack_require__(1639)); -const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('close', onclose); - socket.removeListener('readable', read); - } - function onclose(err) { - debug('onclose had error %o', err); - } - function onend() { - debug('onend'); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); - const statusCode = +firstLine.split(' ')[1]; - debug('got proxy server response: %o', firstLine); - resolve({ - statusCode, - buffered - }); - } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); -} -exports["default"] = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map - -/***/ }), -/* 1650 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_nullishCoalesce": () => (/* binding */ _nullishCoalesce) -/* harmony export */ }); -/** - * Polyfill for the nullish coalescing operator (`??`). - * - * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the - * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. - * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) - * - * @param lhs The value of the expression to the left of the `??` - * @param rhsFn A function returning the value of the expression to the right of the `??` - * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value - */ -function _nullishCoalesce(lhs, rhsFn) { - // by checking for loose equality to `null`, we catch both `null` and `undefined` - return lhs != null ? lhs : rhsFn(); -} - -// Sucrase version: -// function _nullishCoalesce(lhs, rhsFn) { -// if (lhs != null) { -// return lhs; -// } else { -// return rhsFn(); -// } -// } - - -//# sourceMappingURL=_nullishCoalesce.js.map - - -/***/ }), -/* 1651 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "close": () => (/* binding */ close), -/* harmony export */ "defaultIntegrations": () => (/* binding */ defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* binding */ defaultStackParser), -/* harmony export */ "flush": () => (/* binding */ flush), -/* harmony export */ "getSentryRelease": () => (/* binding */ getSentryRelease), -/* harmony export */ "init": () => (/* binding */ init), -/* harmony export */ "isAutoSessionTrackingEnabled": () => (/* binding */ isAutoSessionTrackingEnabled), -/* harmony export */ "lastEventId": () => (/* binding */ lastEventId) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1673); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(1674); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(1602); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(1632); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1675); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(1624); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(1606); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1314); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1627); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1652); -/* harmony import */ var _module_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1671); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1635); -/* harmony import */ var _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1653); -/* harmony import */ var _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1655); -/* harmony import */ var _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1658); -/* harmony import */ var _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1660); -/* harmony import */ var _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1662); -/* harmony import */ var _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1665); -/* harmony import */ var _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1664); -/* harmony import */ var _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1666); -/* harmony import */ var _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1661); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1636); - - - - - - - - - - - - - - - - - - - -/* eslint-disable max-lines */ - -const defaultIntegrations = [ - // Common - new _sentry_core__WEBPACK_IMPORTED_MODULE_15__.InboundFilters(), - new _sentry_core__WEBPACK_IMPORTED_MODULE_16__.FunctionToString(), - // Native Wrappers - new _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__.Console(), - new _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__.Http(), - // Global Handlers - new _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__.OnUncaughtException(), - new _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__.OnUnhandledRejection(), - // Event Info - new _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__.ContextLines(), - new _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__.Context(), - new _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__.Modules(), - new _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__.RequestData(), - // Misc - new _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__.LinkedErrors(), -]; - -/** - * The Sentry Node SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible in the - * main entry module. To set context information or send manual events, use the - * provided methods. - * - * @example - * ``` - * - * const { init } = require('@sentry/node'); - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const { configureScope } = require('@sentry/node'); - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * const { addBreadcrumb } = require('@sentry/node'); - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const Sentry = require('@sentry/node'); - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` - * - * @see {@link NodeOptions} for documentation on configuration options. - */ -function init(options = {}) { - const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getMainCarrier)(); - const autoloadedIntegrations = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || []; - - options.defaultIntegrations = - options.defaultIntegrations === false - ? [] - : [ - ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations), - ...autoloadedIntegrations, - ]; - - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; - } - - if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { - const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); - if (isFinite(tracesSampleRate)) { - options.tracesSampleRate = tracesSampleRate; - } - } - - if (options.release === undefined) { - const detectedRelease = getSentryRelease(); - if (detectedRelease !== undefined) { - options.release = detectedRelease; - } else { - // If release is not provided, then we should disable autoSessionTracking - options.autoSessionTracking = false; - } - } - - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; - } - - if (options.autoSessionTracking === undefined && options.dsn !== undefined) { - options.autoSessionTracking = true; - } - - if (options.instrumenter === undefined) { - options.instrumenter = 'sentry'; - } - - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain__WEBPACK_IMPORTED_MODULE_0__.active) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.setHubOnCarrier)(carrier, (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)()); - } - - // TODO(v7): Refactor this to reduce the logic above - const clientOptions = { - ...options, - stackParser: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.stackParserFromStackParserOptions)(options.stackParser || defaultStackParser), - integrations: (0,_sentry_core__WEBPACK_IMPORTED_MODULE_20__.getIntegrationsToSetup)(options), - transport: options.transport || _transports_http_js__WEBPACK_IMPORTED_MODULE_14__.makeNodeTransport, - }; - - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_21__.initAndBind)(_client_js__WEBPACK_IMPORTED_MODULE_1__.NodeClient, clientOptions); - - if (options.autoSessionTracking) { - startSessionTracking(); - } -} - -/** - * This is the getter for lastEventId. - * - * @returns The last event id of a captured event. - */ -function lastEventId() { - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().lastEventId(); -} - -/** - * Call `flush()` on the current client, if there is one. See {@link Client.flush}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause - * the client to wait until all events are sent before resolving the promise. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -async function flush(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.flush(timeout); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events. No client defined.'); - return Promise.resolve(false); -} - -/** - * Call `close()` on the current client, if there is one. See {@link Client.close}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this - * parameter will cause the client to wait until all events are sent before disabling itself. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -async function close(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.close(timeout); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events and disable SDK. No client defined.'); - return Promise.resolve(false); -} - -/** - * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client - */ -function isAutoSessionTrackingEnabled(client) { - if (client === undefined) { - return false; - } - const clientOptions = client && client.getOptions(); - if (clientOptions && clientOptions.autoSessionTracking !== undefined) { - return clientOptions.autoSessionTracking; - } - return false; -} - -/** - * Returns a release dynamically from environment variables. - */ -function getSentryRelease(fallback) { - // Always read first as Sentry takes this as precedence - if (process.env.SENTRY_RELEASE) { - return process.env.SENTRY_RELEASE; - } - - // This supports the variable that sentry-webpack-plugin injects - if (_sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE && _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id) { - return _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id; - } - - return ( - // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables - process.env.GITHUB_SHA || - // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata - process.env.COMMIT_REF || - // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables - process.env.VERCEL_GIT_COMMIT_SHA || - process.env.VERCEL_GITHUB_COMMIT_SHA || - process.env.VERCEL_GITLAB_COMMIT_SHA || - process.env.VERCEL_BITBUCKET_COMMIT_SHA || - // Zeit (now known as Vercel) - process.env.ZEIT_GITHUB_COMMIT_SHA || - process.env.ZEIT_GITLAB_COMMIT_SHA || - process.env.ZEIT_BITBUCKET_COMMIT_SHA || - fallback - ); -} - -/** Node.js stack parser */ -const defaultStackParser = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.createStackParser)((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.nodeStackLineParser)(_module_js__WEBPACK_IMPORTED_MODULE_3__.getModule)); - -/** - * Enable automatic Session Tracking for the node process. - */ -function startSessionTracking() { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)(); - hub.startSession(); - // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because - // The 'beforeExit' event is not emitted for conditions causing explicit termination, - // such as calling process.exit() or uncaught exceptions. - // Ref: https://nodejs.org/api/process.html#process_event_beforeexit - process.on('beforeExit', () => { - const session = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([hub, 'access', _3 => _3.getScope, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getSession, 'call', _6 => _6()]); - const terminalStates = ['exited', 'crashed']; - // Only call endSession, if the Session exists on Scope and SessionStatus is not a - // Terminal Status i.e. Exited or Crashed because - // "When a session is moved away from ok it must not be updated anymore." - // Ref: https://develop.sentry.dev/sdk/sessions/ - if (session && !terminalStates.includes(session.status)) hub.endSession(); - }); -} - - -//# sourceMappingURL=sdk.js.map - - -/***/ }), -/* 1652 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* reexport safe */ _console_js__WEBPACK_IMPORTED_MODULE_0__.Console), -/* harmony export */ "Http": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_1__.Http), -/* harmony export */ "OnUncaughtException": () => (/* reexport safe */ _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__.OnUncaughtException), -/* harmony export */ "OnUnhandledRejection": () => (/* reexport safe */ _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__.OnUnhandledRejection), -/* harmony export */ "LinkedErrors": () => (/* reexport safe */ _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__.LinkedErrors), -/* harmony export */ "Modules": () => (/* reexport safe */ _modules_js__WEBPACK_IMPORTED_MODULE_5__.Modules), -/* harmony export */ "ContextLines": () => (/* reexport safe */ _contextlines_js__WEBPACK_IMPORTED_MODULE_6__.ContextLines), -/* harmony export */ "Context": () => (/* reexport safe */ _context_js__WEBPACK_IMPORTED_MODULE_7__.Context), -/* harmony export */ "RequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.RequestData) -/* harmony export */ }); -/* harmony import */ var _console_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1655); -/* harmony import */ var _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1658); -/* harmony import */ var _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1660); -/* harmony import */ var _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1661); -/* harmony import */ var _modules_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1664); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1662); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1665); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1666); - - - - - - - - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1653 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* binding */ Console) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1654); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_0__); - - - - -/** Console module integration */ -class Console {constructor() { Console.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Console';} - - /** - * @inheritDoc - */ - __init() {this.name = Console.id;} - - /** - * @inheritDoc - */ - setupOnce() { - for (const level of ['debug', 'info', 'warn', 'error', 'log']) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.fill)(console, level, createConsoleWrapper(level)); - } - } -} Console.__initStatic(); - -/** - * Wrapper function that'll be used for every console level - */ -function createConsoleWrapper(level) { - return function consoleWrapper(originalConsoleMethod) { - const sentryLevel = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.severityLevelFromString)(level); - - /* eslint-disable prefer-rest-params */ - return function () { - if ((0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(Console)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().addBreadcrumb( - { - category: 'console', - level: sentryLevel, - message: util__WEBPACK_IMPORTED_MODULE_0__.format.apply(undefined, arguments), - }, - { - input: [...arguments], - level, - }, - ); - } - - originalConsoleMethod.apply(this, arguments); - }; - /* eslint-enable prefer-rest-params */ - }; -} - - -//# sourceMappingURL=console.js.map - - -/***/ }), -/* 1654 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "severityFromString": () => (/* binding */ severityFromString), -/* harmony export */ "severityLevelFromString": () => (/* binding */ severityLevelFromString), -/* harmony export */ "validSeverityLevels": () => (/* binding */ validSeverityLevels) -/* harmony export */ }); -// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either -// -// a) moving `validSeverityLevels` to `@sentry/types`, -// b) moving the`SeverityLevel` type here, or -// c) importing `validSeverityLevels` from here into `@sentry/types`. -// -// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would -// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the -// type, reminding anyone who changes it to change this list also, will have to do. - -const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug']; - -/** - * Converts a string-based level into a member of the deprecated {@link Severity} enum. - * - * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead. - * - * @param level String representation of Severity - * @returns Severity - */ -function severityFromString(level) { - return severityLevelFromString(level) ; -} - -/** - * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. - * - * @param level String representation of desired `SeverityLevel`. - * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. - */ -function severityLevelFromString(level) { - return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ; -} - - -//# sourceMappingURL=severity.js.map - - -/***/ }), -/* 1655 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Http": () => (/* binding */ Http) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1612); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1610); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1657); -/* harmony import */ var _utils_http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1656); - - - - - -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); - -/** - * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing - * http requests and attaches trace data when tracing is enabled via its `tracing` option. - */ -class Http { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Http';} - - /** - * @inheritDoc - */ - __init() {this.name = Http.id;} - - /** - * @inheritDoc - */ - constructor(options = {}) {;Http.prototype.__init.call(this); - this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; - this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing; - } - - /** - * @inheritDoc - */ - setupOnce( - _addGlobalEventProcessor, - setupOnceGetCurrentHub, - ) { - // No need to instrument if we don't want to track anything - if (!this._breadcrumbs && !this._tracing) { - return; - } - - const clientOptions = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); - - // Do not auto-instrument for other instrumenter - if (clientOptions && clientOptions.instrumenter !== 'sentry') { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('HTTP Integration is skipped because of instrumenter configuration.'); - return; - } - - // TODO (v8): `tracePropagationTargets` and `shouldCreateSpanForRequest` will be removed from clientOptions - // and we will no longer have to do this optional merge, we can just pass `this._tracing` directly. - const tracingOptions = this._tracing ? { ...clientOptions, ...this._tracing } : undefined; - - const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, tracingOptions); - - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpModule = __webpack_require__(80); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'request', wrappedHandlerMaker); - - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // If we do, we'd get double breadcrumbs and double spans for `https` calls. - // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpsModule = __webpack_require__(81); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'request', wrappedHandlerMaker); - } - } -}Http.__initStatic(); - -// for ease of reading below - -/** - * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` - * and `https` modules. (NB: Not a typo - this is a creator^2!) - * - * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs - * @param tracingEnabled Whether or not to record outgoing requests as tracing spans - * - * @returns A function which accepts the exiting handler and returns a wrapped handler - */ -function _createWrappedRequestMethodFactory( - breadcrumbsEnabled, - tracingOptions, -) { - // We're caching results so we don't have to recompute regexp every time we create a request. - const createSpanUrlMap = {}; - const headersUrlMap = {}; - - const shouldCreateSpan = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _6 => _6.shouldCreateSpanForRequest]) === undefined) { - return true; - } - - if (createSpanUrlMap[url]) { - return createSpanUrlMap[url]; - } - - createSpanUrlMap[url] = tracingOptions.shouldCreateSpanForRequest(url); - - return createSpanUrlMap[url]; - }; - - const shouldAttachTraceData = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _7 => _7.tracePropagationTargets]) === undefined) { - return true; - } - - if (headersUrlMap[url]) { - return headersUrlMap[url]; - } - - headersUrlMap[url] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.stringMatchesSomePattern)(url, tracingOptions.tracePropagationTargets); - - return headersUrlMap[url]; - }; - - return function wrappedRequestMethodFactory(originalRequestMethod) { - return function wrappedMethod( ...args) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const httpModule = this; - - const requestArgs = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.normalizeRequestArgs)(this, args); - const requestOptions = requestArgs[0]; - const requestUrl = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.extractUrl)(requestOptions); - - // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method - if ((0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.isSentryRequest)(requestUrl)) { - return originalRequestMethod.apply(httpModule, requestArgs); - } - - let requestSpan; - let parentSpan; - - const scope = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getScope(); - - if (scope && tracingOptions && shouldCreateSpan(requestUrl)) { - parentSpan = scope.getSpan(); - - if (parentSpan) { - requestSpan = parentSpan.startChild({ - description: `${requestOptions.method || 'GET'} ${requestUrl}`, - op: 'http.client', - }); - - if (shouldAttachTraceData(requestUrl)) { - const sentryTraceHeader = requestSpan.toTraceparent(); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `, - ); - - requestOptions.headers = { - ...requestOptions.headers, - 'sentry-trace': sentryTraceHeader, - }; - - if (parentSpan.transaction) { - const dynamicSamplingContext = parentSpan.transaction.getDynamicSamplingContext(); - const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); - - let newBaggageHeaderField; - if (!requestOptions.headers || !requestOptions.headers.baggage) { - newBaggageHeaderField = sentryBaggageHeader; - } else if (!sentryBaggageHeader) { - newBaggageHeaderField = requestOptions.headers.baggage; - } else if (Array.isArray(requestOptions.headers.baggage)) { - newBaggageHeaderField = [...requestOptions.headers.baggage, sentryBaggageHeader]; - } else { - // Type-cast explanation: - // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity - // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this. - newBaggageHeaderField = [requestOptions.headers.baggage, sentryBaggageHeader] ; - } - - requestOptions.headers = { - ...requestOptions.headers, - // Setting a hader to `undefined` will crash in node so we only set the baggage header when it's defined - ...(newBaggageHeaderField && { baggage: newBaggageHeaderField }), - }; - } - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`, - ); - } - - const transaction = parentSpan.transaction; - if (transaction) { - transaction.metadata.propagations++; - } - } - } - - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalRequestMethod - .apply(httpModule, requestArgs) - .once('response', function ( res) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('response', requestUrl, req, res); - } - if (requestSpan) { - if (res.statusCode) { - requestSpan.setHttpStatus(res.statusCode); - } - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }) - .once('error', function () { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; - - if (breadcrumbsEnabled) { - addRequestBreadcrumb('error', requestUrl, req); - } - if (requestSpan) { - requestSpan.setHttpStatus(500); - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }); - }; - }; -} - -/** - * Captures Breadcrumb based on provided request/response pair - */ -function addRequestBreadcrumb(event, url, req, res) { - if (!(0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getIntegration(Http)) { - return; - } - - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().addBreadcrumb( - { - category: 'http', - data: { - method: req.method, - status_code: res && res.statusCode, - url, - }, - type: 'http', - }, - { - event, - request: req, - response: res, - }, - ); -} - - -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1656 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "cleanSpanDescription": () => (/* binding */ cleanSpanDescription), -/* harmony export */ "extractUrl": () => (/* binding */ extractUrl), -/* harmony export */ "isSentryRequest": () => (/* binding */ isSentryRequest), -/* harmony export */ "normalizeRequestArgs": () => (/* binding */ normalizeRequestArgs), -/* harmony export */ "urlToOptions": () => (/* binding */ urlToOptions) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__); - - - - - -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); - -/** - * Checks whether given url points to Sentry server - * @param url url to verify - */ -function isSentryRequest(url) { - const dsn = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getDsn, 'call', _5 => _5()]); - return dsn ? url.includes(dsn.host) : false; -} - -/** - * Assemble a URL to be used for breadcrumbs and spans. - * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL - */ -function extractUrl(requestOptions) { - const protocol = requestOptions.protocol || ''; - const hostname = requestOptions.hostname || requestOptions.host || ''; - // Don't log standard :80 (http) and :443 (https) ports to reduce the noise - const port = - !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`; - const path = requestOptions.path ? requestOptions.path : '/'; - - return `${protocol}//${hostname}${port}${path}`; -} - -/** - * Handle various edge cases in the span description (for spans representing http(s) requests). - * - * @param description current `description` property of the span representing the request - * @param requestOptions Configuration data for the request - * @param Request Request object - * - * @returns The cleaned description - */ -function cleanSpanDescription( - description, - requestOptions, - request, -) { - // nothing to clean - if (!description) { - return description; - } - - // eslint-disable-next-line prefer-const - let [method, requestUrl] = description.split(' '); - - // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, - // we're likely dealing with an internal route and this doesn't apply) - if (requestOptions.host && !requestOptions.protocol) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - requestOptions.protocol = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(request ), 'optionalAccess', _6 => _6.agent, 'optionalAccess', _7 => _7.protocol]); // worst comes to worst, this is undefined and nothing changes - requestUrl = extractUrl(requestOptions); - } - - // internal routes can end up starting with a triple slash rather than a single one - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([requestUrl, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9('///')])) { - requestUrl = requestUrl.slice(2); - } - - return `${method} ${requestUrl}`; -} - -// the node types are missing a few properties which node's `urlToOptions` function spits out - -/** - * Convert a URL object into a RequestOptions object. - * - * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the - * RequestOptions type above. - * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. - */ -function urlToOptions(url) { - const options = { - protocol: url.protocol, - hostname: - typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: `${url.pathname || ''}${url.search || ''}`, - href: url.href, - }; - if (url.port !== '') { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = `${url.username}:${url.password}`; - } - return options; -} - -/** - * Normalize inputs to `http(s).request()` and `http(s).get()`. - * - * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: - * [ RequestOptions | string | URL ], - * [ RequestOptions | string | URL, RequestCallback ], - * [ string | URL, RequestOptions ], and - * [ string | URL, RequestOptions, RequestCallback ]. - * - * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is - * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact - * with the args in a standard way. - * - * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. - * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. - */ -function normalizeRequestArgs( - httpModule, - requestArgs, -) { - let callback, requestOptions; - - // pop off the callback, if there is one - if (typeof requestArgs[requestArgs.length - 1] === 'function') { - callback = requestArgs.pop() ; - } - - // create a RequestOptions object of whatever's at index 0 - if (typeof requestArgs[0] === 'string') { - requestOptions = urlToOptions(new url__WEBPACK_IMPORTED_MODULE_0__.URL(requestArgs[0])); - } else if (requestArgs[0] instanceof url__WEBPACK_IMPORTED_MODULE_0__.URL) { - requestOptions = urlToOptions(requestArgs[0]); - } else { - requestOptions = requestArgs[0]; - } - - // if the options were given separately from the URL, fold them in - if (requestArgs.length === 2) { - requestOptions = { ...requestOptions, ...requestArgs[1] }; - } - - // Figure out the protocol if it's currently missing - if (requestOptions.protocol === undefined) { - // Worst case we end up populating protocol with undefined, which it already is - /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, - // as it will always return `http`, even when using `https` module. - // - // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]); - } else { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - } - - // return args in standardized form - if (callback) { - return [requestOptions, callback]; - } else { - return [requestOptions]; - } -} - - -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1657 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BAGGAGE_HEADER_NAME": () => (/* binding */ BAGGAGE_HEADER_NAME), -/* harmony export */ "MAX_BAGGAGE_STRING_LENGTH": () => (/* binding */ MAX_BAGGAGE_STRING_LENGTH), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX_REGEX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX_REGEX), -/* harmony export */ "baggageHeaderToDynamicSamplingContext": () => (/* binding */ baggageHeaderToDynamicSamplingContext), -/* harmony export */ "dynamicSamplingContextToSentryBaggageHeader": () => (/* binding */ dynamicSamplingContextToSentryBaggageHeader) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); - - - -const BAGGAGE_HEADER_NAME = 'baggage'; - -const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-'; - -const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; - -/** - * Max length of a serialized baggage string - * - * https://www.w3.org/TR/baggage/#limits - */ -const MAX_BAGGAGE_STRING_LENGTH = 8192; - -/** - * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values - * from it. - * - * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. - * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. - */ -function baggageHeaderToDynamicSamplingContext( - // Very liberal definition of what any incoming header might look like - baggageHeader, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(baggageHeader) && !Array.isArray(baggageHeader)) { - return undefined; - } - - // Intermediary object to store baggage key value pairs of incoming baggage headers on. - // It is later used to read Sentry-DSC-values from. - let baggageObject = {}; - - if (Array.isArray(baggageHeader)) { - // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it - baggageObject = baggageHeader.reduce((acc, curr) => { - const currBaggageObject = baggageHeaderToObject(curr); - return { - ...acc, - ...currBaggageObject, - }; - }, {}); - } else { - // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but - // this is how we choose to handle it) - if (!baggageHeader) { - return undefined; - } - - baggageObject = baggageHeaderToObject(baggageHeader); - } - - // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. - const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { - if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { - const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); - acc[nonPrefixedKey] = value; - } - return acc; - }, {}); - - // Only return a dynamic sampling context object if there are keys in it. - // A keyless object means there were no sentry values on the header, which means that there is no DSC. - if (Object.keys(dynamicSamplingContext).length > 0) { - return dynamicSamplingContext ; - } else { - return undefined; - } -} - -/** - * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". - * - * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility - * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is - * `undefined` the function will return `undefined`. - * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` - * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. - */ -function dynamicSamplingContextToSentryBaggageHeader( - // this also takes undefined for convenience and bundle size in other places - dynamicSamplingContext, -) { - // Prefix all DSC keys with "sentry-" and put them into a new object - const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( - (acc, [dscKey, dscValue]) => { - if (dscValue) { - acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; - } - return acc; - }, - {}, - ); - - return objectToBaggageHeader(sentryPrefixedDSC); -} - -/** - * Will parse a baggage header, which is a simple key-value map, into a flat object. - * - * @param baggageHeader The baggage header to parse. - * @returns a flat object containing all the key-value pairs from `baggageHeader`. - */ -function baggageHeaderToObject(baggageHeader) { - return baggageHeader - .split(',') - .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) - .reduce((acc, [key, value]) => { - acc[key] = value; - return acc; - }, {}); -} - -/** - * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. - * - * @param object The object to turn into a baggage header. - * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header - * is not spec compliant. - */ -function objectToBaggageHeader(object) { - if (Object.keys(object).length === 0) { - // An empty baggage header is not spec compliant: We return undefined. - return undefined; - } - - return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { - const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; - const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; - if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn( - `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`, - ); - return baggageHeader; - } else { - return newBaggageHeader; - } - }, ''); -} - - -//# sourceMappingURL=baggage.js.map - - -/***/ }), -/* 1658 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUncaughtException": () => (/* binding */ OnUncaughtException) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1659); - - - - -/** Global Exception handler */ -class OnUncaughtException { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUncaughtException';} - - /** - * @inheritDoc - */ - __init() {this.name = OnUncaughtException.id;} - - /** - * @inheritDoc - */ - __init2() {this.handler = this._makeErrorHandler();} - - // CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts` - - /** - * @inheritDoc - */ - constructor(options = {}) {;OnUncaughtException.prototype.__init.call(this);OnUncaughtException.prototype.__init2.call(this); - this._options = { - exitEvenIfOtherHandlersAreRegistered: true, - ...options, - }; - } - - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('uncaughtException', this.handler); - } - - /** - * @hidden - */ - _makeErrorHandler() { - const timeout = 2000; - let caughtFirstError = false; - let caughtSecondError = false; - let calledFatalError = false; - let firstError; - - return (error) => { - let onFatalError = _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess; - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getClient(); - - if (this._options.onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = this._options.onFatalError; - } else if (client && client.getOptions().onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = client.getOptions().onFatalError ; - } - - // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not - // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust - // exit behaviour of the SDK accordingly: - // - If other listeners are attached, do not exit. - // - If the only listener attached is ours, exit. - const userProvidedListenersCount = global.process - .listeners('uncaughtException') - .reduce((acc, listener) => { - if ( - listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself - listener === this.handler // filter the handler we registered ourselves) - ) { - return acc; - } else { - return acc + 1; - } - }, 0); - - const processWouldExit = userProvidedListenersCount === 0; - const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; - - if (!caughtFirstError) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - - // this is the first uncaught error and the ultimate reason for shutting down - // we want to do absolutely everything possible to ensure it gets captured - // also we want to make sure we don't go recursion crazy if more errors happen after this one - firstError = error; - caughtFirstError = true; - - if (hub.getIntegration(OnUncaughtException)) { - hub.withScope((scope) => { - scope.setLevel('fatal'); - hub.captureException(error, { - originalException: error, - data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, - }); - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - }); - } else { - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - } - } else { - if (shouldApplyFatalHandlingLogic) { - if (calledFatalError) { - // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn( - 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', - ); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(error); - } else if (!caughtSecondError) { - // two cases for how we can hit this branch: - // - capturing of first error blew up and we just caught the exception from that - // - quit trying to capture, proceed with shutdown - // - a second independent error happened while waiting for first error to capture - // - want to avoid causing premature shutdown before first error capture finishes - // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff - // so let's instead just delay a bit before we proceed with our action here - // in case 1, we just wait a bit unnecessarily but ultimately do the same thing - // in case 2, the delay hopefully made us wait long enough for the capture to finish - // two potential nonideal outcomes: - // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError - // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error - // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) - // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish - caughtSecondError = true; - setTimeout(() => { - if (!calledFatalError) { - // it was probably case 1, let's treat err as the sendErr and call onFatalError - calledFatalError = true; - onFatalError(firstError, error); - } else { - // it was probably case 2, our first error finished capturing while we waited, cool, do nothing - } - }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc - } - } - } - }; - } -} OnUncaughtException.__initStatic(); - - -//# sourceMappingURL=onuncaughtexception.js.map - - -/***/ }), -/* 1659 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "logAndExitProcess": () => (/* binding */ logAndExitProcess) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); - - - -const DEFAULT_SHUTDOWN_TIMEOUT = 2000; - -/** - * @hidden - */ -function logAndExitProcess(error) { - // eslint-disable-next-line no-console - console.error(error && error.stack ? error.stack : error); - - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().getClient(); - - if (client === undefined) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('No NodeClient was defined, we are exiting the process now.'); - global.process.exit(1); - } - - const options = client.getOptions(); - const timeout = - (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || - DEFAULT_SHUTDOWN_TIMEOUT; - client.close(timeout).then( - (result) => { - if (!result) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); - } - global.process.exit(1); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error(error); - }, - ); -} - - -//# sourceMappingURL=errorhandling.js.map - - -/***/ }), -/* 1660 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUnhandledRejection": () => (/* binding */ OnUnhandledRejection) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1615); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1659); - - - - -/** Global Promise Rejection handler */ -class OnUnhandledRejection { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUnhandledRejection';} - - /** - * @inheritDoc - */ - __init() {this.name = OnUnhandledRejection.id;} - - /** - * @inheritDoc - */ - constructor( - _options - - = { mode: 'warn' }, - ) {;this._options = _options;OnUnhandledRejection.prototype.__init.call(this);} - - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); - } - - /** - * Send an exception with reason - * @param reason string - * @param promise promise - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any - sendUnhandledPromise(reason, promise) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - if (hub.getIntegration(OnUnhandledRejection)) { - hub.withScope((scope) => { - scope.setExtra('unhandledPromiseRejection', true); - hub.captureException(reason, { - originalException: promise, - data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, - }); - }); - } - this._handleRejection(reason); - } - - /** - * Handler for `mode` option - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _handleRejection(reason) { - // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 - const rejectionWarning = - 'This error originated either by ' + - 'throwing inside of an async function without a catch block, ' + - 'or by rejecting a promise which was not handled with .catch().' + - ' The promise rejected with the reason:'; - - /* eslint-disable no-console */ - if (this._options.mode === 'warn') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - console.error(reason && reason.stack ? reason.stack : reason); - }); - } else if (this._options.mode === 'strict') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - }); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(reason); - } - /* eslint-enable no-console */ - } -} OnUnhandledRejection.__initStatic(); - - -//# sourceMappingURL=onunhandledrejection.js.map - - -/***/ }), -/* 1661 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "LinkedErrors": () => (/* binding */ LinkedErrors) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1603); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1602); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1614); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1628); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1662); - - - - - - -const DEFAULT_KEY = 'cause'; -const DEFAULT_LIMIT = 5; - -/** Adds SDK info to an event. */ -class LinkedErrors { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'LinkedErrors';} - - /** - * @inheritDoc - */ - __init() {this.name = LinkedErrors.id;} - - /** - * @inheritDoc - */ - - /** - * @inheritDoc - */ - - /** - * @inheritDoc - */ - constructor(options = {}) {;LinkedErrors.prototype.__init.call(this); - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; - } - - /** - * @inheritDoc - */ - setupOnce() { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor)(async (event, hint) => { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)(); - const self = hub.getIntegration(LinkedErrors); - const client = hub.getClient(); - if (client && self && self._handler && typeof self._handler === 'function') { - await self._handler(client.getOptions().stackParser, event, hint); - } - return event; - }); - } - - /** - * @inheritDoc - */ - _handler(stackParser, event, hint) { - if (!event.exception || !event.exception.values || !(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(hint.originalException, Error)) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.resolvedSyncPromise)(event); - } - - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SyncPromise(resolve => { - void this._walkErrorTree(stackParser, hint.originalException , this._key) - .then((linkedErrors) => { - if (event && event.exception && event.exception.values) { - event.exception.values = [...linkedErrors, ...event.exception.values]; - } - resolve(event); - }) - .then(null, () => { - resolve(event); - }); - }); - } - - /** - * @inheritDoc - */ - async _walkErrorTree( - stackParser, - error, - key, - stack = [], - ) { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(error[key], Error) || stack.length + 1 >= this._limit) { - return Promise.resolve(stack); - } - - const exception = (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__.exceptionFromError)(stackParser, error[key]); - - // If the ContextLines integration is enabled, we add source code context to linked errors - // because we can't guarantee the order that integrations are run. - const contextLines = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(_contextlines_js__WEBPACK_IMPORTED_MODULE_1__.ContextLines); - if (contextLines && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__._optionalChain)([exception, 'access', _ => _.stacktrace, 'optionalAccess', _2 => _2.frames])) { - await contextLines.addSourceContextToFrames(exception.stacktrace.frames); - } - - return new Promise((resolve, reject) => { - void this._walkErrorTree(stackParser, error[key], key, [exception, ...stack]) - .then(resolve) - .then(null, () => { - reject(); - }); - }); - } -}LinkedErrors.__initStatic(); - - -//# sourceMappingURL=linkederrors.js.map - - -/***/ }), -/* 1662 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "ContextLines": () => (/* binding */ ContextLines), -/* harmony export */ "resetFileContentCache": () => (/* binding */ resetFileContentCache) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1609); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1663); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lru_map__WEBPACK_IMPORTED_MODULE_1__); - - - - - -const FILE_CONTENT_CACHE = new lru_map__WEBPACK_IMPORTED_MODULE_1__.LRUMap(100); -const DEFAULT_LINES_OF_CONTEXT = 7; - -// TODO: Replace with promisify when minimum supported node >= v8 -function readTextFileAsync(path) { - return new Promise((resolve, reject) => { - (0,fs__WEBPACK_IMPORTED_MODULE_0__.readFile)(path, 'utf8', (err, data) => { - if (err) reject(err); - else resolve(data); - }); - }); -} - -/** - * Resets the file cache. Exists for testing purposes. - * @hidden - */ -function resetFileContentCache() { - FILE_CONTENT_CACHE.clear(); -} - -/** Add node modules / packages to the event */ -class ContextLines { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'ContextLines';} - - /** - * @inheritDoc - */ - __init() {this.name = ContextLines.id;} - - constructor( _options = {}) {;this._options = _options;ContextLines.prototype.__init.call(this);} - - /** Get's the number of context lines to add */ - get _contextLines() { - return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; - } - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addSourceContext(event)); - } - - /** Processes an event and adds context lines */ - async addSourceContext(event) { - if (this._contextLines > 0 && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) { - for (const exception of event.exception.values) { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) { - await this.addSourceContextToFrames(exception.stacktrace.frames); - } - } - } - - return event; - } - - /** Adds context lines to frames */ - async addSourceContextToFrames(frames) { - const contextLines = this._contextLines; - - for (const frame of frames) { - // Only add context if we have a filename and it hasn't already been added - if (frame.filename && frame.context_line === undefined) { - const sourceFile = await _readSourceFile(frame.filename); - - if (sourceFile) { - try { - const lines = sourceFile.split('\n'); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.addContextToFrame)(lines, frame, contextLines); - } catch (e) { - // anomaly, being defensive in case - // unlikely to ever happen in practice but can definitely happen in theory - } - } - } - } - } -}ContextLines.__initStatic(); - -/** - * Reads file contents and caches them in a global LRU cache. - * - * @param filename filepath to read content from. - */ -async function _readSourceFile(filename) { - const cachedFile = FILE_CONTENT_CACHE.get(filename); - // We have a cache hit - if (cachedFile !== undefined) { - return cachedFile; - } - - let content = null; - try { - content = await readTextFileAsync(filename); - } catch (_) { - // - } - - FILE_CONTENT_CACHE.set(filename, content); - return content; -} - - -//# sourceMappingURL=contextlines.js.map - - -/***/ }), -/* 1663 */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/** - * 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 <http://hunch.se/> - * 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 (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } -})(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 <D> 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 <key> 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); - - if (entry) { - // update existing - entry.value = value; - this._markEntryAsUsed(entry); - return this; - } - - // new entry - this._keymap.set(key, (entry = new Entry(key, value))); - - 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; - } - - // 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 <entry> 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]; - } -}; - -// ---------------------------------------------------------------------------- -// Following code is optional and can be removed without breaking the core -// functionality. - -LRUMap.prototype.find = function(key) { - let e = this._keymap.get(key); - return e ? e.value : undefined; -}; - -LRUMap.prototype.has = function(key) { - return this._keymap.has(key); -}; - -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; - } - - this.size--; - return entry.value; -}; - -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(); -}; - - -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 }; - } -}; - - -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 }; - } -}; - -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 }; - } -}; - - -LRUMap.prototype.keys = function() { - return new KeyIterator(this.oldest); -}; - -LRUMap.prototype.values = function() { - return new ValueIterator(this.oldest); -}; - -LRUMap.prototype.entries = function() { - return this; -}; - -LRUMap.prototype[Symbol.iterator] = function() { - return new EntryIterator(this.oldest); -}; - -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]; - } -}; - -/** 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; -}; - -}); - - -/***/ }), -/* 1664 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Modules": () => (/* binding */ Modules) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); - - - -let moduleCache; - -/** Extract information about paths */ -function getPaths() { - try { - return __webpack_require__.c ? Object.keys(__webpack_require__.c ) : []; - } catch (e) { - return []; - } -} - -/** Extract information about package.json modules */ -function collectModules() - - { - const mainPaths = (__webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].paths) || []; - const paths = getPaths(); - const infos - - = {}; - const seen - - = {}; - - paths.forEach(path => { - let dir = path; - - /** Traverse directories upward in the search of package.json file */ - const updir = () => { - const orig = dir; - dir = (0,path__WEBPACK_IMPORTED_MODULE_1__.dirname)(orig); - - if (!dir || orig === dir || seen[orig]) { - return undefined; - } - if (mainPaths.indexOf(dir) < 0) { - return updir(); - } - - const pkgfile = (0,path__WEBPACK_IMPORTED_MODULE_1__.join)(orig, 'package.json'); - seen[orig] = true; - - if (!(0,fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(pkgfile)) { - return updir(); - } - - try { - const info = JSON.parse((0,fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(pkgfile, 'utf8')) - -; - infos[info.name] = info.version; - } catch (_oO) { - // no-empty - } - }; - - updir(); - }); - - return infos; -} - -/** Add node modules / packages to the event */ -class Modules {constructor() { Modules.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Modules';} - - /** - * @inheritDoc - */ - __init() {this.name = Modules.id;} - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - addGlobalEventProcessor(event => { - if (!getCurrentHub().getIntegration(Modules)) { - return event; - } - return { - ...event, - modules: { - ...event.modules, - ...this._getModules(), - }, - }; - }); - } - - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ - _getModules() { - if (!moduleCache) { - moduleCache = collectModules(); - } - return moduleCache; - } -} Modules.__initStatic(); - - -//# sourceMappingURL=modules.js.map - - -/***/ }), -/* 1665 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Context": () => (/* binding */ Context), -/* harmony export */ "getDeviceContext": () => (/* binding */ getDeviceContext), -/* harmony export */ "readDirAsync": () => (/* binding */ readDirAsync), -/* harmony export */ "readFileAsync": () => (/* binding */ readFileAsync) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(828); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); - - - - - - - -// TODO: Required until we drop support for Node v8 -const readFileAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readFile); -const readDirAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readdir); - -/** Add node modules / packages to the event */ -class Context { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Context';} - - /** - * @inheritDoc - */ - __init() {this.name = Context.id;} - - /** - * Caches context so it's only evaluated once - */ - - constructor( _options = { app: true, os: true, device: true, culture: true }) {;this._options = _options;Context.prototype.__init.call(this); - // - } - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addContext(event)); - } - - /** Processes an event and adds context */ - async addContext(event) { - if (this._cachedContext === undefined) { - this._cachedContext = this._getContexts(); - } - - const updatedContext = this._updateContext(await this._cachedContext); - - event.contexts = { - ...event.contexts, - app: { ...updatedContext.app, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) }, - os: { ...updatedContext.os, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) }, - device: { ...updatedContext.device, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) }, - culture: { ...updatedContext.culture, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) }, - }; - - return event; - } - - /** - * Updates the context with dynamic values that can change - */ - _updateContext(contexts) { - // Only update properties if they exist - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _9 => _9.app, 'optionalAccess', _10 => _10.app_memory])) { - contexts.app.app_memory = process.memoryUsage().rss; - } - - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _11 => _11.device, 'optionalAccess', _12 => _12.free_memory])) { - contexts.device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); - } - - return contexts; - } - - /** - * Gets the contexts for the current environment - */ - async _getContexts() { - const contexts = {}; - - if (this._options.os) { - contexts.os = await getOsContext(); - } - - if (this._options.app) { - contexts.app = getAppContext(); - } - - if (this._options.device) { - contexts.device = getDeviceContext(this._options.device); - } - - if (this._options.culture) { - const culture = getCultureContext(); - - if (culture) { - contexts.culture = culture; - } - } - - return contexts; - } -}Context.__initStatic(); - -/** - * Returns the operating system context. - * - * Based on the current platform, this uses a different strategy to provide the - * most accurate OS information. Since this might involve spawning subprocesses - * or accessing the file system, this should only be executed lazily and cached. - * - * - On macOS (Darwin), this will execute the `sw_vers` utility. The context - * has a `name`, `version`, `build` and `kernel_version` set. - * - On Linux, this will try to load a distribution release from `/etc` and set - * the `name`, `version` and `kernel_version` fields. - * - On all other platforms, only a `name` and `version` will be returned. Note - * that `version` might actually be the kernel version. - */ -async function getOsContext() { - const platformId = os__WEBPACK_IMPORTED_MODULE_2__.platform(); - switch (platformId) { - case 'darwin': - return getDarwinInfo(); - case 'linux': - return getLinuxInfo(); - default: - return { - name: PLATFORM_NAMES[platformId] || platformId, - version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - }; - } -} - -function getCultureContext() { - try { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (typeof (process.versions ).icu !== 'string') { - // Node was built without ICU support - return; - } - - // Check that node was built with full Intl support. Its possible it was built without support for non-English - // locales which will make resolvedOptions inaccurate - // - // https://nodejs.org/api/intl.html#detecting-internationalization-support - const january = new Date(9e8); - const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); - if (spanish.format(january) === 'enero') { - const options = Intl.DateTimeFormat().resolvedOptions(); - - return { - locale: options.locale, - timezone: options.timeZone, - }; - } - } catch (err) { - // - } - - return; -} - -function getAppContext() { - const app_memory = process.memoryUsage().rss; - const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); - - return { app_start_time, app_memory }; -} - -/** - * Gets device information from os - */ -function getDeviceContext(deviceOpt) { - const device = {}; - - // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). - // Hence, we only set boot time, if we get a valid uptime value. - // @see https://github.com/getsentry/sentry-javascript/issues/5856 - const uptime = os__WEBPACK_IMPORTED_MODULE_2__.uptime && os__WEBPACK_IMPORTED_MODULE_2__.uptime(); - if (typeof uptime === 'number') { - device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); - } - - device.arch = os__WEBPACK_IMPORTED_MODULE_2__.arch(); - - if (deviceOpt === true || deviceOpt.memory) { - device.memory_size = os__WEBPACK_IMPORTED_MODULE_2__.totalmem(); - device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); - } - - if (deviceOpt === true || deviceOpt.cpu) { - const cpuInfo = os__WEBPACK_IMPORTED_MODULE_2__.cpus(); - if (cpuInfo && cpuInfo.length) { - const firstCpu = cpuInfo[0]; - - device.processor_count = cpuInfo.length; - device.cpu_description = firstCpu.model; - device.processor_frequency = firstCpu.speed; - } - } - - return device; -} - -/** Mapping of Node's platform names to actual OS names. */ -const PLATFORM_NAMES = { - aix: 'IBM AIX', - freebsd: 'FreeBSD', - openbsd: 'OpenBSD', - sunos: 'SunOS', - win32: 'Windows', -}; - -/** Linux version file to check for a distribution. */ - -/** Mapping of linux release files located in /etc to distributions. */ -const LINUX_DISTROS = [ - { name: 'fedora-release', distros: ['Fedora'] }, - { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, - { name: 'redhat_version', distros: ['Red Hat Linux'] }, - { name: 'SuSE-release', distros: ['SUSE Linux'] }, - { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, - { name: 'debian_version', distros: ['Debian'] }, - { name: 'debian_release', distros: ['Debian'] }, - { name: 'arch-release', distros: ['Arch Linux'] }, - { name: 'gentoo-release', distros: ['Gentoo Linux'] }, - { name: 'novell-release', distros: ['SUSE Linux'] }, - { name: 'alpine-release', distros: ['Alpine Linux'] }, -]; - -/** Functions to extract the OS version from Linux release files. */ -const LINUX_VERSIONS - - = { - alpine: content => content, - arch: content => matchFirst(/distrib_release=(.*)/, content), - centos: content => matchFirst(/release ([^ ]+)/, content), - debian: content => content, - fedora: content => matchFirst(/release (..)/, content), - mint: content => matchFirst(/distrib_release=(.*)/, content), - red: content => matchFirst(/release ([^ ]+)/, content), - suse: content => matchFirst(/VERSION = (.*)\n/, content), - ubuntu: content => matchFirst(/distrib_release=(.*)/, content), -}; - -/** - * Executes a regular expression with one capture group. - * - * @param regex A regular expression to execute. - * @param text Content to execute the RegEx on. - * @returns The captured string if matched; otherwise undefined. - */ -function matchFirst(regex, text) { - const match = regex.exec(text); - return match ? match[1] : undefined; -} - -/** Loads the macOS operating system context. */ -async function getDarwinInfo() { - // Default values that will be used in case no operating system information - // can be loaded. The default version is computed via heuristics from the - // kernel version, but the build ID is missing. - const darwinInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Mac OS X', - version: `10.${Number(os__WEBPACK_IMPORTED_MODULE_2__.release().split('.')[0]) - 4}`, - }; - - try { - // We try to load the actual macOS version by executing the `sw_vers` tool. - // This tool should be available on every standard macOS installation. In - // case this fails, we stick with the values computed above. - - const output = await new Promise((resolve, reject) => { - (0,child_process__WEBPACK_IMPORTED_MODULE_0__.execFile)('/usr/bin/sw_vers', (error, stdout) => { - if (error) { - reject(error); - return; - } - resolve(stdout); - }); - }); - - darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); - darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); - darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); - } catch (e) { - // ignore - } - - return darwinInfo; -} - -/** Returns a distribution identifier to look up version callbacks. */ -function getLinuxDistroId(name) { - return name.split(' ')[0].toLowerCase(); -} - -/** Loads the Linux operating system context. */ -async function getLinuxInfo() { - // By default, we cannot assume anything about the distribution or Linux - // version. `os.release()` returns the kernel version and we assume a generic - // "Linux" name, which will be replaced down below. - const linuxInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Linux', - }; - - try { - // We start guessing the distribution by listing files in the /etc - // directory. This is were most Linux distributions (except Knoppix) store - // release files with certain distribution-dependent meta data. We search - // for exactly one known file defined in `LINUX_DISTROS` and exit if none - // are found. In case there are more than one file, we just stick with the - // first one. - const etcFiles = await readDirAsync('/etc'); - const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); - if (!distroFile) { - return linuxInfo; - } - - // Once that file is known, load its contents. To make searching in those - // files easier, we lowercase the file contents. Since these files are - // usually quite small, this should not allocate too much memory and we only - // hold on to it for a very short amount of time. - const distroPath = (0,path__WEBPACK_IMPORTED_MODULE_3__.join)('/etc', distroFile.name); - const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase(); - - // Some Linux distributions store their release information in the same file - // (e.g. RHEL and Centos). In those cases, we scan the file for an - // identifier, that basically consists of the first word of the linux - // distribution name (e.g. "red" for Red Hat). In case there is no match, we - // just assume the first distribution in our list. - const { distros } = distroFile; - linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; - - // Based on the found distribution, we can now compute the actual version - // number. This is different for every distribution, so several strategies - // are computed in `LINUX_VERSIONS`. - const id = getLinuxDistroId(linuxInfo.name); - linuxInfo.version = LINUX_VERSIONS[id](contents); - } catch (e) { - // ignore - } - - return linuxInfo; -} - - -//# sourceMappingURL=context.js.map - - -/***/ }), -/* 1666 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "RequestData": () => (/* binding */ RequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1670); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1667); - - - -const DEFAULT_OPTIONS = { - include: { - cookies: true, - data: true, - headers: true, - ip: false, - query_string: true, - url: true, - user: { - id: true, - username: true, - email: true, - }, - }, - transactionNamingScheme: 'methodPath', -}; - -/** Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` - * so it can be used in cross-platform SDKs like `@sentry/nextjs`. */ -class RequestData { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'RequestData';} - - /** - * @inheritDoc - */ - __init() {this.name = RequestData.id;} - - /** - * Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but - * left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use - * something similar in browser-based SDKs in the future. - */ - - /** - * @inheritDoc - */ - constructor(options = {}) {;RequestData.prototype.__init.call(this); - this._addRequestData = _requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent; - this._options = { - ...DEFAULT_OPTIONS, - ...options, - include: { - // @ts-ignore It's mad because `method` isn't a known `include` key. (It's only here and not set by default in - // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) - method: true, - ...DEFAULT_OPTIONS.include, - ...options.include, - user: - options.include && typeof options.include.user === 'boolean' - ? options.include.user - : { - ...DEFAULT_OPTIONS.include.user, - // Unclear why TS still thinks `options.include.user` could be a boolean at this point - ...((options.include || {}).user ), - }, - }, - }; - } - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - // Note: In the long run, most of the logic here should probably move into the request data utility functions. For - // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. - // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once - // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) - const { transactionNamingScheme } = this._options; - - addGlobalEventProcessor(event => { - const hub = getCurrentHub(); - const self = hub.getIntegration(RequestData); - - const { sdkProcessingMetadata = {} } = event; - const req = sdkProcessingMetadata.request; - - // If the globally installed instance of this integration isn't associated with the current hub, `self` will be - // undefined - if (!self || !req) { - return event; - } - - // The Express request handler takes a similar `include` option to that which can be passed to this integration. - // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this - // integration, so that all of this passing and conversion isn't necessary - const addRequestDataOptions = - sdkProcessingMetadata.requestDataOptionsFromExpressHandler || - sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || - convertReqDataIntegrationOptsToAddReqDataOpts(this._options); - - const processedEvent = this._addRequestData(event, req, addRequestDataOptions); - - // Transaction events already have the right `transaction` value - if (event.type === 'transaction' || transactionNamingScheme === 'handler') { - return processedEvent; - } - - // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` - // value with a high-quality one - const reqWithTransaction = req ; - const transaction = reqWithTransaction._sentryTransaction; - if (transaction) { - // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to - // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential - // to break things like alert rules.) - const shouldIncludeMethodInTransactionName = - getSDKName(hub) === 'sentry.javascript.nextjs' - ? transaction.name.startsWith('/api') - : transactionNamingScheme !== 'path'; - - const [transactionValue] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractPathForTransaction)(req, { - path: true, - method: shouldIncludeMethodInTransactionName, - customRoute: transaction.name, - }); - - processedEvent.transaction = transactionValue; - } - - return processedEvent; - }); - } -} RequestData.__initStatic(); - -/** Convert this integration's options to match what `addRequestDataToEvent` expects */ -/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */ -function convertReqDataIntegrationOptsToAddReqDataOpts( - integrationOptions, -) { - const { - transactionNamingScheme, - include: { ip, user, ...requestOptions }, - } = integrationOptions; - - const requestIncludeKeys = []; - for (const [key, value] of Object.entries(requestOptions)) { - if (value) { - requestIncludeKeys.push(key); - } - } - - let addReqDataUserOpt; - if (user === undefined) { - addReqDataUserOpt = true; - } else if (typeof user === 'boolean') { - addReqDataUserOpt = user; - } else { - const userIncludeKeys = []; - for (const [key, value] of Object.entries(user)) { - if (value) { - userIncludeKeys.push(key); - } - } - addReqDataUserOpt = userIncludeKeys; - } - - return { - include: { - ip, - user: addReqDataUserOpt, - request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, - transaction: transactionNamingScheme, - }, - }; -} - -function getSDKName(hub) { - try { - // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to - // write out a long chain of `a && a.b && a.b.c && ...` - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return hub.getClient().getOptions()._metadata.sdk.name; - } catch (err) { - // In theory we should never get here - return undefined; - } -} - - -//# sourceMappingURL=requestdata.js.map - - -/***/ }), -/* 1667 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* binding */ DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1669); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1622); -/* harmony import */ var cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_1__); - - - - - -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, -}; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; - -/** - * Options deciding what parts of the request to use when enhancing an event - */ - -/** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addRequestDataToTransaction(transaction, req) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); - } - transaction.setData('query', extractQueryParams(req)); -} - -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); - - let path = ''; - let source = 'url'; - - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; - } - - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); - } - - let name = ''; - if (options.method && method) { - name += method; - } - if (options.method && options.path) { - name += ' '; - } - if (options.path && path) { - name += path; - } - - return [name, source]; -} - -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; - } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; - } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; - } - } -} - -/** JSDoc */ -function extractUserData( - user - -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; - - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; - } - }); - - return extractedUser; -} - -/** - * Normalize data from the request object - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies - * - * @returns An object containing normalized request data - */ -function extractRequestData( - req, - options - -, -) { - const { include = DEFAULT_REQUEST_INCLUDES } = options || {}; - const requestData = {}; - - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) - -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; - - // Remove the Cookie header in case cookie data should not be included in the event - if (!include.includes('cookies')) { - delete (requestData.headers ).cookie; - } - - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && cookie__WEBPACK_IMPORTED_MODULE_0__.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isString)(req.body) ? req.body : JSON.stringify((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.normalize)(req.body)); - } - break; - } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; - } - } - } - }); - - return requestData; -} - -/** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included - * - * @returns The mutated `Event` object - */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([options, 'optionalAccess', _ => _.include]), - }; - - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request }) - : extractRequestData(req); - - event.request = { - ...event.request, - ...extractedRequestData, - }; - } - - if (include.user) { - const extractedUser = req.user && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; - - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; - } - } - - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; - } - } - - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); - } - - return event; -} - -function extractQueryParams(req) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; - - if (!originalUrl) { - return; - } - - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; - } - - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - url__WEBPACK_IMPORTED_MODULE_1__.parse(originalUrl).query || - undefined - ); -} - - -//# sourceMappingURL=requestdata.js.map - - -/***/ }), -/* 1668 */ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module exports. - * @public - */ - -exports.parse = parse; -exports.serialize = serialize; - -/** - * Module variables. - * @private - */ - -var decode = decodeURIComponent; -var encode = encodeURIComponent; - -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ - -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; - -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ - -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } - - var obj = {} - var opt = options || {}; - var pairs = str.split(';') - var dec = opt.decode || decode; - - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var index = pair.indexOf('=') - - // skip things that don't look like key=value - if (index < 0) { - continue; - } - - var key = pair.substring(0, index).trim() - - // only assign once - if (undefined == obj[key]) { - var val = pair.substring(index + 1, pair.length).trim() - - // quoted values - if (val[0] === '"') { - val = val.slice(1, -1) - } - - obj[key] = tryDecode(val, dec); - } - } - - return obj; -} - -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ - -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; - - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } - - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } - - var value = enc(val); - - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } - - var str = name + '=' + value; - - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; - - if (isNaN(maxAge) || !isFinite(maxAge)) { - throw new TypeError('option maxAge is invalid') - } - - str += '; Max-Age=' + Math.floor(maxAge); - } - - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } - - str += '; Domain=' + opt.domain; - } - - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } - - str += '; Path=' + opt.path; - } - - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); - } - - str += '; Expires=' + opt.expires.toUTCString(); - } - - if (opt.httpOnly) { - str += '; HttpOnly'; - } - - if (opt.secure) { - str += '; Secure'; - } - - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; - - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } - } - - return str; -} - -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ - -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} - - -/***/ }), -/* 1669 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getNumberOfUrlSegments": () => (/* binding */ getNumberOfUrlSegments), -/* harmony export */ "parseUrl": () => (/* binding */ parseUrl), -/* harmony export */ "stripUrlQueryAndFragment": () => (/* binding */ stripUrlQueryAndFragment) -/* harmony export */ }); -/** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not <a/> href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object - */ -function parseUrl(url) - - { - if (!url) { - return {}; - } - - const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - - if (!match) { - return {}; - } - - // coerce to undefined values to empty string so we don't get 'undefined' - const query = match[6] || ''; - const fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, // everything minus origin - }; -} - -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} - -/** - * Returns number of URL segments of a passed string URL. - */ -function getNumberOfUrlSegments(url) { - // split at '/' or at '\/' to split regex urls correctly - return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length; -} - - -//# sourceMappingURL=url.js.map - - -/***/ }), -/* 1670 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1625); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1622); -/* harmony import */ var _url_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1669); - - - - - -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, -}; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; - -/** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addRequestDataToTransaction( - transaction, - req, - deps, -) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); - } - transaction.setData('query', extractQueryParams(req, deps)); -} - -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); - - let path = ''; - let source = 'url'; - - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; - } - - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_url_js__WEBPACK_IMPORTED_MODULE_0__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); - } - - let name = ''; - if (options.method && method) { - name += method; - } - if (options.method && options.path) { - name += ' '; - } - if (options.path && path) { - name += path; - } - - return [name, source]; -} - -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; - } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; - } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; - } - } -} - -/** JSDoc */ -function extractUserData( - user - -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; - - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; - } - }); - - return extractedUser; -} - -/** - * Normalize data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies - * @returns An object containing normalized request data - */ -function extractRequestData( - req, - options - -, -) { - const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; - const requestData = {}; - - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) - -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && deps && deps.cookie && deps.cookie.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req, deps); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(req.body) ? req.body : JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_2__.normalize)(req.body)); - } - break; - } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; - } - } - } - }); - - return requestData; -} - -/** - * Options deciding what parts of the request to use when enhancing an event - */ - -/** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included - * @param options.deps Injected platform-specific dependencies - * @hidden - */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _ => _.include]), - }; - - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request, deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _2 => _2.deps]) }) - : extractRequestData(req, { deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _3 => _3.deps]) }); - - event.request = { - ...event.request, - ...extractedRequestData, - }; - } - - if (include.user) { - const extractedUser = req.user && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; - - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; - } - } - - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; - } - } - - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); - } - - return event; -} - -function extractQueryParams( - req, - deps, -) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; - - if (!originalUrl) { - return; - } - - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; - } - - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - (deps && deps.url && deps.url.parse(originalUrl).query) || - undefined - ); -} - - -//# sourceMappingURL=requestdata.js.map - - -/***/ }), -/* 1671 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getModule": () => (/* binding */ getModule) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1672); - - -/** normalizes Windows paths */ -function normalizePath(path) { - return path - .replace(/^[A-Z]:/, '') // remove Windows-style prefix - .replace(/\\/g, '/'); // replace all `\` instances with `/` -} - -/** Gets the module from a filename */ -function getModule(filename) { - if (!filename) { - return; - } - - const normalizedFilename = normalizePath(filename); - - // We could use optional chaining here but webpack does like that mixed with require - const base = normalizePath( - `${( true && __webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].filename && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(__webpack_require__.c[__webpack_require__.s].filename)) || global.process.cwd()}/`, - ); - - // It's specifically a module - const file = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.basename)(normalizedFilename, '.js'); - - const path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(normalizedFilename); - let n = path.lastIndexOf('/node_modules/'); - if (n > -1) { - // /node_modules/ is 14 chars - return `${path.substr(n + 14).replace(/\//g, '.')}:${file}`; - } - // Let's see if it's a part of the main module - // To be a part of main module, it has to share the same base - n = `${path}/`.lastIndexOf(base, 0); - - if (n === 0) { - let moduleName = path.substr(base.length).replace(/\//g, '.'); - if (moduleName) { - moduleName += ':'; - } - moduleName += file; - return moduleName; - } - return file; -} - - -//# sourceMappingURL=module.js.map - - -/***/ }), -/* 1672 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "basename": () => (/* binding */ basename), -/* harmony export */ "dirname": () => (/* binding */ dirname), -/* harmony export */ "isAbsolute": () => (/* binding */ isAbsolute), -/* harmony export */ "join": () => (/* binding */ join), -/* harmony export */ "normalizePath": () => (/* binding */ normalizePath), -/* harmony export */ "relative": () => (/* binding */ relative), -/* harmony export */ "resolve": () => (/* binding */ resolve) -/* harmony export */ }); -// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript -// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js - -/** JSDoc */ -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - let up = 0; - for (let i = parts.length - 1; i >= 0; i--) { - const last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; -/** JSDoc */ -function splitPath(filename) { - const parts = splitPathRe.exec(filename); - return parts ? parts.slice(1) : []; -} - -// path.resolve([from ...], to) -// posix version -/** JSDoc */ -function resolve(...args) { - let resolvedPath = ''; - let resolvedAbsolute = false; - - for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - const path = i >= 0 ? args[i] : '/'; - - // Skip empty entries - if (!path) { - continue; - } - - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray( - resolvedPath.split('/').filter(p => !!p), - !resolvedAbsolute, - ).join('/'); - - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; -} - -/** JSDoc */ -function trim(arr) { - let start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') { - break; - } - } - - let end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') { - break; - } - } - - if (start > end) { - return []; - } - return arr.slice(start, end - start + 1); -} - -// path.relative(from, to) -// posix version -/** JSDoc */ -function relative(from, to) { - /* eslint-disable no-param-reassign */ - from = resolve(from).substr(1); - to = resolve(to).substr(1); - /* eslint-enable no-param-reassign */ - - const fromParts = trim(from.split('/')); - const toParts = trim(to.split('/')); - - const length = Math.min(fromParts.length, toParts.length); - let samePartsLength = length; - for (let i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - let outputParts = []; - for (let i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -} - -// path.normalize(path) -// posix version -/** JSDoc */ -function normalizePath(path) { - const isPathAbsolute = isAbsolute(path); - const trailingSlash = path.substr(-1) === '/'; - - // Normalize the path - let normalizedPath = normalizeArray( - path.split('/').filter(p => !!p), - !isPathAbsolute, - ).join('/'); - - if (!normalizedPath && !isPathAbsolute) { - normalizedPath = '.'; - } - if (normalizedPath && trailingSlash) { - normalizedPath += '/'; - } - - return (isPathAbsolute ? '/' : '') + normalizedPath; -} - -// posix version -/** JSDoc */ -function isAbsolute(path) { - return path.charAt(0) === '/'; -} - -// posix version -/** JSDoc */ -function join(...args) { - return normalizePath(args.join('/')); -} - -/** JSDoc */ -function dirname(path) { - const result = splitPath(path); - const root = result[0]; - let dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -} - -/** JSDoc */ -function basename(path, ext) { - let f = splitPath(path)[2]; - if (ext && f.substr(ext.length * -1) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -} - - -//# sourceMappingURL=path.js.map - - -/***/ }), -/* 1673 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "InboundFilters": () => (/* binding */ InboundFilters), -/* harmony export */ "_mergeOptions": () => (/* binding */ _mergeOptions), -/* harmony export */ "_shouldDropEvent": () => (/* binding */ _shouldDropEvent) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1610); - - -// "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. -const DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; - -/** Options for the InboundFilters integration */ - -/** Inbound filters configurable by the user */ -class InboundFilters { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'InboundFilters';} - - /** - * @inheritDoc - */ - __init() {this.name = InboundFilters.id;} - - constructor( _options = {}) {;this._options = _options;InboundFilters.prototype.__init.call(this);} - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - const eventProcess = (event) => { - const hub = getCurrentHub(); - if (hub) { - const self = hub.getIntegration(InboundFilters); - if (self) { - const client = hub.getClient(); - const clientOptions = client ? client.getOptions() : {}; - const options = _mergeOptions(self._options, clientOptions); - return _shouldDropEvent(event, options) ? null : event; - } - } - return event; - }; - - eventProcess.id = this.name; - addGlobalEventProcessor(eventProcess); - } -} InboundFilters.__initStatic(); - -/** JSDoc */ -function _mergeOptions( - internalOptions = {}, - clientOptions = {}, -) { - return { - allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], - denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], - ignoreErrors: [ - ...(internalOptions.ignoreErrors || []), - ...(clientOptions.ignoreErrors || []), - ...DEFAULT_IGNORE_ERRORS, - ], - ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, - }; -} - -/** JSDoc */ -function _shouldDropEvent(event, options) { - if (options.ignoreInternal && _isSentryError(event)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return true; - } - if (_isIgnoredError(event, options.ignoreErrors)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`, - ); - return true; - } - if (_isDeniedUrl(event, options.denyUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; - } - if (!_isAllowedUrl(event, options.allowUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; - } - return false; -} - -function _isIgnoredError(event, ignoreErrors) { - if (!ignoreErrors || !ignoreErrors.length) { - return false; - } - - return _getPossibleEventMessages(event).some(message => (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(message, ignoreErrors)); -} - -function _isDeniedUrl(event, denyUrls) { - // TODO: Use Glob instead? - if (!denyUrls || !denyUrls.length) { - return false; - } - const url = _getEventFilterUrl(event); - return !url ? false : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, denyUrls); -} - -function _isAllowedUrl(event, allowUrls) { - // TODO: Use Glob instead? - if (!allowUrls || !allowUrls.length) { - return true; - } - const url = _getEventFilterUrl(event); - return !url ? true : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, allowUrls); -} - -function _getPossibleEventMessages(event) { - if (event.message) { - return [event.message]; - } - if (event.exception) { - try { - const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {}; - return [`${value}`, `${type}: ${value}`]; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract message for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return []; - } - } - return []; -} - -function _isSentryError(event) { - try { - // @ts-ignore can't be a sentry error if undefined - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return event.exception.values[0].type === 'SentryError'; - } catch (e) { - // ignore - } - return false; -} - -function _getLastValidUrl(frames = []) { - for (let i = frames.length - 1; i >= 0; i--) { - const frame = frames[i]; - - if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') { - return frame.filename || null; - } - } - - return null; -} - -function _getEventFilterUrl(event) { - try { - let frames; - try { - // @ts-ignore we only care about frames if the whole thing here is defined - frames = event.exception.values[0].stacktrace.frames; - } catch (e) { - // ignore - } - return frames ? _getLastValidUrl(frames) : null; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract url for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return null; - } -} - - -//# sourceMappingURL=inboundfilters.js.map - - -/***/ }), -/* 1674 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* binding */ FunctionToString) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1612); - - -let originalFunctionToString; - -/** Patch toString calls to return proper name for wrapped functions */ -class FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'FunctionToString';} - - /** - * @inheritDoc - */ - __init() {this.name = FunctionToString.id;} - - /** - * @inheritDoc - */ - setupOnce() { - // 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 ( ...args) { - const context = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.getOriginalFunction)(this) || this; - return originalFunctionToString.apply(context, args); - }; - } -} FunctionToString.__initStatic(); - - -//# sourceMappingURL=functiontostring.js.map - - -/***/ }), -/* 1675 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "initAndBind": () => (/* binding */ initAndBind) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1615); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); - - - -/** A class object that can instantiate Client objects. */ - -/** - * 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) { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.enable(); - } else { - // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped - // eslint-disable-next-line no-console - console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); - } - } - const hub = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - const scope = hub.getScope(); - if (scope) { - scope.update(options.initialScope); - } - - const client = new clientClass(options); - hub.bindClient(client); -} - - -//# sourceMappingURL=sdk.js.map - - -/***/ }), -/* 1676 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "deepReadDirSync": () => (/* binding */ deepReadDirSync) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); - - - -/** - * Recursively read the contents of a directory. - * - * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this - * directory. - * @returns Array holding all relative paths - */ -function deepReadDirSync(targetDir) { - const targetDirAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.resolve(targetDir); - - if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(targetDirAbsPath)) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`); - } - - if (!fs__WEBPACK_IMPORTED_MODULE_0__.statSync(targetDirAbsPath).isDirectory()) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`); - } - - // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it - // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve - // the difference between `targetDirAbsPath` and `currentDirAbsPath`. - const deepReadCurrentDir = (currentDirAbsPath) => { - return fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => { - const itemAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.join(currentDirAbsPath, itemName); - - if (fs__WEBPACK_IMPORTED_MODULE_0__.statSync(itemAbsPath).isDirectory()) { - return [...absPaths, ...deepReadCurrentDir(itemAbsPath)]; - } - - return [...absPaths, itemAbsPath]; - }, []); - }; - - return deepReadCurrentDir(targetDirAbsPath).map(absPath => path__WEBPACK_IMPORTED_MODULE_1__.relative(targetDirAbsPath, absPath)); -} - - -//# sourceMappingURL=utils.js.map - - -/***/ }), -/* 1677 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.extractRequestData), -/* harmony export */ "parseRequest": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.parseRequest), -/* harmony export */ "errorHandler": () => (/* binding */ errorHandler), -/* harmony export */ "requestHandler": () => (/* binding */ requestHandler), -/* harmony export */ "tracingHandler": () => (/* binding */ tracingHandler) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1625); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1602); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1617); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1615); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1611); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1679); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1657); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1670); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1612); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1314); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1667); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1651); -/* harmony import */ var _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1678); - - - - - - - - -/* eslint-disable @typescript-eslint/no-explicit-any */ - -/** - * Express-compatible tracing handler. - * @see Exposed as `Handlers.tracingHandler` - */ -function tracingHandler() - - { - return function sentryTracingMiddleware( - req, - res, - next, - ) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const options = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]); - - if ( - !options || - options.instrumenter !== 'sentry' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _5 => _5.method, 'optionalAccess', _6 => _6.toUpperCase, 'call', _7 => _7()]) === 'OPTIONS' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _8 => _8.method, 'optionalAccess', _9 => _9.toUpperCase, 'call', _10 => _10()]) === 'HEAD' - ) { - return next(); - } - - // TODO: This is the `hasTracingEnabled` check, but we're doing it manually since `@sentry/tracing` isn't a - // dependency of `@sentry/node`. Long term, that function should probably move to `@sentry/hub. - if (!('tracesSampleRate' in options) && !('tracesSampler' in options)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn( - 'Sentry `tracingHandler` is being used, but tracing is disabled. Please enable tracing by setting ' + - 'either `tracesSampleRate` or `tracesSampler` in your `Sentry.init()` options.', - ); - return next(); - } - - // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) - const traceparentData = - req.headers && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.isString)(req.headers['sentry-trace']) && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.extractTraceparentData)(req.headers['sentry-trace']); - const incomingBaggageHeaders = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _11 => _11.headers, 'optionalAccess', _12 => _12.baggage]); - const dynamicSamplingContext = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.baggageHeaderToDynamicSamplingContext)(incomingBaggageHeaders); - - const [name, source] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.extractPathForTransaction)(req, { path: true, method: true }); - const transaction = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.startTransaction)( - { - name, - op: 'http.server', - ...traceparentData, - metadata: { - dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, - // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become - // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the - // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to - // be sure - request: req, - source, - }, - }, - // extra context passed to the tracesSampler - { request: (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_1__.extractRequestData)(req) }, - ); - - // We put the transaction on the scope so users can attach children to it - hub.configureScope(scope => { - scope.setSpan(transaction); - }); - - // We also set __sentry_transaction on the response so people can grab the transaction there to add - // spans to it later. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).__sentry_transaction = transaction; - - res.once('finish', () => { - // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction - // closes - setImmediate(() => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.addRequestDataToTransaction)(transaction, req); - transaction.setHttpStatus(res.statusCode); - transaction.finish(); - }); - }); - - next(); - }; -} - -/** - * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the - * `AddRequestDataToEventOptions` interface. - * - * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`. - */ -function convertReqHandlerOptsToAddReqDataOpts( - reqHandlerOptions = {}, -) { - let addRequestDataOptions; - - if ('include' in reqHandlerOptions) { - addRequestDataOptions = { include: reqHandlerOptions.include }; - } else { - // eslint-disable-next-line deprecation/deprecation - const { ip, request, transaction, user } = reqHandlerOptions ; - - if (ip || request || transaction || user) { - addRequestDataOptions = { include: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.dropUndefinedKeys)({ ip, request, transaction, user }) }; - } - } - - return addRequestDataOptions; -} - -/** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` - */ -function requestHandler( - options, -) { - // TODO (v8): Get rid of this - const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options); - - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const client = currentHub.getClient(); - // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the - // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - client.initSessionFlusher(); - - // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode - const scope = currentHub.getScope(); - if (scope && scope.getSession()) { - scope.setSession(); - } - } - - return function sentryRequestMiddleware( - req, - res, - next, - ) { - if (options && options.flushTimeout && options.flushTimeout > 0) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const _end = res.end; - res.end = function (chunk, encoding, cb) { - void (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.flush)(options.flushTimeout) - .then(() => { - _end.call(this, chunk, encoding, cb); - }) - .then(null, e => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.error(e); - _end.call(this, chunk, encoding, cb); - }); - }; - } - const local = domain__WEBPACK_IMPORTED_MODULE_0__.create(); - local.add(req); - local.add(res); - - local.run(() => { - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - - currentHub.configureScope(scope => { - scope.setSDKProcessingMetadata({ - request: req, - // TODO (v8): Stop passing this - requestDataOptionsFromExpressHandler: requestDataOptions, - }); - - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - const scope = currentHub.getScope(); - if (scope) { - // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope.setRequestSession({ status: 'ok' }); - } - } - }); - - res.once('finish', () => { - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - setImmediate(() => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (client && (client )._captureRequestSession) { - // Calling _captureRequestSession to capture request session at the end of the request by incrementing - // the correct SessionAggregates bucket i.e. crashed, errored or exited - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (client )._captureRequestSession(); - } - }); - } - }); - next(); - }); - }; -} - -/** JSDoc */ - -/** JSDoc */ -function getStatusCodeFromResponse(error) { - const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); - return statusCode ? parseInt(statusCode , 10) : 500; -} - -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error) { - const status = getStatusCodeFromResponse(error); - return status >= 500; -} - -/** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` - */ -function errorHandler(options - -) - - { - return function sentryErrorMiddleware( - error, - _req, - res, - next, - ) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; - - if (shouldHandleError(error)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.withScope)(_scope => { - // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`, - // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't - // hurt to be sure - _scope.setSDKProcessingMetadata({ request: _req }); - - // For some reason we need to set the transaction on the scope again - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const transaction = (res ).__sentry_transaction ; - if (transaction && _scope.getSpan() === undefined) { - _scope.setSpan(transaction); - } - - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)().getClient(); - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the - // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only - // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be - // running in SessionAggregates mode - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const isSessionAggregatesMode = (client )._sessionFlusher !== undefined; - if (isSessionAggregatesMode) { - const requestSession = _scope.getRequestSession(); - // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a - // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within - // the bounds of a request, and if so the status is updated - if (requestSession && requestSession.status !== undefined) { - requestSession.status = 'crashed'; - } - } - } - - const eventId = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.captureException)(error); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).sentry = eventId; - next(error); - }); - - return; - } - - next(error); - }; -} - -// TODO (v8 / #5257): Remove this -// eslint-disable-next-line deprecation/deprecation -; - - -//# sourceMappingURL=handlers.js.map - - -/***/ }), -/* 1678 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData), -/* harmony export */ "parseRequest": () => (/* binding */ parseRequest) -/* harmony export */ }); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1667); - - -/** - * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead. - */ - -/** - * Normalizes data from the request object, accounting for framework differences. - * - * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead. - * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. - * @returns An object containing normalized request data - */ -function extractRequestData(req, keys) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.extractRequestData)(req, { include: keys }); -} - -/** - * Options deciding what parts of the request to use when enhancing an event - * - * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use - * `AddRequestDataToEventOptions` in `@sentry/utils` instead. - */ - -/** - * Enriches passed event with request data. - * - * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead. - * - * @param event Will be mutated and enriched with req data - * @param req Request object - * @param options object containing flags to enable functionality - * @hidden - */ -function parseRequest(event, req, options = {}) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent)(event, req, { include: options }); -} - - -//# sourceMappingURL=requestDataDeprecated.js.map - - -/***/ }), -/* 1679 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "TRACEPARENT_REGEXP": () => (/* binding */ TRACEPARENT_REGEXP), -/* harmony export */ "extractTraceparentData": () => (/* binding */ extractTraceparentData) -/* harmony export */ }); -const TRACEPARENT_REGEXP = new RegExp( - '^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$', // whitespace -); - -/** - * Extract transaction context data from a `sentry-trace` header. - * - * @param traceparent Traceparent string - * - * @returns Object containing data from the header, or undefined if traceparent string is malformed - */ -function extractTraceparentData(traceparent) { - const matches = traceparent.match(TRACEPARENT_REGEXP); - - if (!traceparent || !matches) { - // empty string or no matches is invalid traceparent data - return undefined; - } - - let parentSampled; - if (matches[3] === '1') { - parentSampled = true; - } else if (matches[3] === '0') { - parentSampled = false; - } - - return { - traceId: matches[1], - parentSampled, - parentSpanId: matches[2], - }; -} - - -//# sourceMappingURL=tracing.js.map - - -/***/ }), -/* 1680 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* reexport safe */ _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__.FunctionToString), -/* harmony export */ "InboundFilters": () => (/* reexport safe */ _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__.InboundFilters) -/* harmony export */ }); -/* harmony import */ var _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1674); -/* harmony import */ var _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1673); - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1681 */, -/* 1682 */, -/* 1683 */, -/* 1684 */ +/* 1601 */, +/* 1602 */, +/* 1603 */, +/* 1604 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // @ts-check @@ -240788,7 +227550,6 @@ const soapRequest = __webpack_require__(1337) const { parseTags, parseValue } = __webpack_require__(1561) const { commanderArretServiceSouscritMesures } = __webpack_require__(1562) const xml2js = __webpack_require__(1519) -const Sentry = __webpack_require__(1601) /** * @param {string} url @@ -240824,7 +227585,6 @@ async function terminateContract( }).catch(err => { log('error', 'commanderArretServiceSouscritMesures') log('error', err) - Sentry.captureException('commanderArretServiceSouscritMesures', err) throw errors.VENDOR_DOWN }) @@ -240844,11 +227604,8 @@ async function terminateContract( } return parsedReply } catch (error) { - const errorMessage = - 'Error while parsing user contract termination: ' + error - log('error', errorMessage) + log('error', 'Error while parsing user contract termination: ' + error) log('error', `Enedis issue ${JSON.stringify(parsedReply.Envelope.Body)}`) - Sentry.captureException(errorMessage) throw errors.VENDOR_DOWN } } @@ -240857,17 +227614,17 @@ module.exports = { terminateContract } /***/ }), -/* 1685 */, -/* 1686 */, -/* 1687 */, -/* 1688 */, -/* 1689 */, -/* 1690 */, -/* 1691 */ +/* 1605 */, +/* 1606 */, +/* 1607 */, +/* 1608 */, +/* 1609 */, +/* 1610 */, +/* 1611 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { log, updateOrCreate } = __webpack_require__(1) -const { isLocal } = __webpack_require__(1692) +const { isLocal } = __webpack_require__(1612) const cozyClient = __webpack_require__(485) async function saveAccountData(accountId, accountData) { @@ -240927,7 +227684,7 @@ module.exports = { getAccount, saveAccountData, getAccountForDelete } /***/ }), -/* 1692 */ +/* 1612 */ /***/ ((module) => { function isLocal() { @@ -240953,45 +227710,7 @@ module.exports = { isLocal, isDev } /***/ }), -/* 1693 */, -/* 1694 */, -/* 1695 */, -/* 1696 */, -/* 1697 */, -/* 1698 */, -/* 1699 */, -/* 1700 */, -/* 1701 */, -/* 1702 */, -/* 1703 */, -/* 1704 */, -/* 1705 */, -/* 1706 */, -/* 1707 */, -/* 1708 */, -/* 1709 */, -/* 1710 */, -/* 1711 */, -/* 1712 */, -/* 1713 */, -/* 1714 */, -/* 1715 */, -/* 1716 */, -/* 1717 */, -/* 1718 */, -/* 1719 */, -/* 1720 */, -/* 1721 */, -/* 1722 */, -/* 1723 */, -/* 1724 */, -/* 1725 */, -/* 1726 */, -/* 1727 */, -/* 1728 */, -/* 1729 */, -/* 1730 */, -/* 1731 */ +/* 1613 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // @ts-check @@ -241000,17 +227719,15 @@ const { getAccountRev, getAccountSecret, getAccountId, -} = __webpack_require__(1732) +} = __webpack_require__(1614) const { getBoConsent, deleteBoConsent } = __webpack_require__(1563) -const { terminateContract } = __webpack_require__(1684) -const { getAccountForDelete } = __webpack_require__(1691) +const { terminateContract } = __webpack_require__(1604) +const { getAccountForDelete } = __webpack_require__(1611) const moment = __webpack_require__(1379) __webpack_require__(1516) -const { isLocal, isDev } = __webpack_require__(1692) -const Sentry = __webpack_require__(1601) - moment.locale('fr') // set the language moment.tz.setDefault('Europe/Paris') // set the timezone +const { isLocal, isDev } = __webpack_require__(1612) async function onDeleteAccount() { log('info', 'Deleting account ...') @@ -241062,19 +227779,17 @@ async function onDeleteAccount() { ) } } else { - const errorMessage = `No service id retrieved from BO` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log('error', `No service id retrieved from BO`) throw errors.VENDOR_DOWN } } log('info', 'Deleting account succeed') } else { - const errorMessage = + log( + 'error', 'No account revision was found, something went wrong during the deletion of said account' - log('error', errorMessage) - Sentry.captureException(errorMessage) + ) throw errors.VENDOR_DOWN } } @@ -241084,9 +227799,10 @@ onDeleteAccount().then( log('info', `onDeleteAccount: Successfully delete consent and account.`) }, err => { - const errorMessage = `onDeleteAccount: An error occurred during script: ${err.message}` - log('error', errorMessage) - Sentry.captureException(errorMessage) + log( + 'error', + `onDeleteAccount: An error occured during script: ${err.message}` + ) throw errors.VENDOR_DOWN } ) @@ -241095,21 +227811,18 @@ module.exports = { onDeleteAccount } /***/ }), -/* 1732 */ +/* 1614 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { log } = __webpack_require__(1) -const { isLocal } = __webpack_require__(1692) -const Sentry = __webpack_require__(1601) +const { isLocal } = __webpack_require__(1612) function getAccountId() { log('info', `getAccountId`) try { return JSON.parse(process.env.COZY_FIELDS).account } catch (err) { - const errorMessage = `You must provide 'account' in COZY_FIELDS: ${err.message}` - Sentry.captureException(errorMessage) - throw new Error(errorMessage) + throw new Error(`You must provide 'account' in COZY_FIELDS: ${err.message}`) } } @@ -241121,9 +227834,7 @@ function getAccountRev() { ? 'fakeAccountRev' : JSON.parse(process.env.COZY_FIELDS).account_rev } catch (err) { - const errorMessage = `You must provide 'account' in COZY_FIELDS: ${err.message}` - Sentry.captureException(errorMessage) - throw new Error(errorMessage) + throw new Error(`You must provide 'account' in COZY_FIELDS: ${err.message}`) } } @@ -241139,9 +227850,9 @@ function getAccountSecret() { ? JSON.parse(process.env.COZY_FIELDS) : JSON.parse(process.env.COZY_PARAMETERS).secret } catch (err) { - const errorMessage = `You must provide 'account-types' in COZY_PARAMETERS: ${err.message}` - Sentry.captureException(errorMessage) - throw new Error(errorMessage) + throw new Error( + `You must provide 'account-types' in COZY_PARAMETERS: ${err.message}` + ) } } module.exports = { getAccountId, getAccountRev, getAccountSecret } @@ -241205,21 +227916,6 @@ module.exports = { getAccountId, getAccountRev, getAccountSecret } /******/ }; /******/ })(); /******/ -/******/ /* webpack/runtime/harmony module decorator */ -/******/ (() => { -/******/ __webpack_require__.hmd = (module) => { -/******/ module = Object.create(module); -/******/ if (!module.children) module.children = []; -/******/ Object.defineProperty(module, 'exports', { -/******/ enumerable: true, -/******/ set: () => { -/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); -/******/ } -/******/ }); -/******/ return module; -/******/ }; -/******/ })(); -/******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) @@ -241250,7 +227946,7 @@ module.exports = { getAccountId, getAccountRev, getAccountSecret } /******/ // module cache are used so entry inlining is disabled /******/ // startup /******/ // Load entry module and return exports -/******/ var __webpack_exports__ = __webpack_require__(__webpack_require__.s = 1731); +/******/ var __webpack_exports__ = __webpack_require__(__webpack_require__.s = 1613); /******/ /******/ })() ; \ No newline at end of file diff --git a/package.json b/package.json index 21f4a49..9f9918f 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,8 @@ "build": "webpack", "clean": "rm -rf ./data", "cozyPublish": "cozy-app-publish --token $REGISTRY_TOKEN --build-commit $(git rev-parse ${DEPLOY_BRANCH:-build})", - "deploy": "git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build}", "deploy-dev": "git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build-dev}", + "deploy": "git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build}", "dev": "cozy-konnector-dev", "lint": "eslint --fix .", "onDeleteAccount:standalone": "cozy-konnector-standalone src/onDeleteAccount.js", @@ -48,8 +48,6 @@ "travisDeployKey": "./bin/generate_travis_deploy_key" }, "dependencies": { - "@sentry/node": "^7.23.0", - "@sentry/tracing": "^7.23.0", "axios": "^0.27.2", "cozy-konnector-libs": "4.55.0", "easy-soap-request": "^4.7.0", -- GitLab