const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./GraphView-CDDCHVO0.js","./index-Q1cQr26V.js","./keybindingService-Cak1En5n.js","./serverConfigStore-DCme3xlV.js","./GraphView-CqZ3opAX.css","./UserSelectView-CXmVKOeK.js","./BaseViewTemplate-BhQMaVFP.js","./ServerStartView-48wfE1MS.js","./ServerStartView-CJiwVDQY.css","./InstallView-By3hC1fC.js","./InstallView-CxhfFC8Y.css","./WelcomeView-C8whKl15.js","./WelcomeView-Brz3-luE.css","./NotSupportedView-Vc8_xWgH.js","./NotSupportedView-DQerxQzi.css","./DownloadGitView-rPK_vYgU.js","./ManualConfigurationView-enyqGo0M.js","./ManualConfigurationView-CsirlNfV.css","./MetricsConsentView-lSfLu4nr.js","./DesktopStartView-le6AjGZr.js","./KeybindingPanel-D6O16W_1.js","./index-DpF-ptbJ.js","./KeybindingPanel-DvrUYZ4S.css","./ExtensionPanel-3jWrm6Zi.js","./ServerConfigPanel-B-w0HFlz.js","./index-je62U6DH.js","./index-BRhY6FpL.css"])))=>i.map(i=>d[i]); var __defProp2 = Object.defineProperty; var __name = (target, value4) => __defProp2(target, "name", { value: value4, configurable: true }); (/* @__PURE__ */ __name(function polyfill2() { const relList = document.createElement("link").relList; if (relList && relList.supports && relList.supports("modulepreload")) { return; } for (const link2 of document.querySelectorAll('link[rel="modulepreload"]')) { processPreload(link2); } new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type !== "childList") { continue; } for (const node3 of mutation.addedNodes) { if (node3.tagName === "LINK" && node3.rel === "modulepreload") processPreload(node3); } } }).observe(document, { childList: true, subtree: true }); function getFetchOpts(link2) { const fetchOpts = {}; if (link2.integrity) fetchOpts.integrity = link2.integrity; if (link2.referrerPolicy) fetchOpts.referrerPolicy = link2.referrerPolicy; if (link2.crossOrigin === "use-credentials") fetchOpts.credentials = "include"; else if (link2.crossOrigin === "anonymous") fetchOpts.credentials = "omit"; else fetchOpts.credentials = "same-origin"; return fetchOpts; } __name(getFetchOpts, "getFetchOpts"); function processPreload(link2) { if (link2.ep) return; link2.ep = true; const fetchOpts = getFetchOpts(link2); fetch(link2.href, fetchOpts); } __name(processPreload, "processPreload"); }, "polyfill"))(); var __defProp$2 = Object.defineProperty; var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; var __hasOwnProp$1 = Object.prototype.hasOwnProperty; var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; var __defNormalProp$2 = /* @__PURE__ */ __name((obj, key, value4) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value: value4 }) : obj[key] = value4, "__defNormalProp$2"); var __spreadValues$1 = /* @__PURE__ */ __name((a2, b2) => { for (var prop2 in b2 || (b2 = {})) if (__hasOwnProp$1.call(b2, prop2)) __defNormalProp$2(a2, prop2, b2[prop2]); if (__getOwnPropSymbols$1) for (var prop2 of __getOwnPropSymbols$1(b2)) { if (__propIsEnum$1.call(b2, prop2)) __defNormalProp$2(a2, prop2, b2[prop2]); } return a2; }, "__spreadValues$1"); function isEmpty$1(value4) { return value4 === null || value4 === void 0 || value4 === "" || Array.isArray(value4) && value4.length === 0 || !(value4 instanceof Date) && typeof value4 === "object" && Object.keys(value4).length === 0; } __name(isEmpty$1, "isEmpty$1"); function compare$1(value1, value22, comparator2, order = 1) { let result = -1; const emptyValue1 = isEmpty$1(value1); const emptyValue2 = isEmpty$1(value22); if (emptyValue1 && emptyValue2) result = 0; else if (emptyValue1) result = order; else if (emptyValue2) result = -order; else if (typeof value1 === "string" && typeof value22 === "string") result = comparator2(value1, value22); else result = value1 < value22 ? -1 : value1 > value22 ? 1 : 0; return result; } __name(compare$1, "compare$1"); function deepEquals(obj1, obj2) { if (obj1 === obj2) return true; if (obj1 && obj2 && typeof obj1 == "object" && typeof obj2 == "object") { var arrObj1 = Array.isArray(obj1), arrObj2 = Array.isArray(obj2), i2, length, key; if (arrObj1 && arrObj2) { length = obj1.length; if (length != obj2.length) return false; for (i2 = length; i2-- !== 0; ) if (!deepEquals(obj1[i2], obj2[i2])) return false; return true; } if (arrObj1 != arrObj2) return false; var dateObj1 = obj1 instanceof Date, dateObj2 = obj2 instanceof Date; if (dateObj1 != dateObj2) return false; if (dateObj1 && dateObj2) return obj1.getTime() == obj2.getTime(); var regexpObj1 = obj1 instanceof RegExp, regexpObj2 = obj2 instanceof RegExp; if (regexpObj1 != regexpObj2) return false; if (regexpObj1 && regexpObj2) return obj1.toString() == obj2.toString(); var keys2 = Object.keys(obj1); length = keys2.length; if (length !== Object.keys(obj2).length) return false; for (i2 = length; i2-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(obj2, keys2[i2])) return false; for (i2 = length; i2-- !== 0; ) { key = keys2[i2]; if (!deepEquals(obj1[key], obj2[key])) return false; } return true; } return obj1 !== obj1 && obj2 !== obj2; } __name(deepEquals, "deepEquals"); function isFunction$9(value4) { return !!(value4 && value4.constructor && value4.call && value4.apply); } __name(isFunction$9, "isFunction$9"); function isNotEmpty(value4) { return !isEmpty$1(value4); } __name(isNotEmpty, "isNotEmpty"); function resolveFieldData(data25, field) { if (!data25 || !field) { return null; } try { const value4 = data25[field]; if (isNotEmpty(value4)) return value4; } catch (e2) { } if (Object.keys(data25).length) { if (isFunction$9(field)) { return field(data25); } else if (field.indexOf(".") === -1) { return data25[field]; } else { let fields = field.split("."); let value4 = data25; for (let i2 = 0, len = fields.length; i2 < len; ++i2) { if (value4 == null) { return null; } value4 = value4[fields[i2]]; } return value4; } } return null; } __name(resolveFieldData, "resolveFieldData"); function equals(obj1, obj2, field) { if (field) return resolveFieldData(obj1, field) === resolveFieldData(obj2, field); else return deepEquals(obj1, obj2); } __name(equals, "equals"); function contains(value4, list2) { if (value4 != null && list2 && list2.length) { for (let val of list2) { if (equals(value4, val)) return true; } } return false; } __name(contains, "contains"); function filter(value4, fields, filterValue) { let filteredItems = []; if (value4) { for (let item3 of value4) { for (let field of fields) { if (String(resolveFieldData(item3, field)).toLowerCase().indexOf(filterValue.toLowerCase()) > -1) { filteredItems.push(item3); break; } } } } return filteredItems; } __name(filter, "filter"); function findIndexInList(value4, list2) { let index2 = -1; if (list2) { for (let i2 = 0; i2 < list2.length; i2++) { if (list2[i2] === value4) { index2 = i2; break; } } } return index2; } __name(findIndexInList, "findIndexInList"); function findLast$1(arr, callback) { let item3; if (isNotEmpty(arr)) { try { item3 = arr.findLast(callback); } catch (e2) { item3 = [...arr].reverse().find(callback); } } return item3; } __name(findLast$1, "findLast$1"); function findLastIndex(arr, callback) { let index2 = -1; if (isNotEmpty(arr)) { try { index2 = arr.findLastIndex(callback); } catch (e2) { index2 = arr.lastIndexOf([...arr].reverse().find(callback)); } } return index2; } __name(findLastIndex, "findLastIndex"); function isObject$e(value4, empty3 = true) { return value4 instanceof Object && value4.constructor === Object && (empty3 || Object.keys(value4).length !== 0); } __name(isObject$e, "isObject$e"); function resolve$2(obj, ...params) { return isFunction$9(obj) ? obj(...params) : obj; } __name(resolve$2, "resolve$2"); function isString$9(value4, empty3 = true) { return typeof value4 === "string" && (empty3 || value4 !== ""); } __name(isString$9, "isString$9"); function toFlatCase(str) { return isString$9(str) ? str.replace(/(-|_)/g, "").toLowerCase() : str; } __name(toFlatCase, "toFlatCase"); function getKeyValue(obj, key = "", params = {}) { const fKeys = toFlatCase(key).split("."); const fKey = fKeys.shift(); return fKey ? isObject$e(obj) ? getKeyValue(resolve$2(obj[Object.keys(obj).find((k2) => toFlatCase(k2) === fKey) || ""], params), fKeys.join("."), params) : void 0 : resolve$2(obj, params); } __name(getKeyValue, "getKeyValue"); function insertIntoOrderedArray(item3, index2, arr, sourceArr) { if (arr.length > 0) { let injected = false; for (let i2 = 0; i2 < arr.length; i2++) { let currentItemIndex = findIndexInList(arr[i2], sourceArr); if (currentItemIndex > index2) { arr.splice(i2, 0, item3); injected = true; break; } } if (!injected) { arr.push(item3); } } else { arr.push(item3); } } __name(insertIntoOrderedArray, "insertIntoOrderedArray"); function isArray$a(value4, empty3 = true) { return Array.isArray(value4) && (empty3 || value4.length !== 0); } __name(isArray$a, "isArray$a"); function isDate$3(value4) { return value4 instanceof Date && value4.constructor === Date; } __name(isDate$3, "isDate$3"); function isNumber$5(value4) { return isNotEmpty(value4) && !isNaN(value4); } __name(isNumber$5, "isNumber$5"); function isPrintableCharacter(char = "") { return isNotEmpty(char) && char.length === 1 && !!char.match(/\S| /); } __name(isPrintableCharacter, "isPrintableCharacter"); function localeComparator() { return new Intl.Collator(void 0, { numeric: true }).compare; } __name(localeComparator, "localeComparator"); function matchRegex(str, regex2) { if (regex2) { const match2 = regex2.test(str); regex2.lastIndex = 0; return match2; } return false; } __name(matchRegex, "matchRegex"); function mergeKeys(...args) { const _mergeKeys = /* @__PURE__ */ __name((target = {}, source = {}) => { const mergedObj = __spreadValues$1({}, target); Object.keys(source).forEach((key) => { if (isObject$e(source[key]) && key in target && isObject$e(target[key])) { mergedObj[key] = _mergeKeys(target[key], source[key]); } else { mergedObj[key] = source[key]; } }); return mergedObj; }, "_mergeKeys"); return args.reduce((acc, obj, i2) => i2 === 0 ? obj : _mergeKeys(acc, obj), {}); } __name(mergeKeys, "mergeKeys"); function minifyCSS(css3) { return css3 ? css3.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, "").replace(/ {2,}/g, " ").replace(/ ([{:}]) /g, "$1").replace(/([;,]) /g, "$1").replace(/ !/g, "!").replace(/: /g, ":") : css3; } __name(minifyCSS, "minifyCSS"); function nestedKeys(obj = {}, parentKey = "") { return Object.entries(obj).reduce((o2, [key, value4]) => { const currentKey = parentKey ? `${parentKey}.${key}` : key; isObject$e(value4) ? o2 = o2.concat(nestedKeys(value4, currentKey)) : o2.push(currentKey); return o2; }, []); } __name(nestedKeys, "nestedKeys"); function removeAccents(str) { if (str && str.search(/[\xC0-\xFF]/g) > -1) { str = str.replace(/[\xC0-\xC5]/g, "A").replace(/[\xC6]/g, "AE").replace(/[\xC7]/g, "C").replace(/[\xC8-\xCB]/g, "E").replace(/[\xCC-\xCF]/g, "I").replace(/[\xD0]/g, "D").replace(/[\xD1]/g, "N").replace(/[\xD2-\xD6\xD8]/g, "O").replace(/[\xD9-\xDC]/g, "U").replace(/[\xDD]/g, "Y").replace(/[\xDE]/g, "P").replace(/[\xE0-\xE5]/g, "a").replace(/[\xE6]/g, "ae").replace(/[\xE7]/g, "c").replace(/[\xE8-\xEB]/g, "e").replace(/[\xEC-\xEF]/g, "i").replace(/[\xF1]/g, "n").replace(/[\xF2-\xF6\xF8]/g, "o").replace(/[\xF9-\xFC]/g, "u").replace(/[\xFE]/g, "p").replace(/[\xFD\xFF]/g, "y"); } return str; } __name(removeAccents, "removeAccents"); function reorderArray(value4, from2, to) { if (value4 && from2 !== to) { if (to >= value4.length) { to %= value4.length; from2 %= value4.length; } value4.splice(to, 0, value4.splice(from2, 1)[0]); } } __name(reorderArray, "reorderArray"); function sort(value1, value22, order = 1, comparator2, nullSortOrder = 1) { const result = compare$1(value1, value22, comparator2, order); let finalSortOrder = order; if (isEmpty$1(value1) || isEmpty$1(value22)) { finalSortOrder = nullSortOrder === 1 ? order : nullSortOrder; } return finalSortOrder * result; } __name(sort, "sort"); function stringify(value4, indent = 2, currentIndent = 0) { const currentIndentStr = " ".repeat(currentIndent); const nextIndentStr = " ".repeat(currentIndent + indent); if (isArray$a(value4)) { return "[" + value4.map((v2) => stringify(v2, indent, currentIndent + indent)).join(", ") + "]"; } else if (isDate$3(value4)) { return value4.toISOString(); } else if (isFunction$9(value4)) { return value4.toString(); } else if (isObject$e(value4)) { return "{\n" + Object.entries(value4).map(([k2, v2]) => `${nextIndentStr}${k2}: ${stringify(v2, indent, currentIndent + indent)}`).join(",\n") + ` ${currentIndentStr}}`; } else { return JSON.stringify(value4); } } __name(stringify, "stringify"); function toCapitalCase(str) { return isString$9(str, false) ? str[0].toUpperCase() + str.slice(1) : str; } __name(toCapitalCase, "toCapitalCase"); function toKebabCase(str) { return isString$9(str) ? str.replace(/(_)/g, "-").replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "-" + c2.toLowerCase()).toLowerCase() : str; } __name(toKebabCase, "toKebabCase"); function toTokenKey$1(str) { return isString$9(str) ? str.replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "." + c2.toLowerCase()).toLowerCase() : str; } __name(toTokenKey$1, "toTokenKey$1"); function EventBus() { const allHandlers = /* @__PURE__ */ new Map(); return { on(type, handler6) { let handlers2 = allHandlers.get(type); if (!handlers2) handlers2 = [handler6]; else handlers2.push(handler6); allHandlers.set(type, handlers2); return this; }, off(type, handler6) { let handlers2 = allHandlers.get(type); if (handlers2) { handlers2.splice(handlers2.indexOf(handler6) >>> 0, 1); } return this; }, emit(type, evt) { let handlers2 = allHandlers.get(type); if (handlers2) { handlers2.slice().map((handler6) => { handler6(evt); }); } }, clear() { allHandlers.clear(); } }; } __name(EventBus, "EventBus"); var __defProp$1 = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp$1 = /* @__PURE__ */ __name((obj, key, value4) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value: value4 }) : obj[key] = value4, "__defNormalProp$1"); var __spreadValues = /* @__PURE__ */ __name((a2, b2) => { for (var prop2 in b2 || (b2 = {})) if (__hasOwnProp.call(b2, prop2)) __defNormalProp$1(a2, prop2, b2[prop2]); if (__getOwnPropSymbols) for (var prop2 of __getOwnPropSymbols(b2)) { if (__propIsEnum.call(b2, prop2)) __defNormalProp$1(a2, prop2, b2[prop2]); } return a2; }, "__spreadValues"); var __spreadProps = /* @__PURE__ */ __name((a2, b2) => __defProps(a2, __getOwnPropDescs(b2)), "__spreadProps"); var __objRest = /* @__PURE__ */ __name((source, exclude) => { var target = {}; for (var prop2 in source) if (__hasOwnProp.call(source, prop2) && exclude.indexOf(prop2) < 0) target[prop2] = source[prop2]; if (source != null && __getOwnPropSymbols) for (var prop2 of __getOwnPropSymbols(source)) { if (exclude.indexOf(prop2) < 0 && __propIsEnum.call(source, prop2)) target[prop2] = source[prop2]; } return target; }, "__objRest"); function definePreset(...presets) { return mergeKeys(...presets); } __name(definePreset, "definePreset"); var ThemeService = EventBus(); var service_default = ThemeService; function toTokenKey(str) { return isString$9(str) ? str.replace(/[A-Z]/g, (c2, i2) => i2 === 0 ? c2 : "." + c2.toLowerCase()).toLowerCase() : str; } __name(toTokenKey, "toTokenKey"); function merge$2(value1, value22) { if (isArray$a(value1)) { value1.push(...value22 || []); } else if (isObject$e(value1)) { Object.assign(value1, value22); } } __name(merge$2, "merge$2"); function toValue$2(value4) { return isObject$e(value4) && value4.hasOwnProperty("value") && value4.hasOwnProperty("type") ? value4.value : value4; } __name(toValue$2, "toValue$2"); function toUnit(value4, variable = "") { const excludedProperties = ["opacity", "z-index", "line-height", "font-weight", "flex", "flex-grow", "flex-shrink", "order"]; if (!excludedProperties.some((property) => variable.endsWith(property))) { const val = `${value4}`.trim(); const valArr = val.split(" "); return valArr.map((v2) => isNumber$5(v2) ? `${v2}px` : v2).join(" "); } return value4; } __name(toUnit, "toUnit"); function toNormalizePrefix(prefix2) { return prefix2.replaceAll(/ /g, "").replace(/[^\w]/g, "-"); } __name(toNormalizePrefix, "toNormalizePrefix"); function toNormalizeVariable(prefix2 = "", variable = "") { return toNormalizePrefix(`${isString$9(prefix2, false) && isString$9(variable, false) ? `${prefix2}-` : prefix2}${variable}`); } __name(toNormalizeVariable, "toNormalizeVariable"); function getVariableName(prefix2 = "", variable = "") { return `--${toNormalizeVariable(prefix2, variable)}`; } __name(getVariableName, "getVariableName"); function getVariableValue(value4, variable = "", prefix2 = "", excludedKeyRegexes = [], fallback) { if (isString$9(value4)) { const regex2 = /{([^}]*)}/g; const val = value4.trim(); if (matchRegex(val, regex2)) { const _val = val.replaceAll(regex2, (v2) => { const path = v2.replace(/{|}/g, ""); const keys2 = path.split(".").filter((_v) => !excludedKeyRegexes.some((_r) => matchRegex(_v, _r))); return `var(${getVariableName(prefix2, toKebabCase(keys2.join("-")))}${isNotEmpty(fallback) ? `, ${fallback}` : ""})`; }); const calculationRegex = /(\d+\s+[\+\-\*\/]\s+\d+)/g; const cleanedVarRegex = /var\([^)]+\)/g; return matchRegex(_val.replace(cleanedVarRegex, "0"), calculationRegex) ? `calc(${_val})` : _val; } return toUnit(val, variable); } else if (isNumber$5(value4)) { return toUnit(value4, variable); } return void 0; } __name(getVariableValue, "getVariableValue"); function getComputedValue(obj = {}, value4) { if (isString$9(value4)) { const regex2 = /{([^}]*)}/g; const val = value4.trim(); return matchRegex(val, regex2) ? val.replaceAll(regex2, (v2) => getKeyValue(obj, v2.replace(/{|}/g, ""))) : val; } else if (isNumber$5(value4)) { return value4; } return void 0; } __name(getComputedValue, "getComputedValue"); function setProperty(properties, key, value4) { if (isString$9(key, false)) { properties.push(`${key}:${value4};`); } } __name(setProperty, "setProperty"); function getRule(selector, properties) { if (selector) { return `${selector}{${properties}}`; } return ""; } __name(getRule, "getRule"); function normalizeColor(color2) { if (color2.length === 4) { return `#${color2[1]}${color2[1]}${color2[2]}${color2[2]}${color2[3]}${color2[3]}`; } return color2; } __name(normalizeColor, "normalizeColor"); function hexToRgb$1(hex) { var bigint = parseInt(hex.substring(1), 16); var r2 = bigint >> 16 & 255; var g2 = bigint >> 8 & 255; var b2 = bigint & 255; return { r: r2, g: g2, b: b2 }; } __name(hexToRgb$1, "hexToRgb$1"); function rgbToHex(r2, g2, b2) { return `#${r2.toString(16).padStart(2, "0")}${g2.toString(16).padStart(2, "0")}${b2.toString(16).padStart(2, "0")}`; } __name(rgbToHex, "rgbToHex"); var mix_default = /* @__PURE__ */ __name((color1, color2, weight) => { color1 = normalizeColor(color1); color2 = normalizeColor(color2); var p2 = weight / 100; var w2 = p2 * 2 - 1; var w1 = (w2 + 1) / 2; var w22 = 1 - w1; var rgb1 = hexToRgb$1(color1); var rgb2 = hexToRgb$1(color2); var r2 = Math.round(rgb1.r * w1 + rgb2.r * w22); var g2 = Math.round(rgb1.g * w1 + rgb2.g * w22); var b2 = Math.round(rgb1.b * w1 + rgb2.b * w22); return rgbToHex(r2, g2, b2); }, "mix_default"); var shade_default = /* @__PURE__ */ __name((color2, percent) => mix_default("#000000", color2, percent), "shade_default"); var tint_default = /* @__PURE__ */ __name((color2, percent) => mix_default("#ffffff", color2, percent), "tint_default"); var scales = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]; var palette_default = /* @__PURE__ */ __name((color2) => { if (/{([^}]*)}/g.test(color2)) { const token = color2.replace(/{|}/g, ""); return scales.reduce((acc, scale) => (acc[scale] = `{${token}.${scale}}`, acc), {}); } return typeof color2 === "string" ? scales.reduce((acc, scale, i2) => (acc[scale] = i2 <= 5 ? tint_default(color2, (5 - i2) * 19) : shade_default(color2, (i2 - 5) * 15), acc), {}) : color2; }, "palette_default"); var $dt = /* @__PURE__ */ __name((tokenPath) => { var _a2; const theme42 = config_default.getTheme(); const variable = dtwt(theme42, tokenPath, void 0, "variable"); const name2 = (_a2 = variable.match(/--[\w-]+/g)) == null ? void 0 : _a2[0]; const value4 = dtwt(theme42, tokenPath, void 0, "value"); return { name: name2, variable, value: value4 }; }, "$dt"); var dt = /* @__PURE__ */ __name((...args) => { return dtwt(config_default.getTheme(), ...args); }, "dt"); var dtwt = /* @__PURE__ */ __name((theme42 = {}, tokenPath, fallback, type = "variable") => { if (tokenPath) { const { variable: VARIABLE, options: OPTIONS } = config_default.defaults || {}; const { prefix: prefix2, transform: transform2 } = (theme42 == null ? void 0 : theme42.options) || OPTIONS || {}; const regex2 = /{([^}]*)}/g; const token = matchRegex(tokenPath, regex2) ? tokenPath : `{${tokenPath}}`; const isStrictTransform = type === "value" || transform2 === "strict"; return isStrictTransform ? config_default.getTokenValue(tokenPath) : getVariableValue(token, void 0, prefix2, [VARIABLE.excludedKeyRegex], fallback); } return ""; }, "dtwt"); function css$2(style2) { return resolve$2(style2, { dt }); } __name(css$2, "css$2"); var $t = /* @__PURE__ */ __name((theme42 = {}) => { let { preset: _preset, options: _options } = theme42; return { preset(value4) { _preset = _preset ? mergeKeys(_preset, value4) : value4; return this; }, options(value4) { _options = _options ? __spreadValues(__spreadValues({}, _options), value4) : value4; return this; }, // features primaryPalette(primary) { const { semantic } = _preset || {}; _preset = __spreadProps(__spreadValues({}, _preset), { semantic: __spreadProps(__spreadValues({}, semantic), { primary }) }); return this; }, surfacePalette(surface) { var _a2, _b; const { semantic } = _preset || {}; const lightSurface = (surface == null ? void 0 : surface.hasOwnProperty("light")) ? surface == null ? void 0 : surface.light : surface; const darkSurface = (surface == null ? void 0 : surface.hasOwnProperty("dark")) ? surface == null ? void 0 : surface.dark : surface; const newColorScheme = { colorScheme: { light: __spreadValues(__spreadValues({}, (_a2 = semantic == null ? void 0 : semantic.colorScheme) == null ? void 0 : _a2.light), !!lightSurface && { surface: lightSurface }), dark: __spreadValues(__spreadValues({}, (_b = semantic == null ? void 0 : semantic.colorScheme) == null ? void 0 : _b.dark), !!darkSurface && { surface: darkSurface }) } }; _preset = __spreadProps(__spreadValues({}, _preset), { semantic: __spreadValues(__spreadValues({}, semantic), newColorScheme) }); return this; }, // actions define({ useDefaultPreset = false, useDefaultOptions = false } = {}) { return { preset: useDefaultPreset ? config_default.getPreset() : _preset, options: useDefaultOptions ? config_default.getOptions() : _options }; }, update({ mergePresets = true, mergeOptions: mergeOptions2 = true } = {}) { const newTheme = { preset: mergePresets ? mergeKeys(config_default.getPreset(), _preset) : _preset, options: mergeOptions2 ? __spreadValues(__spreadValues({}, config_default.getOptions()), _options) : _options }; config_default.setTheme(newTheme); return newTheme; }, use(options4) { const newTheme = this.define(options4); config_default.setTheme(newTheme); return newTheme; } }; }, "$t"); function toVariables_default(theme42, options4 = {}) { const VARIABLE = config_default.defaults.variable; const { prefix: prefix2 = VARIABLE.prefix, selector = VARIABLE.selector, excludedKeyRegex = VARIABLE.excludedKeyRegex } = options4; const _toVariables = /* @__PURE__ */ __name((_theme, _prefix = "") => { return Object.entries(_theme).reduce( (acc, [key, value4]) => { const px = matchRegex(key, excludedKeyRegex) ? toNormalizeVariable(_prefix) : toNormalizeVariable(_prefix, toKebabCase(key)); const v2 = toValue$2(value4); if (isObject$e(v2)) { const { variables: variables2, tokens: tokens2 } = _toVariables(v2, px); merge$2(acc["tokens"], tokens2); merge$2(acc["variables"], variables2); } else { acc["tokens"].push((prefix2 ? px.replace(`${prefix2}-`, "") : px).replaceAll("-", ".")); setProperty(acc["variables"], getVariableName(px), getVariableValue(v2, px, prefix2, [excludedKeyRegex])); } return acc; }, { variables: [], tokens: [] } ); }, "_toVariables"); const { variables, tokens } = _toVariables(theme42, prefix2); return { value: variables, tokens, declarations: variables.join(""), css: getRule(selector, variables.join("")) }; } __name(toVariables_default, "toVariables_default"); var themeUtils_default = { regex: { rules: { class: { pattern: /^\.([a-zA-Z][\w-]*)$/, resolve(value4) { return { type: "class", selector: value4, matched: this.pattern.test(value4.trim()) }; } }, attr: { pattern: /^\[(.*)\]$/, resolve(value4) { return { type: "attr", selector: `:root${value4}`, matched: this.pattern.test(value4.trim()) }; } }, media: { pattern: /^@media (.*)$/, resolve(value4) { return { type: "media", selector: `${value4}{:root{[CSS]}}`, matched: this.pattern.test(value4.trim()) }; } }, system: { pattern: /^system$/, resolve(value4) { return { type: "system", selector: "@media (prefers-color-scheme: dark){:root{[CSS]}}", matched: this.pattern.test(value4.trim()) }; } }, custom: { resolve(value4) { return { type: "custom", selector: value4, matched: true }; } } }, resolve(value4) { const rules = Object.keys(this.rules).filter((k2) => k2 !== "custom").map((r2) => this.rules[r2]); return [value4].flat().map((v2) => { var _a2; return (_a2 = rules.map((r2) => r2.resolve(v2)).find((rr) => rr.matched)) != null ? _a2 : this.rules.custom.resolve(v2); }); } }, _toVariables(theme42, options4) { return toVariables_default(theme42, { prefix: options4 == null ? void 0 : options4.prefix }); }, getCommon({ name: name2 = "", theme: theme42 = {}, params, set: set3, defaults: defaults2 }) { var _c, _d, _e, _f; const { preset, options: options4 } = theme42; let primitive_css, primitive_tokens, semantic_css, semantic_tokens; if (isNotEmpty(preset)) { const { primitive, semantic } = preset; const _a2 = semantic || {}, { colorScheme } = _a2, sRest = __objRest(_a2, ["colorScheme"]); const _b = colorScheme || {}, { dark: dark2 } = _b, csRest = __objRest(_b, ["dark"]); const prim_var = isNotEmpty(primitive) ? this._toVariables({ primitive }, options4) : {}; const sRest_var = isNotEmpty(sRest) ? this._toVariables({ semantic: sRest }, options4) : {}; const csRest_var = isNotEmpty(csRest) ? this._toVariables({ light: csRest }, options4) : {}; const dark_var = isNotEmpty(dark2) ? this._toVariables({ dark: dark2 }, options4) : {}; const [prim_css, prim_tokens] = [(_c = prim_var.declarations) != null ? _c : "", prim_var.tokens]; const [sRest_css, sRest_tokens] = [(_d = sRest_var.declarations) != null ? _d : "", sRest_var.tokens || []]; const [csRest_css, csRest_tokens] = [(_e = csRest_var.declarations) != null ? _e : "", csRest_var.tokens || []]; const [dark_css, dark_tokens] = [(_f = dark_var.declarations) != null ? _f : "", dark_var.tokens || []]; primitive_css = this.transformCSS(name2, prim_css, "light", "variable", options4, set3, defaults2); primitive_tokens = prim_tokens; const semantic_light_css = this.transformCSS(name2, `${sRest_css}${csRest_css}color-scheme:light`, "light", "variable", options4, set3, defaults2); const semantic_dark_css = this.transformCSS(name2, `${dark_css}color-scheme:dark`, "dark", "variable", options4, set3, defaults2); semantic_css = `${semantic_light_css}${semantic_dark_css}`; semantic_tokens = [.../* @__PURE__ */ new Set([...sRest_tokens, ...csRest_tokens, ...dark_tokens])]; } return { primitive: { css: primitive_css, tokens: primitive_tokens }, semantic: { css: semantic_css, tokens: semantic_tokens } }; }, getPreset({ name: name2 = "", preset = {}, options: options4, params, set: set3, defaults: defaults2, selector }) { var _c, _d, _e; const _name = name2.replace("-directive", ""); const _a2 = preset, { colorScheme } = _a2, vRest = __objRest(_a2, ["colorScheme"]); const _b = colorScheme || {}, { dark: dark2 } = _b, csRest = __objRest(_b, ["dark"]); const vRest_var = isNotEmpty(vRest) ? this._toVariables({ [_name]: vRest }, options4) : {}; const csRest_var = isNotEmpty(csRest) ? this._toVariables({ [_name]: csRest }, options4) : {}; const dark_var = isNotEmpty(dark2) ? this._toVariables({ [_name]: dark2 }, options4) : {}; const [vRest_css, vRest_tokens] = [(_c = vRest_var.declarations) != null ? _c : "", vRest_var.tokens || []]; const [csRest_css, csRest_tokens] = [(_d = csRest_var.declarations) != null ? _d : "", csRest_var.tokens || []]; const [dark_css, dark_tokens] = [(_e = dark_var.declarations) != null ? _e : "", dark_var.tokens || []]; const tokens = [.../* @__PURE__ */ new Set([...vRest_tokens, ...csRest_tokens, ...dark_tokens])]; const light_variable_css = this.transformCSS(_name, `${vRest_css}${csRest_css}`, "light", "variable", options4, set3, defaults2, selector); const dark_variable_css = this.transformCSS(_name, dark_css, "dark", "variable", options4, set3, defaults2, selector); return { css: `${light_variable_css}${dark_variable_css}`, tokens }; }, getPresetC({ name: name2 = "", theme: theme42 = {}, params, set: set3, defaults: defaults2 }) { var _a2; const { preset, options: options4 } = theme42; const cPreset = (_a2 = preset == null ? void 0 : preset.components) == null ? void 0 : _a2[name2]; return this.getPreset({ name: name2, preset: cPreset, options: options4, params, set: set3, defaults: defaults2 }); }, getPresetD({ name: name2 = "", theme: theme42 = {}, params, set: set3, defaults: defaults2 }) { var _a2; const dName = name2.replace("-directive", ""); const { preset, options: options4 } = theme42; const dPreset = (_a2 = preset == null ? void 0 : preset.directives) == null ? void 0 : _a2[dName]; return this.getPreset({ name: dName, preset: dPreset, options: options4, params, set: set3, defaults: defaults2 }); }, getColorSchemeOption(options4, defaults2) { var _a2; return this.regex.resolve((_a2 = options4.darkModeSelector) != null ? _a2 : defaults2.options.darkModeSelector); }, getLayerOrder(name2, options4 = {}, params, defaults2) { const { cssLayer } = options4; if (cssLayer) { const order = resolve$2(cssLayer.order || "primeui", params); return `@layer ${order}`; } return ""; }, getCommonStyleSheet({ name: name2 = "", theme: theme42 = {}, params, props = {}, set: set3, defaults: defaults2 }) { const common = this.getCommon({ name: name2, theme: theme42, params, set: set3, defaults: defaults2 }); const _props = Object.entries(props).reduce((acc, [k2, v2]) => acc.push(`${k2}="${v2}"`) && acc, []).join(" "); return Object.entries(common || {}).reduce((acc, [key, value4]) => { if (value4 == null ? void 0 : value4.css) { const _css = minifyCSS(value4 == null ? void 0 : value4.css); const id3 = `${key}-variables`; acc.push(``); } return acc; }, []).join(""); }, getStyleSheet({ name: name2 = "", theme: theme42 = {}, params, props = {}, set: set3, defaults: defaults2 }) { var _a2; const options4 = { name: name2, theme: theme42, params, set: set3, defaults: defaults2 }; const preset_css = (_a2 = name2.includes("-directive") ? this.getPresetD(options4) : this.getPresetC(options4)) == null ? void 0 : _a2.css; const _props = Object.entries(props).reduce((acc, [k2, v2]) => acc.push(`${k2}="${v2}"`) && acc, []).join(" "); return preset_css ? `` : ""; }, createTokens(obj = {}, defaults2, parentKey = "", parentPath = "", tokens = {}) { Object.entries(obj).forEach(([key, value4]) => { const currentKey = matchRegex(key, defaults2.variable.excludedKeyRegex) ? parentKey : parentKey ? `${parentKey}.${toTokenKey$1(key)}` : toTokenKey$1(key); const currentPath = parentPath ? `${parentPath}.${key}` : key; if (isObject$e(value4)) { this.createTokens(value4, defaults2, currentKey, currentPath, tokens); } else { tokens[currentKey] || (tokens[currentKey] = { paths: [], computed(colorScheme, tokenPathMap = {}) { if (colorScheme) { const path = this.paths.find((p2) => p2.scheme === colorScheme) || this.paths.find((p2) => p2.scheme === "none"); return path == null ? void 0 : path.computed(colorScheme, tokenPathMap["binding"]); } return this.paths.map((p2) => p2.computed(p2.scheme, tokenPathMap[p2.scheme])); } }); tokens[currentKey].paths.push({ path: currentPath, value: value4, scheme: currentPath.includes("colorScheme.light") ? "light" : currentPath.includes("colorScheme.dark") ? "dark" : "none", computed(colorScheme, tokenPathMap = {}) { const regex2 = /{([^}]*)}/g; let computedValue = value4; tokenPathMap["name"] = this.path; tokenPathMap["binding"] || (tokenPathMap["binding"] = {}); if (matchRegex(value4, regex2)) { const val = value4.trim(); const _val = val.replaceAll(regex2, (v2) => { var _a2, _b; const path = v2.replace(/{|}/g, ""); return (_b = (_a2 = tokens[path]) == null ? void 0 : _a2.computed(colorScheme, tokenPathMap)) == null ? void 0 : _b.value; }); const calculationRegex = /(\d+\w*\s+[\+\-\*\/]\s+\d+\w*)/g; const cleanedVarRegex = /var\([^)]+\)/g; computedValue = matchRegex(_val.replace(cleanedVarRegex, "0"), calculationRegex) ? `calc(${_val})` : _val; } isEmpty$1(tokenPathMap["binding"]) && delete tokenPathMap["binding"]; return { colorScheme, path: this.path, paths: tokenPathMap, value: computedValue.includes("undefined") ? void 0 : computedValue }; } }); } }); return tokens; }, getTokenValue(tokens, path, defaults2) { var _a2; const normalizePath2 = /* @__PURE__ */ __name((str) => { const strArr = str.split("."); return strArr.filter((s2) => !matchRegex(s2.toLowerCase(), defaults2.variable.excludedKeyRegex)).join("."); }, "normalizePath"); const token = normalizePath2(path); const colorScheme = path.includes("colorScheme.light") ? "light" : path.includes("colorScheme.dark") ? "dark" : void 0; const computedValues = [(_a2 = tokens[token]) == null ? void 0 : _a2.computed(colorScheme)].flat().filter((computed2) => computed2); return computedValues.length === 1 ? computedValues[0].value : computedValues.reduce((acc = {}, computed2) => { const _a22 = computed2, { colorScheme: cs } = _a22, rest = __objRest(_a22, ["colorScheme"]); acc[cs] = rest; return acc; }, void 0); }, transformCSS(name2, css22, mode2, type, options4 = {}, set3, defaults2, selector) { if (isNotEmpty(css22)) { const { cssLayer } = options4; if (type !== "style") { const colorSchemeOption = this.getColorSchemeOption(options4, defaults2); const _css = selector ? getRule(selector, css22) : css22; css22 = mode2 === "dark" ? colorSchemeOption.reduce((acc, { selector: _selector }) => { if (isNotEmpty(_selector)) { acc += _selector.includes("[CSS]") ? _selector.replace("[CSS]", _css) : getRule(_selector, _css); } return acc; }, "") : getRule(selector != null ? selector : ":root", css22); } if (cssLayer) { const layerOptions = { name: "primeui", order: "primeui" }; isObject$e(cssLayer) && (layerOptions.name = resolve$2(cssLayer.name, { name: name2, type })); if (isNotEmpty(layerOptions.name)) { css22 = getRule(`@layer ${layerOptions.name}`, css22); set3 == null ? void 0 : set3.layerNames(layerOptions.name); } } return css22; } return ""; } }; var config_default = { defaults: { variable: { prefix: "p", selector: ":root", excludedKeyRegex: /^(primitive|semantic|components|directives|variables|colorscheme|light|dark|common|root|states)$/gi }, options: { prefix: "p", darkModeSelector: "system", cssLayer: false } }, _theme: void 0, _layerNames: /* @__PURE__ */ new Set(), _loadedStyleNames: /* @__PURE__ */ new Set(), _loadingStyles: /* @__PURE__ */ new Set(), _tokens: {}, update(newValues = {}) { const { theme: theme42 } = newValues; if (theme42) { this._theme = __spreadProps(__spreadValues({}, theme42), { options: __spreadValues(__spreadValues({}, this.defaults.options), theme42.options) }); this._tokens = themeUtils_default.createTokens(this.preset, this.defaults); this.clearLoadedStyleNames(); } }, get theme() { return this._theme; }, get preset() { var _a2; return ((_a2 = this.theme) == null ? void 0 : _a2.preset) || {}; }, get options() { var _a2; return ((_a2 = this.theme) == null ? void 0 : _a2.options) || {}; }, get tokens() { return this._tokens; }, getTheme() { return this.theme; }, setTheme(newValue2) { this.update({ theme: newValue2 }); service_default.emit("theme:change", newValue2); }, getPreset() { return this.preset; }, setPreset(newValue2) { this._theme = __spreadProps(__spreadValues({}, this.theme), { preset: newValue2 }); this._tokens = themeUtils_default.createTokens(newValue2, this.defaults); this.clearLoadedStyleNames(); service_default.emit("preset:change", newValue2); service_default.emit("theme:change", this.theme); }, getOptions() { return this.options; }, setOptions(newValue2) { this._theme = __spreadProps(__spreadValues({}, this.theme), { options: newValue2 }); this.clearLoadedStyleNames(); service_default.emit("options:change", newValue2); service_default.emit("theme:change", this.theme); }, getLayerNames() { return [...this._layerNames]; }, setLayerNames(layerName) { this._layerNames.add(layerName); }, getLoadedStyleNames() { return this._loadedStyleNames; }, isStyleNameLoaded(name2) { return this._loadedStyleNames.has(name2); }, setLoadedStyleName(name2) { this._loadedStyleNames.add(name2); }, deleteLoadedStyleName(name2) { this._loadedStyleNames.delete(name2); }, clearLoadedStyleNames() { this._loadedStyleNames.clear(); }, getTokenValue(tokenPath) { return themeUtils_default.getTokenValue(this.tokens, tokenPath, this.defaults); }, getCommon(name2 = "", params) { return themeUtils_default.getCommon({ name: name2, theme: this.theme, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } }); }, getComponent(name2 = "", params) { const options4 = { name: name2, theme: this.theme, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } }; return themeUtils_default.getPresetC(options4); }, getDirective(name2 = "", params) { const options4 = { name: name2, theme: this.theme, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } }; return themeUtils_default.getPresetD(options4); }, getCustomPreset(name2 = "", preset, selector, params) { const options4 = { name: name2, preset, options: this.options, selector, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } }; return themeUtils_default.getPreset(options4); }, getLayerOrderCSS(name2 = "") { return themeUtils_default.getLayerOrder(name2, this.options, { names: this.getLayerNames() }, this.defaults); }, transformCSS(name2 = "", css22, type = "style", mode2) { return themeUtils_default.transformCSS(name2, css22, mode2, type, this.options, { layerNames: this.setLayerNames.bind(this) }, this.defaults); }, getCommonStyleSheet(name2 = "", params, props = {}) { return themeUtils_default.getCommonStyleSheet({ name: name2, theme: this.theme, params, props, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } }); }, getStyleSheet(name2, params, props = {}) { return themeUtils_default.getStyleSheet({ name: name2, theme: this.theme, params, props, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } }); }, onStyleMounted(name2) { this._loadingStyles.add(name2); }, onStyleUpdated(name2) { this._loadingStyles.add(name2); }, onStyleLoaded(event, { name: name2 }) { if (this._loadingStyles.size) { this._loadingStyles.delete(name2); service_default.emit(`theme:${name2}:load`, event); !this._loadingStyles.size && service_default.emit("theme:load"); } } }; function updatePreset(...presets) { const newPreset = mergeKeys(config_default.getPreset(), ...presets); config_default.setPreset(newPreset); return newPreset; } __name(updatePreset, "updatePreset"); function updatePrimaryPalette(primary) { return $t().primaryPalette(primary).update().preset; } __name(updatePrimaryPalette, "updatePrimaryPalette"); function updateSurfacePalette(palette) { return $t().surfacePalette(palette).update().preset; } __name(updateSurfacePalette, "updateSurfacePalette"); function usePreset(...presets) { const newPreset = mergeKeys(...presets); config_default.setPreset(newPreset); return newPreset; } __name(usePreset, "usePreset"); function useTheme(theme42) { return $t(theme42).update({ mergePresets: false }); } __name(useTheme, "useTheme"); var index$1n = { root: { transitionDuration: "{transition.duration}" }, panel: { borderWidth: "0 0 1px 0", borderColor: "{content.border.color}" }, header: { color: "{text.muted.color}", hoverColor: "{text.color}", activeColor: "{text.color}", padding: "1.125rem", fontWeight: "600", borderRadius: "0", borderWidth: "0", borderColor: "{content.border.color}", background: "{content.background}", hoverBackground: "{content.background}", activeBackground: "{content.background}", activeHoverBackground: "{content.background}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, toggleIcon: { color: "{text.muted.color}", hoverColor: "{text.color}", activeColor: "{text.color}", activeHoverColor: "{text.color}" }, first: { topBorderRadius: "{content.border.radius}", borderWidth: "0" }, last: { bottomBorderRadius: "{content.border.radius}", activeBottomBorderRadius: "0" } }, content: { borderWidth: "0", borderColor: "{content.border.color}", background: "{content.background}", color: "{text.color}", padding: "0 1.125rem 1.125rem 1.125rem" } }; var index$1m = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, overlay: { background: "{overlay.select.background}", borderColor: "{overlay.select.border.color}", borderRadius: "{overlay.select.border.radius}", color: "{overlay.select.color}", shadow: "{overlay.select.shadow}" }, list: { padding: "{list.padding}", gap: "{list.gap}" }, option: { focusBackground: "{list.option.focus.background}", selectedBackground: "{list.option.selected.background}", selectedFocusBackground: "{list.option.selected.focus.background}", color: "{list.option.color}", focusColor: "{list.option.focus.color}", selectedColor: "{list.option.selected.color}", selectedFocusColor: "{list.option.selected.focus.color}", padding: "{list.option.padding}", borderRadius: "{list.option.border.radius}" }, optionGroup: { background: "{list.option.group.background}", color: "{list.option.group.color}", fontWeight: "{list.option.group.font.weight}", padding: "{list.option.group.padding}" }, dropdown: { width: "2.5rem", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.border.color}", activeBorderColor: "{form.field.border.color}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, chip: { borderRadius: "{border.radius.sm}" }, emptyMessage: { padding: "{list.option.padding}" }, colorScheme: { light: { dropdown: { background: "{surface.100}", hoverBackground: "{surface.200}", activeBackground: "{surface.300}", color: "{surface.600}", hoverColor: "{surface.700}", activeColor: "{surface.800}" } }, dark: { dropdown: { background: "{surface.800}", hoverBackground: "{surface.700}", activeBackground: "{surface.600}", color: "{surface.300}", hoverColor: "{surface.200}", activeColor: "{surface.100}" } } } }; var index$1l = { root: { width: "2rem", height: "2rem", fontSize: "1rem", background: "{content.border.color}", borderRadius: "{content.border.radius}" }, group: { borderColor: "{content.background}", offset: "-1rem" }, lg: { width: "3rem", height: "3rem", fontSize: "1.5rem" }, xl: { width: "4rem", height: "4rem", fontSize: "2rem" } }; var index$1k = { root: { borderRadius: "{border.radius.md}", padding: "0 0.5rem", fontSize: "0.75rem", fontWeight: "700", minWidth: "1.5rem", height: "1.5rem" }, dot: { size: "0.5rem" }, sm: { fontSize: "0.625rem", minWidth: "1.25rem", height: "1.25rem" }, lg: { fontSize: "0.875rem", minWidth: "1.75rem", height: "1.75rem" }, xl: { fontSize: "1rem", minWidth: "2rem", height: "2rem" }, colorScheme: { light: { primary: { background: "{primary.color}", color: "{primary.contrast.color}" }, secondary: { background: "{surface.100}", color: "{surface.600}" }, success: { background: "{green.500}", color: "{surface.0}" }, info: { background: "{sky.500}", color: "{surface.0}" }, warn: { background: "{orange.500}", color: "{surface.0}" }, danger: { background: "{red.500}", color: "{surface.0}" }, contrast: { background: "{surface.950}", color: "{surface.0}" } }, dark: { primary: { background: "{primary.color}", color: "{primary.contrast.color}" }, secondary: { background: "{surface.800}", color: "{surface.300}" }, success: { background: "{green.400}", color: "{green.950}" }, info: { background: "{sky.400}", color: "{sky.950}" }, warn: { background: "{orange.400}", color: "{orange.950}" }, danger: { background: "{red.400}", color: "{red.950}" }, contrast: { background: "{surface.0}", color: "{surface.950}" } } } }; var index$1j = { root: { borderRadius: "{content.border.radius}" } }; var index$1i = { root: { padding: "1rem", background: "{content.background}", gap: "0.5rem", transitionDuration: "{transition.duration}" }, item: { color: "{text.muted.color}", hoverColor: "{text.color}", borderRadius: "{content.border.radius}", gap: "{navigation.item.gap}", icon: { color: "{navigation.item.icon.color}", hoverColor: "{navigation.item.icon.focus.color}" }, focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, separator: { color: "{navigation.item.icon.color}" } }; var index$1h = { root: { borderRadius: "{form.field.border.radius}", roundedBorderRadius: "2rem", gap: "0.5rem", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", iconOnlyWidth: "2.5rem", sm: { fontSize: "0.875rem", paddingX: "0.625rem", paddingY: "0.375rem" }, lg: { fontSize: "1.125rem", paddingX: "0.875rem", paddingY: "0.625rem" }, label: { fontWeight: "500" }, raisedShadow: "0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12)", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", offset: "{focus.ring.offset}" }, badgeSize: "1rem", transitionDuration: "{form.field.transition.duration}" }, colorScheme: { light: { root: { primary: { background: "{primary.color}", hoverBackground: "{primary.hover.color}", activeBackground: "{primary.active.color}", borderColor: "{primary.color}", hoverBorderColor: "{primary.hover.color}", activeBorderColor: "{primary.active.color}", color: "{primary.contrast.color}", hoverColor: "{primary.contrast.color}", activeColor: "{primary.contrast.color}", focusRing: { color: "{primary.color}", shadow: "none" } }, secondary: { background: "{surface.100}", hoverBackground: "{surface.200}", activeBackground: "{surface.300}", borderColor: "{surface.100}", hoverBorderColor: "{surface.200}", activeBorderColor: "{surface.300}", color: "{surface.600}", hoverColor: "{surface.700}", activeColor: "{surface.800}", focusRing: { color: "{surface.600}", shadow: "none" } }, info: { background: "{sky.500}", hoverBackground: "{sky.600}", activeBackground: "{sky.700}", borderColor: "{sky.500}", hoverBorderColor: "{sky.600}", activeBorderColor: "{sky.700}", color: "#ffffff", hoverColor: "#ffffff", activeColor: "#ffffff", focusRing: { color: "{sky.500}", shadow: "none" } }, success: { background: "{green.500}", hoverBackground: "{green.600}", activeBackground: "{green.700}", borderColor: "{green.500}", hoverBorderColor: "{green.600}", activeBorderColor: "{green.700}", color: "#ffffff", hoverColor: "#ffffff", activeColor: "#ffffff", focusRing: { color: "{green.500}", shadow: "none" } }, warn: { background: "{orange.500}", hoverBackground: "{orange.600}", activeBackground: "{orange.700}", borderColor: "{orange.500}", hoverBorderColor: "{orange.600}", activeBorderColor: "{orange.700}", color: "#ffffff", hoverColor: "#ffffff", activeColor: "#ffffff", focusRing: { color: "{orange.500}", shadow: "none" } }, help: { background: "{purple.500}", hoverBackground: "{purple.600}", activeBackground: "{purple.700}", borderColor: "{purple.500}", hoverBorderColor: "{purple.600}", activeBorderColor: "{purple.700}", color: "#ffffff", hoverColor: "#ffffff", activeColor: "#ffffff", focusRing: { color: "{purple.500}", shadow: "none" } }, danger: { background: "{red.500}", hoverBackground: "{red.600}", activeBackground: "{red.700}", borderColor: "{red.500}", hoverBorderColor: "{red.600}", activeBorderColor: "{red.700}", color: "#ffffff", hoverColor: "#ffffff", activeColor: "#ffffff", focusRing: { color: "{red.500}", shadow: "none" } }, contrast: { background: "{surface.950}", hoverBackground: "{surface.900}", activeBackground: "{surface.800}", borderColor: "{surface.950}", hoverBorderColor: "{surface.900}", activeBorderColor: "{surface.800}", color: "{surface.0}", hoverColor: "{surface.0}", activeColor: "{surface.0}", focusRing: { color: "{surface.950}", shadow: "none" } } }, outlined: { primary: { hoverBackground: "{primary.50}", activeBackground: "{primary.100}", borderColor: "{primary.200}", color: "{primary.color}" }, secondary: { hoverBackground: "{surface.50}", activeBackground: "{surface.100}", borderColor: "{surface.200}", color: "{surface.500}" }, success: { hoverBackground: "{green.50}", activeBackground: "{green.100}", borderColor: "{green.200}", color: "{green.500}" }, info: { hoverBackground: "{sky.50}", activeBackground: "{sky.100}", borderColor: "{sky.200}", color: "{sky.500}" }, warn: { hoverBackground: "{orange.50}", activeBackground: "{orange.100}", borderColor: "{orange.200}", color: "{orange.500}" }, help: { hoverBackground: "{purple.50}", activeBackground: "{purple.100}", borderColor: "{purple.200}", color: "{purple.500}" }, danger: { hoverBackground: "{red.50}", activeBackground: "{red.100}", borderColor: "{red.200}", color: "{red.500}" }, contrast: { hoverBackground: "{surface.50}", activeBackground: "{surface.100}", borderColor: "{surface.700}", color: "{surface.950}" }, plain: { hoverBackground: "{surface.50}", activeBackground: "{surface.100}", borderColor: "{surface.200}", color: "{surface.700}" } }, text: { primary: { hoverBackground: "{primary.50}", activeBackground: "{primary.100}", color: "{primary.color}" }, secondary: { hoverBackground: "{surface.50}", activeBackground: "{surface.100}", color: "{surface.500}" }, success: { hoverBackground: "{green.50}", activeBackground: "{green.100}", color: "{green.500}" }, info: { hoverBackground: "{sky.50}", activeBackground: "{sky.100}", color: "{sky.500}" }, warn: { hoverBackground: "{orange.50}", activeBackground: "{orange.100}", color: "{orange.500}" }, help: { hoverBackground: "{purple.50}", activeBackground: "{purple.100}", color: "{purple.500}" }, danger: { hoverBackground: "{red.50}", activeBackground: "{red.100}", color: "{red.500}" }, plain: { hoverBackground: "{surface.50}", activeBackground: "{surface.100}", color: "{surface.700}" } }, link: { color: "{primary.color}", hoverColor: "{primary.color}", activeColor: "{primary.color}" } }, dark: { root: { primary: { background: "{primary.color}", hoverBackground: "{primary.hover.color}", activeBackground: "{primary.active.color}", borderColor: "{primary.color}", hoverBorderColor: "{primary.hover.color}", activeBorderColor: "{primary.active.color}", color: "{primary.contrast.color}", hoverColor: "{primary.contrast.color}", activeColor: "{primary.contrast.color}", focusRing: { color: "{primary.color}", shadow: "none" } }, secondary: { background: "{surface.800}", hoverBackground: "{surface.700}", activeBackground: "{surface.600}", borderColor: "{surface.800}", hoverBorderColor: "{surface.700}", activeBorderColor: "{surface.600}", color: "{surface.300}", hoverColor: "{surface.200}", activeColor: "{surface.100}", focusRing: { color: "{surface.300}", shadow: "none" } }, info: { background: "{sky.400}", hoverBackground: "{sky.300}", activeBackground: "{sky.200}", borderColor: "{sky.400}", hoverBorderColor: "{sky.300}", activeBorderColor: "{sky.200}", color: "{sky.950}", hoverColor: "{sky.950}", activeColor: "{sky.950}", focusRing: { color: "{sky.400}", shadow: "none" } }, success: { background: "{green.400}", hoverBackground: "{green.300}", activeBackground: "{green.200}", borderColor: "{green.400}", hoverBorderColor: "{green.300}", activeBorderColor: "{green.200}", color: "{green.950}", hoverColor: "{green.950}", activeColor: "{green.950}", focusRing: { color: "{green.400}", shadow: "none" } }, warn: { background: "{orange.400}", hoverBackground: "{orange.300}", activeBackground: "{orange.200}", borderColor: "{orange.400}", hoverBorderColor: "{orange.300}", activeBorderColor: "{orange.200}", color: "{orange.950}", hoverColor: "{orange.950}", activeColor: "{orange.950}", focusRing: { color: "{orange.400}", shadow: "none" } }, help: { background: "{purple.400}", hoverBackground: "{purple.300}", activeBackground: "{purple.200}", borderColor: "{purple.400}", hoverBorderColor: "{purple.300}", activeBorderColor: "{purple.200}", color: "{purple.950}", hoverColor: "{purple.950}", activeColor: "{purple.950}", focusRing: { color: "{purple.400}", shadow: "none" } }, danger: { background: "{red.400}", hoverBackground: "{red.300}", activeBackground: "{red.200}", borderColor: "{red.400}", hoverBorderColor: "{red.300}", activeBorderColor: "{red.200}", color: "{red.950}", hoverColor: "{red.950}", activeColor: "{red.950}", focusRing: { color: "{red.400}", shadow: "none" } }, contrast: { background: "{surface.0}", hoverBackground: "{surface.100}", activeBackground: "{surface.200}", borderColor: "{surface.0}", hoverBorderColor: "{surface.100}", activeBorderColor: "{surface.200}", color: "{surface.950}", hoverColor: "{surface.950}", activeColor: "{surface.950}", focusRing: { color: "{surface.0}", shadow: "none" } } }, outlined: { primary: { hoverBackground: "color-mix(in srgb, {primary.color}, transparent 96%)", activeBackground: "color-mix(in srgb, {primary.color}, transparent 84%)", borderColor: "{primary.700}", color: "{primary.color}" }, secondary: { hoverBackground: "rgba(255,255,255,0.04)", activeBackground: "rgba(255,255,255,0.16)", borderColor: "{surface.700}", color: "{surface.400}" }, success: { hoverBackground: "color-mix(in srgb, {green.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {green.400}, transparent 84%)", borderColor: "{green.700}", color: "{green.400}" }, info: { hoverBackground: "color-mix(in srgb, {sky.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {sky.400}, transparent 84%)", borderColor: "{sky.700}", color: "{sky.400}" }, warn: { hoverBackground: "color-mix(in srgb, {orange.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {orange.400}, transparent 84%)", borderColor: "{orange.700}", color: "{orange.400}" }, help: { hoverBackground: "color-mix(in srgb, {purple.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {purple.400}, transparent 84%)", borderColor: "{purple.700}", color: "{purple.400}" }, danger: { hoverBackground: "color-mix(in srgb, {red.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {red.400}, transparent 84%)", borderColor: "{red.700}", color: "{red.400}" }, contrast: { hoverBackground: "{surface.800}", activeBackground: "{surface.700}", borderColor: "{surface.500}", color: "{surface.0}" }, plain: { hoverBackground: "{surface.800}", activeBackground: "{surface.700}", borderColor: "{surface.600}", color: "{surface.0}" } }, text: { primary: { hoverBackground: "color-mix(in srgb, {primary.color}, transparent 96%)", activeBackground: "color-mix(in srgb, {primary.color}, transparent 84%)", color: "{primary.color}" }, secondary: { hoverBackground: "{surface.800}", activeBackground: "{surface.700}", color: "{surface.400}" }, success: { hoverBackground: "color-mix(in srgb, {green.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {green.400}, transparent 84%)", color: "{green.400}" }, info: { hoverBackground: "color-mix(in srgb, {sky.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {sky.400}, transparent 84%)", color: "{sky.400}" }, warn: { hoverBackground: "color-mix(in srgb, {orange.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {orange.400}, transparent 84%)", color: "{orange.400}" }, help: { hoverBackground: "color-mix(in srgb, {purple.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {purple.400}, transparent 84%)", color: "{purple.400}" }, danger: { hoverBackground: "color-mix(in srgb, {red.400}, transparent 96%)", activeBackground: "color-mix(in srgb, {red.400}, transparent 84%)", color: "{red.400}" }, plain: { hoverBackground: "{surface.800}", activeBackground: "{surface.700}", color: "{surface.0}" } }, link: { color: "{primary.color}", hoverColor: "{primary.color}", activeColor: "{primary.color}" } } } }; var index$1g = { root: { background: "{content.background}", borderRadius: "{border.radius.xl}", color: "{content.color}", shadow: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)" }, body: { padding: "1.25rem", gap: "0.5rem" }, caption: { gap: "0.5rem" }, title: { fontSize: "1.25rem", fontWeight: "500" }, subtitle: { color: "{text.muted.color}" } }; var index$1f = { root: { transitionDuration: "{transition.duration}" }, content: { gap: "0.25rem" }, indicatorList: { padding: "1rem", gap: "0.5rem" }, indicator: { width: "2rem", height: "0.5rem", borderRadius: "{content.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, colorScheme: { light: { indicator: { background: "{surface.200}", hoverBackground: "{surface.300}", activeBackground: "{primary.color}" } }, dark: { indicator: { background: "{surface.700}", hoverBackground: "{surface.600}", activeBackground: "{primary.color}" } } } }; var index$1e = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, dropdown: { width: "2.5rem", color: "{form.field.icon.color}" }, overlay: { background: "{overlay.select.background}", borderColor: "{overlay.select.border.color}", borderRadius: "{overlay.select.border.radius}", color: "{overlay.select.color}", shadow: "{overlay.select.shadow}" }, list: { padding: "{list.padding}", gap: "{list.gap}" }, option: { focusBackground: "{list.option.focus.background}", selectedBackground: "{list.option.selected.background}", selectedFocusBackground: "{list.option.selected.focus.background}", color: "{list.option.color}", focusColor: "{list.option.focus.color}", selectedColor: "{list.option.selected.color}", selectedFocusColor: "{list.option.selected.focus.color}", padding: "{list.option.padding}", borderRadius: "{list.option.border.radius}", icon: { color: "{list.option.icon.color}", focusColor: "{list.option.icon.focus.color}", size: "0.875rem" } } }; var index$1d = { root: { borderRadius: "{border.radius.sm}", width: "1.25rem", height: "1.25rem", background: "{form.field.background}", checkedBackground: "{primary.color}", checkedHoverBackground: "{primary.hover.color}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.border.color}", checkedBorderColor: "{primary.color}", checkedHoverBorderColor: "{primary.hover.color}", checkedFocusBorderColor: "{primary.color}", checkedDisabledBorderColor: "{form.field.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", shadow: "{form.field.shadow}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, icon: { size: "0.875rem", color: "{form.field.color}", checkedColor: "{primary.contrast.color}", checkedHoverColor: "{primary.contrast.color}", disabledColor: "{form.field.disabled.color}" } }; var index$1c = { root: { borderRadius: "16px", paddingX: "0.75rem", paddingY: "0.5rem", gap: "0.5rem", transitionDuration: "{transition.duration}" }, image: { width: "2rem", height: "2rem" }, icon: { size: "1rem" }, removeIcon: { size: "1rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" } }, colorScheme: { light: { root: { background: "{surface.100}", color: "{surface.800}" }, icon: { color: "{surface.800}" }, removeIcon: { color: "{surface.800}" } }, dark: { root: { background: "{surface.800}", color: "{surface.0}" }, icon: { color: "{surface.0}" }, removeIcon: { color: "{surface.0}" } } } }; var index$1b = { root: { transitionDuration: "{transition.duration}" }, preview: { width: "1.5rem", height: "1.5rem", borderRadius: "{form.field.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, panel: { shadow: "{overlay.popover.shadow}", borderRadius: "{overlay.popover.borderRadius}" }, colorScheme: { light: { panel: { background: "{surface.800}", borderColor: "{surface.900}" }, handle: { color: "{surface.0}" } }, dark: { panel: { background: "{surface.900}", borderColor: "{surface.700}" }, handle: { color: "{surface.0}" } } } }; var index$1a = { icon: { size: "2rem", color: "{overlay.modal.color}" }, content: { gap: "1rem" } }; var index$19 = { root: { background: "{overlay.popover.background}", borderColor: "{overlay.popover.border.color}", color: "{overlay.popover.color}", borderRadius: "{overlay.popover.border.radius}", shadow: "{overlay.popover.shadow}", gutter: "10px", arrowOffset: "1.25rem" }, content: { padding: "{overlay.popover.padding}", gap: "1rem" }, icon: { size: "1.5rem", color: "{overlay.popover.color}" }, footer: { gap: "0.5rem", padding: "0 {overlay.popover.padding} {overlay.popover.padding} {overlay.popover.padding}" } }; var index$18 = { root: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", borderRadius: "{content.border.radius}", shadow: "{overlay.navigation.shadow}", transitionDuration: "{transition.duration}" }, list: { padding: "{navigation.list.padding}", gap: "{navigation.list.gap}" }, item: { focusBackground: "{navigation.item.focus.background}", activeBackground: "{navigation.item.active.background}", color: "{navigation.item.color}", focusColor: "{navigation.item.focus.color}", activeColor: "{navigation.item.active.color}", padding: "{navigation.item.padding}", borderRadius: "{navigation.item.border.radius}", gap: "{navigation.item.gap}", icon: { color: "{navigation.item.icon.color}", focusColor: "{navigation.item.icon.focus.color}", activeColor: "{navigation.item.icon.active.color}" } }, submenuIcon: { size: "{navigation.submenu.icon.size}", color: "{navigation.submenu.icon.color}", focusColor: "{navigation.submenu.icon.focus.color}", activeColor: "{navigation.submenu.icon.active.color}" }, separator: { borderColor: "{content.border.color}" } }; var index$17 = { root: { transitionDuration: "{transition.duration}" }, header: { background: "{content.background}", borderColor: "{datatable.border.color}", color: "{content.color}", borderWidth: "0 0 1px 0", padding: "0.75rem 1rem" }, headerCell: { background: "{content.background}", hoverBackground: "{content.hover.background}", selectedBackground: "{highlight.background}", borderColor: "{datatable.border.color}", color: "{content.color}", hoverColor: "{content.hover.color}", selectedColor: "{highlight.color}", gap: "0.5rem", padding: "0.75rem 1rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "-1px", shadow: "{focus.ring.shadow}" } }, columnTitle: { fontWeight: "600" }, row: { background: "{content.background}", hoverBackground: "{content.hover.background}", selectedBackground: "{highlight.background}", color: "{content.color}", hoverColor: "{content.hover.color}", selectedColor: "{highlight.color}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "-1px", shadow: "{focus.ring.shadow}" } }, bodyCell: { borderColor: "{datatable.border.color}", padding: "0.75rem 1rem" }, footerCell: { background: "{content.background}", borderColor: "{datatable.border.color}", color: "{content.color}", padding: "0.75rem 1rem" }, columnFooter: { fontWeight: "600" }, footer: { background: "{content.background}", borderColor: "{datatable.border.color}", color: "{content.color}", borderWidth: "0 0 1px 0", padding: "0.75rem 1rem" }, dropPointColor: "{primary.color}", columnResizerWidth: "0.5rem", resizeIndicator: { width: "1px", color: "{primary.color}" }, sortIcon: { color: "{text.muted.color}", hoverColor: "{text.hover.muted.color}" }, loadingIcon: { size: "2rem" }, rowToggleButton: { hoverBackground: "{content.hover.background}", selectedHoverBackground: "{content.background}", color: "{text.muted.color}", hoverColor: "{text.color}", selectedHoverColor: "{primary.color}", size: "1.75rem", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, filter: { inlineGap: "0.5rem", overlaySelect: { background: "{overlay.select.background}", borderColor: "{overlay.select.border.color}", borderRadius: "{overlay.select.border.radius}", color: "{overlay.select.color}", shadow: "{overlay.select.shadow}" }, overlayPopover: { background: "{overlay.popover.background}", borderColor: "{overlay.popover.border.color}", borderRadius: "{overlay.popover.border.radius}", color: "{overlay.popover.color}", shadow: "{overlay.popover.shadow}", padding: "{overlay.popover.padding}", gap: "0.5rem" }, rule: { borderColor: "{content.border.color}" }, constraintList: { padding: "{list.padding}", gap: "{list.gap}" }, constraint: { focusBackground: "{list.option.focus.background}", selectedBackground: "{list.option.selected.background}", selectedFocusBackground: "{list.option.selected.focus.background}", color: "{list.option.color}", focusColor: "{list.option.focus.color}", selectedColor: "{list.option.selected.color}", selectedFocusColor: "{list.option.selected.focus.color}", separator: { borderColor: "{content.border.color}" }, padding: "{list.option.padding}", borderRadius: "{list.option.border.radius}" } }, paginatorTop: { borderColor: "{datatable.border.color}", borderWidth: "0 0 1px 0" }, paginatorBottom: { borderColor: "{datatable.border.color}", borderWidth: "0 0 1px 0" }, colorScheme: { light: { root: { borderColor: "{content.border.color}" }, row: { stripedBackground: "{surface.50}" }, bodyCell: { selectedBorderColor: "{primary.100}" } }, dark: { root: { borderColor: "{surface.800}" }, row: { stripedBackground: "{surface.950}" }, bodyCell: { selectedBorderColor: "{primary.900}" } } } }; var index$16 = { root: { borderColor: "transparent", borderWidth: "0", borderRadius: "0", padding: "0" }, header: { background: "{content.background}", color: "{content.color}", borderColor: "{content.border.color}", borderWidth: "0 0 1px 0", padding: "0.75rem 1rem", borderRadius: "0" }, content: { background: "{content.background}", color: "{content.color}", borderColor: "transparent", borderWidth: "0", padding: "0", borderRadius: "0" }, footer: { background: "{content.background}", color: "{content.color}", borderColor: "{content.border.color}", borderWidth: "1px 0 0 0", padding: "0.75rem 1rem", borderRadius: "0" }, paginatorTop: { borderColor: "{content.border.color}", borderWidth: "0 0 1px 0" }, paginatorBottom: { borderColor: "{content.border.color}", borderWidth: "1px 0 0 0" } }; var index$15 = { root: { transitionDuration: "{transition.duration}" }, panel: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", borderRadius: "{content.border.radius}", shadow: "{overlay.popover.shadow}", padding: "{overlay.popover.padding}" }, header: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", padding: "0 0 0.5rem 0", fontWeight: "500", gap: "0.5rem" }, title: { gap: "0.5rem", fontWeight: "500" }, dropdown: { width: "2.5rem", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.border.color}", activeBorderColor: "{form.field.border.color}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, inputIcon: { color: "{form.field.icon.color}" }, selectMonth: { hoverBackground: "{content.hover.background}", color: "{content.color}", hoverColor: "{content.hover.color}", padding: "0.25rem 0.5rem", borderRadius: "{content.border.radius}" }, selectYear: { hoverBackground: "{content.hover.background}", color: "{content.color}", hoverColor: "{content.hover.color}", padding: "0.25rem 0.5rem", borderRadius: "{content.border.radius}" }, group: { borderColor: "{content.border.color}", gap: "{overlay.popover.padding}" }, dayView: { margin: "0.5rem 0 0 0" }, weekDay: { padding: "0.25rem", fontWeight: "500", color: "{content.color}" }, date: { hoverBackground: "{content.hover.background}", selectedBackground: "{primary.color}", rangeSelectedBackground: "{highlight.background}", color: "{content.color}", hoverColor: "{content.hover.color}", selectedColor: "{primary.contrast.color}", rangeSelectedColor: "{highlight.color}", width: "2rem", height: "2rem", borderRadius: "50%", padding: "0.25rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, monthView: { margin: "0.5rem 0 0 0" }, month: { borderRadius: "{content.border.radius}" }, yearView: { margin: "0.5rem 0 0 0" }, year: { borderRadius: "{content.border.radius}" }, buttonbar: { padding: "0.5rem 0 0 0", borderColor: "{content.border.color}" }, timePicker: { padding: "0.5rem 0 0 0", borderColor: "{content.border.color}", gap: "0.5rem", buttonGap: "0.25rem" }, colorScheme: { light: { dropdown: { background: "{surface.100}", hoverBackground: "{surface.200}", activeBackground: "{surface.300}", color: "{surface.600}", hoverColor: "{surface.700}", activeColor: "{surface.800}" }, today: { background: "{surface.200}", color: "{surface.900}" } }, dark: { dropdown: { background: "{surface.800}", hoverBackground: "{surface.700}", activeBackground: "{surface.600}", color: "{surface.300}", hoverColor: "{surface.200}", activeColor: "{surface.100}" }, today: { background: "{surface.700}", color: "{surface.0}" } } } }; var index$14 = { root: { background: "{overlay.modal.background}", borderColor: "{overlay.modal.border.color}", color: "{overlay.modal.color}", borderRadius: "{overlay.modal.border.radius}", shadow: "{overlay.modal.shadow}" }, header: { padding: "{overlay.modal.padding}", gap: "0.5rem" }, title: { fontSize: "1.25rem", fontWeight: "600" }, content: { padding: "0 {overlay.modal.padding} {overlay.modal.padding} {overlay.modal.padding}" }, footer: { padding: "0 {overlay.modal.padding} {overlay.modal.padding} {overlay.modal.padding}", gap: "0.5rem" } }; var index$13 = { root: { borderColor: "{content.border.color}" }, content: { background: "{content.background}", color: "{text.color}" }, horizontal: { margin: "1rem 0", padding: "0 1rem", content: { padding: "0 0.5rem" } }, vertical: { margin: "0 1rem", padding: "0.5rem 0", content: { padding: "0.5rem 0" } } }; var index$12 = { root: { background: "rgba(255, 255, 255, 0.1)", borderColor: "rgba(255, 255, 255, 0.2)", padding: "0.5rem", borderRadius: "{border.radius.xl}" }, item: { borderRadius: "{content.border.radius}", padding: "0.5rem", size: "3rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } } }; var index$11 = { root: { background: "{overlay.modal.background}", borderColor: "{overlay.modal.border.color}", color: "{overlay.modal.color}", borderRadius: "{overlay.modal.border.radius}", shadow: "{overlay.modal.shadow}" }, header: { padding: "{overlay.modal.padding}" }, title: { fontSize: "1.5rem", fontWeight: "600" }, content: { padding: "0 {overlay.modal.padding} {overlay.modal.padding} {overlay.modal.padding}" } }; var index$10 = { toolbar: { background: "{content.background}", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}" }, toolbarItem: { color: "{text.muted.color}", hoverColor: "{text.color}", activeColor: "{primary.color}" }, overlay: { background: "{overlay.select.background}", borderColor: "{overlay.select.border.color}", borderRadius: "{overlay.select.border.radius}", color: "{overlay.select.color}", shadow: "{overlay.select.shadow}", padding: "{list.padding}" }, overlayOption: { focusBackground: "{list.option.focus.background}", color: "{list.option.color}", focusColor: "{list.option.focus.color}", padding: "{list.option.padding}", borderRadius: "{list.option.border.radius}" }, content: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", borderRadius: "{content.border.radius}" } }; var index$$ = { root: { background: "{content.background}", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}", color: "{content.color}", padding: "0 1.125rem 1.125rem 1.125rem", transitionDuration: "{transition.duration}" }, legend: { background: "{content.background}", hoverBackground: "{content.hover.background}", color: "{content.color}", hoverColor: "{content.hover.color}", borderRadius: "{content.border.radius}", borderWidth: "1px", borderColor: "transparent", padding: "0.5rem 0.75rem", gap: "0.5rem", fontWeight: "600", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, toggleIcon: { color: "{text.muted.color}", hoverColor: "{text.hover.muted.color}" }, content: { padding: "0" } }; var index$_ = { root: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", borderRadius: "{content.border.radius}", transitionDuration: "{transition.duration}" }, header: { background: "transparent", color: "{text.color}", padding: "1.125rem", borderWidth: "0", borderRadius: "0", gap: "0.5rem" }, content: { highlightBorderColor: "{primary.color}", padding: "0 1.125rem 1.125rem 1.125rem" }, file: { padding: "1rem", gap: "1rem", borderColor: "{content.border.color}", info: { gap: "0.5rem" } }, progressbar: { height: "0.25rem" }, basic: { gap: "0.5rem" } }; var index$Z = { root: { color: "{form.field.float.label.color}", focusColor: "{form.field.float.label.focus.color}", invalidColor: "{form.field.float.label.invalid.color}", transitionDuration: "0.2s" } }; var index$Y = { root: { borderWidth: "1px", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}", transitionDuration: "{transition.duration}" }, navButton: { background: "rgba(255, 255, 255, 0.1)", hoverBackground: "rgba(255, 255, 255, 0.2)", color: "{surface.100}", hoverColor: "{surface.0}", size: "3rem", gutter: "0.5rem", prev: { borderRadius: "50%" }, next: { borderRadius: "50%" }, focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, navIcon: { size: "1.5rem" }, thumbnailsContent: { background: "{content.background}", padding: "1rem 0.25rem" }, thumbnailNavButton: { size: "2rem", borderRadius: "{content.border.radius}", gutter: "0.5rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, thumbnailNavButtonIcon: { size: "1rem" }, caption: { background: "rgba(0, 0, 0, 0.5)", color: "{surface.100}", padding: "1rem" }, indicatorList: { gap: "0.5rem", padding: "1rem" }, indicatorButton: { width: "1rem", height: "1rem", activeBackground: "{primary.color}", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, insetIndicatorList: { background: "rgba(0, 0, 0, 0.5)" }, insetIndicatorButton: { background: "rgba(255, 255, 255, 0.4)", hoverBackground: "rgba(255, 255, 255, 0.6)", activeBackground: "rgba(255, 255, 255, 0.9)" }, mask: { background: "{mask.background}", color: "{mask.color}" }, closeButton: { size: "3rem", gutter: "0.5rem", background: "rgba(255, 255, 255, 0.1)", hoverBackground: "rgba(255, 255, 255, 0.2)", color: "{surface.50}", hoverColor: "{surface.0}", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, closeButtonIcon: { size: "1.5rem" }, colorScheme: { light: { thumbnailNavButton: { hoverBackground: "{surface.100}", color: "{surface.600}", hoverColor: "{surface.700}" }, indicatorButton: { background: "{surface.200}", hoverBackground: "{surface.300}" } }, dark: { thumbnailNavButton: { hoverBackground: "{surface.700}", color: "{surface.400}", hoverColor: "{surface.0}" }, indicatorButton: { background: "{surface.700}", hoverBackground: "{surface.600}" } } } }; var index$X = { icon: { color: "{form.field.icon.color}" } }; var index$W = { root: { transitionDuration: "{transition.duration}" }, preview: { icon: { size: "1.5rem" }, mask: { background: "{mask.background}", color: "{mask.color}" } }, toolbar: { position: { left: "auto", right: "1rem", top: "1rem", bottom: "auto" }, blur: "8px", background: "rgba(255,255,255,0.1)", borderColor: "rgba(255,255,255,0.2)", borderWidth: "1px", borderRadius: "30px", padding: ".5rem", gap: "0.5rem" }, action: { hoverBackground: "rgba(255,255,255,0.1)", color: "{surface.50}", hoverColor: "{surface.0}", size: "3rem", iconSize: "1.5rem", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } } }; var index$V = { root: { padding: "{form.field.padding.y} {form.field.padding.x}", borderRadius: "{content.border.radius}", gap: "0.5rem" }, text: { fontWeight: "500" }, icon: { size: "1rem" }, colorScheme: { light: { info: { background: "color-mix(in srgb, {blue.50}, transparent 5%)", borderColor: "{blue.200}", color: "{blue.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)" }, success: { background: "color-mix(in srgb, {green.50}, transparent 5%)", borderColor: "{green.200}", color: "{green.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)" }, warn: { background: "color-mix(in srgb,{yellow.50}, transparent 5%)", borderColor: "{yellow.200}", color: "{yellow.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)" }, error: { background: "color-mix(in srgb, {red.50}, transparent 5%)", borderColor: "{red.200}", color: "{red.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)" }, secondary: { background: "{surface.100}", borderColor: "{surface.200}", color: "{surface.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)" }, contrast: { background: "{surface.900}", borderColor: "{surface.950}", color: "{surface.50}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)" } }, dark: { info: { background: "color-mix(in srgb, {blue.500}, transparent 84%)", borderColor: "color-mix(in srgb, {blue.700}, transparent 64%)", color: "{blue.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)" }, success: { background: "color-mix(in srgb, {green.500}, transparent 84%)", borderColor: "color-mix(in srgb, {green.700}, transparent 64%)", color: "{green.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)" }, warn: { background: "color-mix(in srgb, {yellow.500}, transparent 84%)", borderColor: "color-mix(in srgb, {yellow.700}, transparent 64%)", color: "{yellow.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)" }, error: { background: "color-mix(in srgb, {red.500}, transparent 84%)", borderColor: "color-mix(in srgb, {red.700}, transparent 64%)", color: "{red.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)" }, secondary: { background: "{surface.800}", borderColor: "{surface.700}", color: "{surface.300}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)" }, contrast: { background: "{surface.0}", borderColor: "{surface.100}", color: "{surface.950}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)" } } } }; var index$U = { root: { padding: "{form.field.padding.y} {form.field.padding.x}", borderRadius: "{content.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, transitionDuration: "{transition.duration}" }, display: { hoverBackground: "{content.hover.background}", hoverColor: "{content.hover.color}" } }; var index$T = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, chip: { borderRadius: "{border.radius.sm}" }, colorScheme: { light: { chip: { focusBackground: "{surface.200}", color: "{surface.800}" } }, dark: { chip: { focusBackground: "{surface.700}", color: "{surface.0}" } } } }; var index$S = { addon: { background: "{form.field.background}", borderColor: "{form.field.border.color}", color: "{form.field.icon.color}", borderRadius: "{form.field.border.radius}" } }; var index$R = { root: { transitionDuration: "{transition.duration}" }, button: { width: "2.5rem", borderRadius: "{form.field.border.radius}", verticalPadding: "{form.field.padding.y}" }, colorScheme: { light: { button: { background: "transparent", hoverBackground: "{surface.100}", activeBackground: "{surface.200}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.border.color}", activeBorderColor: "{form.field.border.color}", color: "{surface.400}", hoverColor: "{surface.500}", activeColor: "{surface.600}" } }, dark: { button: { background: "transparent", hoverBackground: "{surface.800}", activeBackground: "{surface.700}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.border.color}", activeBorderColor: "{form.field.border.color}", color: "{surface.400}", hoverColor: "{surface.300}", activeColor: "{surface.200}" } } } }; var index$Q = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}", sm: { fontSize: "0.875rem", paddingX: "0.625rem", paddingY: "0.375rem" }, lg: { fontSize: "1.125rem", paddingX: "0.875rem", paddingY: "0.625rem" } } }; var index$P = { root: { transitionDuration: "{transition.duration}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, value: { background: "{primary.color}" }, range: { background: "{content.border.color}" }, text: { color: "{text.muted.color}" } }; var index$O = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", shadow: "{form.field.shadow}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, list: { padding: "{list.padding}", gap: "{list.gap}", header: { padding: "{list.header.padding}" } }, option: { focusBackground: "{list.option.focus.background}", selectedBackground: "{list.option.selected.background}", selectedFocusBackground: "{list.option.selected.focus.background}", color: "{list.option.color}", focusColor: "{list.option.focus.color}", selectedColor: "{list.option.selected.color}", selectedFocusColor: "{list.option.selected.focus.color}", padding: "{list.option.padding}", borderRadius: "{list.option.border.radius}" }, optionGroup: { background: "{list.option.group.background}", color: "{list.option.group.color}", fontWeight: "{list.option.group.font.weight}", padding: "{list.option.group.padding}" }, checkmark: { color: "{list.option.color}", gutterStart: "-0.375rem", gutterEnd: "0.375rem" }, emptyMessage: { padding: "{list.option.padding}" }, colorScheme: { light: { option: { stripedBackground: "{surface.50}" } }, dark: { option: { stripedBackground: "{surface.900}" } } } }; var index$N = { root: { background: "{content.background}", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}", color: "{content.color}", gap: "0.5rem", verticalOrientation: { padding: "{navigation.list.padding}", gap: "0" }, horizontalOrientation: { padding: "0.5rem 0.75rem" }, transitionDuration: "{transition.duration}" }, baseItem: { borderRadius: "{content.border.radius}", padding: "{navigation.item.padding}" }, item: { focusBackground: "{navigation.item.focus.background}", activeBackground: "{navigation.item.active.background}", color: "{navigation.item.color}", focusColor: "{navigation.item.focus.color}", activeColor: "{navigation.item.active.color}", padding: "{navigation.item.padding}", borderRadius: "{navigation.item.border.radius}", gap: "{navigation.item.gap}", icon: { color: "{navigation.item.icon.color}", focusColor: "{navigation.item.icon.focus.color}", activeColor: "{navigation.item.icon.active.color}" } }, overlay: { padding: "0", background: "{content.background}", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}", color: "{content.color}", shadow: "{overlay.navigation.shadow}", gap: "0.5rem" }, submenu: { padding: "{navigation.list.padding}", gap: "{navigation.list.gap}" }, submenuLabel: { padding: "{navigation.submenu.label.padding}", fontWeight: "{navigation.submenu.label.font.weight}", background: "{navigation.submenu.label.background.}", color: "{navigation.submenu.label.color}" }, submenuIcon: { size: "{navigation.submenu.icon.size}", color: "{navigation.submenu.icon.color}", focusColor: "{navigation.submenu.icon.focus.color}", activeColor: "{navigation.submenu.icon.active.color}" }, separator: { borderColor: "{content.border.color}" }, mobileButton: { borderRadius: "50%", size: "1.75rem", color: "{text.muted.color}", hoverColor: "{text.muted.hover.color}", hoverBackground: "{content.hover.background}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } } }; var index$M = { root: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", borderRadius: "{content.border.radius}", shadow: "{overlay.navigation.shadow}", transitionDuration: "{transition.duration}" }, list: { padding: "{navigation.list.padding}", gap: "{navigation.list.gap}" }, item: { focusBackground: "{navigation.item.focus.background}", color: "{navigation.item.color}", focusColor: "{navigation.item.focus.color}", padding: "{navigation.item.padding}", borderRadius: "{navigation.item.border.radius}", gap: "{navigation.item.gap}", icon: { color: "{navigation.item.icon.color}", focusColor: "{navigation.item.icon.focus.color}" } }, submenuLabel: { padding: "{navigation.submenu.label.padding}", fontWeight: "{navigation.submenu.label.font.weight}", background: "{navigation.submenu.label.background}", color: "{navigation.submenu.label.color}" }, separator: { borderColor: "{content.border.color}" } }; var index$L = { root: { background: "{content.background}", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}", color: "{content.color}", gap: "0.5rem", padding: "0.5rem 0.75rem", transitionDuration: "{transition.duration}" }, baseItem: { borderRadius: "{content.border.radius}", padding: "{navigation.item.padding}" }, item: { focusBackground: "{navigation.item.focus.background}", activeBackground: "{navigation.item.active.background}", color: "{navigation.item.color}", focusColor: "{navigation.item.focus.color}", activeColor: "{navigation.item.active.color}", padding: "{navigation.item.padding}", borderRadius: "{navigation.item.border.radius}", gap: "{navigation.item.gap}", icon: { color: "{navigation.item.icon.color}", focusColor: "{navigation.item.icon.focus.color}", activeColor: "{navigation.item.icon.active.color}" } }, submenu: { padding: "{navigation.list.padding}", gap: "{navigation.list.gap}", background: "{content.background}", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}", shadow: "{overlay.navigation.shadow}", mobileIndent: "1rem" }, submenuIcon: { size: "{navigation.submenu.icon.size}", color: "{navigation.submenu.icon.color}", focusColor: "{navigation.submenu.icon.focus.color}", activeColor: "{navigation.submenu.icon.active.color}" }, separator: { borderColor: "{content.border.color}" }, mobileButton: { borderRadius: "50%", size: "1.75rem", color: "{text.muted.color}", hoverColor: "{text.muted.hover.color}", hoverBackground: "{content.hover.background}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } } }; var index$K = { root: { borderRadius: "{content.border.radius}", borderWidth: "1px", transitionDuration: "{transition.duration}" }, content: { padding: "0.5rem 0.75rem", gap: "0.5rem" }, text: { fontSize: "1rem", fontWeight: "500" }, icon: { size: "1.125rem" }, closeButton: { width: "1.75rem", height: "1.75rem", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", offset: "{focus.ring.offset}" } }, closeIcon: { size: "1rem" }, colorScheme: { light: { info: { background: "color-mix(in srgb, {blue.50}, transparent 5%)", borderColor: "{blue.200}", color: "{blue.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)", closeButton: { hoverBackground: "{blue.100}", focusRing: { color: "{blue.600}", shadow: "none" } } }, success: { background: "color-mix(in srgb, {green.50}, transparent 5%)", borderColor: "{green.200}", color: "{green.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)", closeButton: { hoverBackground: "{green.100}", focusRing: { color: "{green.600}", shadow: "none" } } }, warn: { background: "color-mix(in srgb,{yellow.50}, transparent 5%)", borderColor: "{yellow.200}", color: "{yellow.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)", closeButton: { hoverBackground: "{yellow.100}", focusRing: { color: "{yellow.600}", shadow: "none" } } }, error: { background: "color-mix(in srgb, {red.50}, transparent 5%)", borderColor: "{red.200}", color: "{red.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)", closeButton: { hoverBackground: "{red.100}", focusRing: { color: "{red.600}", shadow: "none" } } }, secondary: { background: "{surface.100}", borderColor: "{surface.200}", color: "{surface.600}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)", closeButton: { hoverBackground: "{surface.200}", focusRing: { color: "{surface.600}", shadow: "none" } } }, contrast: { background: "{surface.900}", borderColor: "{surface.950}", color: "{surface.50}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)", closeButton: { hoverBackground: "{surface.800}", focusRing: { color: "{surface.50}", shadow: "none" } } } }, dark: { info: { background: "color-mix(in srgb, {blue.500}, transparent 84%)", borderColor: "color-mix(in srgb, {blue.700}, transparent 64%)", color: "{blue.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{blue.500}", shadow: "none" } } }, success: { background: "color-mix(in srgb, {green.500}, transparent 84%)", borderColor: "color-mix(in srgb, {green.700}, transparent 64%)", color: "{green.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{green.500}", shadow: "none" } } }, warn: { background: "color-mix(in srgb, {yellow.500}, transparent 84%)", borderColor: "color-mix(in srgb, {yellow.700}, transparent 64%)", color: "{yellow.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{yellow.500}", shadow: "none" } } }, error: { background: "color-mix(in srgb, {red.500}, transparent 84%)", borderColor: "color-mix(in srgb, {red.700}, transparent 64%)", color: "{red.500}", shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{red.500}", shadow: "none" } } }, secondary: { background: "{surface.800}", borderColor: "{surface.700}", color: "{surface.300}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)", closeButton: { hoverBackground: "{surface.700}", focusRing: { color: "{surface.300}", shadow: "none" } } }, contrast: { background: "{surface.0}", borderColor: "{surface.100}", color: "{surface.950}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)", closeButton: { hoverBackground: "{surface.100}", focusRing: { color: "{surface.950}", shadow: "none" } } } } } }; var index$J = { root: { borderRadius: "{content.border.radius}", gap: "1rem" }, meters: { background: "{content.border.color}", size: "0.5rem" }, label: { gap: "0.5rem" }, labelMarker: { size: "0.5rem" }, labelIcon: { size: "1rem" }, labelList: { verticalGap: "0.5rem", horizontalGap: "1rem" } }; var index$I = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, dropdown: { width: "2.5rem", color: "{form.field.icon.color}" }, overlay: { background: "{overlay.select.background}", borderColor: "{overlay.select.border.color}", borderRadius: "{overlay.select.border.radius}", color: "{overlay.select.color}", shadow: "{overlay.select.shadow}" }, list: { padding: "{list.padding}", gap: "{list.gap}", header: { padding: "{list.header.padding}" } }, option: { focusBackground: "{list.option.focus.background}", selectedBackground: "{list.option.selected.background}", selectedFocusBackground: "{list.option.selected.focus.background}", color: "{list.option.color}", focusColor: "{list.option.focus.color}", selectedColor: "{list.option.selected.color}", selectedFocusColor: "{list.option.selected.focus.color}", padding: "{list.option.padding}", borderRadius: "{list.option.border.radius}", gap: "0.5rem" }, optionGroup: { background: "{list.option.group.background}", color: "{list.option.group.color}", fontWeight: "{list.option.group.font.weight}", padding: "{list.option.group.padding}" }, chip: { borderRadius: "{border.radius.sm}" }, emptyMessage: { padding: "{list.option.padding}" } }; var index$H = { root: { gap: "1.125rem" }, controls: { gap: "0.5rem" } }; var index$G = { root: { gutter: "0.75rem", transitionDuration: "{transition.duration}" }, node: { background: "{content.background}", hoverBackground: "{content.hover.background}", selectedBackground: "{highlight.background}", borderColor: "{content.border.color}", color: "{content.color}", selectedColor: "{highlight.color}", hoverColor: "{content.hover.color}", padding: "0.75rem 1rem", toggleablePadding: "0.75rem 1rem 1.25rem 1rem", borderRadius: "{content.border.radius}" }, nodeToggleButton: { background: "{content.background}", hoverBackground: "{content.hover.background}", borderColor: "{content.border.color}", color: "{text.muted.color}", hoverColor: "{text.color}", size: "1.5rem", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, connector: { color: "{content.border.color}", borderRadius: "{content.border.radius}", height: "24px" } }; var index$F = { root: { outline: { width: "2px", color: "{content.background}" } } }; var index$E = { root: { padding: "0.5rem 1rem", gap: "0.25rem", borderRadius: "{content.border.radius}", background: "{content.background}", color: "{content.color}", transitionDuration: "{transition.duration}" }, navButton: { background: "transparent", hoverBackground: "{content.hover.background}", selectedBackground: "{highlight.background}", color: "{text.muted.color}", hoverColor: "{text.hover.muted.color}", selectedColor: "{highlight.color}", width: "2.5rem", height: "2.5rem", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, currentPageReport: { color: "{text.muted.color}" }, jumpToPageInput: { maxWidth: "2.5rem" } }; var index$D = { root: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", borderRadius: "{content.border.radius}" }, header: { background: "transparent", color: "{text.color}", padding: "1.125rem", borderColor: "{content.border.color}", borderWidth: "0", borderRadius: "0" }, toggleableHeader: { padding: "0.375rem 1.125rem" }, title: { fontWeight: "600" }, content: { padding: "0 1.125rem 1.125rem 1.125rem" }, footer: { padding: "0 1.125rem 1.125rem 1.125rem" } }; var index$C = { root: { gap: "0.5rem", transitionDuration: "{transition.duration}" }, panel: { background: "{content.background}", borderColor: "{content.border.color}", borderWidth: "1px", color: "{content.color}", padding: "0.25rem 0.25rem", borderRadius: "{content.border.radius}", first: { borderWidth: "1px", topBorderRadius: "{content.border.radius}" }, last: { borderWidth: "1px", bottomBorderRadius: "{content.border.radius}" } }, item: { focusBackground: "{navigation.item.focus.background}", color: "{navigation.item.color}", focusColor: "{navigation.item.focus.color}", gap: "0.5rem", padding: "{navigation.item.padding}", borderRadius: "{content.border.radius}", icon: { color: "{navigation.item.icon.color}", focusColor: "{navigation.item.icon.focus.color}" } }, submenu: { indent: "1rem" }, submenuIcon: { color: "{navigation.submenu.icon.color}", focusColor: "{navigation.submenu.icon.focus.color}" } }; var index$B = { meter: { background: "{content.border.color}", borderRadius: "{content.border.radius}", height: ".75rem" }, icon: { color: "{form.field.icon.color}" }, overlay: { background: "{overlay.popover.background}", borderColor: "{overlay.popover.border.color}", borderRadius: "{overlay.popover.border.radius}", color: "{overlay.popover.color}", padding: "{overlay.popover.padding}", shadow: "{overlay.popover.shadow}" }, content: { gap: "0.5rem" }, colorScheme: { light: { strength: { weakBackground: "{red.500}", mediumBackground: "{amber.500}", strongBackground: "{green.500}" } }, dark: { strength: { weakBackground: "{red.400}", mediumBackground: "{amber.400}", strongBackground: "{green.400}" } } } }; var index$A = { root: { gap: "1.125rem" }, controls: { gap: "0.5rem" } }; var index$z = { root: { background: "{overlay.popover.background}", borderColor: "{overlay.popover.border.color}", color: "{overlay.popover.color}", borderRadius: "{overlay.popover.border.radius}", shadow: "{overlay.popover.shadow}", gutter: "10px", arrowOffset: "1.25rem" }, content: { padding: "{overlay.popover.padding}" } }; var index$y = { root: { background: "{content.border.color}", borderRadius: "{content.border.radius}", height: "1.25rem" }, value: { background: "{primary.color}" }, label: { color: "{primary.contrast.color}", fontSize: "0.75rem", fontWeight: "600" } }; var index$x = { colorScheme: { light: { root: { "color.1": "{red.500}", "color.2": "{blue.500}", "color.3": "{green.500}", "color.4": "{yellow.500}" } }, dark: { root: { "color.1": "{red.400}", "color.2": "{blue.400}", "color.3": "{green.400}", "color.4": "{yellow.400}" } } } }; var index$w = { root: { width: "1.25rem", height: "1.25rem", background: "{form.field.background}", checkedBackground: "{primary.color}", checkedHoverBackground: "{primary.hover.color}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.border.color}", checkedBorderColor: "{primary.color}", checkedHoverBorderColor: "{primary.hover.color}", checkedFocusBorderColor: "{primary.color}", checkedDisabledBorderColor: "{form.field.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", shadow: "{form.field.shadow}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, icon: { size: "0.75rem", checkedColor: "{primary.contrast.color}", checkedHoverColor: "{primary.contrast.color}", disabledColor: "{form.field.disabled.color}" } }; var index$v = { root: { gap: "0.25rem", transitionDuration: "{transition.duration}" }, icon: { size: "1rem", color: "{text.muted.color}", hoverColor: "{primary.color}", activeColor: "{primary.color}" } }; var index$u = { colorScheme: { light: { root: { background: "rgba(0,0,0,0.1)" } }, dark: { root: { background: "rgba(255,255,255,0.3)" } } } }; var index$t = { root: { transitionDuration: "{transition.duration}" }, bar: { size: "9px", borderRadius: "{border.radius.sm}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, colorScheme: { light: { bar: { background: "{surface.100}" } }, dark: { bar: { background: "{surface.800}" } } } }; var index$s = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, dropdown: { width: "2.5rem", color: "{form.field.icon.color}" }, overlay: { background: "{overlay.select.background}", borderColor: "{overlay.select.border.color}", borderRadius: "{overlay.select.border.radius}", color: "{overlay.select.color}", shadow: "{overlay.select.shadow}" }, list: { padding: "{list.padding}", gap: "{list.gap}", header: { padding: "{list.header.padding}" } }, option: { focusBackground: "{list.option.focus.background}", selectedBackground: "{list.option.selected.background}", selectedFocusBackground: "{list.option.selected.focus.background}", color: "{list.option.color}", focusColor: "{list.option.focus.color}", selectedColor: "{list.option.selected.color}", selectedFocusColor: "{list.option.selected.focus.color}", padding: "{list.option.padding}", borderRadius: "{list.option.border.radius}" }, optionGroup: { background: "{list.option.group.background}", color: "{list.option.group.color}", fontWeight: "{list.option.group.font.weight}", padding: "{list.option.group.padding}" }, clearIcon: { color: "{form.field.icon.color}" }, checkmark: { color: "{list.option.color}", gutterStart: "-0.375rem", gutterEnd: "0.375rem" }, emptyMessage: { padding: "{list.option.padding}" } }; var index$r = { root: { borderRadius: "{form.field.border.radius}" }, colorScheme: { light: { root: { invalidBorderColor: "{form.field.invalid.border.color}" } }, dark: { root: { invalidBorderColor: "{form.field.invalid.border.color}" } } } }; var index$q = { root: { borderRadius: "{content.border.radius}" }, colorScheme: { light: { root: { background: "{surface.200}", animationBackground: "rgba(255,255,255,0.4)" } }, dark: { root: { background: "rgba(255, 255, 255, 0.06)", animationBackground: "rgba(255, 255, 255, 0.04)" } } } }; var index$p = { root: { transitionDuration: "{transition.duration}" }, track: { background: "{content.border.color}", borderRadius: "{content.border.radius}", size: "3px" }, range: { background: "{primary.color}" }, handle: { width: "20px", height: "20px", borderRadius: "50%", background: "{content.border.color}", hoverBackground: "{content.border.color}", content: { borderRadius: "50%", hoverBackground: "{content.background}", width: "16px", height: "16px", shadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.08), 0px 1px 1px 0px rgba(0, 0, 0, 0.14)" }, focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, colorScheme: { light: { handle: { contentBackground: "{surface.0}" } }, dark: { handle: { contentBackground: "{surface.950}" } } } }; var index$o = { root: { gap: "0.5rem", transitionDuration: "{transition.duration}" } }; var index$n = { root: { borderRadius: "{form.field.border.radius}", roundedBorderRadius: "2rem", raisedShadow: "0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12)" } }; var index$m = { root: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", transitionDuration: "{transition.duration}" }, gutter: { background: "{content.border.color}" }, handle: { size: "24px", background: "transparent", borderRadius: "{content.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } } }; var index$l = { root: { transitionDuration: "{transition.duration}" }, separator: { background: "{content.border.color}", activeBackground: "{primary.color}", margin: "0 0 0 1.625rem", size: "2px" }, step: { padding: "0.5rem", gap: "1rem" }, stepHeader: { padding: "0", borderRadius: "{content.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, gap: "0.5rem" }, stepTitle: { color: "{text.muted.color}", activeColor: "{primary.color}", fontWeight: "500" }, stepNumber: { background: "{content.background}", activeBackground: "{content.background}", borderColor: "{content.border.color}", activeBorderColor: "{content.border.color}", color: "{text.muted.color}", activeColor: "{primary.color}", size: "2rem", fontSize: "1.143rem", fontWeight: "500", borderRadius: "50%", shadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.06), 0px 1px 1px 0px rgba(0, 0, 0, 0.12)" }, steppanels: { padding: "0.875rem 0.5rem 1.125rem 0.5rem" }, steppanel: { background: "{content.background}", color: "{content.color}", padding: "0 0 0 1rem" } }; var index$k = { root: { transitionDuration: "{transition.duration}" }, separator: { background: "{content.border.color}" }, itemLink: { borderRadius: "{content.border.radius}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, gap: "0.5rem" }, itemLabel: { color: "{text.muted.color}", activeColor: "{primary.color}", fontWeight: "500" }, itemNumber: { background: "{content.background}", activeBackground: "{content.background}", borderColor: "{content.border.color}", activeBorderColor: "{content.border.color}", color: "{text.muted.color}", activeColor: "{primary.color}", size: "2rem", fontSize: "1.143rem", fontWeight: "500", borderRadius: "50%", shadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.06), 0px 1px 1px 0px rgba(0, 0, 0, 0.12)" } }; var index$j = { root: { transitionDuration: "{transition.duration}" }, tablist: { borderWidth: "0 0 1px 0", background: "{content.background}", borderColor: "{content.border.color}" }, item: { background: "transparent", hoverBackground: "transparent", activeBackground: "transparent", borderWidth: "0 0 1px 0", borderColor: "{content.border.color}", hoverBorderColor: "{content.border.color}", activeBorderColor: "{primary.color}", color: "{text.muted.color}", hoverColor: "{text.color}", activeColor: "{primary.color}", padding: "1rem 1.125rem", fontWeight: "600", margin: "0 0 -1px 0", gap: "0.5rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, itemIcon: { color: "{text.muted.color}", hoverColor: "{text.color}", activeColor: "{primary.color}" }, activeBar: { height: "1px", bottom: "-1px", background: "{primary.color}" } }; var index$i = { root: { transitionDuration: "{transition.duration}" }, tablist: { borderWidth: "0 0 1px 0", background: "{content.background}", borderColor: "{content.border.color}" }, tab: { background: "transparent", hoverBackground: "transparent", activeBackground: "transparent", borderWidth: "0 0 1px 0", borderColor: "{content.border.color}", hoverBorderColor: "{content.border.color}", activeBorderColor: "{primary.color}", color: "{text.muted.color}", hoverColor: "{text.color}", activeColor: "{primary.color}", padding: "1rem 1.125rem", fontWeight: "600", margin: "0 0 -1px 0", gap: "0.5rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "-1px", shadow: "{focus.ring.shadow}" } }, tabpanel: { background: "{content.background}", color: "{content.color}", padding: "0.875rem 1.125rem 1.125rem 1.125rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "inset {focus.ring.shadow}" } }, navButton: { background: "{content.background}", color: "{text.muted.color}", hoverColor: "{text.color}", width: "2.5rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "-1px", shadow: "{focus.ring.shadow}" } }, activeBar: { height: "1px", bottom: "-1px", background: "{primary.color}" }, colorScheme: { light: { navButton: { shadow: "0px 0px 10px 50px rgba(255, 255, 255, 0.6)" } }, dark: { navButton: { shadow: "0px 0px 10px 50px color-mix(in srgb, {content.background}, transparent 50%)" } } } }; var index$h = { root: { transitionDuration: "{transition.duration}" }, tabList: { background: "{content.background}", borderColor: "{content.border.color}" }, tab: { borderColor: "{content.border.color}", activeBorderColor: "{primary.color}", color: "{text.muted.color}", hoverColor: "{text.color}", activeColor: "{primary.color}" }, tabPanel: { background: "{content.background}", color: "{content.color}" }, navButton: { background: "{content.background}", color: "{text.muted.color}", hoverColor: "{text.color}" }, colorScheme: { light: { navButton: { shadow: "0px 0px 10px 50px rgba(255, 255, 255, 0.6)" } }, dark: { navButton: { shadow: "0px 0px 10px 50px color-mix(in srgb, {content.background}, transparent 50%)" } } } }; var index$g = { root: { fontSize: "0.875rem", fontWeight: "700", padding: "0.25rem 0.5rem", gap: "0.25rem", borderRadius: "{content.border.radius}", roundedBorderRadius: "{border.radius.xl}" }, icon: { size: "0.75rem" }, colorScheme: { light: { primary: { background: "{primary.100}", color: "{primary.700}" }, secondary: { background: "{surface.100}", color: "{surface.600}" }, success: { background: "{green.100}", color: "{green.700}" }, info: { background: "{sky.100}", color: "{sky.700}" }, warn: { background: "{orange.100}", color: "{orange.700}" }, danger: { background: "{red.100}", color: "{red.700}" }, contrast: { background: "{surface.950}", color: "{surface.0}" } }, dark: { primary: { background: "color-mix(in srgb, {primary.500}, transparent 84%)", color: "{primary.300}" }, secondary: { background: "{surface.800}", color: "{surface.300}" }, success: { background: "color-mix(in srgb, {green.500}, transparent 84%)", color: "{green.300}" }, info: { background: "color-mix(in srgb, {sky.500}, transparent 84%)", color: "{sky.300}" }, warn: { background: "color-mix(in srgb, {orange.500}, transparent 84%)", color: "{orange.300}" }, danger: { background: "color-mix(in srgb, {red.500}, transparent 84%)", color: "{red.300}" }, contrast: { background: "{surface.0}", color: "{surface.950}" } } } }; var index$f = { root: { background: "{form.field.background}", borderColor: "{form.field.border.color}", color: "{form.field.color}", height: "18rem", padding: "{form.field.padding.y} {form.field.padding.x}", borderRadius: "{form.field.border.radius}" }, prompt: { gap: "0.25rem" }, commandResponse: { margin: "2px 0" } }; var index$e = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" } }; var index$d = { root: { background: "{content.background}", borderColor: "{content.border.color}", color: "{content.color}", borderRadius: "{content.border.radius}", shadow: "{overlay.navigation.shadow}", transitionDuration: "{transition.duration}" }, list: { padding: "{navigation.list.padding}", gap: "{navigation.list.gap}" }, item: { focusBackground: "{navigation.item.focus.background}", activeBackground: "{navigation.item.active.background}", color: "{navigation.item.color}", focusColor: "{navigation.item.focus.color}", activeColor: "{navigation.item.active.color}", padding: "{navigation.item.padding}", borderRadius: "{navigation.item.border.radius}", gap: "{navigation.item.gap}", icon: { color: "{navigation.item.icon.color}", focusColor: "{navigation.item.icon.focus.color}", activeColor: "{navigation.item.icon.active.color}" } }, submenuLabel: { padding: "{navigation.submenu.label.padding}", fontWeight: "{navigation.submenu.label.font.weight}", background: "{navigation.submenu.label.background.}", color: "{navigation.submenu.label.color}" }, submenuIcon: { size: "{navigation.submenu.icon.size}", color: "{navigation.submenu.icon.color}", focusColor: "{navigation.submenu.icon.focus.color}", activeColor: "{navigation.submenu.icon.active.color}" }, separator: { borderColor: "{content.border.color}" } }; var index$c = { event: { minHeight: "5rem" }, horizontal: { eventContent: { padding: "1rem 0" } }, vertical: { eventContent: { padding: "0 1rem" } }, eventMarker: { size: "1.125rem", borderRadius: "50%", borderWidth: "2px", background: "{content.background}", borderColor: "{content.border.color}", content: { borderRadius: "50%", size: "0.375rem", background: "{primary.color}", insetShadow: "0px 0.5px 0px 0px rgba(0, 0, 0, 0.06), 0px 1px 1px 0px rgba(0, 0, 0, 0.12)" } }, eventConnector: { color: "{content.border.color}", size: "2px" } }; var index$b = { root: { width: "25rem", borderRadius: "{content.border.radius}", borderWidth: "1px", transitionDuration: "{transition.duration}" }, icon: { size: "1.125rem" }, content: { padding: "{overlay.popover.padding}", gap: "0.5rem" }, text: { gap: "0.5rem" }, summary: { fontWeight: "500", fontSize: "1rem" }, detail: { fontWeight: "500", fontSize: "0.875rem" }, closeButton: { width: "1.75rem", height: "1.75rem", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", offset: "{focus.ring.offset}" } }, closeIcon: { size: "1rem" }, colorScheme: { light: { blur: "1.5px", info: { background: "color-mix(in srgb, {blue.50}, transparent 5%)", borderColor: "{blue.200}", color: "{blue.600}", detailColor: "{surface.700}", shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)", closeButton: { hoverBackground: "{blue.100}", focusRing: { color: "{blue.600}", shadow: "none" } } }, success: { background: "color-mix(in srgb, {green.50}, transparent 5%)", borderColor: "{green.200}", color: "{green.600}", detailColor: "{surface.700}", shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)", closeButton: { hoverBackground: "{green.100}", focusRing: { color: "{green.600}", shadow: "none" } } }, warn: { background: "color-mix(in srgb,{yellow.50}, transparent 5%)", borderColor: "{yellow.200}", color: "{yellow.600}", detailColor: "{surface.700}", shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)", closeButton: { hoverBackground: "{yellow.100}", focusRing: { color: "{yellow.600}", shadow: "none" } } }, error: { background: "color-mix(in srgb, {red.50}, transparent 5%)", borderColor: "{red.200}", color: "{red.600}", detailColor: "{surface.700}", shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)", closeButton: { hoverBackground: "{red.100}", focusRing: { color: "{red.600}", shadow: "none" } } }, secondary: { background: "{surface.100}", borderColor: "{surface.200}", color: "{surface.600}", detailColor: "{surface.700}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)", closeButton: { hoverBackground: "{surface.200}", focusRing: { color: "{surface.600}", shadow: "none" } } }, contrast: { background: "{surface.900}", borderColor: "{surface.950}", color: "{surface.50}", detailColor: "{surface.0}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)", closeButton: { hoverBackground: "{surface.800}", focusRing: { color: "{surface.50}", shadow: "none" } } } }, dark: { blur: "10px", info: { background: "color-mix(in srgb, {blue.500}, transparent 84%)", borderColor: "color-mix(in srgb, {blue.700}, transparent 64%)", color: "{blue.500}", detailColor: "{surface.0}", shadow: "0px 4px 8px 0px color-mix(in srgb, {blue.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{blue.500}", shadow: "none" } } }, success: { background: "color-mix(in srgb, {green.500}, transparent 84%)", borderColor: "color-mix(in srgb, {green.700}, transparent 64%)", color: "{green.500}", detailColor: "{surface.0}", shadow: "0px 4px 8px 0px color-mix(in srgb, {green.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{green.500}", shadow: "none" } } }, warn: { background: "color-mix(in srgb, {yellow.500}, transparent 84%)", borderColor: "color-mix(in srgb, {yellow.700}, transparent 64%)", color: "{yellow.500}", detailColor: "{surface.0}", shadow: "0px 4px 8px 0px color-mix(in srgb, {yellow.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{yellow.500}", shadow: "none" } } }, error: { background: "color-mix(in srgb, {red.500}, transparent 84%)", borderColor: "color-mix(in srgb, {red.700}, transparent 64%)", color: "{red.500}", detailColor: "{surface.0}", shadow: "0px 4px 8px 0px color-mix(in srgb, {red.500}, transparent 96%)", closeButton: { hoverBackground: "rgba(255, 255, 255, 0.05)", focusRing: { color: "{red.500}", shadow: "none" } } }, secondary: { background: "{surface.800}", borderColor: "{surface.700}", color: "{surface.300}", detailColor: "{surface.0}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.500}, transparent 96%)", closeButton: { hoverBackground: "{surface.700}", focusRing: { color: "{surface.300}", shadow: "none" } } }, contrast: { background: "{surface.0}", borderColor: "{surface.100}", color: "{surface.950}", detailColor: "{surface.950}", shadow: "0px 4px 8px 0px color-mix(in srgb, {surface.950}, transparent 96%)", closeButton: { hoverBackground: "{surface.100}", focusRing: { color: "{surface.950}", shadow: "none" } } } } } }; var index$a = { root: { padding: "0.5rem 1rem", borderRadius: "{content.border.radius}", gap: "0.5rem", fontWeight: "500", disabledBackground: "{form.field.disabled.background}", disabledBorderColor: "{form.field.disabled.background}", disabledColor: "{form.field.disabled.color}", invalidBorderColor: "{form.field.invalid.border.color}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, icon: { disabledColor: "{form.field.disabled.color}" }, content: { left: "0.25rem", top: "0.25rem", checkedShadow: "0px 1px 2px 0px rgba(0, 0, 0, 0.02), 0px 1px 2px 0px rgba(0, 0, 0, 0.04)" }, colorScheme: { light: { root: { background: "{surface.100}", checkedBackground: "{surface.100}", hoverBackground: "{surface.100}", borderColor: "{surface.100}", color: "{surface.500}", hoverColor: "{surface.700}", checkedColor: "{surface.900}", checkedBorderColor: "{surface.100}" }, content: { checkedBackground: "{surface.0}" }, icon: { color: "{surface.500}", hoverColor: "{surface.700}", checkedColor: "{surface.900}" } }, dark: { root: { background: "{surface.950}", checkedBackground: "{surface.950}", hoverBackground: "{surface.950}", borderColor: "{surface.950}", color: "{surface.400}", hoverColor: "{surface.300}", checkedColor: "{surface.0}", checkedBorderColor: "{surface.950}" }, content: { checkedBackground: "{surface.800}" }, icon: { color: "{surface.400}", hoverColor: "{surface.300}", checkedColor: "{surface.0}" } } } }; var index$9 = { root: { width: "2.5rem", height: "1.5rem", borderRadius: "30px", gap: "0.25rem", shadow: "{form.field.shadow}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" }, borderWidth: "1px", borderColor: "transparent", hoverBorderColor: "transparent", checkedBorderColor: "transparent", checkedHoverBorderColor: "transparent", invalidBorderColor: "{form.field.invalid.border.color}", transitionDuration: "{form.field.transition.duration}", slideDuration: "0.2s", disabledBackground: "{form.field.disabled.background}" }, handle: { borderRadius: "50%", size: "1rem", disabledBackground: "{form.field.disabled.color}" }, colorScheme: { light: { root: { background: "{surface.300}", hoverBackground: "{surface.400}", checkedBackground: "{primary.color}", checkedHoverBackground: "{primary.hover.color}" }, handle: { background: "{surface.0}", hoverBackground: "{surface.0}", checkedBackground: "{surface.0}", checkedHoverBackground: "{surface.0}" } }, dark: { root: { background: "{surface.700}", hoverBackground: "{surface.600}", checkedBackground: "{primary.color}", checkedHoverBackground: "{primary.hover.color}" }, handle: { background: "{surface.400}", hoverBackground: "{surface.300}", checkedBackground: "{surface.900}", checkedHoverBackground: "{surface.900}" } } } }; var index$8 = { root: { background: "{content.background}", borderColor: "{content.border.color}", borderRadius: "{content.border.radius}", color: "{content.color}", gap: "0.5rem", padding: "0.75rem" } }; var index$7 = { root: { maxWidth: "12.5rem", gutter: "0.25rem", shadow: "{overlay.popover.shadow}", padding: "0.5rem 0.75rem", borderRadius: "{overlay.popover.border.radius}" }, colorScheme: { light: { root: { background: "{surface.700}", color: "{surface.0}" } }, dark: { root: { background: "{surface.700}", color: "{surface.0}" } } } }; var index$6 = { root: { background: "{content.background}", color: "{content.color}", padding: "1rem", gap: "2px", indent: "1rem", transitionDuration: "{transition.duration}" }, node: { padding: "0.25rem 0.5rem", borderRadius: "{content.border.radius}", hoverBackground: "{content.hover.background}", selectedBackground: "{highlight.background}", color: "{text.color}", hoverColor: "{text.hover.color}", selectedColor: "{highlight.color}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "-1px", shadow: "{focus.ring.shadow}" }, gap: "0.25rem" }, nodeIcon: { color: "{text.muted.color}", hoverColor: "{text.hover.muted.color}", selectedColor: "{highlight.color}" }, nodeToggleButton: { borderRadius: "50%", size: "1.75rem", hoverBackground: "{content.hover.background}", selectedHoverBackground: "{content.background}", color: "{text.muted.color}", hoverColor: "{text.hover.muted.color}", selectedHoverColor: "{primary.color}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, loadingIcon: { size: "2rem" } }; var index$5 = { root: { background: "{form.field.background}", disabledBackground: "{form.field.disabled.background}", filledBackground: "{form.field.filled.background}", filledFocusBackground: "{form.field.filled.focus.background}", borderColor: "{form.field.border.color}", hoverBorderColor: "{form.field.hover.border.color}", focusBorderColor: "{form.field.focus.border.color}", invalidBorderColor: "{form.field.invalid.border.color}", color: "{form.field.color}", disabledColor: "{form.field.disabled.color}", placeholderColor: "{form.field.placeholder.color}", shadow: "{form.field.shadow}", paddingX: "{form.field.padding.x}", paddingY: "{form.field.padding.y}", borderRadius: "{form.field.border.radius}", focusRing: { width: "{form.field.focus.ring.width}", style: "{form.field.focus.ring.style}", color: "{form.field.focus.ring.color}", offset: "{form.field.focus.ring.offset}", shadow: "{form.field.focus.ring.shadow}" }, transitionDuration: "{form.field.transition.duration}" }, dropdown: { width: "2.5rem", color: "{form.field.icon.color}" }, overlay: { background: "{overlay.select.background}", borderColor: "{overlay.select.border.color}", borderRadius: "{overlay.select.border.radius}", color: "{overlay.select.color}", shadow: "{overlay.select.shadow}" }, tree: { padding: "{list.padding}" }, emptyMessage: { padding: "{list.option.padding}" }, chip: { borderRadius: "{border.radius.sm}" } }; var index$4 = { root: { transitionDuration: "{transition.duration}" }, header: { background: "{content.background}", borderColor: "{treetable.border.color}", color: "{content.color}", borderWidth: "0 0 1px 0", padding: "0.75rem 1rem" }, headerCell: { background: "{content.background}", hoverBackground: "{content.hover.background}", selectedBackground: "{highlight.background}", borderColor: "{treetable.border.color}", color: "{content.color}", hoverColor: "{content.hover.color}", selectedColor: "{highlight.color}", gap: "0.5rem", padding: "0.75rem 1rem", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "-1px", shadow: "{focus.ring.shadow}" } }, columnTitle: { fontWeight: "600" }, row: { background: "{content.background}", hoverBackground: "{content.hover.background}", selectedBackground: "{highlight.background}", color: "{content.color}", hoverColor: "{content.hover.color}", selectedColor: "{highlight.color}", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "-1px", shadow: "{focus.ring.shadow}" } }, bodyCell: { borderColor: "{treetable.border.color}", padding: "0.75rem 1rem", gap: "0.5rem" }, footerCell: { background: "{content.background}", borderColor: "{treetable.border.color}", color: "{content.color}", padding: "0.75rem 1rem" }, columnFooter: { fontWeight: "600" }, footer: { background: "{content.background}", borderColor: "{treetable.border.color}", color: "{content.color}", borderWidth: "0 0 1px 0", padding: "0.75rem 1rem" }, columnResizerWidth: "0.5rem", resizeIndicator: { width: "1px", color: "{primary.color}" }, sortIcon: { color: "{text.muted.color}", hoverColor: "{text.hover.muted.color}" }, loadingIcon: { size: "2rem" }, nodeToggleButton: { hoverBackground: "{content.hover.background}", selectedHoverBackground: "{content.background}", color: "{text.muted.color}", hoverColor: "{text.color}", selectedHoverColor: "{primary.color}", size: "1.75rem", borderRadius: "50%", focusRing: { width: "{focus.ring.width}", style: "{focus.ring.style}", color: "{focus.ring.color}", offset: "{focus.ring.offset}", shadow: "{focus.ring.shadow}" } }, paginatorTop: { borderColor: "{content.border.color}", borderWidth: "0 0 1px 0" }, paginatorBottom: { borderColor: "{content.border.color}", borderWidth: "0 0 1px 0" }, colorScheme: { light: { root: { borderColor: "{content.border.color}" }, bodyCell: { selectedBorderColor: "{primary.100}" } }, dark: { root: { borderColor: "{surface.800}" }, bodyCell: { selectedBorderColor: "{primary.900}" } } } }; var index$3 = { loader: { mask: { background: "{content.background}", color: "{text.muted.color}" }, icon: { size: "2rem" } } }; var index$2 = { primitive: { borderRadius: { none: "0", xs: "2px", sm: "4px", md: "6px", lg: "8px", xl: "12px" }, emerald: { 50: "#ecfdf5", 100: "#d1fae5", 200: "#a7f3d0", 300: "#6ee7b7", 400: "#34d399", 500: "#10b981", 600: "#059669", 700: "#047857", 800: "#065f46", 900: "#064e3b", 950: "#022c22" }, green: { 50: "#f0fdf4", 100: "#dcfce7", 200: "#bbf7d0", 300: "#86efac", 400: "#4ade80", 500: "#22c55e", 600: "#16a34a", 700: "#15803d", 800: "#166534", 900: "#14532d", 950: "#052e16" }, lime: { 50: "#f7fee7", 100: "#ecfccb", 200: "#d9f99d", 300: "#bef264", 400: "#a3e635", 500: "#84cc16", 600: "#65a30d", 700: "#4d7c0f", 800: "#3f6212", 900: "#365314", 950: "#1a2e05" }, red: { 50: "#fef2f2", 100: "#fee2e2", 200: "#fecaca", 300: "#fca5a5", 400: "#f87171", 500: "#ef4444", 600: "#dc2626", 700: "#b91c1c", 800: "#991b1b", 900: "#7f1d1d", 950: "#450a0a" }, orange: { 50: "#fff7ed", 100: "#ffedd5", 200: "#fed7aa", 300: "#fdba74", 400: "#fb923c", 500: "#f97316", 600: "#ea580c", 700: "#c2410c", 800: "#9a3412", 900: "#7c2d12", 950: "#431407" }, amber: { 50: "#fffbeb", 100: "#fef3c7", 200: "#fde68a", 300: "#fcd34d", 400: "#fbbf24", 500: "#f59e0b", 600: "#d97706", 700: "#b45309", 800: "#92400e", 900: "#78350f", 950: "#451a03" }, yellow: { 50: "#fefce8", 100: "#fef9c3", 200: "#fef08a", 300: "#fde047", 400: "#facc15", 500: "#eab308", 600: "#ca8a04", 700: "#a16207", 800: "#854d0e", 900: "#713f12", 950: "#422006" }, teal: { 50: "#f0fdfa", 100: "#ccfbf1", 200: "#99f6e4", 300: "#5eead4", 400: "#2dd4bf", 500: "#14b8a6", 600: "#0d9488", 700: "#0f766e", 800: "#115e59", 900: "#134e4a", 950: "#042f2e" }, cyan: { 50: "#ecfeff", 100: "#cffafe", 200: "#a5f3fc", 300: "#67e8f9", 400: "#22d3ee", 500: "#06b6d4", 600: "#0891b2", 700: "#0e7490", 800: "#155e75", 900: "#164e63", 950: "#083344" }, sky: { 50: "#f0f9ff", 100: "#e0f2fe", 200: "#bae6fd", 300: "#7dd3fc", 400: "#38bdf8", 500: "#0ea5e9", 600: "#0284c7", 700: "#0369a1", 800: "#075985", 900: "#0c4a6e", 950: "#082f49" }, blue: { 50: "#eff6ff", 100: "#dbeafe", 200: "#bfdbfe", 300: "#93c5fd", 400: "#60a5fa", 500: "#3b82f6", 600: "#2563eb", 700: "#1d4ed8", 800: "#1e40af", 900: "#1e3a8a", 950: "#172554" }, indigo: { 50: "#eef2ff", 100: "#e0e7ff", 200: "#c7d2fe", 300: "#a5b4fc", 400: "#818cf8", 500: "#6366f1", 600: "#4f46e5", 700: "#4338ca", 800: "#3730a3", 900: "#312e81", 950: "#1e1b4b" }, violet: { 50: "#f5f3ff", 100: "#ede9fe", 200: "#ddd6fe", 300: "#c4b5fd", 400: "#a78bfa", 500: "#8b5cf6", 600: "#7c3aed", 700: "#6d28d9", 800: "#5b21b6", 900: "#4c1d95", 950: "#2e1065" }, purple: { 50: "#faf5ff", 100: "#f3e8ff", 200: "#e9d5ff", 300: "#d8b4fe", 400: "#c084fc", 500: "#a855f7", 600: "#9333ea", 700: "#7e22ce", 800: "#6b21a8", 900: "#581c87", 950: "#3b0764" }, fuchsia: { 50: "#fdf4ff", 100: "#fae8ff", 200: "#f5d0fe", 300: "#f0abfc", 400: "#e879f9", 500: "#d946ef", 600: "#c026d3", 700: "#a21caf", 800: "#86198f", 900: "#701a75", 950: "#4a044e" }, pink: { 50: "#fdf2f8", 100: "#fce7f3", 200: "#fbcfe8", 300: "#f9a8d4", 400: "#f472b6", 500: "#ec4899", 600: "#db2777", 700: "#be185d", 800: "#9d174d", 900: "#831843", 950: "#500724" }, rose: { 50: "#fff1f2", 100: "#ffe4e6", 200: "#fecdd3", 300: "#fda4af", 400: "#fb7185", 500: "#f43f5e", 600: "#e11d48", 700: "#be123c", 800: "#9f1239", 900: "#881337", 950: "#4c0519" }, slate: { 50: "#f8fafc", 100: "#f1f5f9", 200: "#e2e8f0", 300: "#cbd5e1", 400: "#94a3b8", 500: "#64748b", 600: "#475569", 700: "#334155", 800: "#1e293b", 900: "#0f172a", 950: "#020617" }, gray: { 50: "#f9fafb", 100: "#f3f4f6", 200: "#e5e7eb", 300: "#d1d5db", 400: "#9ca3af", 500: "#6b7280", 600: "#4b5563", 700: "#374151", 800: "#1f2937", 900: "#111827", 950: "#030712" }, zinc: { 50: "#fafafa", 100: "#f4f4f5", 200: "#e4e4e7", 300: "#d4d4d8", 400: "#a1a1aa", 500: "#71717a", 600: "#52525b", 700: "#3f3f46", 800: "#27272a", 900: "#18181b", 950: "#09090b" }, neutral: { 50: "#fafafa", 100: "#f5f5f5", 200: "#e5e5e5", 300: "#d4d4d4", 400: "#a3a3a3", 500: "#737373", 600: "#525252", 700: "#404040", 800: "#262626", 900: "#171717", 950: "#0a0a0a" }, stone: { 50: "#fafaf9", 100: "#f5f5f4", 200: "#e7e5e4", 300: "#d6d3d1", 400: "#a8a29e", 500: "#78716c", 600: "#57534e", 700: "#44403c", 800: "#292524", 900: "#1c1917", 950: "#0c0a09" } }, semantic: { transitionDuration: "0.2s", focusRing: { width: "1px", style: "solid", color: "{primary.color}", offset: "2px", shadow: "none" }, disabledOpacity: "0.6", iconSize: "1rem", anchorGutter: "2px", primary: { 50: "{emerald.50}", 100: "{emerald.100}", 200: "{emerald.200}", 300: "{emerald.300}", 400: "{emerald.400}", 500: "{emerald.500}", 600: "{emerald.600}", 700: "{emerald.700}", 800: "{emerald.800}", 900: "{emerald.900}", 950: "{emerald.950}" }, formField: { paddingX: "0.75rem", paddingY: "0.5rem", borderRadius: "{border.radius.md}", focusRing: { width: "0", style: "none", color: "transparent", offset: "0", shadow: "none" }, transitionDuration: "{transition.duration}" }, list: { padding: "0.25rem 0.25rem", gap: "2px", header: { padding: "0.5rem 1rem 0.25rem 1rem" }, option: { padding: "0.5rem 0.75rem", borderRadius: "{border.radius.sm}" }, optionGroup: { padding: "0.5rem 0.75rem", fontWeight: "600" } }, content: { borderRadius: "{border.radius.md}" }, mask: { transitionDuration: "0.15s" }, navigation: { list: { padding: "0.25rem 0.25rem", gap: "2px" }, item: { padding: "0.5rem 0.75rem", borderRadius: "{border.radius.sm}", gap: "0.5rem" }, submenuLabel: { padding: "0.5rem 0.75rem", fontWeight: "600" }, submenuIcon: { size: "0.875rem" } }, overlay: { select: { borderRadius: "{border.radius.md}", shadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)" }, popover: { borderRadius: "{border.radius.md}", padding: "0.75rem", shadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)" }, modal: { borderRadius: "{border.radius.xl}", padding: "1.25rem", shadow: "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1)" }, navigation: { shadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)" } }, colorScheme: { light: { surface: { 0: "#ffffff", 50: "{slate.50}", 100: "{slate.100}", 200: "{slate.200}", 300: "{slate.300}", 400: "{slate.400}", 500: "{slate.500}", 600: "{slate.600}", 700: "{slate.700}", 800: "{slate.800}", 900: "{slate.900}", 950: "{slate.950}" }, primary: { color: "{primary.500}", contrastColor: "#ffffff", hoverColor: "{primary.600}", activeColor: "{primary.700}" }, highlight: { background: "{primary.50}", focusBackground: "{primary.100}", color: "{primary.700}", focusColor: "{primary.800}" }, mask: { background: "rgba(0,0,0,0.4)", color: "{surface.200}" }, formField: { background: "{surface.0}", disabledBackground: "{surface.200}", filledBackground: "{surface.50}", filledFocusBackground: "{surface.50}", borderColor: "{surface.300}", hoverBorderColor: "{surface.400}", focusBorderColor: "{primary.color}", invalidBorderColor: "{red.400}", color: "{surface.700}", disabledColor: "{surface.500}", placeholderColor: "{surface.500}", floatLabelColor: "{surface.500}", floatLabelFocusColor: "{surface.500}", floatLabelInvalidColor: "{red.400}", iconColor: "{surface.400}", shadow: "0 0 #0000, 0 0 #0000, 0 1px 2px 0 rgba(18, 18, 23, 0.05)" }, text: { color: "{surface.700}", hoverColor: "{surface.800}", mutedColor: "{surface.500}", hoverMutedColor: "{surface.600}" }, content: { background: "{surface.0}", hoverBackground: "{surface.100}", borderColor: "{surface.200}", color: "{text.color}", hoverColor: "{text.hover.color}" }, overlay: { select: { background: "{surface.0}", borderColor: "{surface.200}", color: "{text.color}" }, popover: { background: "{surface.0}", borderColor: "{surface.200}", color: "{text.color}" }, modal: { background: "{surface.0}", borderColor: "{surface.200}", color: "{text.color}" } }, list: { option: { focusBackground: "{surface.100}", selectedBackground: "{highlight.background}", selectedFocusBackground: "{highlight.focus.background}", color: "{text.color}", focusColor: "{text.hover.color}", selectedColor: "{highlight.color}", selectedFocusColor: "{highlight.focus.color}", icon: { color: "{surface.400}", focusColor: "{surface.500}" } }, optionGroup: { background: "transparent", color: "{text.muted.color}" } }, navigation: { item: { focusBackground: "{surface.100}", activeBackground: "{surface.100}", color: "{text.color}", focusColor: "{text.hover.color}", activeColor: "{text.hover.color}", icon: { color: "{surface.400}", focusColor: "{surface.500}", activeColor: "{surface.500}" } }, submenuLabel: { background: "transparent", color: "{text.muted.color}" }, submenuIcon: { color: "{surface.400}", focusColor: "{surface.500}", activeColor: "{surface.500}" } } }, dark: { surface: { 0: "#ffffff", 50: "{zinc.50}", 100: "{zinc.100}", 200: "{zinc.200}", 300: "{zinc.300}", 400: "{zinc.400}", 500: "{zinc.500}", 600: "{zinc.600}", 700: "{zinc.700}", 800: "{zinc.800}", 900: "{zinc.900}", 950: "{zinc.950}" }, primary: { color: "{primary.400}", contrastColor: "{surface.900}", hoverColor: "{primary.300}", activeColor: "{primary.200}" }, highlight: { background: "color-mix(in srgb, {primary.400}, transparent 84%)", focusBackground: "color-mix(in srgb, {primary.400}, transparent 76%)", color: "rgba(255,255,255,.87)", focusColor: "rgba(255,255,255,.87)" }, mask: { background: "rgba(0,0,0,0.6)", color: "{surface.200}" }, formField: { background: "{surface.950}", disabledBackground: "{surface.700}", filledBackground: "{surface.800}", filledFocusBackground: "{surface.800}", borderColor: "{surface.700}", hoverBorderColor: "{surface.600}", focusBorderColor: "{primary.color}", invalidBorderColor: "{red.300}", color: "{surface.0}", disabledColor: "{surface.400}", placeholderColor: "{surface.400}", floatLabelColor: "{surface.400}", floatLabelFocusColor: "{surface.400}", floatLabelInvalidColor: "{red.300}", iconColor: "{surface.400}", shadow: "0 0 #0000, 0 0 #0000, 0 1px 2px 0 rgba(18, 18, 23, 0.05)" }, text: { color: "{surface.0}", hoverColor: "{surface.0}", mutedColor: "{surface.400}", hoverMutedColor: "{surface.300}" }, content: { background: "{surface.900}", hoverBackground: "{surface.800}", borderColor: "{surface.700}", color: "{text.color}", hoverColor: "{text.hover.color}" }, overlay: { select: { background: "{surface.900}", borderColor: "{surface.700}", color: "{text.color}" }, popover: { background: "{surface.900}", borderColor: "{surface.700}", color: "{text.color}" }, modal: { background: "{surface.900}", borderColor: "{surface.700}", color: "{text.color}" } }, list: { option: { focusBackground: "{surface.800}", selectedBackground: "{highlight.background}", selectedFocusBackground: "{highlight.focus.background}", color: "{text.color}", focusColor: "{text.hover.color}", selectedColor: "{highlight.color}", selectedFocusColor: "{highlight.focus.color}", icon: { color: "{surface.500}", focusColor: "{surface.400}" } }, optionGroup: { background: "transparent", color: "{text.muted.color}" } }, navigation: { item: { focusBackground: "{surface.800}", activeBackground: "{surface.800}", color: "{text.color}", focusColor: "{text.hover.color}", activeColor: "{text.hover.color}", icon: { color: "{surface.500}", focusColor: "{surface.400}", activeColor: "{surface.400}" } }, submenuLabel: { background: "transparent", color: "{text.muted.color}" }, submenuIcon: { color: "{surface.500}", focusColor: "{surface.400}", activeColor: "{surface.400}" } } } } }, components: { accordion: index$1n, autocomplete: index$1m, avatar: index$1l, badge: index$1k, blockui: index$1j, breadcrumb: index$1i, button: index$1h, datepicker: index$15, card: index$1g, carousel: index$1f, cascadeselect: index$1e, checkbox: index$1d, chip: index$1c, colorpicker: index$1b, confirmdialog: index$1a, confirmpopup: index$19, contextmenu: index$18, dataview: index$16, datatable: index$17, dialog: index$14, divider: index$13, dock: index$12, drawer: index$11, editor: index$10, fieldset: index$$, fileupload: index$_, floatlabel: index$Z, galleria: index$Y, iconfield: index$X, image: index$W, inlinemessage: index$V, inplace: index$U, inputchips: index$T, inputgroup: index$S, inputnumber: index$R, inputtext: index$Q, knob: index$P, listbox: index$O, megamenu: index$N, menu: index$M, menubar: index$L, message: index$K, metergroup: index$J, multiselect: index$I, orderlist: index$H, organizationchart: index$G, overlaybadge: index$F, popover: index$z, paginator: index$E, password: index$B, panel: index$D, panelmenu: index$C, picklist: index$A, progressbar: index$y, progressspinner: index$x, radiobutton: index$w, rating: index$v, scrollpanel: index$t, select: index$s, selectbutton: index$r, skeleton: index$q, slider: index$p, speeddial: index$o, splitter: index$m, splitbutton: index$n, stepper: index$l, steps: index$k, tabmenu: index$j, tabs: index$i, tabview: index$h, textarea: index$e, tieredmenu: index$d, tag: index$g, terminal: index$f, timeline: index$c, togglebutton: index$a, toggleswitch: index$9, tree: index$6, treeselect: index$5, treetable: index$4, toast: index$b, toolbar: index$8, virtualscroller: index$3 }, directives: { tooltip: index$7, ripple: index$u } }; const DEBUG_BUILD$6 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; const SDK_VERSION = "8.48.0"; const GLOBAL_OBJ = globalThis; function getGlobalSingleton(name2, creator, obj) { const gbl = obj || GLOBAL_OBJ; const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {}; const versionedCarrier = __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {}; return versionedCarrier[name2] || (versionedCarrier[name2] = creator()); } __name(getGlobalSingleton, "getGlobalSingleton"); const DEBUG_BUILD$5 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; const PREFIX$2 = "Sentry Logger "; const CONSOLE_LEVELS$1 = [ "debug", "info", "warn", "error", "log", "assert", "trace" ]; const originalConsoleMethods = {}; function consoleSandbox(callback) { if (!("console" in GLOBAL_OBJ)) { return callback(); } const console2 = GLOBAL_OBJ.console; const wrappedFuncs = {}; const wrappedLevels = Object.keys(originalConsoleMethods); wrappedLevels.forEach((level) => { const originalConsoleMethod = originalConsoleMethods[level]; wrappedFuncs[level] = console2[level]; console2[level] = originalConsoleMethod; }); try { return callback(); } finally { wrappedLevels.forEach((level) => { console2[level] = wrappedFuncs[level]; }); } } __name(consoleSandbox, "consoleSandbox"); function makeLogger() { let enabled = false; const logger2 = { enable: /* @__PURE__ */ __name(() => { enabled = true; }, "enable"), disable: /* @__PURE__ */ __name(() => { enabled = false; }, "disable"), isEnabled: /* @__PURE__ */ __name(() => enabled, "isEnabled") }; if (DEBUG_BUILD$5) { CONSOLE_LEVELS$1.forEach((name2) => { logger2[name2] = (...args) => { if (enabled) { consoleSandbox(() => { GLOBAL_OBJ.console[name2](`${PREFIX$2}[${name2}]:`, ...args); }); } }; }); } else { CONSOLE_LEVELS$1.forEach((name2) => { logger2[name2] = () => void 0; }); } return logger2; } __name(makeLogger, "makeLogger"); const logger$2 = getGlobalSingleton("logger", makeLogger); const STACKTRACE_FRAME_LIMIT = 50; const UNKNOWN_FUNCTION = "?"; const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/; const STRIP_FRAME_REGEXP = /captureMessage|captureException/; function createStackParser(...parsers) { const sortedParsers = parsers.sort((a2, b2) => a2[0] - b2[0]).map((p2) => p2[1]); return (stack2, skipFirstLines = 0, framesToPop = 0) => { const frames = []; const lines = stack2.split("\n"); for (let i2 = skipFirstLines; i2 < lines.length; i2++) { const line = lines[i2]; if (line.length > 1024) { continue; } const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line; if (cleanedLine.match(/\S*Error: /)) { continue; } for (const parser of sortedParsers) { const frame = parser(cleanedLine); if (frame) { frames.push(frame); break; } } if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) { break; } } return stripSentryFramesAndReverse(frames.slice(framesToPop)); }; } __name(createStackParser, "createStackParser"); function stackParserFromStackParserOptions(stackParser) { if (Array.isArray(stackParser)) { return createStackParser(...stackParser); } return stackParser; } __name(stackParserFromStackParserOptions, "stackParserFromStackParserOptions"); function stripSentryFramesAndReverse(stack2) { if (!stack2.length) { return []; } const localStack = Array.from(stack2); if (/sentryWrapped/.test(getLastStackFrame(localStack).function || "")) { localStack.pop(); } localStack.reverse(); if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) { localStack.pop(); if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) { localStack.pop(); } } return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({ ...frame, filename: frame.filename || getLastStackFrame(localStack).filename, function: frame.function || UNKNOWN_FUNCTION })); } __name(stripSentryFramesAndReverse, "stripSentryFramesAndReverse"); function getLastStackFrame(arr) { return arr[arr.length - 1] || {}; } __name(getLastStackFrame, "getLastStackFrame"); const defaultFunctionName = ""; function getFunctionName(fn) { try { if (!fn || typeof fn !== "function") { return defaultFunctionName; } return fn.name || defaultFunctionName; } catch (e2) { return defaultFunctionName; } } __name(getFunctionName, "getFunctionName"); function getFramesFromEvent(event) { const exception = event.exception; if (exception) { const frames = []; try { exception.values.forEach((value4) => { if (value4.stacktrace.frames) { frames.push(...value4.stacktrace.frames); } }); return frames; } catch (_oO) { return void 0; } } return void 0; } __name(getFramesFromEvent, "getFramesFromEvent"); const handlers$4 = {}; const instrumented$1 = {}; function addHandler$1(type, handler6) { handlers$4[type] = handlers$4[type] || []; handlers$4[type].push(handler6); } __name(addHandler$1, "addHandler$1"); function resetInstrumentationHandlers() { Object.keys(handlers$4).forEach((key) => { handlers$4[key] = void 0; }); } __name(resetInstrumentationHandlers, "resetInstrumentationHandlers"); function maybeInstrument(type, instrumentFn) { if (!instrumented$1[type]) { instrumented$1[type] = true; try { instrumentFn(); } catch (e2) { DEBUG_BUILD$5 && logger$2.error(`Error while instrumenting ${type}`, e2); } } } __name(maybeInstrument, "maybeInstrument"); function triggerHandlers$1(type, data25) { const typeHandlers = type && handlers$4[type]; if (!typeHandlers) { return; } for (const handler6 of typeHandlers) { try { handler6(data25); } catch (e2) { DEBUG_BUILD$5 && logger$2.error( `Error while triggering instrumentation handler. Type: ${type} Name: ${getFunctionName(handler6)} Error:`, e2 ); } } } __name(triggerHandlers$1, "triggerHandlers$1"); let _oldOnErrorHandler = null; function addGlobalErrorInstrumentationHandler(handler6) { const type = "error"; addHandler$1(type, handler6); maybeInstrument(type, instrumentError); } __name(addGlobalErrorInstrumentationHandler, "addGlobalErrorInstrumentationHandler"); function instrumentError() { _oldOnErrorHandler = GLOBAL_OBJ.onerror; GLOBAL_OBJ.onerror = function(msg, url, line, column, error2) { const handlerData = { column, error: error2, line, msg, url }; triggerHandlers$1("error", handlerData); if (_oldOnErrorHandler) { return _oldOnErrorHandler.apply(this, arguments); } return false; }; GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; } __name(instrumentError, "instrumentError"); let _oldOnUnhandledRejectionHandler = null; function addGlobalUnhandledRejectionInstrumentationHandler(handler6) { const type = "unhandledrejection"; addHandler$1(type, handler6); maybeInstrument(type, instrumentUnhandledRejection); } __name(addGlobalUnhandledRejectionInstrumentationHandler, "addGlobalUnhandledRejectionInstrumentationHandler"); function instrumentUnhandledRejection() { _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; GLOBAL_OBJ.onunhandledrejection = function(e2) { const handlerData = e2; triggerHandlers$1("unhandledrejection", handlerData); if (_oldOnUnhandledRejectionHandler) { return _oldOnUnhandledRejectionHandler.apply(this, arguments); } return true; }; GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; } __name(instrumentUnhandledRejection, "instrumentUnhandledRejection"); function getMainCarrier() { getSentryCarrier(GLOBAL_OBJ); return GLOBAL_OBJ; } __name(getMainCarrier, "getMainCarrier"); function getSentryCarrier(carrier) { const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {}; __SENTRY__.version = __SENTRY__.version || SDK_VERSION; return __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {}; } __name(getSentryCarrier, "getSentryCarrier"); const objectToString$4 = Object.prototype.toString; function isError(wat) { switch (objectToString$4.call(wat)) { case "[object Error]": case "[object Exception]": case "[object DOMException]": case "[object WebAssembly.Exception]": return true; default: return isInstanceOf(wat, Error); } } __name(isError, "isError"); function isBuiltin(wat, className) { return objectToString$4.call(wat) === `[object ${className}]`; } __name(isBuiltin, "isBuiltin"); function isErrorEvent$2(wat) { return isBuiltin(wat, "ErrorEvent"); } __name(isErrorEvent$2, "isErrorEvent$2"); function isDOMError(wat) { return isBuiltin(wat, "DOMError"); } __name(isDOMError, "isDOMError"); function isDOMException(wat) { return isBuiltin(wat, "DOMException"); } __name(isDOMException, "isDOMException"); function isString$8(wat) { return isBuiltin(wat, "String"); } __name(isString$8, "isString$8"); function isParameterizedString(wat) { return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat; } __name(isParameterizedString, "isParameterizedString"); function isPrimitive(wat) { return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function"; } __name(isPrimitive, "isPrimitive"); function isPlainObject$5(wat) { return isBuiltin(wat, "Object"); } __name(isPlainObject$5, "isPlainObject$5"); function isEvent(wat) { return typeof Event !== "undefined" && isInstanceOf(wat, Event); } __name(isEvent, "isEvent"); function isElement$3(wat) { return typeof Element !== "undefined" && isInstanceOf(wat, Element); } __name(isElement$3, "isElement$3"); function isRegExp$5(wat) { return isBuiltin(wat, "RegExp"); } __name(isRegExp$5, "isRegExp$5"); function isThenable$1(wat) { return Boolean(wat && wat.then && typeof wat.then === "function"); } __name(isThenable$1, "isThenable$1"); function isSyntheticEvent(wat) { return isPlainObject$5(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat; } __name(isSyntheticEvent, "isSyntheticEvent"); function isInstanceOf(wat, base2) { try { return wat instanceof base2; } catch (_e) { return false; } } __name(isInstanceOf, "isInstanceOf"); function isVueViewModel(wat) { return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue)); } __name(isVueViewModel, "isVueViewModel"); const WINDOW$8 = GLOBAL_OBJ; const DEFAULT_MAX_STRING_LENGTH = 80; function htmlTreeAsString(elem, options4 = {}) { if (!elem) { return ""; } try { let currentElem = elem; const MAX_TRAVERSE_HEIGHT = 5; const out = []; let height = 0; let len = 0; const separator = " > "; const sepLength = separator.length; let nextStr; const keyAttrs = Array.isArray(options4) ? options4 : options4.keyAttrs; const maxStringLength = !Array.isArray(options4) && options4.maxStringLength || DEFAULT_MAX_STRING_LENGTH; while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { nextStr = _htmlElementAsString(currentElem, keyAttrs); if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) { break; } out.push(nextStr); len += nextStr.length; currentElem = currentElem.parentNode; } return out.reverse().join(separator); } catch (_oO) { return ""; } } __name(htmlTreeAsString, "htmlTreeAsString"); function _htmlElementAsString(el, keyAttrs) { const elem = el; const out = []; if (!elem || !elem.tagName) { return ""; } if (WINDOW$8.HTMLElement) { if (elem instanceof HTMLElement && elem.dataset) { if (elem.dataset["sentryComponent"]) { return elem.dataset["sentryComponent"]; } if (elem.dataset["sentryElement"]) { return elem.dataset["sentryElement"]; } } } out.push(elem.tagName.toLowerCase()); 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}`); } const className = elem.className; if (className && isString$8(className)) { const classes2 = className.split(/\s+/); for (const c2 of classes2) { out.push(`.${c2}`); } } } const allowedAttrs = ["aria-label", "type", "name", "title", "alt"]; for (const k2 of allowedAttrs) { const attr = elem.getAttribute(k2); if (attr) { out.push(`[${k2}="${attr}"]`); } } return out.join(""); } __name(_htmlElementAsString, "_htmlElementAsString"); function getLocationHref() { try { return WINDOW$8.document.location.href; } catch (oO) { return ""; } } __name(getLocationHref, "getLocationHref"); function getDomElement(selector) { if (WINDOW$8.document && WINDOW$8.document.querySelector) { return WINDOW$8.document.querySelector(selector); } return null; } __name(getDomElement, "getDomElement"); function getComponentName$1(elem) { if (!WINDOW$8.HTMLElement) { return null; } let currentElem = elem; const MAX_TRAVERSE_HEIGHT = 5; for (let i2 = 0; i2 < MAX_TRAVERSE_HEIGHT; i2++) { if (!currentElem) { return null; } if (currentElem instanceof HTMLElement) { if (currentElem.dataset["sentryComponent"]) { return currentElem.dataset["sentryComponent"]; } if (currentElem.dataset["sentryElement"]) { return currentElem.dataset["sentryElement"]; } } currentElem = currentElem.parentNode; } return null; } __name(getComponentName$1, "getComponentName$1"); function truncate(str, max = 0) { if (typeof str !== "string" || max === 0) { return str; } return str.length <= max ? str : `${str.slice(0, max)}...`; } __name(truncate, "truncate"); function snipLine(line, colno) { let newLine = line; const lineLength = newLine.length; if (lineLength <= 150) { return newLine; } if (colno > lineLength) { colno = lineLength; } let start2 = Math.max(colno - 60, 0); if (start2 < 5) { start2 = 0; } let end = Math.min(start2 + 140, lineLength); if (end > lineLength - 5) { end = lineLength; } if (end === lineLength) { start2 = Math.max(end - 140, 0); } newLine = newLine.slice(start2, end); if (start2 > 0) { newLine = `'{snip} ${newLine}`; } if (end < lineLength) { newLine += " {snip}"; } return newLine; } __name(snipLine, "snipLine"); function safeJoin(input, delimiter2) { if (!Array.isArray(input)) { return ""; } const output = []; for (let i2 = 0; i2 < input.length; i2++) { const value4 = input[i2]; try { if (isVueViewModel(value4)) { output.push("[VueViewModel]"); } else { output.push(String(value4)); } } catch (e2) { output.push("[value cannot be serialized]"); } } return output.join(delimiter2); } __name(safeJoin, "safeJoin"); function isMatchingPattern(value4, pattern, requireExactStringMatch = false) { if (!isString$8(value4)) { return false; } if (isRegExp$5(pattern)) { return pattern.test(value4); } if (isString$8(pattern)) { return requireExactStringMatch ? value4 === pattern : value4.includes(pattern); } return false; } __name(isMatchingPattern, "isMatchingPattern"); function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) { return patterns.some((pattern) => isMatchingPattern(testString, pattern, requireExactStringMatch)); } __name(stringMatchesSomePattern, "stringMatchesSomePattern"); function fill(source, name2, replacementFactory) { if (!(name2 in source)) { return; } const original = source[name2]; const wrapped = replacementFactory(original); if (typeof wrapped === "function") { markFunctionWrapped(wrapped, original); } try { source[name2] = wrapped; } catch (e2) { DEBUG_BUILD$5 && logger$2.log(`Failed to replace method "${name2}" in object`, source); } } __name(fill, "fill"); function addNonEnumerableProperty(obj, name2, value4) { try { Object.defineProperty(obj, name2, { // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it value: value4, writable: true, configurable: true }); } catch (o_O) { DEBUG_BUILD$5 && logger$2.log(`Failed to add non-enumerable property "${name2}" to object`, obj); } } __name(addNonEnumerableProperty, "addNonEnumerableProperty"); function markFunctionWrapped(wrapped, original) { try { const proto = original.prototype || {}; wrapped.prototype = original.prototype = proto; addNonEnumerableProperty(wrapped, "__sentry_original__", original); } catch (o_O) { } } __name(markFunctionWrapped, "markFunctionWrapped"); function getOriginalFunction(func) { return func.__sentry_original__; } __name(getOriginalFunction, "getOriginalFunction"); function urlEncode(object) { return Object.entries(object).map(([key, value4]) => `${encodeURIComponent(key)}=${encodeURIComponent(value4)}`).join("&"); } __name(urlEncode, "urlEncode"); function convertToPlainObject(value4) { if (isError(value4)) { return { message: value4.message, name: value4.name, stack: value4.stack, ...getOwnProperties(value4) }; } else if (isEvent(value4)) { const newObj = { type: value4.type, target: serializeEventTarget(value4.target), currentTarget: serializeEventTarget(value4.currentTarget), ...getOwnProperties(value4) }; if (typeof CustomEvent !== "undefined" && isInstanceOf(value4, CustomEvent)) { newObj.detail = value4.detail; } return newObj; } else { return value4; } } __name(convertToPlainObject, "convertToPlainObject"); function serializeEventTarget(target) { try { return isElement$3(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target); } catch (_oO) { return ""; } } __name(serializeEventTarget, "serializeEventTarget"); 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 {}; } } __name(getOwnProperties, "getOwnProperties"); function extractExceptionKeysForMessage(exception, maxLength = 40) { const keys2 = Object.keys(convertToPlainObject(exception)); keys2.sort(); const firstKey = keys2[0]; if (!firstKey) { return "[object has no keys]"; } if (firstKey.length >= maxLength) { return truncate(firstKey, maxLength); } for (let includedKeys = keys2.length; includedKeys > 0; includedKeys--) { const serialized = keys2.slice(0, includedKeys).join(", "); if (serialized.length > maxLength) { continue; } if (includedKeys === keys2.length) { return serialized; } return truncate(serialized, maxLength); } return ""; } __name(extractExceptionKeysForMessage, "extractExceptionKeysForMessage"); function dropUndefinedKeys(inputValue) { const memoizationMap = /* @__PURE__ */ new Map(); return _dropUndefinedKeys(inputValue, memoizationMap); } __name(dropUndefinedKeys, "dropUndefinedKeys"); function _dropUndefinedKeys(inputValue, memoizationMap) { if (isPojo(inputValue)) { const memoVal = memoizationMap.get(inputValue); if (memoVal !== void 0) { return memoVal; } const returnValue = {}; memoizationMap.set(inputValue, returnValue); for (const key of Object.getOwnPropertyNames(inputValue)) { if (typeof inputValue[key] !== "undefined") { returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); } } return returnValue; } if (Array.isArray(inputValue)) { const memoVal = memoizationMap.get(inputValue); if (memoVal !== void 0) { return memoVal; } const returnValue = []; memoizationMap.set(inputValue, returnValue); inputValue.forEach((item3) => { returnValue.push(_dropUndefinedKeys(item3, memoizationMap)); }); return returnValue; } return inputValue; } __name(_dropUndefinedKeys, "_dropUndefinedKeys"); function isPojo(input) { if (!isPlainObject$5(input)) { return false; } try { const name2 = Object.getPrototypeOf(input).constructor.name; return !name2 || name2 === "Object"; } catch (e2) { return true; } } __name(isPojo, "isPojo"); function objectify(wat) { let objectified; switch (true) { case wat == void 0: objectified = new String(wat); break; case (typeof wat === "symbol" || typeof wat === "bigint"): objectified = Object(wat); break; case isPrimitive(wat): objectified = new wat.constructor(wat); break; default: objectified = wat; break; } return objectified; } __name(objectify, "objectify"); const ONE_SECOND_IN_MS = 1e3; function dateTimestampInSeconds() { return Date.now() / ONE_SECOND_IN_MS; } __name(dateTimestampInSeconds, "dateTimestampInSeconds"); function createUnixTimestampInSecondsFunc() { const { performance: performance2 } = GLOBAL_OBJ; if (!performance2 || !performance2.now) { return dateTimestampInSeconds; } const approxStartingTimeOrigin = Date.now() - performance2.now(); const timeOrigin = performance2.timeOrigin == void 0 ? approxStartingTimeOrigin : performance2.timeOrigin; return () => { return (timeOrigin + performance2.now()) / ONE_SECOND_IN_MS; }; } __name(createUnixTimestampInSecondsFunc, "createUnixTimestampInSecondsFunc"); const timestampInSeconds = createUnixTimestampInSecondsFunc(); let _browserPerformanceTimeOriginMode; const browserPerformanceTimeOrigin = (() => { const { performance: performance2 } = GLOBAL_OBJ; if (!performance2 || !performance2.now) { _browserPerformanceTimeOriginMode = "none"; return void 0; } const threshold = 3600 * 1e3; const performanceNow = performance2.now(); const dateNow = Date.now(); const timeOriginDelta = performance2.timeOrigin ? Math.abs(performance2.timeOrigin + performanceNow - dateNow) : threshold; const timeOriginIsReliable = timeOriginDelta < threshold; const navigationStart = performance2.timing && performance2.timing.navigationStart; const hasNavigationStart = typeof navigationStart === "number"; const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; const navigationStartIsReliable = navigationStartDelta < threshold; if (timeOriginIsReliable || navigationStartIsReliable) { if (timeOriginDelta <= navigationStartDelta) { _browserPerformanceTimeOriginMode = "timeOrigin"; return performance2.timeOrigin; } else { _browserPerformanceTimeOriginMode = "navigationStart"; return navigationStart; } } _browserPerformanceTimeOriginMode = "dateNow"; return dateNow; })(); function uuid4() { const gbl = GLOBAL_OBJ; const crypto = gbl.crypto || gbl.msCrypto; let getRandomByte = /* @__PURE__ */ __name(() => Math.random() * 16, "getRandomByte"); try { if (crypto && crypto.randomUUID) { return crypto.randomUUID().replace(/-/g, ""); } if (crypto && crypto.getRandomValues) { getRandomByte = /* @__PURE__ */ __name(() => { const typedArray = new Uint8Array(1); crypto.getRandomValues(typedArray); return typedArray[0]; }, "getRandomByte"); } } catch (_2) { } return ("10000000100040008000" + 1e11).replace( /[018]/g, (c2) => ( // eslint-disable-next-line no-bitwise (c2 ^ (getRandomByte() & 15) >> c2 / 4).toString(16) ) ); } __name(uuid4, "uuid4"); function getFirstException(event) { return event.exception && event.exception.values ? event.exception.values[0] : void 0; } __name(getFirstException, "getFirstException"); function getEventDescription(event) { const { message: message3, event_id: eventId } = event; if (message3) { return message3; } const firstException = getFirstException(event); if (firstException) { if (firstException.type && firstException.value) { return `${firstException.type}: ${firstException.value}`; } return firstException.type || firstException.value || eventId || ""; } return eventId || ""; } __name(getEventDescription, "getEventDescription"); function addExceptionTypeValue(event, value4, type) { const exception = event.exception = event.exception || {}; const values = exception.values = exception.values || []; const firstException = values[0] = values[0] || {}; if (!firstException.value) { firstException.value = value4 || ""; } if (!firstException.type) { firstException.type = type || "Error"; } } __name(addExceptionTypeValue, "addExceptionTypeValue"); 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; } } __name(addExceptionMechanism, "addExceptionMechanism"); 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-]+)*))?$/; function _parseInt(input) { return parseInt(input || "", 10); } __name(_parseInt, "_parseInt"); function parseSemver(input) { const match2 = input.match(SEMVER_REGEXP) || []; const major = _parseInt(match2[1]); const minor = _parseInt(match2[2]); const patch2 = _parseInt(match2[3]); return { buildmetadata: match2[5], major: isNaN(major) ? void 0 : major, minor: isNaN(minor) ? void 0 : minor, patch: isNaN(patch2) ? void 0 : patch2, prerelease: match2[4] }; } __name(parseSemver, "parseSemver"); function addContextToFrame(lines, frame, linesOfContext = 5) { if (frame.lineno === void 0) { return; } const maxLines = lines.length; const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0); frame.pre_context = lines.slice(Math.max(0, sourceLine - linesOfContext), sourceLine).map((line) => snipLine(line, 0)); const lineIndex = Math.min(maxLines - 1, sourceLine); frame.context_line = snipLine(lines[lineIndex], frame.colno || 0); frame.post_context = lines.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext).map((line) => snipLine(line, 0)); } __name(addContextToFrame, "addContextToFrame"); function checkOrSetAlreadyCaught(exception) { if (isAlreadyCaptured(exception)) { return true; } try { addNonEnumerableProperty(exception, "__sentry_captured__", true); } catch (err) { } return false; } __name(checkOrSetAlreadyCaught, "checkOrSetAlreadyCaught"); function isAlreadyCaptured(exception) { try { return exception.__sentry_captured__; } catch (e2) { } } __name(isAlreadyCaptured, "isAlreadyCaptured"); function arrayify(maybeArray) { return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; } __name(arrayify, "arrayify"); var States; (function(States2) { const PENDING = 0; States2[States2["PENDING"] = PENDING] = "PENDING"; const RESOLVED = 1; States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED"; const REJECTED = 2; States2[States2["REJECTED"] = REJECTED] = "REJECTED"; })(States || (States = {})); function resolvedSyncPromise(value4) { return new SyncPromise((resolve2) => { resolve2(value4); }); } __name(resolvedSyncPromise, "resolvedSyncPromise"); function rejectedSyncPromise(reason) { return new SyncPromise((_2, reject3) => { reject3(reason); }); } __name(rejectedSyncPromise, "rejectedSyncPromise"); class SyncPromise { static { __name(this, "SyncPromise"); } constructor(executor) { SyncPromise.prototype.__init.call(this); SyncPromise.prototype.__init2.call(this); SyncPromise.prototype.__init3.call(this); SyncPromise.prototype.__init4.call(this); this._state = States.PENDING; this._handlers = []; try { executor(this._resolve, this._reject); } catch (e2) { this._reject(e2); } } /** JSDoc */ then(onfulfilled, onrejected) { return new SyncPromise((resolve2, reject3) => { this._handlers.push([ false, (result) => { if (!onfulfilled) { resolve2(result); } else { try { resolve2(onfulfilled(result)); } catch (e2) { reject3(e2); } } }, (reason) => { if (!onrejected) { reject3(reason); } else { try { resolve2(onrejected(reason)); } catch (e2) { reject3(e2); } } } ]); this._executeHandlers(); }); } /** JSDoc */ catch(onrejected) { return this.then((val) => val, onrejected); } /** JSDoc */ finally(onfinally) { return new SyncPromise((resolve2, reject3) => { let val; let isRejected; return this.then( (value4) => { isRejected = false; val = value4; if (onfinally) { onfinally(); } }, (reason) => { isRejected = true; val = reason; if (onfinally) { onfinally(); } } ).then(() => { if (isRejected) { reject3(val); return; } resolve2(val); }); }); } /** JSDoc */ __init() { this._resolve = (value4) => { this._setResult(States.RESOLVED, value4); }; } /** JSDoc */ __init2() { this._reject = (reason) => { this._setResult(States.REJECTED, reason); }; } /** JSDoc */ __init3() { this._setResult = (state, value4) => { if (this._state !== States.PENDING) { return; } if (isThenable$1(value4)) { void value4.then(this._resolve, this._reject); return; } this._state = state; this._value = value4; this._executeHandlers(); }; } /** JSDoc */ __init4() { this._executeHandlers = () => { if (this._state === States.PENDING) { return; } const cachedHandlers = this._handlers.slice(); this._handlers = []; cachedHandlers.forEach((handler6) => { if (handler6[0]) { return; } if (this._state === States.RESOLVED) { handler6[1](this._value); } if (this._state === States.REJECTED) { handler6[2](this._value); } handler6[0] = true; }); }; } } function makeSession$1(context) { const startingTime = timestampInSeconds(); const session = { sid: uuid4(), init: true, timestamp: startingTime, started: startingTime, duration: 0, status: "ok", errors: 0, ignoreDuration: false, toJSON: /* @__PURE__ */ __name(() => sessionToJSON(session), "toJSON") }; if (context) { updateSession(session, context); } return session; } __name(makeSession$1, "makeSession$1"); 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 || timestampInSeconds(); if (context.abnormal_mechanism) { session.abnormal_mechanism = context.abnormal_mechanism; } if (context.ignoreDuration) { session.ignoreDuration = context.ignoreDuration; } if (context.sid) { session.sid = context.sid.length === 32 ? context.sid : uuid4(); } if (context.init !== void 0) { 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 = void 0; } 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; } } __name(updateSession, "updateSession"); function closeSession(session, status) { let context = {}; if (status) { context = { status }; } else if (session.status === "ok") { context = { status: "exited" }; } updateSession(session, context); } __name(closeSession, "closeSession"); function sessionToJSON(session) { return dropUndefinedKeys({ sid: `${session.sid}`, init: session.init, // Make sure that sec is converted to ms for date constructor started: new Date(session.started * 1e3).toISOString(), timestamp: new Date(session.timestamp * 1e3).toISOString(), status: session.status, errors: session.errors, did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0, duration: session.duration, abnormal_mechanism: session.abnormal_mechanism, attrs: { release: session.release, environment: session.environment, ip_address: session.ipAddress, user_agent: session.userAgent } }); } __name(sessionToJSON, "sessionToJSON"); function generatePropagationContext() { return { traceId: generateTraceId(), spanId: generateSpanId() }; } __name(generatePropagationContext, "generatePropagationContext"); function generateTraceId() { return uuid4(); } __name(generateTraceId, "generateTraceId"); function generateSpanId() { return uuid4().substring(16); } __name(generateSpanId, "generateSpanId"); function merge$1(initialObj, mergeObj, levels = 2) { if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) { return mergeObj; } if (initialObj && mergeObj && Object.keys(mergeObj).length === 0) { return initialObj; } const output = { ...initialObj }; for (const key in mergeObj) { if (Object.prototype.hasOwnProperty.call(mergeObj, key)) { output[key] = merge$1(output[key], mergeObj[key], levels - 1); } } return output; } __name(merge$1, "merge$1"); const SCOPE_SPAN_FIELD = "_sentrySpan"; function _setSpanForScope(scope, span) { if (span) { addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, span); } else { delete scope[SCOPE_SPAN_FIELD]; } } __name(_setSpanForScope, "_setSpanForScope"); function _getSpanForScope(scope) { return scope[SCOPE_SPAN_FIELD]; } __name(_getSpanForScope, "_getSpanForScope"); const DEFAULT_MAX_BREADCRUMBS = 100; class ScopeClass { static { __name(this, "ScopeClass"); } /** Flag if notifying is happening. */ /** Callback for client to receive scope changes. */ /** Callback list that will be called during event processing. */ /** Array of breadcrumbs. */ /** User */ /** Tags */ /** Extra */ /** Contexts */ /** Attachments */ /** Propagation Context for distributed tracing */ /** * 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 */ /** * Transaction Name * * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects. * It's purpose is to assign a transaction to the scope that's added to non-transaction events. */ /** Session */ /** Request Mode Session Status */ // eslint-disable-next-line deprecation/deprecation /** The client on this scope */ /** Contains the last event id of a captured event. */ // 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 = {}; this._propagationContext = { traceId: generateTraceId(), spanId: generateSpanId() }; } /** * @inheritDoc */ clone() { const newScope = new ScopeClass(); newScope._breadcrumbs = [...this._breadcrumbs]; newScope._tags = { ...this._tags }; newScope._extra = { ...this._extra }; newScope._contexts = { ...this._contexts }; if (this._contexts.flags) { newScope._contexts.flags = { values: [...this._contexts.flags.values] }; } newScope._user = this._user; newScope._level = this._level; newScope._session = this._session; newScope._transactionName = this._transactionName; newScope._fingerprint = this._fingerprint; newScope._eventProcessors = [...this._eventProcessors]; newScope._requestSession = this._requestSession; newScope._attachments = [...this._attachments]; newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata }; newScope._propagationContext = { ...this._propagationContext }; newScope._client = this._client; newScope._lastEventId = this._lastEventId; _setSpanForScope(newScope, _getSpanForScope(this)); return newScope; } /** * @inheritDoc */ setClient(client) { this._client = client; } /** * @inheritDoc */ setLastEventId(lastEventId2) { this._lastEventId = lastEventId2; } /** * @inheritDoc */ getClient() { return this._client; } /** * @inheritDoc */ lastEventId() { return this._lastEventId; } /** * @inheritDoc */ addScopeListener(callback) { this._scopeListeners.push(callback); } /** * @inheritDoc */ addEventProcessor(callback) { this._eventProcessors.push(callback); return this; } /** * @inheritDoc */ setUser(user) { this._user = user || { email: void 0, id: void 0, ip_address: void 0, username: void 0 }; if (this._session) { updateSession(this._session, { user }); } this._notifyScopeListeners(); return this; } /** * @inheritDoc */ getUser() { return this._user; } /** * @inheritDoc */ // eslint-disable-next-line deprecation/deprecation getRequestSession() { return this._requestSession; } /** * @inheritDoc */ // eslint-disable-next-line deprecation/deprecation setRequestSession(requestSession) { this._requestSession = requestSession; return this; } /** * @inheritDoc */ setTags(tags) { this._tags = { ...this._tags, ...tags }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setTag(key, value4) { this._tags = { ...this._tags, [key]: value4 }; 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(level) { this._level = level; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setTransactionName(name2) { this._transactionName = name2; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setContext(key, context) { if (context === null) { delete this._contexts[key]; } else { this._contexts[key] = context; } this._notifyScopeListeners(); return this; } /** * @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; } const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext; const [scopeInstance, requestSession] = scopeToMerge instanceof Scope ? ( // eslint-disable-next-line deprecation/deprecation [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()] ) : isPlainObject$5(scopeToMerge) ? [captureContext, captureContext.requestSession] : []; const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {}; this._tags = { ...this._tags, ...tags }; this._extra = { ...this._extra, ...extra }; this._contexts = { ...this._contexts, ...contexts }; if (user && Object.keys(user).length) { this._user = user; } if (level) { this._level = level; } if (fingerprint.length) { this._fingerprint = fingerprint; } if (propagationContext) { this._propagationContext = propagationContext; } if (requestSession) { this._requestSession = requestSession; } return this; } /** * @inheritDoc */ clear() { this._breadcrumbs = []; this._tags = {}; this._extra = {}; this._user = {}; this._contexts = {}; this._level = void 0; this._transactionName = void 0; this._fingerprint = void 0; this._requestSession = void 0; this._session = void 0; _setSpanForScope(this, void 0); this._attachments = []; this.setPropagationContext({ traceId: generateTraceId() }); this._notifyScopeListeners(); return this; } /** * @inheritDoc */ addBreadcrumb(breadcrumb, maxBreadcrumbs) { const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; if (maxCrumbs <= 0) { return this; } const mergedBreadcrumb = { timestamp: dateTimestampInSeconds(), ...breadcrumb }; const breadcrumbs = this._breadcrumbs; breadcrumbs.push(mergedBreadcrumb); this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ getLastBreadcrumb() { return this._breadcrumbs[this._breadcrumbs.length - 1]; } /** * @inheritDoc */ clearBreadcrumbs() { this._breadcrumbs = []; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ addAttachment(attachment) { this._attachments.push(attachment); return this; } /** * @inheritDoc */ clearAttachments() { this._attachments = []; return this; } /** @inheritDoc */ getScopeData() { return { breadcrumbs: this._breadcrumbs, attachments: this._attachments, contexts: this._contexts, tags: this._tags, extra: this._extra, user: this._user, level: this._level, fingerprint: this._fingerprint || [], eventProcessors: this._eventProcessors, propagationContext: this._propagationContext, sdkProcessingMetadata: this._sdkProcessingMetadata, transactionName: this._transactionName, span: _getSpanForScope(this) }; } /** * @inheritDoc */ setSDKProcessingMetadata(newData) { this._sdkProcessingMetadata = merge$1(this._sdkProcessingMetadata, newData, 2); return this; } /** * @inheritDoc */ setPropagationContext(context) { this._propagationContext = { // eslint-disable-next-line deprecation/deprecation spanId: generateSpanId(), ...context }; return this; } /** * @inheritDoc */ getPropagationContext() { return this._propagationContext; } /** * @inheritDoc */ captureException(exception, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!this._client) { logger$2.warn("No client configured on scope - will not capture exception!"); return eventId; } const syntheticException = new Error("Sentry syntheticException"); this._client.captureException( exception, { originalException: exception, syntheticException, ...hint, event_id: eventId }, this ); return eventId; } /** * @inheritDoc */ captureMessage(message3, level, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!this._client) { logger$2.warn("No client configured on scope - will not capture message!"); return eventId; } const syntheticException = new Error(message3); this._client.captureMessage( message3, level, { originalException: message3, syntheticException, ...hint, event_id: eventId }, this ); return eventId; } /** * @inheritDoc */ captureEvent(event, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!this._client) { logger$2.warn("No client configured on scope - will not capture event!"); return eventId; } this._client.captureEvent(event, { ...hint, event_id: eventId }, this); return eventId; } /** * This will be called on every set call. */ _notifyScopeListeners() { if (!this._notifyingListeners) { this._notifyingListeners = true; this._scopeListeners.forEach((callback) => { callback(this); }); this._notifyingListeners = false; } } } const Scope = ScopeClass; function getDefaultCurrentScope() { return getGlobalSingleton("defaultCurrentScope", () => new Scope()); } __name(getDefaultCurrentScope, "getDefaultCurrentScope"); function getDefaultIsolationScope() { return getGlobalSingleton("defaultIsolationScope", () => new Scope()); } __name(getDefaultIsolationScope, "getDefaultIsolationScope"); class AsyncContextStack { static { __name(this, "AsyncContextStack"); } constructor(scope, isolationScope) { let assignedScope; if (!scope) { assignedScope = new Scope(); } else { assignedScope = scope; } let assignedIsolationScope; if (!isolationScope) { assignedIsolationScope = new Scope(); } else { assignedIsolationScope = isolationScope; } this._stack = [{ scope: assignedScope }]; this._isolationScope = assignedIsolationScope; } /** * Fork a scope for the stack. */ withScope(callback) { const scope = this._pushScope(); let maybePromiseResult; try { maybePromiseResult = callback(scope); } catch (e2) { this._popScope(); throw e2; } if (isThenable$1(maybePromiseResult)) { return maybePromiseResult.then( (res) => { this._popScope(); return res; }, (e2) => { this._popScope(); throw e2; } ); } this._popScope(); return maybePromiseResult; } /** * Get the client of the stack. */ getClient() { return this.getStackTop().client; } /** * Returns the scope of the top stack. */ getScope() { return this.getStackTop().scope; } /** * Get the isolation scope for the stack. */ getIsolationScope() { return this._isolationScope; } /** * Returns the topmost scope layer in the order domain > local > process. */ getStackTop() { return this._stack[this._stack.length - 1]; } /** * Push a scope to the stack. */ _pushScope() { const scope = this.getScope().clone(); this._stack.push({ client: this.getClient(), scope }); return scope; } /** * Pop a scope from the stack. */ _popScope() { if (this._stack.length <= 1) return false; return !!this._stack.pop(); } } function getAsyncContextStack() { const registry = getMainCarrier(); const sentry = getSentryCarrier(registry); return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()); } __name(getAsyncContextStack, "getAsyncContextStack"); function withScope$1(callback) { return getAsyncContextStack().withScope(callback); } __name(withScope$1, "withScope$1"); function withSetScope(scope, callback) { const stack2 = getAsyncContextStack(); return stack2.withScope(() => { stack2.getStackTop().scope = scope; return callback(scope); }); } __name(withSetScope, "withSetScope"); function withIsolationScope$1(callback) { return getAsyncContextStack().withScope(() => { return callback(getAsyncContextStack().getIsolationScope()); }); } __name(withIsolationScope$1, "withIsolationScope$1"); function getStackAsyncContextStrategy() { return { withIsolationScope: withIsolationScope$1, withScope: withScope$1, withSetScope, withSetIsolationScope: /* @__PURE__ */ __name((_isolationScope, callback) => { return withIsolationScope$1(callback); }, "withSetIsolationScope"), getCurrentScope: /* @__PURE__ */ __name(() => getAsyncContextStack().getScope(), "getCurrentScope"), getIsolationScope: /* @__PURE__ */ __name(() => getAsyncContextStack().getIsolationScope(), "getIsolationScope") }; } __name(getStackAsyncContextStrategy, "getStackAsyncContextStrategy"); function setAsyncContextStrategy(strategy) { const registry = getMainCarrier(); const sentry = getSentryCarrier(registry); sentry.acs = strategy; } __name(setAsyncContextStrategy, "setAsyncContextStrategy"); function getAsyncContextStrategy(carrier) { const sentry = getSentryCarrier(carrier); if (sentry.acs) { return sentry.acs; } return getStackAsyncContextStrategy(); } __name(getAsyncContextStrategy, "getAsyncContextStrategy"); function getCurrentScope$1() { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); return acs.getCurrentScope(); } __name(getCurrentScope$1, "getCurrentScope$1"); function getIsolationScope() { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); return acs.getIsolationScope(); } __name(getIsolationScope, "getIsolationScope"); function getGlobalScope() { return getGlobalSingleton("globalScope", () => new Scope()); } __name(getGlobalScope, "getGlobalScope"); function withScope(...rest) { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); if (rest.length === 2) { const [scope, callback] = rest; if (!scope) { return acs.withScope(callback); } return acs.withSetScope(scope, callback); } return acs.withScope(rest[0]); } __name(withScope, "withScope"); function withIsolationScope(...rest) { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); if (rest.length === 2) { const [isolationScope, callback] = rest; if (!isolationScope) { return acs.withIsolationScope(callback); } return acs.withSetIsolationScope(isolationScope, callback); } return acs.withIsolationScope(rest[0]); } __name(withIsolationScope, "withIsolationScope"); function getClient() { return getCurrentScope$1().getClient(); } __name(getClient, "getClient"); function getTraceContextFromScope(scope) { const propagationContext = scope.getPropagationContext(); const { traceId, spanId, parentSpanId } = propagationContext; const traceContext = dropUndefinedKeys({ trace_id: traceId, span_id: spanId, parent_span_id: parentSpanId }); return traceContext; } __name(getTraceContextFromScope, "getTraceContextFromScope"); const METRICS_SPAN_FIELD = "_sentryMetrics"; function getMetricSummaryJsonForSpan(span) { const storage = span[METRICS_SPAN_FIELD]; if (!storage) { return void 0; } const output = {}; for (const [, [exportKey, summary]] of storage) { const arr = output[exportKey] || (output[exportKey] = []); arr.push(dropUndefinedKeys(summary)); } return output; } __name(getMetricSummaryJsonForSpan, "getMetricSummaryJsonForSpan"); function updateMetricSummaryOnSpan(span, metricType, sanitizedName, value4, unit, tags, bucketKey) { const existingStorage = span[METRICS_SPAN_FIELD]; const storage = existingStorage || (span[METRICS_SPAN_FIELD] = /* @__PURE__ */ new Map()); const exportKey = `${metricType}:${sanitizedName}@${unit}`; const bucketItem = storage.get(bucketKey); if (bucketItem) { const [, summary] = bucketItem; storage.set(bucketKey, [ exportKey, { min: Math.min(summary.min, value4), max: Math.max(summary.max, value4), count: summary.count += 1, sum: summary.sum += value4, tags: summary.tags } ]); } else { storage.set(bucketKey, [ exportKey, { min: value4, max: value4, count: 1, sum: value4, tags } ]); } } __name(updateMetricSummaryOnSpan, "updateMetricSummaryOnSpan"); const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source"; const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate"; const SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op"; const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin"; const SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = "sentry.idle_span_finish_reason"; const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = "sentry.measurement_unit"; const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = "sentry.measurement_value"; const SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = "sentry.custom_span_name"; const SEMANTIC_ATTRIBUTE_PROFILE_ID = "sentry.profile_id"; const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = "sentry.exclusive_time"; const SEMANTIC_ATTRIBUTE_CACHE_HIT = "cache.hit"; const SEMANTIC_ATTRIBUTE_CACHE_KEY = "cache.key"; const SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = "cache.item_size"; const SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = "http.request.method"; const SEMANTIC_ATTRIBUTE_URL_FULL = "url.full"; const SPAN_STATUS_UNSET = 0; const SPAN_STATUS_OK = 1; const SPAN_STATUS_ERROR = 2; function getSpanStatusFromHttpCode(httpStatus) { if (httpStatus < 400 && httpStatus >= 100) { return { code: SPAN_STATUS_OK }; } if (httpStatus >= 400 && httpStatus < 500) { switch (httpStatus) { case 401: return { code: SPAN_STATUS_ERROR, message: "unauthenticated" }; case 403: return { code: SPAN_STATUS_ERROR, message: "permission_denied" }; case 404: return { code: SPAN_STATUS_ERROR, message: "not_found" }; case 409: return { code: SPAN_STATUS_ERROR, message: "already_exists" }; case 413: return { code: SPAN_STATUS_ERROR, message: "failed_precondition" }; case 429: return { code: SPAN_STATUS_ERROR, message: "resource_exhausted" }; case 499: return { code: SPAN_STATUS_ERROR, message: "cancelled" }; default: return { code: SPAN_STATUS_ERROR, message: "invalid_argument" }; } } if (httpStatus >= 500 && httpStatus < 600) { switch (httpStatus) { case 501: return { code: SPAN_STATUS_ERROR, message: "unimplemented" }; case 503: return { code: SPAN_STATUS_ERROR, message: "unavailable" }; case 504: return { code: SPAN_STATUS_ERROR, message: "deadline_exceeded" }; default: return { code: SPAN_STATUS_ERROR, message: "internal_error" }; } } return { code: SPAN_STATUS_ERROR, message: "unknown_error" }; } __name(getSpanStatusFromHttpCode, "getSpanStatusFromHttpCode"); function setHttpStatus(span, httpStatus) { span.setAttribute("http.response.status_code", httpStatus); const spanStatus = getSpanStatusFromHttpCode(httpStatus); if (spanStatus.message !== "unknown_error") { span.setStatus(spanStatus); } } __name(setHttpStatus, "setHttpStatus"); const BAGGAGE_HEADER_NAME = "baggage"; const SENTRY_BAGGAGE_KEY_PREFIX = "sentry-"; const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; const MAX_BAGGAGE_STRING_LENGTH = 8192; function baggageHeaderToDynamicSamplingContext(baggageHeader) { const baggageObject = parseBaggageHeader(baggageHeader); if (!baggageObject) { return void 0; } const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value4]) => { if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); acc[nonPrefixedKey] = value4; } return acc; }, {}); if (Object.keys(dynamicSamplingContext).length > 0) { return dynamicSamplingContext; } else { return void 0; } } __name(baggageHeaderToDynamicSamplingContext, "baggageHeaderToDynamicSamplingContext"); function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) { if (!dynamicSamplingContext) { return void 0; } const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( (acc, [dscKey, dscValue]) => { if (dscValue) { acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; } return acc; }, {} ); return objectToBaggageHeader(sentryPrefixedDSC); } __name(dynamicSamplingContextToSentryBaggageHeader, "dynamicSamplingContextToSentryBaggageHeader"); function parseBaggageHeader(baggageHeader) { if (!baggageHeader || !isString$8(baggageHeader) && !Array.isArray(baggageHeader)) { return void 0; } if (Array.isArray(baggageHeader)) { return baggageHeader.reduce((acc, curr) => { const currBaggageObject = baggageHeaderToObject(curr); Object.entries(currBaggageObject).forEach(([key, value4]) => { acc[key] = value4; }); return acc; }, {}); } return baggageHeaderToObject(baggageHeader); } __name(parseBaggageHeader, "parseBaggageHeader"); function baggageHeaderToObject(baggageHeader) { return baggageHeader.split(",").map((baggageEntry) => baggageEntry.split("=").map((keyOrValue) => decodeURIComponent(keyOrValue.trim()))).reduce((acc, [key, value4]) => { if (key && value4) { acc[key] = value4; } return acc; }, {}); } __name(baggageHeaderToObject, "baggageHeaderToObject"); function objectToBaggageHeader(object) { if (Object.keys(object).length === 0) { return void 0; } 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) { DEBUG_BUILD$5 && logger$2.warn( `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.` ); return baggageHeader; } else { return newBaggageHeader; } }, ""); } __name(objectToBaggageHeader, "objectToBaggageHeader"); const TRACEPARENT_REGEXP = new RegExp( "^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$" // whitespace ); function extractTraceparentData(traceparent) { if (!traceparent) { return void 0; } const matches2 = traceparent.match(TRACEPARENT_REGEXP); if (!matches2) { return void 0; } let parentSampled; if (matches2[3] === "1") { parentSampled = true; } else if (matches2[3] === "0") { parentSampled = false; } return { traceId: matches2[1], parentSampled, parentSpanId: matches2[2] }; } __name(extractTraceparentData, "extractTraceparentData"); function propagationContextFromHeaders(sentryTrace, baggage) { const traceparentData = extractTraceparentData(sentryTrace); const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage); if (!traceparentData || !traceparentData.traceId) { return { traceId: generateTraceId(), spanId: generateSpanId() }; } const { traceId, parentSpanId, parentSampled } = traceparentData; const virtualSpanId = generateSpanId(); return { traceId, parentSpanId, spanId: virtualSpanId, sampled: parentSampled, dsc: dynamicSamplingContext || {} // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it }; } __name(propagationContextFromHeaders, "propagationContextFromHeaders"); function generateSentryTraceHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) { let sampledString = ""; if (sampled !== void 0) { sampledString = sampled ? "-1" : "-0"; } return `${traceId}-${spanId}${sampledString}`; } __name(generateSentryTraceHeader, "generateSentryTraceHeader"); const TRACE_FLAG_NONE = 0; const TRACE_FLAG_SAMPLED = 1; let hasShownSpanDropWarning = false; function spanToTransactionTraceContext(span) { const { spanId: span_id, traceId: trace_id } = span.spanContext(); const { data: data25, op, parent_span_id, status, origin: origin2 } = spanToJSON(span); return dropUndefinedKeys({ parent_span_id, span_id, trace_id, data: data25, op, status, origin: origin2 }); } __name(spanToTransactionTraceContext, "spanToTransactionTraceContext"); function spanToTraceContext(span) { const { spanId, traceId: trace_id, isRemote } = span.spanContext(); const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id; const span_id = isRemote ? generateSpanId() : spanId; return dropUndefinedKeys({ parent_span_id, span_id, trace_id }); } __name(spanToTraceContext, "spanToTraceContext"); function spanToTraceHeader(span) { const { traceId, spanId } = span.spanContext(); const sampled = spanIsSampled(span); return generateSentryTraceHeader(traceId, spanId, sampled); } __name(spanToTraceHeader, "spanToTraceHeader"); function spanTimeInputToSeconds(input) { if (typeof input === "number") { return ensureTimestampInSeconds(input); } if (Array.isArray(input)) { return input[0] + input[1] / 1e9; } if (input instanceof Date) { return ensureTimestampInSeconds(input.getTime()); } return timestampInSeconds(); } __name(spanTimeInputToSeconds, "spanTimeInputToSeconds"); function ensureTimestampInSeconds(timestamp2) { const isMs = timestamp2 > 9999999999; return isMs ? timestamp2 / 1e3 : timestamp2; } __name(ensureTimestampInSeconds, "ensureTimestampInSeconds"); function spanToJSON(span) { if (spanIsSentrySpan(span)) { return span.getSpanJSON(); } try { const { spanId: span_id, traceId: trace_id } = span.spanContext(); if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { const { attributes, startTime, name: name2, endTime, parentSpanId, status } = span; return dropUndefinedKeys({ span_id, trace_id, data: attributes, description: name2, parent_span_id: parentSpanId, start_timestamp: spanTimeInputToSeconds(startTime), // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time timestamp: spanTimeInputToSeconds(endTime) || void 0, status: getStatusMessage(status), op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP], origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN], _metrics_summary: getMetricSummaryJsonForSpan(span) }); } return { span_id, trace_id }; } catch (e2) { return {}; } } __name(spanToJSON, "spanToJSON"); function spanIsOpenTelemetrySdkTraceBaseSpan(span) { const castSpan = span; return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status; } __name(spanIsOpenTelemetrySdkTraceBaseSpan, "spanIsOpenTelemetrySdkTraceBaseSpan"); function spanIsSentrySpan(span) { return typeof span.getSpanJSON === "function"; } __name(spanIsSentrySpan, "spanIsSentrySpan"); function spanIsSampled(span) { const { traceFlags } = span.spanContext(); return traceFlags === TRACE_FLAG_SAMPLED; } __name(spanIsSampled, "spanIsSampled"); function getStatusMessage(status) { if (!status || status.code === SPAN_STATUS_UNSET) { return void 0; } if (status.code === SPAN_STATUS_OK) { return "ok"; } return status.message || "unknown_error"; } __name(getStatusMessage, "getStatusMessage"); const CHILD_SPANS_FIELD = "_sentryChildSpans"; const ROOT_SPAN_FIELD = "_sentryRootSpan"; function addChildSpanToSpan(span, childSpan) { const rootSpan = span[ROOT_SPAN_FIELD] || span; addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, rootSpan); if (span[CHILD_SPANS_FIELD]) { span[CHILD_SPANS_FIELD].add(childSpan); } else { addNonEnumerableProperty(span, CHILD_SPANS_FIELD, /* @__PURE__ */ new Set([childSpan])); } } __name(addChildSpanToSpan, "addChildSpanToSpan"); function removeChildSpanFromSpan(span, childSpan) { if (span[CHILD_SPANS_FIELD]) { span[CHILD_SPANS_FIELD].delete(childSpan); } } __name(removeChildSpanFromSpan, "removeChildSpanFromSpan"); function getSpanDescendants(span) { const resultSet = /* @__PURE__ */ new Set(); function addSpanChildren(span2) { if (resultSet.has(span2)) { return; } else if (spanIsSampled(span2)) { resultSet.add(span2); const childSpans = span2[CHILD_SPANS_FIELD] ? Array.from(span2[CHILD_SPANS_FIELD]) : []; for (const childSpan of childSpans) { addSpanChildren(childSpan); } } } __name(addSpanChildren, "addSpanChildren"); addSpanChildren(span); return Array.from(resultSet); } __name(getSpanDescendants, "getSpanDescendants"); function getRootSpan(span) { return span[ROOT_SPAN_FIELD] || span; } __name(getRootSpan, "getRootSpan"); function getActiveSpan() { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); if (acs.getActiveSpan) { return acs.getActiveSpan(); } return _getSpanForScope(getCurrentScope$1()); } __name(getActiveSpan, "getActiveSpan"); function updateMetricSummaryOnActiveSpan(metricType, sanitizedName, value4, unit, tags, bucketKey) { const span = getActiveSpan(); if (span) { updateMetricSummaryOnSpan(span, metricType, sanitizedName, value4, unit, tags, bucketKey); } } __name(updateMetricSummaryOnActiveSpan, "updateMetricSummaryOnActiveSpan"); function showSpanDropWarning() { if (!hasShownSpanDropWarning) { consoleSandbox(() => { console.warn( "[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly." ); }); hasShownSpanDropWarning = true; } } __name(showSpanDropWarning, "showSpanDropWarning"); function updateSpanName(span, name2) { span.updateName(name2); span.setAttributes({ [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom", [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name2 }); } __name(updateSpanName, "updateSpanName"); let errorsInstrumented = false; function registerSpanErrorInstrumentation() { if (errorsInstrumented) { return; } errorsInstrumented = true; addGlobalErrorInstrumentationHandler(errorCallback); addGlobalUnhandledRejectionInstrumentationHandler(errorCallback); } __name(registerSpanErrorInstrumentation, "registerSpanErrorInstrumentation"); function errorCallback() { const activeSpan = getActiveSpan(); const rootSpan = activeSpan && getRootSpan(activeSpan); if (rootSpan) { const message3 = "internal_error"; DEBUG_BUILD$6 && logger$2.log(`[Tracing] Root span: ${message3} -> Global error occurred`); rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message: message3 }); } } __name(errorCallback, "errorCallback"); errorCallback.tag = "sentry_tracingErrorCallback"; const SCOPE_ON_START_SPAN_FIELD = "_sentryScope"; const ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope"; function setCapturedScopesOnSpan(span, scope, isolationScope) { if (span) { addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope); addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope); } } __name(setCapturedScopesOnSpan, "setCapturedScopesOnSpan"); function getCapturedScopesOnSpan(span) { return { scope: span[SCOPE_ON_START_SPAN_FIELD], isolationScope: span[ISOLATION_SCOPE_ON_START_SPAN_FIELD] }; } __name(getCapturedScopesOnSpan, "getCapturedScopesOnSpan"); function addTracingExtensions() { registerSpanErrorInstrumentation(); } __name(addTracingExtensions, "addTracingExtensions"); function hasTracingEnabled(maybeOptions) { if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) { return false; } const client = getClient(); const options4 = maybeOptions || client && client.getOptions(); return !!options4 && (options4.enableTracing || "tracesSampleRate" in options4 || "tracesSampler" in options4); } __name(hasTracingEnabled, "hasTracingEnabled"); class SentryNonRecordingSpan { static { __name(this, "SentryNonRecordingSpan"); } constructor(spanContext = {}) { this._traceId = spanContext.traceId || generateTraceId(); this._spanId = spanContext.spanId || generateSpanId(); } /** @inheritdoc */ spanContext() { return { spanId: this._spanId, traceId: this._traceId, traceFlags: TRACE_FLAG_NONE }; } /** @inheritdoc */ // eslint-disable-next-line @typescript-eslint/no-empty-function end(_timestamp) { } /** @inheritdoc */ setAttribute(_key, _value) { return this; } /** @inheritdoc */ setAttributes(_values) { return this; } /** @inheritdoc */ setStatus(_status) { return this; } /** @inheritdoc */ updateName(_name) { return this; } /** @inheritdoc */ isRecording() { return false; } /** @inheritdoc */ addEvent(_name, _attributesOrStartTime, _startTime) { return this; } /** * This should generally not be used, * but we need it for being compliant with the OTEL Span interface. * * @hidden * @internal */ addLink(_link) { return this; } /** * This should generally not be used, * but we need it for being compliant with the OTEL Span interface. * * @hidden * @internal */ addLinks(_links) { return this; } /** * This should generally not be used, * but we need it for being compliant with the OTEL Span interface. * * @hidden * @internal */ recordException(_exception, _time) { } } function handleCallbackErrors(fn, onError, onFinally = () => { }) { let maybePromiseResult; try { maybePromiseResult = fn(); } catch (e2) { onError(e2); onFinally(); throw e2; } return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally); } __name(handleCallbackErrors, "handleCallbackErrors"); function maybeHandlePromiseRejection(value4, onError, onFinally) { if (isThenable$1(value4)) { return value4.then( (res) => { onFinally(); return res; }, (e2) => { onError(e2); onFinally(); throw e2; } ); } onFinally(); return value4; } __name(maybeHandlePromiseRejection, "maybeHandlePromiseRejection"); const DEFAULT_ENVIRONMENT = "production"; const FROZEN_DSC_FIELD = "_frozenDsc"; function freezeDscOnSpan(span, dsc) { const spanWithMaybeDsc = span; addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc); } __name(freezeDscOnSpan, "freezeDscOnSpan"); function getDynamicSamplingContextFromClient(trace_id, client) { const options4 = client.getOptions(); const { publicKey: public_key } = client.getDsn() || {}; const dsc = dropUndefinedKeys({ environment: options4.environment || DEFAULT_ENVIRONMENT, release: options4.release, public_key, trace_id }); client.emit("createDsc", dsc); return dsc; } __name(getDynamicSamplingContextFromClient, "getDynamicSamplingContextFromClient"); function getDynamicSamplingContextFromScope(client, scope) { const propagationContext = scope.getPropagationContext(); return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client); } __name(getDynamicSamplingContextFromScope, "getDynamicSamplingContextFromScope"); function getDynamicSamplingContextFromSpan(span) { const client = getClient(); if (!client) { return {}; } const rootSpan = getRootSpan(span); const frozenDsc = rootSpan[FROZEN_DSC_FIELD]; if (frozenDsc) { return frozenDsc; } const traceState = rootSpan.spanContext().traceState; const traceStateDsc = traceState && traceState.get("sentry.dsc"); const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc); if (dscOnTraceState) { return dscOnTraceState; } const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client); const jsonSpan = spanToJSON(rootSpan); const attributes = jsonSpan.data || {}; const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]; if (maybeSampleRate != null) { dsc.sample_rate = `${maybeSampleRate}`; } const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; const name2 = jsonSpan.description; if (source !== "url" && name2) { dsc.transaction = name2; } if (hasTracingEnabled()) { dsc.sampled = String(spanIsSampled(rootSpan)); } client.emit("createDsc", dsc, rootSpan); return dsc; } __name(getDynamicSamplingContextFromSpan, "getDynamicSamplingContextFromSpan"); function spanToBaggageHeader(span) { const dsc = getDynamicSamplingContextFromSpan(span); return dynamicSamplingContextToSentryBaggageHeader(dsc); } __name(spanToBaggageHeader, "spanToBaggageHeader"); function logSpanStart(span) { if (!DEBUG_BUILD$6) return; const { description = "< unknown name >", op = "< unknown op >", parent_span_id: parentSpanId } = spanToJSON(span); const { spanId } = span.spanContext(); const sampled = spanIsSampled(span); const rootSpan = getRootSpan(span); const isRootSpan = rootSpan === span; const header3 = `[Tracing] Starting ${sampled ? "sampled" : "unsampled"} ${isRootSpan ? "root " : ""}span`; const infoParts = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`]; if (parentSpanId) { infoParts.push(`parent ID: ${parentSpanId}`); } if (!isRootSpan) { const { op: op2, description: description2 } = spanToJSON(rootSpan); infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`); if (op2) { infoParts.push(`root op: ${op2}`); } if (description2) { infoParts.push(`root description: ${description2}`); } } logger$2.log(`${header3} ${infoParts.join("\n ")}`); } __name(logSpanStart, "logSpanStart"); function logSpanEnd(span) { if (!DEBUG_BUILD$6) return; const { description = "< unknown name >", op = "< unknown op >" } = spanToJSON(span); const { spanId } = span.spanContext(); const rootSpan = getRootSpan(span); const isRootSpan = rootSpan === span; const msg = `[Tracing] Finishing "${op}" ${isRootSpan ? "root " : ""}span "${description}" with ID ${spanId}`; logger$2.log(msg); } __name(logSpanEnd, "logSpanEnd"); function parseSampleRate(sampleRate) { if (typeof sampleRate === "boolean") { return Number(sampleRate); } const rate = typeof sampleRate === "string" ? parseFloat(sampleRate) : sampleRate; if (typeof rate !== "number" || isNaN(rate) || rate < 0 || rate > 1) { DEBUG_BUILD$6 && logger$2.warn( `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify( sampleRate )} of type ${JSON.stringify(typeof sampleRate)}.` ); return void 0; } return rate; } __name(parseSampleRate, "parseSampleRate"); function sampleSpan(options4, samplingContext) { if (!hasTracingEnabled(options4)) { return [false]; } const normalizedRequest = getIsolationScope().getScopeData().sdkProcessingMetadata.normalizedRequest; const enhancedSamplingContext = { ...samplingContext, normalizedRequest: samplingContext.normalizedRequest || normalizedRequest }; let sampleRate; if (typeof options4.tracesSampler === "function") { sampleRate = options4.tracesSampler(enhancedSamplingContext); } else if (enhancedSamplingContext.parentSampled !== void 0) { sampleRate = enhancedSamplingContext.parentSampled; } else if (typeof options4.tracesSampleRate !== "undefined") { sampleRate = options4.tracesSampleRate; } else { sampleRate = 1; } const parsedSampleRate = parseSampleRate(sampleRate); if (parsedSampleRate === void 0) { DEBUG_BUILD$6 && logger$2.warn("[Tracing] Discarding transaction because of invalid sample rate."); return [false]; } if (!parsedSampleRate) { DEBUG_BUILD$6 && logger$2.log( `[Tracing] Discarding transaction because ${typeof options4.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}` ); return [false, parsedSampleRate]; } const shouldSample = Math.random() < parsedSampleRate; if (!shouldSample) { DEBUG_BUILD$6 && logger$2.log( `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number( sampleRate )})` ); return [false, parsedSampleRate]; } return [true, parsedSampleRate]; } __name(sampleSpan, "sampleSpan"); const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; function isValidProtocol(protocol) { return protocol === "http" || protocol === "https"; } __name(isValidProtocol, "isValidProtocol"); 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}`; } __name(dsnToString, "dsnToString"); function dsnFromString(str) { const match2 = DSN_REGEX.exec(str); if (!match2) { consoleSandbox(() => { console.error(`Invalid Sentry Dsn: ${str}`); }); return void 0; } const [protocol, publicKey, pass = "", host = "", port = "", lastPath = ""] = match2.slice(1); let path = ""; let projectId = lastPath; const split2 = projectId.split("/"); if (split2.length > 1) { path = split2.slice(0, -1).join("/"); projectId = split2.pop(); } if (projectId) { const projectMatch = projectId.match(/^\d+/); if (projectMatch) { projectId = projectMatch[0]; } } return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey }); } __name(dsnFromString, "dsnFromString"); 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 }; } __name(dsnFromComponents, "dsnFromComponents"); function validateDsn(dsn) { if (!DEBUG_BUILD$5) { return true; } const { port, projectId, protocol } = dsn; const requiredComponents = ["protocol", "publicKey", "host", "projectId"]; const hasMissingRequiredComponent = requiredComponents.find((component) => { if (!dsn[component]) { logger$2.error(`Invalid Sentry Dsn: ${component} missing`); return true; } return false; }); if (hasMissingRequiredComponent) { return false; } if (!projectId.match(/^\d+$/)) { logger$2.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); return false; } if (!isValidProtocol(protocol)) { logger$2.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); return false; } if (port && isNaN(parseInt(port, 10))) { logger$2.error(`Invalid Sentry Dsn: Invalid port ${port}`); return false; } return true; } __name(validateDsn, "validateDsn"); function makeDsn(from2) { const components = typeof from2 === "string" ? dsnFromString(from2) : dsnFromComponents(from2); if (!components || !validateDsn(components)) { return void 0; } return components; } __name(makeDsn, "makeDsn"); function memoBuilder() { const hasWeakSet = typeof WeakSet === "function"; const inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : []; function memoize(obj) { if (hasWeakSet) { if (inner.has(obj)) { return true; } inner.add(obj); return false; } for (let i2 = 0; i2 < inner.length; i2++) { const value4 = inner[i2]; if (value4 === obj) { return true; } } inner.push(obj); return false; } __name(memoize, "memoize"); function unmemoize(obj) { if (hasWeakSet) { inner.delete(obj); } else { for (let i2 = 0; i2 < inner.length; i2++) { if (inner[i2] === obj) { inner.splice(i2, 1); break; } } } } __name(unmemoize, "unmemoize"); return [memoize, unmemoize]; } __name(memoBuilder, "memoBuilder"); function normalize$2(input, depth = 100, maxProperties = Infinity) { try { return visit("", input, depth, maxProperties); } catch (err) { return { ERROR: `**non-serializable** (${err})` }; } } __name(normalize$2, "normalize$2"); function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) { const normalized = normalize$2(object, depth); if (jsonSize(normalized) > maxSize) { return normalizeToSize(object, depth - 1, maxSize); } return normalized; } __name(normalizeToSize, "normalizeToSize"); function visit(key, value4, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) { const [memoize, unmemoize] = memo; if (value4 == null || // this matches null and undefined -> eqeq not eqeqeq ["boolean", "string"].includes(typeof value4) || typeof value4 === "number" && Number.isFinite(value4)) { return value4; } const stringified = stringifyValue(key, value4); if (!stringified.startsWith("[object ")) { return stringified; } if (value4["__sentry_skip_normalization__"]) { return value4; } const remainingDepth = typeof value4["__sentry_override_normalization_depth__"] === "number" ? value4["__sentry_override_normalization_depth__"] : depth; if (remainingDepth === 0) { return stringified.replace("object ", ""); } if (memoize(value4)) { return "[Circular ~]"; } const valueWithToJSON = value4; if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") { try { const jsonValue = valueWithToJSON.toJSON(); return visit("", jsonValue, remainingDepth - 1, maxProperties, memo); } catch (err) { } } const normalized = Array.isArray(value4) ? [] : {}; let numAdded = 0; const visitable = convertToPlainObject(value4); for (const visitKey in visitable) { if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { continue; } if (numAdded >= maxProperties) { normalized[visitKey] = "[MaxProperties ~]"; break; } const visitValue = visitable[visitKey]; normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo); numAdded++; } unmemoize(value4); return normalized; } __name(visit, "visit"); function stringifyValue(key, value4) { try { if (key === "domain" && value4 && typeof value4 === "object" && value4._events) { return "[Domain]"; } if (key === "domainEmitter") { return "[DomainEmitter]"; } if (typeof global !== "undefined" && value4 === global) { return "[Global]"; } if (typeof window !== "undefined" && value4 === window) { return "[Window]"; } if (typeof document !== "undefined" && value4 === document) { return "[Document]"; } if (isVueViewModel(value4)) { return "[VueViewModel]"; } if (isSyntheticEvent(value4)) { return "[SyntheticEvent]"; } if (typeof value4 === "number" && !Number.isFinite(value4)) { return `[${value4}]`; } if (typeof value4 === "function") { return `[Function: ${getFunctionName(value4)}]`; } if (typeof value4 === "symbol") { return `[${String(value4)}]`; } if (typeof value4 === "bigint") { return `[BigInt: ${String(value4)}]`; } const objName = getConstructorName(value4); if (/^HTML(\w*)Element$/.test(objName)) { return `[HTMLElement: ${objName}]`; } return `[object ${objName}]`; } catch (err) { return `**non-serializable** (${err})`; } } __name(stringifyValue, "stringifyValue"); function getConstructorName(value4) { const prototype2 = Object.getPrototypeOf(value4); return prototype2 ? prototype2.constructor.name : "null prototype"; } __name(getConstructorName, "getConstructorName"); function utf8Length(value4) { return ~-encodeURI(value4).split(/%..|./).length; } __name(utf8Length, "utf8Length"); function jsonSize(value4) { return utf8Length(JSON.stringify(value4)); } __name(jsonSize, "jsonSize"); function normalizeUrlToBase(url, basePath2) { const escapedBase = basePath2.replace(/\\/g, "/").replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); let newUrl = url; try { newUrl = decodeURI(url); } catch (_Oo) { } return newUrl.replace(/\\/g, "/").replace(/webpack:\/?/g, "").replace(new RegExp(`(file://)?/*${escapedBase}/*`, "ig"), "app:///"); } __name(normalizeUrlToBase, "normalizeUrlToBase"); function createEnvelope(headers, items2 = []) { return [headers, items2]; } __name(createEnvelope, "createEnvelope"); function addItemToEnvelope(envelope, newItem) { const [headers, items2] = envelope; return [headers, [...items2, newItem]]; } __name(addItemToEnvelope, "addItemToEnvelope"); function forEachEnvelopeItem(envelope, callback) { const envelopeItems = envelope[1]; for (const envelopeItem of envelopeItems) { const envelopeItemType = envelopeItem[0].type; const result = callback(envelopeItem, envelopeItemType); if (result) { return true; } } return false; } __name(forEachEnvelopeItem, "forEachEnvelopeItem"); function envelopeContainsItemType(envelope, types) { return forEachEnvelopeItem(envelope, (_2, type) => types.includes(type)); } __name(envelopeContainsItemType, "envelopeContainsItemType"); function encodeUTF8(input) { return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input) : new TextEncoder().encode(input); } __name(encodeUTF8, "encodeUTF8"); function decodeUTF8(input) { return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.decodePolyfill ? GLOBAL_OBJ.__SENTRY__.decodePolyfill(input) : new TextDecoder().decode(input); } __name(decodeUTF8, "decodeUTF8"); function serializeEnvelope(envelope) { const [envHeaders, items2] = envelope; let parts2 = JSON.stringify(envHeaders); function append3(next2) { if (typeof parts2 === "string") { parts2 = typeof next2 === "string" ? parts2 + next2 : [encodeUTF8(parts2), next2]; } else { parts2.push(typeof next2 === "string" ? encodeUTF8(next2) : next2); } } __name(append3, "append"); for (const item3 of items2) { const [itemHeaders, payload] = item3; append3(` ${JSON.stringify(itemHeaders)} `); if (typeof payload === "string" || payload instanceof Uint8Array) { append3(payload); } else { let stringifiedPayload; try { stringifiedPayload = JSON.stringify(payload); } catch (e2) { stringifiedPayload = JSON.stringify(normalize$2(payload)); } append3(stringifiedPayload); } } return typeof parts2 === "string" ? parts2 : concatBuffers(parts2); } __name(serializeEnvelope, "serializeEnvelope"); function concatBuffers(buffers) { const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); const merged = new Uint8Array(totalLength); let offset = 0; for (const buffer2 of buffers) { merged.set(buffer2, offset); offset += buffer2.length; } return merged; } __name(concatBuffers, "concatBuffers"); function parseEnvelope(env) { let buffer2 = typeof env === "string" ? encodeUTF8(env) : env; function readBinary(length) { const bin = buffer2.subarray(0, length); buffer2 = buffer2.subarray(length + 1); return bin; } __name(readBinary, "readBinary"); function readJson() { let i2 = buffer2.indexOf(10); if (i2 < 0) { i2 = buffer2.length; } return JSON.parse(decodeUTF8(readBinary(i2))); } __name(readJson, "readJson"); const envelopeHeader = readJson(); const items2 = []; while (buffer2.length) { const itemHeader = readJson(); const binaryLength = typeof itemHeader.length === "number" ? itemHeader.length : void 0; items2.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]); } return [envelopeHeader, items2]; } __name(parseEnvelope, "parseEnvelope"); function createSpanEnvelopeItem(spanJson) { const spanHeaders = { type: "span" }; return [spanHeaders, spanJson]; } __name(createSpanEnvelopeItem, "createSpanEnvelopeItem"); function createAttachmentEnvelopeItem(attachment) { const buffer2 = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data; return [ dropUndefinedKeys({ type: "attachment", length: buffer2.length, filename: attachment.filename, content_type: attachment.contentType, attachment_type: attachment.attachmentType }), buffer2 ]; } __name(createAttachmentEnvelopeItem, "createAttachmentEnvelopeItem"); const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { session: "session", sessions: "session", attachment: "attachment", transaction: "transaction", event: "error", client_report: "internal", user_report: "default", profile: "profile", profile_chunk: "profile", replay_event: "replay", replay_recording: "replay", check_in: "monitor", feedback: "feedback", span: "span", statsd: "metric_bucket", raw_security: "security" }; function envelopeItemTypeToDataCategory(type) { return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; } __name(envelopeItemTypeToDataCategory, "envelopeItemTypeToDataCategory"); function getSdkMetadataForEnvelopeHeader(metadataOrEvent) { if (!metadataOrEvent || !metadataOrEvent.sdk) { return; } const { name: name2, version: version2 } = metadataOrEvent.sdk; return { name: name2, version: version2 }; } __name(getSdkMetadataForEnvelopeHeader, "getSdkMetadataForEnvelopeHeader"); function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) { const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; return { event_id: event.event_id, sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...sdkInfo && { sdk: sdkInfo }, ...!!tunnel && dsn && { dsn: dsnToString(dsn) }, ...dynamicSamplingContext && { trace: dropUndefinedKeys({ ...dynamicSamplingContext }) } }; } __name(createEventEnvelopeHeaders, "createEventEnvelopeHeaders"); 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; } __name(enhanceEventWithSdkInfo, "enhanceEventWithSdkInfo"); function createSessionEnvelope(session, dsn, metadata, tunnel) { const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); const envelopeHeaders = { sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...sdkInfo && { sdk: sdkInfo }, ...!!tunnel && dsn && { dsn: dsnToString(dsn) } }; const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()]; return createEnvelope(envelopeHeaders, [envelopeItem]); } __name(createSessionEnvelope, "createSessionEnvelope"); function createEventEnvelope(event, dsn, metadata, tunnel) { const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); const eventType = event.type && event.type !== "replay_event" ? event.type : "event"; enhanceEventWithSdkInfo(event, metadata && metadata.sdk); const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); delete event.sdkProcessingMetadata; const eventItem = [{ type: eventType }, event]; return createEnvelope(envelopeHeaders, [eventItem]); } __name(createEventEnvelope, "createEventEnvelope"); function createSpanEnvelope(spans, client) { function dscHasRequiredProps(dsc2) { return !!dsc2.trace_id && !!dsc2.public_key; } __name(dscHasRequiredProps, "dscHasRequiredProps"); const dsc = getDynamicSamplingContextFromSpan(spans[0]); const dsn = client && client.getDsn(); const tunnel = client && client.getOptions().tunnel; const headers = { sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...dscHasRequiredProps(dsc) && { trace: dsc }, ...!!tunnel && dsn && { dsn: dsnToString(dsn) } }; const beforeSendSpan = client && client.getOptions().beforeSendSpan; const convertToSpanJSON = beforeSendSpan ? (span) => { const spanJson = beforeSendSpan(spanToJSON(span)); if (!spanJson) { showSpanDropWarning(); } return spanJson; } : (span) => spanToJSON(span); const items2 = []; for (const span of spans) { const spanJson = convertToSpanJSON(span); if (spanJson) { items2.push(createSpanEnvelopeItem(spanJson)); } } return createEnvelope(headers, items2); } __name(createSpanEnvelope, "createSpanEnvelope"); function setMeasurement(name2, value4, unit, activeSpan = getActiveSpan()) { const rootSpan = activeSpan && getRootSpan(activeSpan); if (rootSpan) { DEBUG_BUILD$6 && logger$2.log(`[Measurement] Setting measurement on root span: ${name2} = ${value4} ${unit}`); rootSpan.addEvent(name2, { [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value4, [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit }); } } __name(setMeasurement, "setMeasurement"); function timedEventsToMeasurements(events2) { if (!events2 || events2.length === 0) { return void 0; } const measurements = {}; events2.forEach((event) => { const attributes = event.attributes || {}; const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]; const value4 = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]; if (typeof unit === "string" && typeof value4 === "number") { measurements[event.name] = { value: value4, unit }; } }); return measurements; } __name(timedEventsToMeasurements, "timedEventsToMeasurements"); const MAX_SPAN_COUNT = 1e3; class SentrySpan { static { __name(this, "SentrySpan"); } /** Epoch timestamp in seconds when the span started. */ /** Epoch timestamp in seconds when the span ended. */ /** Internal keeper of the status */ /** The timed events added to this span. */ /** if true, treat span as a standalone span (not part of a transaction) */ /** * You should never call the constructor manually, always use `Sentry.startSpan()` * or other span methods. * @internal * @hideconstructor * @hidden */ constructor(spanContext = {}) { this._traceId = spanContext.traceId || generateTraceId(); this._spanId = spanContext.spanId || generateSpanId(); this._startTime = spanContext.startTimestamp || timestampInSeconds(); this._attributes = {}; this.setAttributes({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "manual", [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op, ...spanContext.attributes }); this._name = spanContext.name; if (spanContext.parentSpanId) { this._parentSpanId = spanContext.parentSpanId; } if ("sampled" in spanContext) { this._sampled = spanContext.sampled; } if (spanContext.endTimestamp) { this._endTime = spanContext.endTimestamp; } this._events = []; this._isStandaloneSpan = spanContext.isStandalone; if (this._endTime) { this._onSpanEnded(); } } /** * This should generally not be used, * but it is needed for being compliant with the OTEL Span interface. * * @hidden * @internal */ addLink(_link) { return this; } /** * This should generally not be used, * but it is needed for being compliant with the OTEL Span interface. * * @hidden * @internal */ addLinks(_links) { return this; } /** * This should generally not be used, * but it is needed for being compliant with the OTEL Span interface. * * @hidden * @internal */ recordException(_exception, _time) { } /** @inheritdoc */ spanContext() { const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this; return { spanId, traceId, traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE }; } /** @inheritdoc */ setAttribute(key, value4) { if (value4 === void 0) { delete this._attributes[key]; } else { this._attributes[key] = value4; } return this; } /** @inheritdoc */ setAttributes(attributes) { Object.keys(attributes).forEach((key) => this.setAttribute(key, attributes[key])); return this; } /** * This should generally not be used, * but we need it for browser tracing where we want to adjust the start time afterwards. * USE THIS WITH CAUTION! * * @hidden * @internal */ updateStartTime(timeInput) { this._startTime = spanTimeInputToSeconds(timeInput); } /** * @inheritDoc */ setStatus(value4) { this._status = value4; return this; } /** * @inheritDoc */ updateName(name2) { this._name = name2; this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, "custom"); return this; } /** @inheritdoc */ end(endTimestamp) { if (this._endTime) { return; } this._endTime = spanTimeInputToSeconds(endTimestamp); logSpanEnd(this); this._onSpanEnded(); } /** * Get JSON representation of this span. * * @hidden * @internal This method is purely for internal purposes and should not be used outside * of SDK code. If you need to get a JSON representation of a span, * use `spanToJSON(span)` instead. */ getSpanJSON() { return dropUndefinedKeys({ data: this._attributes, description: this._name, op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP], parent_span_id: this._parentSpanId, span_id: this._spanId, start_timestamp: this._startTime, status: getStatusMessage(this._status), timestamp: this._endTime, trace_id: this._traceId, origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN], _metrics_summary: getMetricSummaryJsonForSpan(this), profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID], exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME], measurements: timedEventsToMeasurements(this._events), is_segment: this._isStandaloneSpan && getRootSpan(this) === this || void 0, segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : void 0 }); } /** @inheritdoc */ isRecording() { return !this._endTime && !!this._sampled; } /** * @inheritdoc */ addEvent(name2, attributesOrStartTime, startTime) { DEBUG_BUILD$6 && logger$2.log("[Tracing] Adding an event to span:", name2); const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds(); const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {}; const event = { name: name2, time: spanTimeInputToSeconds(time), attributes }; this._events.push(event); return this; } /** * This method should generally not be used, * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set. * USE THIS WITH CAUTION! * @internal * @hidden * @experimental */ isStandaloneSpan() { return !!this._isStandaloneSpan; } /** Emit `spanEnd` when the span is ended. */ _onSpanEnded() { const client = getClient(); if (client) { client.emit("spanEnd", this); } const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this); if (!isSegmentSpan) { return; } if (this._isStandaloneSpan) { if (this._sampled) { sendSpanEnvelope(createSpanEnvelope([this], client)); } else { DEBUG_BUILD$6 && logger$2.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."); if (client) { client.recordDroppedEvent("sample_rate", "span"); } } return; } const transactionEvent = this._convertSpanToTransaction(); if (transactionEvent) { const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope$1(); scope.captureEvent(transactionEvent); } } /** * Finish the transaction & prepare the event to send to Sentry. */ _convertSpanToTransaction() { if (!isFullFinishedSpan(spanToJSON(this))) { return void 0; } if (!this._name) { DEBUG_BUILD$6 && logger$2.warn("Transaction has no name, falling back to ``."); this._name = ""; } const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this); const scope = capturedSpanScope || getCurrentScope$1(); const client = scope.getClient() || getClient(); if (this._sampled !== true) { DEBUG_BUILD$6 && logger$2.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled."); if (client) { client.recordDroppedEvent("sample_rate", "transaction"); } return void 0; } const finishedSpans = getSpanDescendants(this).filter((span) => span !== this && !isStandaloneSpan(span)); const spans = finishedSpans.map((span) => spanToJSON(span)).filter(isFullFinishedSpan); const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; spans.forEach((span) => { span.data && delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]; }); const transaction = { contexts: { trace: spanToTransactionTraceContext(this) }, spans: ( // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here // we do not use spans anymore after this point spans.length > MAX_SPAN_COUNT ? spans.sort((a2, b2) => a2.start_timestamp - b2.start_timestamp).slice(0, MAX_SPAN_COUNT) : spans ), start_timestamp: this._startTime, timestamp: this._endTime, transaction: this._name, type: "transaction", sdkProcessingMetadata: { capturedSpanScope, capturedSpanIsolationScope, ...dropUndefinedKeys({ dynamicSamplingContext: getDynamicSamplingContextFromSpan(this) }) }, _metrics_summary: getMetricSummaryJsonForSpan(this), ...source && { transaction_info: { source } } }; const measurements = timedEventsToMeasurements(this._events); const hasMeasurements = measurements && Object.keys(measurements).length; if (hasMeasurements) { DEBUG_BUILD$6 && logger$2.log( "[Measurements] Adding measurements to transaction event", JSON.stringify(measurements, void 0, 2) ); transaction.measurements = measurements; } return transaction; } } function isSpanTimeInput(value4) { return value4 && typeof value4 === "number" || value4 instanceof Date || Array.isArray(value4); } __name(isSpanTimeInput, "isSpanTimeInput"); function isFullFinishedSpan(input) { return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id; } __name(isFullFinishedSpan, "isFullFinishedSpan"); function isStandaloneSpan(span) { return span instanceof SentrySpan && span.isStandaloneSpan(); } __name(isStandaloneSpan, "isStandaloneSpan"); function sendSpanEnvelope(envelope) { const client = getClient(); if (!client) { return; } const spanItems = envelope[1]; if (!spanItems || spanItems.length === 0) { client.recordDroppedEvent("before_send", "span"); return; } client.sendEnvelope(envelope); } __name(sendSpanEnvelope, "sendSpanEnvelope"); const SUPPRESS_TRACING_KEY = "__SENTRY_SUPPRESS_TRACING__"; function startSpan(options4, callback) { const acs = getAcs(); if (acs.startSpan) { return acs.startSpan(options4, callback); } const spanArguments = parseSentrySpanArguments(options4); const { forceTransaction, parentSpan: customParentSpan } = options4; return withScope(options4.scope, () => { const wrapper = getActiveSpanWrapper(customParentSpan); return wrapper(() => { const scope = getCurrentScope$1(); const parentSpan = getParentSpan(scope); const shouldSkipSpan = options4.onlyIfParent && !parentSpan; const activeSpan = shouldSkipSpan ? new SentryNonRecordingSpan() : createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }); _setSpanForScope(scope, activeSpan); return handleCallbackErrors( () => callback(activeSpan), () => { const { status } = spanToJSON(activeSpan); if (activeSpan.isRecording() && (!status || status === "ok")) { activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); } }, () => activeSpan.end() ); }); }); } __name(startSpan, "startSpan"); function startSpanManual(options4, callback) { const acs = getAcs(); if (acs.startSpanManual) { return acs.startSpanManual(options4, callback); } const spanArguments = parseSentrySpanArguments(options4); const { forceTransaction, parentSpan: customParentSpan } = options4; return withScope(options4.scope, () => { const wrapper = getActiveSpanWrapper(customParentSpan); return wrapper(() => { const scope = getCurrentScope$1(); const parentSpan = getParentSpan(scope); const shouldSkipSpan = options4.onlyIfParent && !parentSpan; const activeSpan = shouldSkipSpan ? new SentryNonRecordingSpan() : createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }); _setSpanForScope(scope, activeSpan); function finishAndSetSpan() { activeSpan.end(); } __name(finishAndSetSpan, "finishAndSetSpan"); return handleCallbackErrors( () => callback(activeSpan, finishAndSetSpan), () => { const { status } = spanToJSON(activeSpan); if (activeSpan.isRecording() && (!status || status === "ok")) { activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); } } ); }); }); } __name(startSpanManual, "startSpanManual"); function startInactiveSpan(options4) { const acs = getAcs(); if (acs.startInactiveSpan) { return acs.startInactiveSpan(options4); } const spanArguments = parseSentrySpanArguments(options4); const { forceTransaction, parentSpan: customParentSpan } = options4; const wrapper = options4.scope ? (callback) => withScope(options4.scope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback(); return wrapper(() => { const scope = getCurrentScope$1(); const parentSpan = getParentSpan(scope); const shouldSkipSpan = options4.onlyIfParent && !parentSpan; if (shouldSkipSpan) { return new SentryNonRecordingSpan(); } return createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }); }); } __name(startInactiveSpan, "startInactiveSpan"); const continueTrace = /* @__PURE__ */ __name((options4, callback) => { const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); if (acs.continueTrace) { return acs.continueTrace(options4, callback); } const { sentryTrace, baggage } = options4; return withScope((scope) => { const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); scope.setPropagationContext(propagationContext); return callback(); }); }, "continueTrace"); function withActiveSpan(span, callback) { const acs = getAcs(); if (acs.withActiveSpan) { return acs.withActiveSpan(span, callback); } return withScope((scope) => { _setSpanForScope(scope, span || void 0); return callback(scope); }); } __name(withActiveSpan, "withActiveSpan"); function suppressTracing(callback) { const acs = getAcs(); if (acs.suppressTracing) { return acs.suppressTracing(callback); } return withScope((scope) => { scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true }); return callback(); }); } __name(suppressTracing, "suppressTracing"); function startNewTrace(callback) { return withScope((scope) => { scope.setPropagationContext({ traceId: generateTraceId() }); DEBUG_BUILD$6 && logger$2.info(`Starting a new trace with id ${scope.getPropagationContext().traceId}`); return withActiveSpan(null, callback); }); } __name(startNewTrace, "startNewTrace"); function createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }) { if (!hasTracingEnabled()) { return new SentryNonRecordingSpan(); } const isolationScope = getIsolationScope(); let span; if (parentSpan && !forceTransaction) { span = _startChildSpan(parentSpan, scope, spanArguments); addChildSpanToSpan(parentSpan, span); } else if (parentSpan) { const dsc = getDynamicSamplingContextFromSpan(parentSpan); const { traceId, spanId: parentSpanId } = parentSpan.spanContext(); const parentSampled = spanIsSampled(parentSpan); span = _startRootSpan( { traceId, parentSpanId, ...spanArguments }, scope, parentSampled ); freezeDscOnSpan(span, dsc); } else { const { traceId, dsc, parentSpanId, sampled: parentSampled } = { ...isolationScope.getPropagationContext(), ...scope.getPropagationContext() }; span = _startRootSpan( { traceId, parentSpanId, ...spanArguments }, scope, parentSampled ); if (dsc) { freezeDscOnSpan(span, dsc); } } logSpanStart(span); setCapturedScopesOnSpan(span, scope, isolationScope); return span; } __name(createChildOrRootSpan, "createChildOrRootSpan"); function parseSentrySpanArguments(options4) { const exp = options4.experimental || {}; const initialCtx = { isStandalone: exp.standalone, ...options4 }; if (options4.startTime) { const ctx = { ...initialCtx }; ctx.startTimestamp = spanTimeInputToSeconds(options4.startTime); delete ctx.startTime; return ctx; } return initialCtx; } __name(parseSentrySpanArguments, "parseSentrySpanArguments"); function getAcs() { const carrier = getMainCarrier(); return getAsyncContextStrategy(carrier); } __name(getAcs, "getAcs"); function _startRootSpan(spanArguments, scope, parentSampled) { const client = getClient(); const options4 = client && client.getOptions() || {}; const { name: name2 = "", attributes } = spanArguments; const [sampled, sampleRate] = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? [false] : sampleSpan(options4, { name: name2, parentSampled, attributes, transactionContext: { name: name2, parentSampled } }); const rootSpan = new SentrySpan({ ...spanArguments, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "custom", ...spanArguments.attributes }, sampled }); if (sampleRate !== void 0) { rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate); } if (client) { client.emit("spanStart", rootSpan); } return rootSpan; } __name(_startRootSpan, "_startRootSpan"); function _startChildSpan(parentSpan, scope, spanArguments) { const { spanId, traceId } = parentSpan.spanContext(); const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan); const childSpan = sampled ? new SentrySpan({ ...spanArguments, parentSpanId: spanId, traceId, sampled }) : new SentryNonRecordingSpan({ traceId }); addChildSpanToSpan(parentSpan, childSpan); const client = getClient(); if (client) { client.emit("spanStart", childSpan); if (spanArguments.endTimestamp) { client.emit("spanEnd", childSpan); } } return childSpan; } __name(_startChildSpan, "_startChildSpan"); function getParentSpan(scope) { const span = _getSpanForScope(scope); if (!span) { return void 0; } const client = getClient(); const options4 = client ? client.getOptions() : {}; if (options4.parentSpanIsAlwaysRootSpan) { return getRootSpan(span); } return span; } __name(getParentSpan, "getParentSpan"); function getActiveSpanWrapper(parentSpan) { return parentSpan !== void 0 ? (callback) => { return withActiveSpan(parentSpan, callback); } : (callback) => callback(); } __name(getActiveSpanWrapper, "getActiveSpanWrapper"); const TRACING_DEFAULTS = { idleTimeout: 1e3, finalTimeout: 3e4, childSpanTimeout: 15e3 }; const FINISH_REASON_HEARTBEAT_FAILED = "heartbeatFailed"; const FINISH_REASON_IDLE_TIMEOUT = "idleTimeout"; const FINISH_REASON_FINAL_TIMEOUT = "finalTimeout"; const FINISH_REASON_EXTERNAL_FINISH = "externalFinish"; function startIdleSpan(startSpanOptions, options4 = {}) { const activities = /* @__PURE__ */ new Map(); let _finished = false; let _idleTimeoutID; let _finishReason = FINISH_REASON_EXTERNAL_FINISH; let _autoFinishAllowed = !options4.disableAutoFinish; const _cleanupHooks = []; const { idleTimeout = TRACING_DEFAULTS.idleTimeout, finalTimeout = TRACING_DEFAULTS.finalTimeout, childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout, beforeSpanEnd } = options4; const client = getClient(); if (!client || !hasTracingEnabled()) { return new SentryNonRecordingSpan(); } const scope = getCurrentScope$1(); const previousActiveSpan = getActiveSpan(); const span = _startIdleSpan(startSpanOptions); span.end = new Proxy(span.end, { apply(target, thisArg, args) { if (beforeSpanEnd) { beforeSpanEnd(span); } const [definedEndTimestamp, ...rest] = args; const timestamp2 = definedEndTimestamp || timestampInSeconds(); const spanEndTimestamp = spanTimeInputToSeconds(timestamp2); const spans = getSpanDescendants(span).filter((child) => child !== span); if (!spans.length) { onIdleSpanEnded(spanEndTimestamp); return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]); } const childEndTimestamps = spans.map((span2) => spanToJSON(span2).timestamp).filter((timestamp3) => !!timestamp3); const latestSpanEndTimestamp = childEndTimestamps.length ? Math.max(...childEndTimestamps) : void 0; const spanStartTimestamp = spanToJSON(span).start_timestamp; const endTimestamp = Math.min( spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1e3 : Infinity, Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity)) ); onIdleSpanEnded(endTimestamp); return Reflect.apply(target, thisArg, [endTimestamp, ...rest]); } }); function _cancelIdleTimeout() { if (_idleTimeoutID) { clearTimeout(_idleTimeoutID); _idleTimeoutID = void 0; } } __name(_cancelIdleTimeout, "_cancelIdleTimeout"); function _restartIdleTimeout(endTimestamp) { _cancelIdleTimeout(); _idleTimeoutID = setTimeout(() => { if (!_finished && activities.size === 0 && _autoFinishAllowed) { _finishReason = FINISH_REASON_IDLE_TIMEOUT; span.end(endTimestamp); } }, idleTimeout); } __name(_restartIdleTimeout, "_restartIdleTimeout"); function _restartChildSpanTimeout(endTimestamp) { _idleTimeoutID = setTimeout(() => { if (!_finished && _autoFinishAllowed) { _finishReason = FINISH_REASON_HEARTBEAT_FAILED; span.end(endTimestamp); } }, childSpanTimeout); } __name(_restartChildSpanTimeout, "_restartChildSpanTimeout"); function _pushActivity(spanId) { _cancelIdleTimeout(); activities.set(spanId, true); const endTimestamp = timestampInSeconds(); _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1e3); } __name(_pushActivity, "_pushActivity"); function _popActivity(spanId) { if (activities.has(spanId)) { activities.delete(spanId); } if (activities.size === 0) { const endTimestamp = timestampInSeconds(); _restartIdleTimeout(endTimestamp + idleTimeout / 1e3); } } __name(_popActivity, "_popActivity"); function onIdleSpanEnded(endTimestamp) { _finished = true; activities.clear(); _cleanupHooks.forEach((cleanup) => cleanup()); _setSpanForScope(scope, previousActiveSpan); const spanJSON = spanToJSON(span); const { start_timestamp: startTimestamp } = spanJSON; if (!startTimestamp) { return; } const attributes = spanJSON.data || {}; if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) { span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason); } logger$2.log(`[Tracing] Idle span "${spanJSON.op}" finished`); const childSpans = getSpanDescendants(span).filter((child) => child !== span); let discardedSpans = 0; childSpans.forEach((childSpan) => { if (childSpan.isRecording()) { childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: "cancelled" }); childSpan.end(endTimestamp); DEBUG_BUILD$6 && logger$2.log("[Tracing] Cancelling span since span ended early", JSON.stringify(childSpan, void 0, 2)); } const childSpanJSON = spanToJSON(childSpan); const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON; const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp; const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1e3; const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError; if (DEBUG_BUILD$6) { const stringifiedSpan = JSON.stringify(childSpan, void 0, 2); if (!spanStartedBeforeIdleSpanEnd) { logger$2.log("[Tracing] Discarding span since it happened after idle span was finished", stringifiedSpan); } else if (!spanEndedBeforeFinalTimeout) { logger$2.log("[Tracing] Discarding span since it finished after idle span final timeout", stringifiedSpan); } } if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) { removeChildSpanFromSpan(span, childSpan); discardedSpans++; } }); if (discardedSpans > 0) { span.setAttribute("sentry.idle_span_discarded_spans", discardedSpans); } } __name(onIdleSpanEnded, "onIdleSpanEnded"); _cleanupHooks.push( client.on("spanStart", (startedSpan) => { if (_finished || startedSpan === span || !!spanToJSON(startedSpan).timestamp) { return; } const allSpans = getSpanDescendants(span); if (allSpans.includes(startedSpan)) { _pushActivity(startedSpan.spanContext().spanId); } }) ); _cleanupHooks.push( client.on("spanEnd", (endedSpan) => { if (_finished) { return; } _popActivity(endedSpan.spanContext().spanId); }) ); _cleanupHooks.push( client.on("idleSpanEnableAutoFinish", (spanToAllowAutoFinish) => { if (spanToAllowAutoFinish === span) { _autoFinishAllowed = true; _restartIdleTimeout(); if (activities.size) { _restartChildSpanTimeout(); } } }) ); if (!options4.disableAutoFinish) { _restartIdleTimeout(); } setTimeout(() => { if (!_finished) { span.setStatus({ code: SPAN_STATUS_ERROR, message: "deadline_exceeded" }); _finishReason = FINISH_REASON_FINAL_TIMEOUT; span.end(); } }, finalTimeout); return span; } __name(startIdleSpan, "startIdleSpan"); function _startIdleSpan(options4) { const span = startInactiveSpan(options4); _setSpanForScope(getCurrentScope$1(), span); DEBUG_BUILD$6 && logger$2.log("[Tracing] Started span is an idle span"); return span; } __name(_startIdleSpan, "_startIdleSpan"); function notifyEventProcessors(processors, event, hint, index2 = 0) { return new SyncPromise((resolve2, reject3) => { const processor = processors[index2]; if (event === null || typeof processor !== "function") { resolve2(event); } else { const result = processor({ ...event }, hint); DEBUG_BUILD$6 && processor.id && result === null && logger$2.log(`Event processor "${processor.id}" dropped event`); if (isThenable$1(result)) { void result.then((final) => notifyEventProcessors(processors, final, hint, index2 + 1).then(resolve2)).then(null, reject3); } else { void notifyEventProcessors(processors, result, hint, index2 + 1).then(resolve2).then(null, reject3); } } }); } __name(notifyEventProcessors, "notifyEventProcessors"); let parsedStackResults; let lastKeysCount; let cachedFilenameDebugIds; function getFilenameToDebugIdMap(stackParser) { const debugIdMap = GLOBAL_OBJ._sentryDebugIds; if (!debugIdMap) { return {}; } const debugIdKeys = Object.keys(debugIdMap); if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) { return cachedFilenameDebugIds; } lastKeysCount = debugIdKeys.length; cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => { if (!parsedStackResults) { parsedStackResults = {}; } const result = parsedStackResults[stackKey]; if (result) { acc[result[0]] = result[1]; } else { const parsedStack = stackParser(stackKey); for (let i2 = parsedStack.length - 1; i2 >= 0; i2--) { const stackFrame = parsedStack[i2]; const filename = stackFrame && stackFrame.filename; const debugId = debugIdMap[stackKey]; if (filename && debugId) { acc[filename] = debugId; parsedStackResults[stackKey] = [filename, debugId]; break; } } } return acc; }, {}); return cachedFilenameDebugIds; } __name(getFilenameToDebugIdMap, "getFilenameToDebugIdMap"); function getDebugImagesForResources(stackParser, resource_paths) { const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser); if (!filenameDebugIdMap) { return []; } const images = []; for (const path of resource_paths) { if (path && filenameDebugIdMap[path]) { images.push({ type: "sourcemap", code_file: path, debug_id: filenameDebugIdMap[path] }); } } return images; } __name(getDebugImagesForResources, "getDebugImagesForResources"); function applyScopeDataToEvent(event, data25) { const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data25; applyDataToEvent(event, data25); if (span) { applySpanToEvent(event, span); } applyFingerprintToEvent(event, fingerprint); applyBreadcrumbsToEvent(event, breadcrumbs); applySdkMetadataToEvent(event, sdkProcessingMetadata); } __name(applyScopeDataToEvent, "applyScopeDataToEvent"); function mergeScopeData(data25, mergeData) { const { extra, tags, user, contexts, level, sdkProcessingMetadata, breadcrumbs, fingerprint, eventProcessors, attachments, propagationContext, transactionName, span } = mergeData; mergeAndOverwriteScopeData(data25, "extra", extra); mergeAndOverwriteScopeData(data25, "tags", tags); mergeAndOverwriteScopeData(data25, "user", user); mergeAndOverwriteScopeData(data25, "contexts", contexts); data25.sdkProcessingMetadata = merge$1(data25.sdkProcessingMetadata, sdkProcessingMetadata, 2); if (level) { data25.level = level; } if (transactionName) { data25.transactionName = transactionName; } if (span) { data25.span = span; } if (breadcrumbs.length) { data25.breadcrumbs = [...data25.breadcrumbs, ...breadcrumbs]; } if (fingerprint.length) { data25.fingerprint = [...data25.fingerprint, ...fingerprint]; } if (eventProcessors.length) { data25.eventProcessors = [...data25.eventProcessors, ...eventProcessors]; } if (attachments.length) { data25.attachments = [...data25.attachments, ...attachments]; } data25.propagationContext = { ...data25.propagationContext, ...propagationContext }; } __name(mergeScopeData, "mergeScopeData"); function mergeAndOverwriteScopeData(data25, prop2, mergeVal) { data25[prop2] = merge$1(data25[prop2], mergeVal, 1); } __name(mergeAndOverwriteScopeData, "mergeAndOverwriteScopeData"); function applyDataToEvent(event, data25) { const { extra, tags, user, contexts, level, transactionName } = data25; const cleanedExtra = dropUndefinedKeys(extra); if (cleanedExtra && Object.keys(cleanedExtra).length) { event.extra = { ...cleanedExtra, ...event.extra }; } const cleanedTags = dropUndefinedKeys(tags); if (cleanedTags && Object.keys(cleanedTags).length) { event.tags = { ...cleanedTags, ...event.tags }; } const cleanedUser = dropUndefinedKeys(user); if (cleanedUser && Object.keys(cleanedUser).length) { event.user = { ...cleanedUser, ...event.user }; } const cleanedContexts = dropUndefinedKeys(contexts); if (cleanedContexts && Object.keys(cleanedContexts).length) { event.contexts = { ...cleanedContexts, ...event.contexts }; } if (level) { event.level = level; } if (transactionName && event.type !== "transaction") { event.transaction = transactionName; } } __name(applyDataToEvent, "applyDataToEvent"); function applyBreadcrumbsToEvent(event, breadcrumbs) { const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs]; event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0; } __name(applyBreadcrumbsToEvent, "applyBreadcrumbsToEvent"); function applySdkMetadataToEvent(event, sdkProcessingMetadata) { event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...sdkProcessingMetadata }; } __name(applySdkMetadataToEvent, "applySdkMetadataToEvent"); function applySpanToEvent(event, span) { event.contexts = { trace: spanToTraceContext(span), ...event.contexts }; event.sdkProcessingMetadata = { dynamicSamplingContext: getDynamicSamplingContextFromSpan(span), ...event.sdkProcessingMetadata }; const rootSpan = getRootSpan(span); const transactionName = spanToJSON(rootSpan).description; if (transactionName && !event.transaction && event.type === "transaction") { event.transaction = transactionName; } } __name(applySpanToEvent, "applySpanToEvent"); function applyFingerprintToEvent(event, fingerprint) { event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : []; if (fingerprint) { event.fingerprint = event.fingerprint.concat(fingerprint); } if (event.fingerprint && !event.fingerprint.length) { delete event.fingerprint; } } __name(applyFingerprintToEvent, "applyFingerprintToEvent"); function prepareEvent(options4, event, hint, scope, client, isolationScope) { const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options4; const prepared = { ...event, event_id: event.event_id || hint.event_id || uuid4(), timestamp: event.timestamp || dateTimestampInSeconds() }; const integrations = hint.integrations || options4.integrations.map((i2) => i2.name); applyClientOptions(prepared, options4); applyIntegrationsMetadata(prepared, integrations); if (client) { client.emit("applyFrameMetadata", event); } if (event.type === void 0) { applyDebugIds(prepared, options4.stackParser); } const finalScope = getFinalScope(scope, hint.captureContext); if (hint.mechanism) { addExceptionMechanism(prepared, hint.mechanism); } const clientEventProcessors = client ? client.getEventProcessors() : []; const data25 = getGlobalScope().getScopeData(); if (isolationScope) { const isolationData = isolationScope.getScopeData(); mergeScopeData(data25, isolationData); } if (finalScope) { const finalScopeData = finalScope.getScopeData(); mergeScopeData(data25, finalScopeData); } const attachments = [...hint.attachments || [], ...data25.attachments]; if (attachments.length) { hint.attachments = attachments; } applyScopeDataToEvent(prepared, data25); const eventProcessors = [ ...clientEventProcessors, // Run scope event processors _after_ all other processors ...data25.eventProcessors ]; const result = notifyEventProcessors(eventProcessors, prepared, hint); return result.then((evt) => { if (evt) { applyDebugMeta(evt); } if (typeof normalizeDepth === "number" && normalizeDepth > 0) { return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); } return evt; }); } __name(prepareEvent, "prepareEvent"); function applyClientOptions(event, options4) { const { environment, release, dist: dist3, maxValueLength = 250 } = options4; event.environment = event.environment || environment || DEFAULT_ENVIRONMENT; if (!event.release && release) { event.release = release; } if (!event.dist && dist3) { event.dist = dist3; } if (event.message) { event.message = truncate(event.message, maxValueLength); } const exception = event.exception && event.exception.values && event.exception.values[0]; if (exception && exception.value) { exception.value = truncate(exception.value, maxValueLength); } const request = event.request; if (request && request.url) { request.url = truncate(request.url, maxValueLength); } } __name(applyClientOptions, "applyClientOptions"); function applyDebugIds(event, stackParser) { const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser); try { event.exception.values.forEach((exception) => { exception.stacktrace.frames.forEach((frame) => { if (filenameDebugIdMap && frame.filename) { frame.debug_id = filenameDebugIdMap[frame.filename]; } }); }); } catch (e2) { } } __name(applyDebugIds, "applyDebugIds"); function applyDebugMeta(event) { const filenameDebugIdMap = {}; try { event.exception.values.forEach((exception) => { exception.stacktrace.frames.forEach((frame) => { if (frame.debug_id) { if (frame.abs_path) { filenameDebugIdMap[frame.abs_path] = frame.debug_id; } else if (frame.filename) { filenameDebugIdMap[frame.filename] = frame.debug_id; } delete frame.debug_id; } }); }); } catch (e2) { } if (Object.keys(filenameDebugIdMap).length === 0) { return; } event.debug_meta = event.debug_meta || {}; event.debug_meta.images = event.debug_meta.images || []; const images = event.debug_meta.images; Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => { images.push({ type: "sourcemap", code_file: filename, debug_id }); }); } __name(applyDebugMeta, "applyDebugMeta"); function applyIntegrationsMetadata(event, integrationNames) { if (integrationNames.length > 0) { event.sdk = event.sdk || {}; event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames]; } } __name(applyIntegrationsMetadata, "applyIntegrationsMetadata"); function normalizeEvent(event, depth, maxBreadth) { if (!event) { return null; } const normalized = { ...event, ...event.breadcrumbs && { breadcrumbs: event.breadcrumbs.map((b2) => ({ ...b2, ...b2.data && { data: normalize$2(b2.data, depth, maxBreadth) } })) }, ...event.user && { user: normalize$2(event.user, depth, maxBreadth) }, ...event.contexts && { contexts: normalize$2(event.contexts, depth, maxBreadth) }, ...event.extra && { extra: normalize$2(event.extra, depth, maxBreadth) } }; if (event.contexts && event.contexts.trace && normalized.contexts) { normalized.contexts.trace = event.contexts.trace; if (event.contexts.trace.data) { normalized.contexts.trace.data = normalize$2(event.contexts.trace.data, depth, maxBreadth); } } if (event.spans) { normalized.spans = event.spans.map((span) => { return { ...span, ...span.data && { data: normalize$2(span.data, depth, maxBreadth) } }; }); } if (event.contexts && event.contexts.flags && normalized.contexts) { normalized.contexts.flags = normalize$2(event.contexts.flags, 3, maxBreadth); } return normalized; } __name(normalizeEvent, "normalizeEvent"); function getFinalScope(scope, captureContext) { if (!captureContext) { return scope; } const finalScope = scope ? scope.clone() : new Scope(); finalScope.update(captureContext); return finalScope; } __name(getFinalScope, "getFinalScope"); function parseEventHintOrCaptureContext(hint) { if (!hint) { return void 0; } if (hintIsScopeOrFunction(hint)) { return { captureContext: hint }; } if (hintIsScopeContext(hint)) { return { captureContext: hint }; } return hint; } __name(parseEventHintOrCaptureContext, "parseEventHintOrCaptureContext"); function hintIsScopeOrFunction(hint) { return hint instanceof Scope || typeof hint === "function"; } __name(hintIsScopeOrFunction, "hintIsScopeOrFunction"); const captureContextKeys = [ "user", "level", "extra", "contexts", "tags", "fingerprint", "requestSession", "propagationContext" ]; function hintIsScopeContext(hint) { return Object.keys(hint).some((key) => captureContextKeys.includes(key)); } __name(hintIsScopeContext, "hintIsScopeContext"); function captureException(exception, hint) { return getCurrentScope$1().captureException(exception, parseEventHintOrCaptureContext(hint)); } __name(captureException, "captureException"); function captureMessage(message3, captureContext) { const level = typeof captureContext === "string" ? captureContext : void 0; const context = typeof captureContext !== "string" ? { captureContext } : void 0; return getCurrentScope$1().captureMessage(message3, level, context); } __name(captureMessage, "captureMessage"); function captureEvent(event, hint) { return getCurrentScope$1().captureEvent(event, hint); } __name(captureEvent, "captureEvent"); function setContext(name2, context) { getIsolationScope().setContext(name2, context); } __name(setContext, "setContext"); function setExtras(extras) { getIsolationScope().setExtras(extras); } __name(setExtras, "setExtras"); function setExtra(key, extra) { getIsolationScope().setExtra(key, extra); } __name(setExtra, "setExtra"); function setTags(tags) { getIsolationScope().setTags(tags); } __name(setTags, "setTags"); function setTag$5(key, value4) { getIsolationScope().setTag(key, value4); } __name(setTag$5, "setTag$5"); function setUser(user) { getIsolationScope().setUser(user); } __name(setUser, "setUser"); function lastEventId() { return getIsolationScope().lastEventId(); } __name(lastEventId, "lastEventId"); function captureCheckIn(checkIn, upsertMonitorConfig) { const scope = getCurrentScope$1(); const client = getClient(); if (!client) { DEBUG_BUILD$6 && logger$2.warn("Cannot capture check-in. No client defined."); } else if (!client.captureCheckIn) { DEBUG_BUILD$6 && logger$2.warn("Cannot capture check-in. Client does not support sending check-ins."); } else { return client.captureCheckIn(checkIn, upsertMonitorConfig, scope); } return uuid4(); } __name(captureCheckIn, "captureCheckIn"); function withMonitor(monitorSlug, callback, upsertMonitorConfig) { const checkInId = captureCheckIn({ monitorSlug, status: "in_progress" }, upsertMonitorConfig); const now2 = timestampInSeconds(); function finishCheckIn(status) { captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now2 }); } __name(finishCheckIn, "finishCheckIn"); return withIsolationScope(() => { let maybePromiseResult; try { maybePromiseResult = callback(); } catch (e2) { finishCheckIn("error"); throw e2; } if (isThenable$1(maybePromiseResult)) { Promise.resolve(maybePromiseResult).then( () => { finishCheckIn("ok"); }, (e2) => { finishCheckIn("error"); throw e2; } ); } else { finishCheckIn("ok"); } return maybePromiseResult; }); } __name(withMonitor, "withMonitor"); async function flush(timeout) { const client = getClient(); if (client) { return client.flush(timeout); } DEBUG_BUILD$6 && logger$2.warn("Cannot flush events. No client defined."); return Promise.resolve(false); } __name(flush, "flush"); async function close$1(timeout) { const client = getClient(); if (client) { return client.close(timeout); } DEBUG_BUILD$6 && logger$2.warn("Cannot flush events and disable SDK. No client defined."); return Promise.resolve(false); } __name(close$1, "close$1"); function isInitialized() { return !!getClient(); } __name(isInitialized, "isInitialized"); function isEnabled() { const client = getClient(); return !!client && client.getOptions().enabled !== false && !!client.getTransport(); } __name(isEnabled, "isEnabled"); function addEventProcessor(callback) { getIsolationScope().addEventProcessor(callback); } __name(addEventProcessor, "addEventProcessor"); function startSession(context) { const client = getClient(); const isolationScope = getIsolationScope(); const currentScope = getCurrentScope$1(); const { release, environment = DEFAULT_ENVIRONMENT } = client && client.getOptions() || {}; const { userAgent } = GLOBAL_OBJ.navigator || {}; const session = makeSession$1({ release, environment, user: currentScope.getUser() || isolationScope.getUser(), ...userAgent && { userAgent }, ...context }); const currentSession = isolationScope.getSession(); if (currentSession && currentSession.status === "ok") { updateSession(currentSession, { status: "exited" }); } endSession(); isolationScope.setSession(session); currentScope.setSession(session); return session; } __name(startSession, "startSession"); function endSession() { const isolationScope = getIsolationScope(); const currentScope = getCurrentScope$1(); const session = currentScope.getSession() || isolationScope.getSession(); if (session) { closeSession(session); } _sendSessionUpdate$1(); isolationScope.setSession(); currentScope.setSession(); } __name(endSession, "endSession"); function _sendSessionUpdate$1() { const isolationScope = getIsolationScope(); const currentScope = getCurrentScope$1(); const client = getClient(); const session = currentScope.getSession() || isolationScope.getSession(); if (session && client) { client.captureSession(session); } } __name(_sendSessionUpdate$1, "_sendSessionUpdate$1"); function captureSession(end = false) { if (end) { endSession(); return; } _sendSessionUpdate$1(); } __name(captureSession, "captureSession"); class SessionFlusher { static { __name(this, "SessionFlusher"); } // We adjust the type here to add the `unref()` part, as setInterval can technically return a number or a NodeJS.Timer constructor(client, attrs4) { this._client = client; this.flushTimeout = 60; this._pendingAggregates = /* @__PURE__ */ new Map(); this._isEnabled = true; this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1e3); if (this._intervalId.unref) { this._intervalId.unref(); } this._sessionAttrs = attrs4; } /** 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 = /* @__PURE__ */ new Map(); this._client.sendSession(sessionAggregates); } /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ getSessionAggregates() { const aggregates = Array.from(this._pendingAggregates.values()); const sessionAggregates = { attrs: this._sessionAttrs, aggregates }; return 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 isolationScope = getIsolationScope(); const requestSession = isolationScope.getRequestSession(); if (requestSession && requestSession.status) { this._incrementSessionStatusCount(requestSession.status, /* @__PURE__ */ new Date()); isolationScope.setRequestSession(void 0); } } /** * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of * the session received */ // eslint-disable-next-line deprecation/deprecation _incrementSessionStatusCount(status, date) { const sessionStartedTrunc = new Date(date).setSeconds(0, 0); let aggregationCounts = this._pendingAggregates.get(sessionStartedTrunc); if (!aggregationCounts) { aggregationCounts = { started: new Date(sessionStartedTrunc).toISOString() }; this._pendingAggregates.set(sessionStartedTrunc, aggregationCounts); } 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; } } } const SENTRY_API_VERSION = "7"; 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/`; } __name(getBaseApiEndpoint, "getBaseApiEndpoint"); function _getIngestEndpoint(dsn) { return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; } __name(_getIngestEndpoint, "_getIngestEndpoint"); function _encodedAuth(dsn, sdkInfo) { const params = { sentry_version: SENTRY_API_VERSION }; if (dsn.publicKey) { params.sentry_key = dsn.publicKey; } if (sdkInfo) { params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`; } return new URLSearchParams(params).toString(); } __name(_encodedAuth, "_encodedAuth"); function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) { return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; } __name(getEnvelopeEndpointWithUrlEncodedAuth, "getEnvelopeEndpointWithUrlEncodedAuth"); function getReportDialogEndpoint(dsnLike, dialogOptions) { const dsn = makeDsn(dsnLike); if (!dsn) { return ""; } const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; let encodedOptions = `dsn=${dsnToString(dsn)}`; for (const key in dialogOptions) { if (key === "dsn") { continue; } if (key === "onClose") { 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}`; } __name(getReportDialogEndpoint, "getReportDialogEndpoint"); const installedIntegrations = []; function filterDuplicates(integrations) { const integrationsByName = {}; integrations.forEach((currentInstance2) => { const { name: name2 } = currentInstance2; const existingInstance = integrationsByName[name2]; if (existingInstance && !existingInstance.isDefaultInstance && currentInstance2.isDefaultInstance) { return; } integrationsByName[name2] = currentInstance2; }); return Object.values(integrationsByName); } __name(filterDuplicates, "filterDuplicates"); function getIntegrationsToSetup(options4) { const defaultIntegrations = options4.defaultIntegrations || []; const userIntegrations = options4.integrations; defaultIntegrations.forEach((integration) => { integration.isDefaultInstance = true; }); let integrations; if (Array.isArray(userIntegrations)) { integrations = [...defaultIntegrations, ...userIntegrations]; } else if (typeof userIntegrations === "function") { const resolvedUserIntegrations = userIntegrations(defaultIntegrations); integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations]; } else { integrations = defaultIntegrations; } const finalIntegrations = filterDuplicates(integrations); const debugIndex = finalIntegrations.findIndex((integration) => integration.name === "Debug"); if (debugIndex > -1) { const [debugInstance] = finalIntegrations.splice(debugIndex, 1); finalIntegrations.push(debugInstance); } return finalIntegrations; } __name(getIntegrationsToSetup, "getIntegrationsToSetup"); function setupIntegrations(client, integrations) { const integrationIndex = {}; integrations.forEach((integration) => { if (integration) { setupIntegration(client, integration, integrationIndex); } }); return integrationIndex; } __name(setupIntegrations, "setupIntegrations"); function afterSetupIntegrations(client, integrations) { for (const integration of integrations) { if (integration && integration.afterAllSetup) { integration.afterAllSetup(client); } } } __name(afterSetupIntegrations, "afterSetupIntegrations"); function setupIntegration(client, integration, integrationIndex) { if (integrationIndex[integration.name]) { DEBUG_BUILD$6 && logger$2.log(`Integration skipped because it was already installed: ${integration.name}`); return; } integrationIndex[integration.name] = integration; if (installedIntegrations.indexOf(integration.name) === -1 && typeof integration.setupOnce === "function") { integration.setupOnce(); installedIntegrations.push(integration.name); } if (integration.setup && typeof integration.setup === "function") { integration.setup(client); } if (typeof integration.preprocessEvent === "function") { const callback = integration.preprocessEvent.bind(integration); client.on("preprocessEvent", (event, hint) => callback(event, hint, client)); } if (typeof integration.processEvent === "function") { const callback = integration.processEvent.bind(integration); const processor = Object.assign((event, hint) => callback(event, hint, client), { id: integration.name }); client.addEventProcessor(processor); } DEBUG_BUILD$6 && logger$2.log(`Integration installed: ${integration.name}`); } __name(setupIntegration, "setupIntegration"); function addIntegration(integration) { const client = getClient(); if (!client) { DEBUG_BUILD$6 && logger$2.warn(`Cannot add integration "${integration.name}" because no SDK Client is available.`); return; } client.addIntegration(integration); } __name(addIntegration, "addIntegration"); function defineIntegration(fn) { return fn; } __name(defineIntegration, "defineIntegration"); function createClientReportEnvelope(discarded_events, dsn, timestamp2) { const clientReportItem = [ { type: "client_report" }, { timestamp: timestamp2 || dateTimestampInSeconds(), discarded_events } ]; return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]); } __name(createClientReportEnvelope, "createClientReportEnvelope"); class SentryError extends Error { static { __name(this, "SentryError"); } /** Display name of this error instance. */ constructor(message3, logLevel = "warn") { super(message3); this.message = message3; this.name = new.target.prototype.constructor.name; Object.setPrototypeOf(this, new.target.prototype); this.logLevel = logLevel; } } const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; class BaseClient { static { __name(this, "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. */ /** Number of calls being processed */ /** Holds flushable */ // eslint-disable-next-line @typescript-eslint/ban-types /** * Initializes this client instance. * * @param options Options for the client. */ constructor(options4) { this._options = options4; this._integrations = {}; this._numProcessing = 0; this._outcomes = {}; this._hooks = {}; this._eventProcessors = []; if (options4.dsn) { this._dsn = makeDsn(options4.dsn); } else { DEBUG_BUILD$6 && logger$2.warn("No DSN provided, client will not send events."); } if (this._dsn) { const url = getEnvelopeEndpointWithUrlEncodedAuth( this._dsn, options4.tunnel, options4._metadata ? options4._metadata.sdk : void 0 ); this._transport = options4.transport({ tunnel: this._options.tunnel, recordDroppedEvent: this.recordDroppedEvent.bind(this), ...options4.transportOptions, url }); } const tracingOptions = ["enableTracing", "tracesSampleRate", "tracesSampler"]; const undefinedOption = tracingOptions.find((option3) => option3 in options4 && options4[option3] == void 0); if (undefinedOption) { consoleSandbox(() => { console.warn( `[Sentry] Deprecation warning: \`${undefinedOption}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.` ); }); } } /** * @inheritDoc */ captureException(exception, hint, scope) { const eventId = uuid4(); if (checkOrSetAlreadyCaught(exception)) { DEBUG_BUILD$6 && logger$2.log(ALREADY_SEEN_ERROR); return eventId; } const hintWithEventId = { event_id: eventId, ...hint }; this._process( this.eventFromException(exception, hintWithEventId).then( (event) => this._captureEvent(event, hintWithEventId, scope) ) ); return hintWithEventId.event_id; } /** * @inheritDoc */ captureMessage(message3, level, hint, currentScope) { const hintWithEventId = { event_id: uuid4(), ...hint }; const eventMessage = isParameterizedString(message3) ? message3 : String(message3); const promisedEvent = isPrimitive(message3) ? this.eventFromMessage(eventMessage, level, hintWithEventId) : this.eventFromException(message3, hintWithEventId); this._process(promisedEvent.then((event) => this._captureEvent(event, hintWithEventId, currentScope))); return hintWithEventId.event_id; } /** * @inheritDoc */ captureEvent(event, hint, currentScope) { const eventId = uuid4(); if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) { DEBUG_BUILD$6 && logger$2.log(ALREADY_SEEN_ERROR); return eventId; } const hintWithEventId = { event_id: eventId, ...hint }; const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope; this._process(this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope)); return hintWithEventId.event_id; } /** * @inheritDoc */ captureSession(session) { if (!(typeof session.release === "string")) { DEBUG_BUILD$6 && logger$2.warn("Discarded session because of missing or non-string release"); } else { this.sendSession(session); updateSession(session, { init: false }); } } /** * @inheritDoc */ getDsn() { return this._dsn; } /** * @inheritDoc */ getOptions() { return this._options; } /** * @see SdkMetadata * * @return The metadata of the SDK */ getSdkMetadata() { return this._options._metadata; } /** * @inheritDoc */ getTransport() { return this._transport; } /** * @inheritDoc */ flush(timeout) { const transport = this._transport; if (transport) { this.emit("flush"); return this._isClientDoneProcessing(timeout).then((clientFinished) => { return transport.flush(timeout).then((transportFlushed) => clientFinished && transportFlushed); }); } else { return resolvedSyncPromise(true); } } /** * @inheritDoc */ close(timeout) { return this.flush(timeout).then((result) => { this.getOptions().enabled = false; this.emit("close"); return result; }); } /** Get all installed event processors. */ getEventProcessors() { return this._eventProcessors; } /** @inheritDoc */ addEventProcessor(eventProcessor) { this._eventProcessors.push(eventProcessor); } /** @inheritdoc */ init() { if (this._isEnabled() || // Force integrations to be setup even if no DSN was set when we have // Spotlight enabled. This is particularly important for browser as we // don't support the `spotlight` option there and rely on the users // adding the `spotlightBrowserIntegration()` to their integrations which // wouldn't get initialized with the check below when there's no DSN set. this._options.integrations.some(({ name: name2 }) => name2.startsWith("Spotlight"))) { this._setupIntegrations(); } } /** * Gets an installed integration by its name. * * @returns The installed integration or `undefined` if no integration with that `name` was installed. */ getIntegrationByName(integrationName) { return this._integrations[integrationName]; } /** * @inheritDoc */ addIntegration(integration) { const isAlreadyInstalled = this._integrations[integration.name]; setupIntegration(this, integration, this._integrations); if (!isAlreadyInstalled) { afterSetupIntegrations(this, [integration]); } } /** * @inheritDoc */ sendEvent(event, hint = {}) { this.emit("beforeSendEvent", event, hint); let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel); for (const attachment of hint.attachments || []) { env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment)); } const promise = this.sendEnvelope(env); if (promise) { promise.then((sendResponse) => this.emit("afterSendEvent", event, sendResponse), null); } } /** * @inheritDoc */ sendSession(session) { const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel); this.sendEnvelope(env); } /** * @inheritDoc */ recordDroppedEvent(reason, category, eventOrCount) { if (this._options.sendClientReports) { const count = typeof eventOrCount === "number" ? eventOrCount : 1; const key = `${reason}:${category}`; DEBUG_BUILD$6 && logger$2.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ""}`); this._outcomes[key] = (this._outcomes[key] || 0) + count; } } // Keep on() & emit() signatures in sync with types' client.ts interface /* eslint-disable @typescript-eslint/unified-signatures */ /** @inheritdoc */ /** @inheritdoc */ on(hook, callback) { const hooks2 = this._hooks[hook] = this._hooks[hook] || []; hooks2.push(callback); return () => { const cbIndex = hooks2.indexOf(callback); if (cbIndex > -1) { hooks2.splice(cbIndex, 1); } }; } /** @inheritdoc */ /** @inheritdoc */ emit(hook, ...rest) { const callbacks = this._hooks[hook]; if (callbacks) { callbacks.forEach((callback) => callback(...rest)); } } /** * @inheritdoc */ sendEnvelope(envelope) { this.emit("beforeEnvelope", envelope); if (this._isEnabled() && this._transport) { return this._transport.send(envelope).then(null, (reason) => { DEBUG_BUILD$6 && logger$2.error("Error while sending envelope:", reason); return reason; }); } DEBUG_BUILD$6 && logger$2.error("Transport disabled"); return resolvedSyncPromise({}); } /* eslint-enable @typescript-eslint/unified-signatures */ /** Setup integrations for this client. */ _setupIntegrations() { const { integrations } = this._options; this._integrations = setupIntegrations(this, integrations); afterSetupIntegrations(this, integrations); } /** 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; } } } const sessionNonTerminal = session.status === "ok"; const shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed; if (shouldUpdateAndSend) { 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 SyncPromise((resolve2) => { let ticked = 0; const tick = 1; const interval = setInterval(() => { if (this._numProcessing == 0) { clearInterval(interval); resolve2(true); } else { ticked += tick; if (timeout && ticked >= timeout) { clearInterval(interval); resolve2(false); } } }, tick); }); } /** Determines whether this SDK is enabled and a transport is present. */ _isEnabled() { return this.getOptions().enabled !== false && this._transport !== void 0; } /** * 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 currentScope A scope containing event metadata. * @returns A new event with more information. */ _prepareEvent(event, hint, currentScope = getCurrentScope$1(), isolationScope = getIsolationScope()) { const options4 = this.getOptions(); const integrations = Object.keys(this._integrations); if (!hint.integrations && integrations.length > 0) { hint.integrations = integrations; } this.emit("preprocessEvent", event, hint); if (!event.type) { isolationScope.setLastEventId(event.event_id || hint.event_id); } return prepareEvent(options4, event, hint, currentScope, this, isolationScope).then((evt) => { if (evt === null) { return evt; } evt.contexts = { trace: getTraceContextFromScope(currentScope), ...evt.contexts }; const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope); evt.sdkProcessingMetadata = { dynamicSamplingContext, ...evt.sdkProcessingMetadata }; return evt; }); } /** * 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 (DEBUG_BUILD$6) { const sentryError = reason; if (sentryError.logLevel === "log") { logger$2.log(sentryError.message); } else { logger$2.warn(sentryError); } } return void 0; } ); } /** * 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 currentScope 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, currentScope) { const options4 = this.getOptions(); const { sampleRate } = options4; const isTransaction = isTransactionEvent$1(event); const isError2 = isErrorEvent$1(event); const eventType = event.type || "error"; const beforeSendLabel = `before send for type \`${eventType}\``; const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : parseSampleRate(sampleRate); if (isError2 && typeof parsedSampleRate === "number" && Math.random() > parsedSampleRate) { this.recordDroppedEvent("sample_rate", "error", event); return rejectedSyncPromise( new SentryError( `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, "log" ) ); } const dataCategory = eventType === "replay_event" ? "replay" : eventType; const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope; return this._prepareEvent(event, hint, currentScope, capturedSpanIsolationScope).then((prepared) => { if (prepared === null) { this.recordDroppedEvent("event_processor", dataCategory, event); throw new SentryError("An event processor returned `null`, will not send event.", "log"); } const isInternalException = hint.data && hint.data.__sentry__ === true; if (isInternalException) { return prepared; } const result = processBeforeSend(this, options4, prepared, hint); return _validateBeforeSendResult(result, beforeSendLabel); }).then((processedEvent) => { if (processedEvent === null) { this.recordDroppedEvent("before_send", dataCategory, event); if (isTransaction) { const spans = event.spans || []; const spanCount = 1 + spans.length; this.recordDroppedEvent("before_send", "span", spanCount); } throw new SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, "log"); } const session = currentScope && currentScope.getSession(); if (!isTransaction && session) { this._updateSessionFromEvent(session, processedEvent); } if (isTransaction) { const spanCountBefore = processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing || 0; const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0; const droppedSpanCount = spanCountBefore - spanCountAfter; if (droppedSpanCount > 0) { this.recordDroppedEvent("before_send", "span", droppedSpanCount); } } const transactionInfo = processedEvent.transaction_info; if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { const source = "custom"; processedEvent.transaction_info = { ...transactionInfo, source }; } this.sendEvent(processedEvent, hint); return processedEvent; }).then(null, (reason) => { if (reason instanceof SentryError) { throw reason; } this.captureException(reason, { data: { __sentry__: true }, originalException: reason }); throw new SentryError( `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event. Reason: ${reason}` ); }); } /** * Occupies the client with processing and event */ _process(promise) { this._numProcessing++; void promise.then( (value4) => { this._numProcessing--; return value4; }, (reason) => { this._numProcessing--; return reason; } ); } /** * Clears outcomes on this client and returns them. */ _clearOutcomes() { const outcomes = this._outcomes; this._outcomes = {}; return Object.entries(outcomes).map(([key, quantity]) => { const [reason, category] = key.split(":"); return { reason, category, quantity }; }); } /** * Sends client reports as an envelope. */ _flushOutcomes() { DEBUG_BUILD$6 && logger$2.log("Flushing outcomes..."); const outcomes = this._clearOutcomes(); if (outcomes.length === 0) { DEBUG_BUILD$6 && logger$2.log("No outcomes to send"); return; } if (!this._dsn) { DEBUG_BUILD$6 && logger$2.log("No dsn provided, will not send outcomes"); return; } DEBUG_BUILD$6 && logger$2.log("Sending outcomes:", outcomes); const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn)); this.sendEnvelope(envelope); } /** * @inheritDoc */ } function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) { const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`; if (isThenable$1(beforeSendResult)) { return beforeSendResult.then( (event) => { if (!isPlainObject$5(event) && event !== null) { throw new SentryError(invalidValueError); } return event; }, (e2) => { throw new SentryError(`${beforeSendLabel} rejected with ${e2}`); } ); } else if (!isPlainObject$5(beforeSendResult) && beforeSendResult !== null) { throw new SentryError(invalidValueError); } return beforeSendResult; } __name(_validateBeforeSendResult, "_validateBeforeSendResult"); function processBeforeSend(client, options4, event, hint) { const { beforeSend, beforeSendTransaction, beforeSendSpan } = options4; if (isErrorEvent$1(event) && beforeSend) { return beforeSend(event, hint); } if (isTransactionEvent$1(event)) { if (event.spans && beforeSendSpan) { const processedSpans = []; for (const span of event.spans) { const processedSpan = beforeSendSpan(span); if (processedSpan) { processedSpans.push(processedSpan); } else { showSpanDropWarning(); client.recordDroppedEvent("before_send", "span"); } } event.spans = processedSpans; } if (beforeSendTransaction) { if (event.spans) { const spanCountBefore = event.spans.length; event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, spanCountBeforeProcessing: spanCountBefore }; } return beforeSendTransaction(event, hint); } } return event; } __name(processBeforeSend, "processBeforeSend"); function isErrorEvent$1(event) { return event.type === void 0; } __name(isErrorEvent$1, "isErrorEvent$1"); function isTransactionEvent$1(event) { return event.type === "transaction"; } __name(isTransactionEvent$1, "isTransactionEvent$1"); function createCheckInEnvelope(checkIn, dynamicSamplingContext, metadata, tunnel, dsn) { const headers = { sent_at: (/* @__PURE__ */ new Date()).toISOString() }; if (metadata && metadata.sdk) { headers.sdk = { name: metadata.sdk.name, version: metadata.sdk.version }; } if (!!tunnel && !!dsn) { headers.dsn = dsnToString(dsn); } if (dynamicSamplingContext) { headers.trace = dropUndefinedKeys(dynamicSamplingContext); } const item3 = createCheckInEnvelopeItem(checkIn); return createEnvelope(headers, [item3]); } __name(createCheckInEnvelope, "createCheckInEnvelope"); function createCheckInEnvelopeItem(checkIn) { const checkInHeaders = { type: "check_in" }; return [checkInHeaders, checkIn]; } __name(createCheckInEnvelopeItem, "createCheckInEnvelopeItem"); function parseStackFrames$1(stackParser, error2) { return stackParser(error2.stack || "", 1); } __name(parseStackFrames$1, "parseStackFrames$1"); function exceptionFromError$1(stackParser, error2) { const exception = { type: error2.name || error2.constructor.name, value: error2.message }; const frames = parseStackFrames$1(stackParser, error2); if (frames.length) { exception.stacktrace = { frames }; } return exception; } __name(exceptionFromError$1, "exceptionFromError$1"); function getErrorPropertyFromObject$1(obj) { for (const prop2 in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop2)) { const value4 = obj[prop2]; if (value4 instanceof Error) { return value4; } } } return void 0; } __name(getErrorPropertyFromObject$1, "getErrorPropertyFromObject$1"); function getMessageForObject(exception) { if ("name" in exception && typeof exception.name === "string") { let message3 = `'${exception.name}' captured as exception`; if ("message" in exception && typeof exception.message === "string") { message3 += ` with message '${exception.message}'`; } return message3; } else if ("message" in exception && typeof exception.message === "string") { return exception.message; } const keys2 = extractExceptionKeysForMessage(exception); if (isErrorEvent$2(exception)) { return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``; } const className = getObjectClassName$1(exception); return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys2}`; } __name(getMessageForObject, "getMessageForObject"); function getObjectClassName$1(obj) { try { const prototype2 = Object.getPrototypeOf(obj); return prototype2 ? prototype2.constructor.name : void 0; } catch (e2) { } } __name(getObjectClassName$1, "getObjectClassName$1"); function getException(client, mechanism, exception, hint) { if (isError(exception)) { return [exception, void 0]; } mechanism.synthetic = true; if (isPlainObject$5(exception)) { const normalizeDepth = client && client.getOptions().normalizeDepth; const extras = { ["__serialized__"]: normalizeToSize(exception, normalizeDepth) }; const errorFromProp = getErrorPropertyFromObject$1(exception); if (errorFromProp) { return [errorFromProp, extras]; } const message3 = getMessageForObject(exception); const ex2 = hint && hint.syntheticException || new Error(message3); ex2.message = message3; return [ex2, extras]; } const ex = hint && hint.syntheticException || new Error(exception); ex.message = `${exception}`; return [ex, void 0]; } __name(getException, "getException"); function eventFromUnknownInput$1(client, stackParser, exception, hint) { const providedMechanism = hint && hint.data && hint.data.mechanism; const mechanism = providedMechanism || { handled: true, type: "generic" }; const [ex, extras] = getException(client, mechanism, exception, hint); const event = { exception: { values: [exceptionFromError$1(stackParser, ex)] } }; if (extras) { event.extra = extras; } addExceptionTypeValue(event, void 0, void 0); addExceptionMechanism(event, mechanism); return { ...event, event_id: hint && hint.event_id }; } __name(eventFromUnknownInput$1, "eventFromUnknownInput$1"); function eventFromMessage$1(stackParser, message3, level = "info", hint, attachStacktrace) { const event = { event_id: hint && hint.event_id, level }; if (attachStacktrace && hint && hint.syntheticException) { const frames = parseStackFrames$1(stackParser, hint.syntheticException); if (frames.length) { event.exception = { values: [ { value: message3, stacktrace: { frames } } ] }; addExceptionMechanism(event, { synthetic: true }); } } if (isParameterizedString(message3)) { const { __sentry_template_string__, __sentry_template_values__ } = message3; event.logentry = { message: __sentry_template_string__, params: __sentry_template_values__ }; return event; } event.message = message3; return event; } __name(eventFromMessage$1, "eventFromMessage$1"); class ServerRuntimeClient extends BaseClient { static { __name(this, "ServerRuntimeClient"); } // eslint-disable-next-line deprecation/deprecation /** * Creates a new Edge SDK instance. * @param options Configuration options for this SDK. */ constructor(options4) { registerSpanErrorInstrumentation(); super(options4); } /** * @inheritDoc */ eventFromException(exception, hint) { const event = eventFromUnknownInput$1(this, this._options.stackParser, exception, hint); event.level = "error"; return resolvedSyncPromise(event); } /** * @inheritDoc */ eventFromMessage(message3, level = "info", hint) { return resolvedSyncPromise( eventFromMessage$1(this._options.stackParser, message3, level, hint, this._options.attachStacktrace) ); } /** * @inheritDoc */ captureException(exception, hint, scope) { if (this._options.autoSessionTracking && this._sessionFlusher) { const requestSession = getIsolationScope().getRequestSession(); if (requestSession && requestSession.status === "ok") { requestSession.status = "errored"; } } return super.captureException(exception, hint, scope); } /** * @inheritDoc */ captureEvent(event, hint, scope) { if (this._options.autoSessionTracking && this._sessionFlusher) { const eventType = event.type || "exception"; const isException = eventType === "exception" && event.exception && event.exception.values && event.exception.values.length > 0; if (isException) { const requestSession = getIsolationScope().getRequestSession(); if (requestSession && requestSession.status === "ok") { requestSession.status = "errored"; } } } return super.captureEvent(event, hint, scope); } /** * * @inheritdoc */ close(timeout) { if (this._sessionFlusher) { this._sessionFlusher.close(); } return super.close(timeout); } /** * Initializes an instance of SessionFlusher on the client which will aggregate and periodically flush session data. * * NOTICE: This method will implicitly create an interval that is periodically called. * To clean up this resources, call `.close()` when you no longer intend to use the client. * Not doing so will result in a memory leak. */ initSessionFlusher() { const { release, environment } = this._options; if (!release) { DEBUG_BUILD$6 && logger$2.warn("Cannot initialize an instance of SessionFlusher if no release is provided!"); } else { this._sessionFlusher = new SessionFlusher(this, { release, environment }); } } /** * Create a cron monitor check in and send it to Sentry. * * @param checkIn An object that describes a check in. * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want * to create a monitor automatically when sending a check in. */ captureCheckIn(checkIn, monitorConfig, scope) { const id3 = "checkInId" in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4(); if (!this._isEnabled()) { DEBUG_BUILD$6 && logger$2.warn("SDK not enabled, will not capture checkin."); return id3; } const options4 = this.getOptions(); const { release, environment, tunnel } = options4; const serializedCheckIn = { check_in_id: id3, monitor_slug: checkIn.monitorSlug, status: checkIn.status, release, environment }; if ("duration" in checkIn) { serializedCheckIn.duration = checkIn.duration; } if (monitorConfig) { serializedCheckIn.monitor_config = { schedule: monitorConfig.schedule, checkin_margin: monitorConfig.checkinMargin, max_runtime: monitorConfig.maxRuntime, timezone: monitorConfig.timezone, failure_issue_threshold: monitorConfig.failureIssueThreshold, recovery_threshold: monitorConfig.recoveryThreshold }; } const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(scope); if (traceContext) { serializedCheckIn.contexts = { trace: traceContext }; } const envelope = createCheckInEnvelope( serializedCheckIn, dynamicSamplingContext, this.getSdkMetadata(), tunnel, this.getDsn() ); DEBUG_BUILD$6 && logger$2.info("Sending checkin:", checkIn.monitorSlug, checkIn.status); this.sendEnvelope(envelope); return id3; } /** * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment * appropriate session aggregates bucket * * @deprecated This method should not be used or extended. It's functionality will move into the `httpIntegration` and not be part of any public API. */ _captureRequestSession() { if (!this._sessionFlusher) { DEBUG_BUILD$6 && logger$2.warn("Discarded request mode session because autoSessionTracking option was disabled"); } else { this._sessionFlusher.incrementSessionStatusCount(); } } /** * @inheritDoc */ _prepareEvent(event, hint, scope, isolationScope) { if (this._options.platform) { event.platform = event.platform || this._options.platform; } if (this._options.runtime) { event.contexts = { ...event.contexts, runtime: (event.contexts || {}).runtime || this._options.runtime }; } if (this._options.serverName) { event.server_name = event.server_name || this._options.serverName; } return super._prepareEvent(event, hint, scope, isolationScope); } /** Extract trace information from scope */ _getTraceInfoFromScope(scope) { if (!scope) { return [void 0, void 0]; } const span = _getSpanForScope(scope); const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope); const dynamicSamplingContext = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(this, scope); return [dynamicSamplingContext, traceContext]; } } function initAndBind(clientClass, options4) { if (options4.debug === true) { if (DEBUG_BUILD$6) { logger$2.enable(); } else { consoleSandbox(() => { console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle."); }); } } const scope = getCurrentScope$1(); scope.update(options4.initialScope); const client = new clientClass(options4); setCurrentClient(client); client.init(); return client; } __name(initAndBind, "initAndBind"); function setCurrentClient(client) { getCurrentScope$1().setClient(client); } __name(setCurrentClient, "setCurrentClient"); function makePromiseBuffer(limit) { const buffer2 = []; function isReady() { return limit === void 0 || buffer2.length < limit; } __name(isReady, "isReady"); function remove4(task) { return buffer2.splice(buffer2.indexOf(task), 1)[0] || Promise.resolve(void 0); } __name(remove4, "remove"); function add3(taskProducer) { if (!isReady()) { return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached.")); } const task = taskProducer(); if (buffer2.indexOf(task) === -1) { buffer2.push(task); } void task.then(() => remove4(task)).then( null, () => remove4(task).then(null, () => { }) ); return task; } __name(add3, "add"); function drain(timeout) { return new SyncPromise((resolve2, reject3) => { let counter = buffer2.length; if (!counter) { return resolve2(true); } const capturedSetTimeout = setTimeout(() => { if (timeout && timeout > 0) { resolve2(false); } }, timeout); buffer2.forEach((item3) => { void resolvedSyncPromise(item3).then(() => { if (!--counter) { clearTimeout(capturedSetTimeout); resolve2(true); } }, reject3); }); }); } __name(drain, "drain"); return { $: buffer2, add: add3, drain }; } __name(makePromiseBuffer, "makePromiseBuffer"); const DEFAULT_RETRY_AFTER = 60 * 1e3; function parseRetryAfterHeader(header3, now2 = Date.now()) { const headerDelay = parseInt(`${header3}`, 10); if (!isNaN(headerDelay)) { return headerDelay * 1e3; } const headerDate = Date.parse(`${header3}`); if (!isNaN(headerDate)) { return headerDate - now2; } return DEFAULT_RETRY_AFTER; } __name(parseRetryAfterHeader, "parseRetryAfterHeader"); function disabledUntil(limits, dataCategory) { return limits[dataCategory] || limits.all || 0; } __name(disabledUntil, "disabledUntil"); function isRateLimited(limits, dataCategory, now2 = Date.now()) { return disabledUntil(limits, dataCategory) > now2; } __name(isRateLimited, "isRateLimited"); function updateRateLimits(limits, { statusCode, headers }, now2 = Date.now()) { const updatedRateLimits = { ...limits }; const rateLimitHeader = headers && headers["x-sentry-rate-limits"]; const retryAfterHeader = headers && headers["retry-after"]; if (rateLimitHeader) { for (const limit of rateLimitHeader.trim().split(",")) { const [retryAfter, categories, , , namespaces] = limit.split(":", 5); const headerDelay = parseInt(retryAfter, 10); const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3; if (!categories) { updatedRateLimits.all = now2 + delay; } else { for (const category of categories.split(";")) { if (category === "metric_bucket") { if (!namespaces || namespaces.split(";").includes("custom")) { updatedRateLimits[category] = now2 + delay; } } else { updatedRateLimits[category] = now2 + delay; } } } } } else if (retryAfterHeader) { updatedRateLimits.all = now2 + parseRetryAfterHeader(retryAfterHeader, now2); } else if (statusCode === 429) { updatedRateLimits.all = now2 + 60 * 1e3; } return updatedRateLimits; } __name(updateRateLimits, "updateRateLimits"); const DEFAULT_TRANSPORT_BUFFER_SIZE = 64; function createTransport(options4, makeRequest, buffer2 = makePromiseBuffer( options4.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE )) { let rateLimits = {}; const flush2 = /* @__PURE__ */ __name((timeout) => buffer2.drain(timeout), "flush"); function send(envelope) { const filteredEnvelopeItems = []; forEachEnvelopeItem(envelope, (item3, type) => { const dataCategory = envelopeItemTypeToDataCategory(type); if (isRateLimited(rateLimits, dataCategory)) { const event = getEventForEnvelopeItem(item3, type); options4.recordDroppedEvent("ratelimit_backoff", dataCategory, event); } else { filteredEnvelopeItems.push(item3); } }); if (filteredEnvelopeItems.length === 0) { return resolvedSyncPromise({}); } const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems); const recordEnvelopeLoss = /* @__PURE__ */ __name((reason) => { forEachEnvelopeItem(filteredEnvelope, (item3, type) => { const event = getEventForEnvelopeItem(item3, type); options4.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event); }); }, "recordEnvelopeLoss"); const requestTask = /* @__PURE__ */ __name(() => makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then( (response) => { if (response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) { DEBUG_BUILD$6 && logger$2.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); } rateLimits = updateRateLimits(rateLimits, response); return response; }, (error2) => { recordEnvelopeLoss("network_error"); throw error2; } ), "requestTask"); return buffer2.add(requestTask).then( (result) => result, (error2) => { if (error2 instanceof SentryError) { DEBUG_BUILD$6 && logger$2.error("Skipped sending event because buffer is full."); recordEnvelopeLoss("queue_overflow"); return resolvedSyncPromise({}); } else { throw error2; } } ); } __name(send, "send"); return { send, flush: flush2 }; } __name(createTransport, "createTransport"); function getEventForEnvelopeItem(item3, type) { if (type !== "event" && type !== "transaction") { return void 0; } return Array.isArray(item3) ? item3[1] : void 0; } __name(getEventForEnvelopeItem, "getEventForEnvelopeItem"); const MIN_DELAY = 100; const START_DELAY = 5e3; const MAX_DELAY = 36e5; function makeOfflineTransport(createTransport2) { function log2(...args) { DEBUG_BUILD$6 && logger$2.info("[Offline]:", ...args); } __name(log2, "log"); return (options4) => { const transport = createTransport2(options4); if (!options4.createStore) { throw new Error("No `createStore` function was provided"); } const store = options4.createStore(options4); let retryDelay = START_DELAY; let flushTimer; function shouldQueue(env, error2, retryDelay2) { if (envelopeContainsItemType(env, ["client_report"])) { return false; } if (options4.shouldStore) { return options4.shouldStore(env, error2, retryDelay2); } return true; } __name(shouldQueue, "shouldQueue"); function flushIn(delay) { if (flushTimer) { clearTimeout(flushTimer); } flushTimer = setTimeout(async () => { flushTimer = void 0; const found2 = await store.shift(); if (found2) { log2("Attempting to send previously queued event"); found2[0].sent_at = (/* @__PURE__ */ new Date()).toISOString(); void send(found2, true).catch((e2) => { log2("Failed to retry sending", e2); }); } }, delay); if (typeof flushTimer !== "number" && flushTimer.unref) { flushTimer.unref(); } } __name(flushIn, "flushIn"); function flushWithBackOff() { if (flushTimer) { return; } flushIn(retryDelay); retryDelay = Math.min(retryDelay * 2, MAX_DELAY); } __name(flushWithBackOff, "flushWithBackOff"); async function send(envelope, isRetry = false) { if (!isRetry && envelopeContainsItemType(envelope, ["replay_event", "replay_recording"])) { await store.push(envelope); flushIn(MIN_DELAY); return {}; } try { const result = await transport.send(envelope); let delay = MIN_DELAY; if (result) { if (result.headers && result.headers["retry-after"]) { delay = parseRetryAfterHeader(result.headers["retry-after"]); } else if (result.headers && result.headers["x-sentry-rate-limits"]) { delay = 6e4; } else if ((result.statusCode || 0) >= 400) { return result; } } flushIn(delay); retryDelay = START_DELAY; return result; } catch (e2) { if (await shouldQueue(envelope, e2, retryDelay)) { if (isRetry) { await store.unshift(envelope); } else { await store.push(envelope); } flushWithBackOff(); log2("Error sending. Event queued.", e2); return {}; } else { throw e2; } } } __name(send, "send"); if (options4.flushAtStartup) { flushWithBackOff(); } return { send, flush: /* @__PURE__ */ __name((t2) => transport.flush(t2), "flush") }; }; } __name(makeOfflineTransport, "makeOfflineTransport"); function eventFromEnvelope(env, types) { let event; forEachEnvelopeItem(env, (item3, type) => { if (types.includes(type)) { event = Array.isArray(item3) ? item3[1] : void 0; } return !!event; }); return event; } __name(eventFromEnvelope, "eventFromEnvelope"); function makeOverrideReleaseTransport(createTransport2, release) { return (options4) => { const transport = createTransport2(options4); return { ...transport, send: /* @__PURE__ */ __name(async (envelope) => { const event = eventFromEnvelope(envelope, ["event", "transaction", "profile", "replay_event"]); if (event) { event.release = release; } return transport.send(envelope); }, "send") }; }; } __name(makeOverrideReleaseTransport, "makeOverrideReleaseTransport"); function overrideDsn(envelope, dsn) { return createEnvelope( dsn ? { ...envelope[0], dsn } : envelope[0], envelope[1] ); } __name(overrideDsn, "overrideDsn"); function makeMultiplexedTransport(createTransport2, matcher) { return (options4) => { const fallbackTransport = createTransport2(options4); const otherTransports = /* @__PURE__ */ new Map(); function getTransport(dsn, release) { const key = release ? `${dsn}:${release}` : dsn; let transport = otherTransports.get(key); if (!transport) { const validatedDsn = dsnFromString(dsn); if (!validatedDsn) { return void 0; } const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options4.tunnel); transport = release ? makeOverrideReleaseTransport(createTransport2, release)({ ...options4, url }) : createTransport2({ ...options4, url }); otherTransports.set(key, transport); } return [dsn, transport]; } __name(getTransport, "getTransport"); async function send(envelope) { function getEvent(types) { const eventTypes = types && types.length ? types : ["event"]; return eventFromEnvelope(envelope, eventTypes); } __name(getEvent, "getEvent"); const transports = matcher({ envelope, getEvent }).map((result) => { if (typeof result === "string") { return getTransport(result, void 0); } else { return getTransport(result.dsn, result.release); } }).filter((t2) => !!t2); const transportsWithFallback = transports.length ? transports : [["", fallbackTransport]]; const results = await Promise.all( transportsWithFallback.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn))) ); return results[0]; } __name(send, "send"); async function flush2(timeout) { const allTransports = [...otherTransports.values(), fallbackTransport]; const results = await Promise.all(allTransports.map((transport) => transport.flush(timeout))); return results.every((r2) => r2); } __name(flush2, "flush"); return { send, flush: flush2 }; }; } __name(makeMultiplexedTransport, "makeMultiplexedTransport"); function isSentryRequestUrl(url, client) { const dsn = client && client.getDsn(); const tunnel = client && client.getOptions().tunnel; return checkDsn(url, dsn) || checkTunnel(url, tunnel); } __name(isSentryRequestUrl, "isSentryRequestUrl"); function checkTunnel(url, tunnel) { if (!tunnel) { return false; } return removeTrailingSlash$1(url) === removeTrailingSlash$1(tunnel); } __name(checkTunnel, "checkTunnel"); function checkDsn(url, dsn) { return dsn ? url.includes(dsn.host) : false; } __name(checkDsn, "checkDsn"); function removeTrailingSlash$1(str) { return str[str.length - 1] === "/" ? str.slice(0, -1) : str; } __name(removeTrailingSlash$1, "removeTrailingSlash$1"); function parameterize(strings, ...values) { const formatted = new String(String.raw(strings, ...values)); formatted.__sentry_template_string__ = strings.join("\0").replace(/%/g, "%%").replace(/\0/g, "%s"); formatted.__sentry_template_values__ = values; return formatted; } __name(parameterize, "parameterize"); function applySdkMetadata(options4, name2, names = [name2], source = "npm") { const metadata = options4._metadata || {}; if (!metadata.sdk) { metadata.sdk = { name: `sentry.javascript.${name2}`, packages: names.map((name3) => ({ name: `${source}:@sentry/${name3}`, version: SDK_VERSION })), version: SDK_VERSION }; } options4._metadata = metadata; } __name(applySdkMetadata, "applySdkMetadata"); function getTraceData(options4 = {}) { const client = getClient(); if (!isEnabled() || !client) { return {}; } const carrier = getMainCarrier(); const acs = getAsyncContextStrategy(carrier); if (acs.getTraceData) { return acs.getTraceData(options4); } const scope = getCurrentScope$1(); const span = options4.span || getActiveSpan(); const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope); const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope); const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc); const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace); if (!isValidSentryTraceHeader) { logger$2.warn("Invalid sentry-trace data. Cannot generate trace data"); return {}; } return { "sentry-trace": sentryTrace, baggage }; } __name(getTraceData, "getTraceData"); function scopeToTraceHeader(scope) { const { traceId, sampled, spanId } = scope.getPropagationContext(); return generateSentryTraceHeader(traceId, spanId, sampled); } __name(scopeToTraceHeader, "scopeToTraceHeader"); function getTraceMetaTags() { return Object.entries(getTraceData()).map(([key, value4]) => ``).join("\n"); } __name(getTraceMetaTags, "getTraceMetaTags"); const DEFAULT_BREADCRUMBS = 100; function addBreadcrumb(breadcrumb, hint) { const client = getClient(); const isolationScope = getIsolationScope(); if (!client) return; const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions(); if (maxBreadcrumbs <= 0) return; const timestamp2 = dateTimestampInSeconds(); const mergedBreadcrumb = { timestamp: timestamp2, ...breadcrumb }; const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb; if (finalBreadcrumb === null) return; if (client.emit) { client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint); } isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); } __name(addBreadcrumb, "addBreadcrumb"); let originalFunctionToString; const INTEGRATION_NAME$l = "FunctionToString"; const SETUP_CLIENTS$1 = /* @__PURE__ */ new WeakMap(); const _functionToStringIntegration = /* @__PURE__ */ __name(() => { return { name: INTEGRATION_NAME$l, setupOnce() { originalFunctionToString = Function.prototype.toString; try { Function.prototype.toString = function(...args) { const originalFunction = getOriginalFunction(this); const context = SETUP_CLIENTS$1.has(getClient()) && originalFunction !== void 0 ? originalFunction : this; return originalFunctionToString.apply(context, args); }; } catch (e2) { } }, setup(client) { SETUP_CLIENTS$1.set(client, true); } }; }, "_functionToStringIntegration"); const functionToStringIntegration = defineIntegration(_functionToStringIntegration); const DEFAULT_IGNORE_ERRORS = [ /^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/, /^ResizeObserver loop completed with undelivered notifications.$/, // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness. /^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker "undefined is not an object (evaluating 'a.L')", // Random error that happens but not actionable or noticeable to end-users. `can't redefine non-configurable property "solana"`, // Probably a browser extension or custom browser (Brave) throwing this error "vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)", // Error thrown by GTM, seemingly not affecting end-users "Can't find variable: _AutofillCallbackHandler", // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/ /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/ // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps ]; const INTEGRATION_NAME$k = "InboundFilters"; const _inboundFiltersIntegration = /* @__PURE__ */ __name((options4 = {}) => { return { name: INTEGRATION_NAME$k, processEvent(event, _hint, client) { const clientOptions = client.getOptions(); const mergedOptions = _mergeOptions(options4, clientOptions); return _shouldDropEvent$1(event, mergedOptions) ? null : event; } }; }, "_inboundFiltersIntegration"); const inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration); function _mergeOptions(internalOptions = {}, clientOptions = {}) { return { allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []], denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []], ignoreErrors: [ ...internalOptions.ignoreErrors || [], ...clientOptions.ignoreErrors || [], ...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS ], ignoreTransactions: [...internalOptions.ignoreTransactions || [], ...clientOptions.ignoreTransactions || []], ignoreInternal: internalOptions.ignoreInternal !== void 0 ? internalOptions.ignoreInternal : true }; } __name(_mergeOptions, "_mergeOptions"); function _shouldDropEvent$1(event, options4) { if (options4.ignoreInternal && _isSentryError(event)) { DEBUG_BUILD$6 && logger$2.warn(`Event dropped due to being internal Sentry Error. Event: ${getEventDescription(event)}`); return true; } if (_isIgnoredError(event, options4.ignoreErrors)) { DEBUG_BUILD$6 && logger$2.warn( `Event dropped due to being matched by \`ignoreErrors\` option. Event: ${getEventDescription(event)}` ); return true; } if (_isUselessError(event)) { DEBUG_BUILD$6 && logger$2.warn( `Event dropped due to not having an error message, error type or stacktrace. Event: ${getEventDescription( event )}` ); return true; } if (_isIgnoredTransaction(event, options4.ignoreTransactions)) { DEBUG_BUILD$6 && logger$2.warn( `Event dropped due to being matched by \`ignoreTransactions\` option. Event: ${getEventDescription(event)}` ); return true; } if (_isDeniedUrl(event, options4.denyUrls)) { DEBUG_BUILD$6 && logger$2.warn( `Event dropped due to being matched by \`denyUrls\` option. Event: ${getEventDescription( event )}. Url: ${_getEventFilterUrl(event)}` ); return true; } if (!_isAllowedUrl(event, options4.allowUrls)) { DEBUG_BUILD$6 && logger$2.warn( `Event dropped due to not being matched by \`allowUrls\` option. Event: ${getEventDescription( event )}. Url: ${_getEventFilterUrl(event)}` ); return true; } return false; } __name(_shouldDropEvent$1, "_shouldDropEvent$1"); function _isIgnoredError(event, ignoreErrors) { if (event.type || !ignoreErrors || !ignoreErrors.length) { return false; } return _getPossibleEventMessages(event).some((message3) => stringMatchesSomePattern(message3, ignoreErrors)); } __name(_isIgnoredError, "_isIgnoredError"); function _isIgnoredTransaction(event, ignoreTransactions) { if (event.type !== "transaction" || !ignoreTransactions || !ignoreTransactions.length) { return false; } const name2 = event.transaction; return name2 ? stringMatchesSomePattern(name2, ignoreTransactions) : false; } __name(_isIgnoredTransaction, "_isIgnoredTransaction"); function _isDeniedUrl(event, denyUrls) { if (!denyUrls || !denyUrls.length) { return false; } const url = _getEventFilterUrl(event); return !url ? false : stringMatchesSomePattern(url, denyUrls); } __name(_isDeniedUrl, "_isDeniedUrl"); function _isAllowedUrl(event, allowUrls) { if (!allowUrls || !allowUrls.length) { return true; } const url = _getEventFilterUrl(event); return !url ? true : stringMatchesSomePattern(url, allowUrls); } __name(_isAllowedUrl, "_isAllowedUrl"); function _getPossibleEventMessages(event) { const possibleMessages = []; if (event.message) { possibleMessages.push(event.message); } let lastException; try { lastException = event.exception.values[event.exception.values.length - 1]; } catch (e2) { } if (lastException) { if (lastException.value) { possibleMessages.push(lastException.value); if (lastException.type) { possibleMessages.push(`${lastException.type}: ${lastException.value}`); } } } return possibleMessages; } __name(_getPossibleEventMessages, "_getPossibleEventMessages"); function _isSentryError(event) { try { return event.exception.values[0].type === "SentryError"; } catch (e2) { } return false; } __name(_isSentryError, "_isSentryError"); function _getLastValidUrl(frames = []) { for (let i2 = frames.length - 1; i2 >= 0; i2--) { const frame = frames[i2]; if (frame && frame.filename !== "" && frame.filename !== "[native code]") { return frame.filename || null; } } return null; } __name(_getLastValidUrl, "_getLastValidUrl"); function _getEventFilterUrl(event) { try { let frames; try { frames = event.exception.values[0].stacktrace.frames; } catch (e2) { } return frames ? _getLastValidUrl(frames) : null; } catch (oO) { DEBUG_BUILD$6 && logger$2.error(`Cannot extract url for event ${getEventDescription(event)}`); return null; } } __name(_getEventFilterUrl, "_getEventFilterUrl"); function _isUselessError(event) { if (event.type) { return false; } if (!event.exception || !event.exception.values || event.exception.values.length === 0) { return false; } return ( // No top-level message !event.message && // There are no exception values that have a stacktrace, a non-generic-Error type or value !event.exception.values.some((value4) => value4.stacktrace || value4.type && value4.type !== "Error" || value4.value) ); } __name(_isUselessError, "_isUselessError"); function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, maxValueLimit = 250, key, limit, event, hint) { if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) { return; } const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : void 0; if (originalException) { event.exception.values = truncateAggregateExceptions( aggregateExceptionsFromError( exceptionFromErrorImplementation, parser, limit, hint.originalException, key, event.exception.values, originalException, 0 ), maxValueLimit ); } } __name(applyAggregateErrorsToEvent, "applyAggregateErrorsToEvent"); function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error2, key, prevExceptions, exception, exceptionId) { if (prevExceptions.length >= limit + 1) { return prevExceptions; } let newExceptions = [...prevExceptions]; if (isInstanceOf(error2[key], Error)) { applyExceptionGroupFieldsForParentException(exception, exceptionId); const newException = exceptionFromErrorImplementation(parser, error2[key]); const newExceptionId = newExceptions.length; applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId); newExceptions = aggregateExceptionsFromError( exceptionFromErrorImplementation, parser, limit, error2[key], key, [newException, ...newExceptions], newException, newExceptionId ); } if (Array.isArray(error2.errors)) { error2.errors.forEach((childError, i2) => { if (isInstanceOf(childError, Error)) { applyExceptionGroupFieldsForParentException(exception, exceptionId); const newException = exceptionFromErrorImplementation(parser, childError); const newExceptionId = newExceptions.length; applyExceptionGroupFieldsForChildException(newException, `errors[${i2}]`, newExceptionId, exceptionId); newExceptions = aggregateExceptionsFromError( exceptionFromErrorImplementation, parser, limit, childError, key, [newException, ...newExceptions], newException, newExceptionId ); } }); } return newExceptions; } __name(aggregateExceptionsFromError, "aggregateExceptionsFromError"); function applyExceptionGroupFieldsForParentException(exception, exceptionId) { exception.mechanism = exception.mechanism || { type: "generic", handled: true }; exception.mechanism = { ...exception.mechanism, ...exception.type === "AggregateError" && { is_exception_group: true }, exception_id: exceptionId }; } __name(applyExceptionGroupFieldsForParentException, "applyExceptionGroupFieldsForParentException"); function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) { exception.mechanism = exception.mechanism || { type: "generic", handled: true }; exception.mechanism = { ...exception.mechanism, type: "chained", source, exception_id: exceptionId, parent_id: parentId }; } __name(applyExceptionGroupFieldsForChildException, "applyExceptionGroupFieldsForChildException"); function truncateAggregateExceptions(exceptions, maxValueLength) { return exceptions.map((exception) => { if (exception.value) { exception.value = truncate(exception.value, maxValueLength); } return exception; }); } __name(truncateAggregateExceptions, "truncateAggregateExceptions"); const DEFAULT_KEY$1 = "cause"; const DEFAULT_LIMIT$2 = 5; const INTEGRATION_NAME$j = "LinkedErrors"; const _linkedErrorsIntegration$1 = /* @__PURE__ */ __name((options4 = {}) => { const limit = options4.limit || DEFAULT_LIMIT$2; const key = options4.key || DEFAULT_KEY$1; return { name: INTEGRATION_NAME$j, preprocessEvent(event, hint, client) { const options5 = client.getOptions(); applyAggregateErrorsToEvent( exceptionFromError$1, options5.stackParser, options5.maxValueLength, key, limit, event, hint ); } }; }, "_linkedErrorsIntegration$1"); const linkedErrorsIntegration$1 = defineIntegration(_linkedErrorsIntegration$1); const filenameMetadataMap = /* @__PURE__ */ new Map(); const parsedStacks = /* @__PURE__ */ new Set(); function ensureMetadataStacksAreParsed(parser) { if (!GLOBAL_OBJ._sentryModuleMetadata) { return; } for (const stack2 of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) { const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack2]; if (parsedStacks.has(stack2)) { continue; } parsedStacks.add(stack2); const frames = parser(stack2); for (const frame of frames.reverse()) { if (frame.filename) { filenameMetadataMap.set(frame.filename, metadata); break; } } } } __name(ensureMetadataStacksAreParsed, "ensureMetadataStacksAreParsed"); function getMetadataForUrl(parser, filename) { ensureMetadataStacksAreParsed(parser); return filenameMetadataMap.get(filename); } __name(getMetadataForUrl, "getMetadataForUrl"); function addMetadataToStackFrames(parser, event) { try { event.exception.values.forEach((exception) => { if (!exception.stacktrace) { return; } for (const frame of exception.stacktrace.frames || []) { if (!frame.filename || frame.module_metadata) { continue; } const metadata = getMetadataForUrl(parser, frame.filename); if (metadata) { frame.module_metadata = metadata; } } }); } catch (_2) { } } __name(addMetadataToStackFrames, "addMetadataToStackFrames"); function stripMetadataFromStackFrames(event) { try { event.exception.values.forEach((exception) => { if (!exception.stacktrace) { return; } for (const frame of exception.stacktrace.frames || []) { delete frame.module_metadata; } }); } catch (_2) { } } __name(stripMetadataFromStackFrames, "stripMetadataFromStackFrames"); const moduleMetadataIntegration = defineIntegration(() => { return { name: "ModuleMetadata", setup(client) { client.on("beforeEnvelope", (envelope) => { forEachEnvelopeItem(envelope, (item3, type) => { if (type === "event") { const event = Array.isArray(item3) ? item3[1] : void 0; if (event) { stripMetadataFromStackFrames(event); item3[1] = event; } } }); }); client.on("applyFrameMetadata", (event) => { if (event.type) { return; } const stackParser = client.getOptions().stackParser; addMetadataToStackFrames(stackParser, event); }); } }; }); function parseCookie(str) { const obj = {}; let index2 = 0; while (index2 < str.length) { const eqIdx = str.indexOf("=", index2); if (eqIdx === -1) { break; } let endIdx = str.indexOf(";", index2); if (endIdx === -1) { endIdx = str.length; } else if (endIdx < eqIdx) { index2 = str.lastIndexOf(";", eqIdx - 1) + 1; continue; } const key = str.slice(index2, eqIdx).trim(); if (void 0 === obj[key]) { let val = str.slice(eqIdx + 1, endIdx).trim(); if (val.charCodeAt(0) === 34) { val = val.slice(1, -1); } try { obj[key] = val.indexOf("%") !== -1 ? decodeURIComponent(val) : val; } catch (e2) { obj[key] = val; } } index2 = endIdx + 1; } return obj; } __name(parseCookie, "parseCookie"); function parseUrl$1(url) { if (!url) { return {}; } const match2 = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); if (!match2) { return {}; } const query = match2[6] || ""; const fragment = match2[8] || ""; return { host: match2[4], path: match2[5], protocol: match2[2], search: query, hash: fragment, relative: match2[5] + query + fragment // everything minus origin }; } __name(parseUrl$1, "parseUrl$1"); function stripUrlQueryAndFragment(urlPath) { return urlPath.split(/[?#]/, 1)[0]; } __name(stripUrlQueryAndFragment, "stripUrlQueryAndFragment"); function getNumberOfUrlSegments(url) { return url.split(/\\?\//).filter((s2) => s2.length > 0 && s2 !== ",").length; } __name(getNumberOfUrlSegments, "getNumberOfUrlSegments"); function getSanitizedUrlString(url) { const { protocol, host, path } = url; const filteredHost = host && host.replace(/^.*@/, "[filtered]:[filtered]@").replace(/(:80)$/, "").replace(/(:443)$/, "") || ""; return `${protocol ? `${protocol}://` : ""}${filteredHost}${path}`; } __name(getSanitizedUrlString, "getSanitizedUrlString"); const ipHeaderNames = [ "X-Client-IP", "X-Forwarded-For", "Fly-Client-IP", "CF-Connecting-IP", "Fastly-Client-Ip", "True-Client-Ip", "X-Real-IP", "X-Cluster-Client-IP", "X-Forwarded", "Forwarded-For", "Forwarded", "X-Vercel-Forwarded-For" ]; function getClientIPAddress(headers) { const headerValues = ipHeaderNames.map((headerName) => { const rawValue = headers[headerName]; const value4 = Array.isArray(rawValue) ? rawValue.join(";") : rawValue; if (headerName === "Forwarded") { return parseForwardedHeader(value4); } return value4 && value4.split(",").map((v2) => v2.trim()); }); const flattenedHeaderValues = headerValues.reduce((acc, val) => { if (!val) { return acc; } return acc.concat(val); }, []); const ipAddress = flattenedHeaderValues.find((ip) => ip !== null && isIP(ip)); return ipAddress || null; } __name(getClientIPAddress, "getClientIPAddress"); function parseForwardedHeader(value4) { if (!value4) { return null; } for (const part of value4.split(";")) { if (part.startsWith("for=")) { return part.slice(4); } } return null; } __name(parseForwardedHeader, "parseForwardedHeader"); function isIP(str) { const regex2 = /(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-fA-F\d]{1,4}:){7}(?:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-fA-F\d]{1,4}|:)|(?:[a-fA-F\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,2}|:)|(?:[a-fA-F\d]{1,4}:){4}(?:(?::[a-fA-F\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,3}|:)|(?:[a-fA-F\d]{1,4}:){3}(?:(?::[a-fA-F\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,4}|:)|(?:[a-fA-F\d]{1,4}:){2}(?:(?::[a-fA-F\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,5}|:)|(?:[a-fA-F\d]{1,4}:){1}(?:(?::[a-fA-F\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-fA-F\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$)/; return regex2.test(str); } __name(isIP, "isIP"); const DEFAULT_INCLUDES = { ip: false, request: true, user: true }; const DEFAULT_REQUEST_INCLUDES = ["cookies", "data", "headers", "method", "query_string", "url"]; const DEFAULT_USER_INCLUDES = ["id", "username", "email"]; function extractPathForTransaction(req, options4 = {}) { const method = req.method && req.method.toUpperCase(); let path = ""; let source = "url"; if (options4.customRoute || req.route) { path = options4.customRoute || `${req.baseUrl || ""}${req.route && req.route.path}`; source = "route"; } else if (req.originalUrl || req.url) { path = stripUrlQueryAndFragment(req.originalUrl || req.url || ""); } let name2 = ""; if (options4.method && method) { name2 += method; } if (options4.method && options4.path) { name2 += " "; } if (options4.path && path) { name2 += path; } return [name2, source]; } __name(extractPathForTransaction, "extractPathForTransaction"); function extractUserData(user, keys2) { const extractedUser = {}; const attributes = Array.isArray(keys2) ? keys2 : DEFAULT_USER_INCLUDES; attributes.forEach((key) => { if (user && key in user) { extractedUser[key] = user[key]; } }); return extractedUser; } __name(extractUserData, "extractUserData"); function extractRequestData(req, options4 = {}) { const { include = DEFAULT_REQUEST_INCLUDES } = options4; const requestData = {}; const headers = req.headers || {}; const method = req.method; const host = headers.host || req.hostname || req.host || ""; const protocol = req.protocol === "https" || req.socket && req.socket.encrypted ? "https" : "http"; const originalUrl = req.originalUrl || req.url || ""; const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; include.forEach((key) => { switch (key) { case "headers": { requestData.headers = headers; if (!include.includes("cookies")) { delete requestData.headers.cookie; } if (!include.includes("ip")) { ipHeaderNames.forEach((ipHeaderName) => { delete requestData.headers[ipHeaderName]; }); } break; } case "method": { requestData.method = method; break; } case "url": { requestData.url = absoluteUrl; break; } case "cookies": { 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 && parseCookie(headers.cookie) || {}; break; } case "query_string": { requestData.query_string = extractQueryParams(req); break; } case "data": { if (method === "GET" || method === "HEAD") { break; } const body = req.body; if (body !== void 0) { const stringBody = isString$8(body) ? body : isPlainObject$5(body) ? JSON.stringify(normalize$2(body)) : truncate(`${body}`, 1024); if (stringBody) { requestData.data = stringBody; } } break; } default: { if ({}.hasOwnProperty.call(req, key)) { requestData[key] = req[key]; } } } }); return requestData; } __name(extractRequestData, "extractRequestData"); function addNormalizedRequestDataToEvent(event, req, additionalData, options4) { const include = { ...DEFAULT_INCLUDES, ...options4 && options4.include }; if (include.request) { const includeRequest = Array.isArray(include.request) ? [...include.request] : [...DEFAULT_REQUEST_INCLUDES]; if (include.ip) { includeRequest.push("ip"); } const extractedRequestData = extractNormalizedRequestData(req, { include: includeRequest }); event.request = { ...event.request, ...extractedRequestData }; } if (include.user) { const extractedUser = additionalData.user && isPlainObject$5(additionalData.user) ? extractUserData(additionalData.user, include.user) : {}; if (Object.keys(extractedUser).length) { event.user = { ...extractedUser, ...event.user }; } } if (include.ip) { const ip = req.headers && getClientIPAddress(req.headers) || additionalData.ipAddress; if (ip) { event.user = { ...event.user, ip_address: ip }; } } } __name(addNormalizedRequestDataToEvent, "addNormalizedRequestDataToEvent"); function addRequestDataToEvent(event, req, options4) { const include = { ...DEFAULT_INCLUDES, ...options4 && options4.include }; if (include.request) { const includeRequest = Array.isArray(include.request) ? [...include.request] : [...DEFAULT_REQUEST_INCLUDES]; if (include.ip) { includeRequest.push("ip"); } const extractedRequestData = extractRequestData(req, { include: includeRequest }); event.request = { ...event.request, ...extractedRequestData }; } if (include.user) { const extractedUser = req.user && isPlainObject$5(req.user) ? extractUserData(req.user, include.user) : {}; if (Object.keys(extractedUser).length) { event.user = { ...event.user, ...extractedUser }; } } if (include.ip) { const ip = req.headers && getClientIPAddress(req.headers) || req.ip || req.socket && req.socket.remoteAddress; if (ip) { event.user = { ...event.user, ip_address: ip }; } } return event; } __name(addRequestDataToEvent, "addRequestDataToEvent"); function extractQueryParams(req) { let originalUrl = req.originalUrl || req.url || ""; if (!originalUrl) { return; } if (originalUrl.startsWith("/")) { originalUrl = `http://dogs.are.great${originalUrl}`; } try { const queryParams = req.query || new URL(originalUrl).search.slice(1); return queryParams.length ? queryParams : void 0; } catch (e2) { return void 0; } } __name(extractQueryParams, "extractQueryParams"); function winterCGHeadersToDict(winterCGHeaders) { const headers = {}; try { winterCGHeaders.forEach((value4, key) => { if (typeof value4 === "string") { headers[key] = value4; } }); } catch (e2) { DEBUG_BUILD$5 && logger$2.warn("Sentry failed extracting headers from a request object. If you see this, please file an issue."); } return headers; } __name(winterCGHeadersToDict, "winterCGHeadersToDict"); function headersToDict(reqHeaders) { const headers = /* @__PURE__ */ Object.create(null); try { Object.entries(reqHeaders).forEach(([key, value4]) => { if (typeof value4 === "string") { headers[key] = value4; } }); } catch (e2) { DEBUG_BUILD$5 && logger$2.warn("Sentry failed extracting headers from a request object. If you see this, please file an issue."); } return headers; } __name(headersToDict, "headersToDict"); function winterCGRequestToRequestData(req) { const headers = winterCGHeadersToDict(req.headers); return { method: req.method, url: req.url, query_string: extractQueryParamsFromUrl(req.url), headers // TODO: Can we extract body data from the request? }; } __name(winterCGRequestToRequestData, "winterCGRequestToRequestData"); function httpRequestToRequestData(request) { const headers = request.headers || {}; const host = headers.host || ""; const protocol = request.socket && request.socket.encrypted ? "https" : "http"; const originalUrl = request.url || ""; const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; const data25 = request.body || void 0; const cookies2 = request.cookies; return dropUndefinedKeys({ url: absoluteUrl, method: request.method, query_string: extractQueryParamsFromUrl(originalUrl), headers: headersToDict(headers), cookies: cookies2, data: data25 }); } __name(httpRequestToRequestData, "httpRequestToRequestData"); function extractQueryParamsFromUrl(url) { if (!url) { return; } try { const queryParams = new URL(url, "http://dogs.are.great").search.slice(1); return queryParams.length ? queryParams : void 0; } catch (e3) { return void 0; } } __name(extractQueryParamsFromUrl, "extractQueryParamsFromUrl"); function extractNormalizedRequestData(normalizedRequest, { include }) { const includeKeys = include ? Array.isArray(include) ? include : DEFAULT_REQUEST_INCLUDES : []; const requestData = {}; const headers = { ...normalizedRequest.headers }; if (includeKeys.includes("headers")) { requestData.headers = headers; if (!include.includes("cookies")) { delete headers.cookie; } if (!include.includes("ip")) { ipHeaderNames.forEach((ipHeaderName) => { delete headers[ipHeaderName]; }); } } if (includeKeys.includes("method")) { requestData.method = normalizedRequest.method; } if (includeKeys.includes("url")) { requestData.url = normalizedRequest.url; } if (includeKeys.includes("cookies")) { const cookies2 = normalizedRequest.cookies || (headers && headers.cookie ? parseCookie(headers.cookie) : void 0); requestData.cookies = cookies2 || {}; } if (includeKeys.includes("query_string")) { requestData.query_string = normalizedRequest.query_string; } if (includeKeys.includes("data")) { requestData.data = normalizedRequest.data; } return requestData; } __name(extractNormalizedRequestData, "extractNormalizedRequestData"); const DEFAULT_OPTIONS$1 = { include: { cookies: true, data: true, headers: true, ip: false, query_string: true, url: true, user: { id: true, username: true, email: true } }, transactionNamingScheme: "methodPath" }; const INTEGRATION_NAME$i = "RequestData"; const _requestDataIntegration = /* @__PURE__ */ __name((options4 = {}) => { const _options = { ...DEFAULT_OPTIONS$1, ...options4, include: { ...DEFAULT_OPTIONS$1.include, ...options4.include, user: options4.include && typeof options4.include.user === "boolean" ? options4.include.user : { ...DEFAULT_OPTIONS$1.include.user, // Unclear why TS still thinks `options.include.user` could be a boolean at this point ...(options4.include || {}).user } } }; return { name: INTEGRATION_NAME$i, processEvent(event) { const { sdkProcessingMetadata = {} } = event; const { request, normalizedRequest } = sdkProcessingMetadata; const addRequestDataOptions = convertReqDataIntegrationOptsToAddReqDataOpts(_options); if (normalizedRequest) { const ipAddress = request ? request.ip || request.socket && request.socket.remoteAddress : void 0; const user = request ? request.user : void 0; addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress, user }, addRequestDataOptions); return event; } if (!request) { return event; } return addRequestDataToEvent(event, request, addRequestDataOptions); } }; }, "_requestDataIntegration"); const requestDataIntegration = defineIntegration(_requestDataIntegration); function convertReqDataIntegrationOptsToAddReqDataOpts(integrationOptions) { const { // eslint-disable-next-line deprecation/deprecation transactionNamingScheme, include: { ip, user, ...requestOptions } } = integrationOptions; const requestIncludeKeys = ["method"]; for (const [key, value4] of Object.entries(requestOptions)) { if (value4) { requestIncludeKeys.push(key); } } let addReqDataUserOpt; if (user === void 0) { addReqDataUserOpt = true; } else if (typeof user === "boolean") { addReqDataUserOpt = user; } else { const userIncludeKeys = []; for (const [key, value4] of Object.entries(user)) { if (value4) { userIncludeKeys.push(key); } } addReqDataUserOpt = userIncludeKeys; } return { include: { ip, user: addReqDataUserOpt, request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : void 0, transaction: transactionNamingScheme } }; } __name(convertReqDataIntegrationOptsToAddReqDataOpts, "convertReqDataIntegrationOptsToAddReqDataOpts"); function addConsoleInstrumentationHandler(handler6) { const type = "console"; addHandler$1(type, handler6); maybeInstrument(type, instrumentConsole); } __name(addConsoleInstrumentationHandler, "addConsoleInstrumentationHandler"); function instrumentConsole() { if (!("console" in GLOBAL_OBJ)) { return; } CONSOLE_LEVELS$1.forEach(function(level) { if (!(level in GLOBAL_OBJ.console)) { return; } fill(GLOBAL_OBJ.console, level, function(originalConsoleMethod) { originalConsoleMethods[level] = originalConsoleMethod; return function(...args) { const handlerData = { args, level }; triggerHandlers$1("console", handlerData); const log2 = originalConsoleMethods[level]; log2 && log2.apply(GLOBAL_OBJ.console, args); }; }); }); } __name(instrumentConsole, "instrumentConsole"); const validSeverityLevels = ["fatal", "error", "warning", "log", "info", "debug"]; function severityLevelFromString(level) { return level === "warn" ? "warning" : ["fatal", "error", "warning", "log", "info", "debug"].includes(level) ? level : "log"; } __name(severityLevelFromString, "severityLevelFromString"); const INTEGRATION_NAME$h = "CaptureConsole"; const _captureConsoleIntegration = /* @__PURE__ */ __name((options4 = {}) => { const levels = options4.levels || CONSOLE_LEVELS$1; const handled = !!options4.handled; return { name: INTEGRATION_NAME$h, setup(client) { if (!("console" in GLOBAL_OBJ)) { return; } addConsoleInstrumentationHandler(({ args, level }) => { if (getClient() !== client || !levels.includes(level)) { return; } consoleHandler(args, level, handled); }); } }; }, "_captureConsoleIntegration"); const captureConsoleIntegration = defineIntegration(_captureConsoleIntegration); function consoleHandler(args, level, handled) { const captureContext = { level: severityLevelFromString(level), extra: { arguments: args } }; withScope((scope) => { scope.addEventProcessor((event) => { event.logger = "console"; addExceptionMechanism(event, { handled, type: "console" }); return event; }); if (level === "assert") { if (!args[0]) { const message4 = `Assertion failed: ${safeJoin(args.slice(1), " ") || "console.assert"}`; scope.setExtra("arguments", args.slice(1)); captureMessage(message4, captureContext); } return; } const error2 = args.find((arg) => arg instanceof Error); if (error2) { captureException(error2, captureContext); return; } const message3 = safeJoin(args, " "); captureMessage(message3, captureContext); }); } __name(consoleHandler, "consoleHandler"); const INTEGRATION_NAME$g = "Debug"; const _debugIntegration = /* @__PURE__ */ __name((options4 = {}) => { const _options = { debugger: false, stringify: false, ...options4 }; return { name: INTEGRATION_NAME$g, setup(client) { client.on("beforeSendEvent", (event, hint) => { if (_options.debugger) { debugger; } consoleSandbox(() => { if (_options.stringify) { console.log(JSON.stringify(event, null, 2)); if (hint && Object.keys(hint).length) { console.log(JSON.stringify(hint, null, 2)); } } else { console.log(event); if (hint && Object.keys(hint).length) { console.log(hint); } } }); }); } }; }, "_debugIntegration"); const debugIntegration = defineIntegration(_debugIntegration); const INTEGRATION_NAME$f = "Dedupe"; const _dedupeIntegration = /* @__PURE__ */ __name(() => { let previousEvent; return { name: INTEGRATION_NAME$f, processEvent(currentEvent) { if (currentEvent.type) { return currentEvent; } try { if (_shouldDropEvent(currentEvent, previousEvent)) { DEBUG_BUILD$6 && logger$2.warn("Event dropped due to being a duplicate of previously captured event."); return null; } } catch (_oO) { } return previousEvent = currentEvent; } }; }, "_dedupeIntegration"); const dedupeIntegration = defineIntegration(_dedupeIntegration); function _shouldDropEvent(currentEvent, previousEvent) { if (!previousEvent) { return false; } if (_isSameMessageEvent(currentEvent, previousEvent)) { return true; } if (_isSameExceptionEvent(currentEvent, previousEvent)) { return true; } return false; } __name(_shouldDropEvent, "_shouldDropEvent"); function _isSameMessageEvent(currentEvent, previousEvent) { const currentMessage = currentEvent.message; const previousMessage = previousEvent.message; if (!currentMessage && !previousMessage) { return false; } if (currentMessage && !previousMessage || !currentMessage && previousMessage) { return false; } if (currentMessage !== previousMessage) { return false; } if (!_isSameFingerprint(currentEvent, previousEvent)) { return false; } if (!_isSameStacktrace(currentEvent, previousEvent)) { return false; } return true; } __name(_isSameMessageEvent, "_isSameMessageEvent"); function _isSameExceptionEvent(currentEvent, previousEvent) { const previousException = _getExceptionFromEvent(previousEvent); const currentException = _getExceptionFromEvent(currentEvent); if (!previousException || !currentException) { return false; } if (previousException.type !== currentException.type || previousException.value !== currentException.value) { return false; } if (!_isSameFingerprint(currentEvent, previousEvent)) { return false; } if (!_isSameStacktrace(currentEvent, previousEvent)) { return false; } return true; } __name(_isSameExceptionEvent, "_isSameExceptionEvent"); function _isSameStacktrace(currentEvent, previousEvent) { let currentFrames = getFramesFromEvent(currentEvent); let previousFrames = getFramesFromEvent(previousEvent); if (!currentFrames && !previousFrames) { return true; } if (currentFrames && !previousFrames || !currentFrames && previousFrames) { return false; } currentFrames = currentFrames; previousFrames = previousFrames; if (previousFrames.length !== currentFrames.length) { return false; } for (let i2 = 0; i2 < previousFrames.length; i2++) { const frameA = previousFrames[i2]; const frameB = currentFrames[i2]; if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) { return false; } } return true; } __name(_isSameStacktrace, "_isSameStacktrace"); function _isSameFingerprint(currentEvent, previousEvent) { let currentFingerprint = currentEvent.fingerprint; let previousFingerprint = previousEvent.fingerprint; if (!currentFingerprint && !previousFingerprint) { return true; } if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) { return false; } currentFingerprint = currentFingerprint; previousFingerprint = previousFingerprint; try { return !!(currentFingerprint.join("") === previousFingerprint.join("")); } catch (_oO) { return false; } } __name(_isSameFingerprint, "_isSameFingerprint"); function _getExceptionFromEvent(event) { return event.exception && event.exception.values && event.exception.values[0]; } __name(_getExceptionFromEvent, "_getExceptionFromEvent"); const INTEGRATION_NAME$e = "ExtraErrorData"; const _extraErrorDataIntegration = /* @__PURE__ */ __name((options4 = {}) => { const { depth = 3, captureErrorCause = true } = options4; return { name: INTEGRATION_NAME$e, processEvent(event, hint, client) { const { maxValueLength = 250 } = client.getOptions(); return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause, maxValueLength); } }; }, "_extraErrorDataIntegration"); const extraErrorDataIntegration = defineIntegration(_extraErrorDataIntegration); function _enhanceEventWithErrorData(event, hint = {}, depth, captureErrorCause, maxValueLength) { if (!hint.originalException || !isError(hint.originalException)) { return event; } const exceptionName = hint.originalException.name || hint.originalException.constructor.name; const errorData = _extractErrorData(hint.originalException, captureErrorCause, maxValueLength); if (errorData) { const contexts = { ...event.contexts }; const normalizedErrorData = normalize$2(errorData, depth); if (isPlainObject$5(normalizedErrorData)) { addNonEnumerableProperty(normalizedErrorData, "__sentry_skip_normalization__", true); contexts[exceptionName] = normalizedErrorData; } return { ...event, contexts }; } return event; } __name(_enhanceEventWithErrorData, "_enhanceEventWithErrorData"); function _extractErrorData(error2, captureErrorCause, maxValueLength) { try { const nativeKeys2 = [ "name", "message", "stack", "line", "column", "fileName", "lineNumber", "columnNumber", "toJSON" ]; const extraErrorInfo = {}; for (const key of Object.keys(error2)) { if (nativeKeys2.indexOf(key) !== -1) { continue; } const value4 = error2[key]; extraErrorInfo[key] = isError(value4) || typeof value4 === "string" ? truncate(`${value4}`, maxValueLength) : value4; } if (captureErrorCause && error2.cause !== void 0) { extraErrorInfo.cause = isError(error2.cause) ? error2.cause.toString() : error2.cause; } if (typeof error2.toJSON === "function") { const serializedError = error2.toJSON(); for (const key of Object.keys(serializedError)) { const value4 = serializedError[key]; extraErrorInfo[key] = isError(value4) ? value4.toString() : value4; } } return extraErrorInfo; } catch (oO) { DEBUG_BUILD$6 && logger$2.error("Unable to extract extra data from the Error object:", oO); } return null; } __name(_extractErrorData, "_extractErrorData"); function normalizeArray(parts2, allowAboveRoot) { let up = 0; for (let i2 = parts2.length - 1; i2 >= 0; i2--) { const last = parts2[i2]; if (last === ".") { parts2.splice(i2, 1); } else if (last === "..") { parts2.splice(i2, 1); up++; } else if (up) { parts2.splice(i2, 1); up--; } } if (allowAboveRoot) { for (; up--; up) { parts2.unshift(".."); } } return parts2; } __name(normalizeArray, "normalizeArray"); const splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/; function splitPath(filename) { const truncated = filename.length > 1024 ? `${filename.slice(-1024)}` : filename; const parts2 = splitPathRe.exec(truncated); return parts2 ? parts2.slice(1) : []; } __name(splitPath, "splitPath"); function resolve$1(...args) { let resolvedPath = ""; let resolvedAbsolute = false; for (let i2 = args.length - 1; i2 >= -1 && !resolvedAbsolute; i2--) { const path = i2 >= 0 ? args[i2] : "/"; if (!path) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = path.charAt(0) === "/"; } resolvedPath = normalizeArray( resolvedPath.split("/").filter((p2) => !!p2), !resolvedAbsolute ).join("/"); return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; } __name(resolve$1, "resolve$1"); function trim$1(arr) { let start2 = 0; for (; start2 < arr.length; start2++) { if (arr[start2] !== "") { break; } } let end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== "") { break; } } if (start2 > end) { return []; } return arr.slice(start2, end - start2 + 1); } __name(trim$1, "trim$1"); function relative(from2, to) { from2 = resolve$1(from2).slice(1); to = resolve$1(to).slice(1); const fromParts = trim$1(from2.split("/")); const toParts = trim$1(to.split("/")); const length = Math.min(fromParts.length, toParts.length); let samePartsLength = length; for (let i2 = 0; i2 < length; i2++) { if (fromParts[i2] !== toParts[i2]) { samePartsLength = i2; break; } } let outputParts = []; for (let i2 = samePartsLength; i2 < fromParts.length; i2++) { outputParts.push(".."); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join("/"); } __name(relative, "relative"); function normalizePath(path) { const isPathAbsolute = isAbsolute(path); const trailingSlash = path.slice(-1) === "/"; let normalizedPath = normalizeArray( path.split("/").filter((p2) => !!p2), !isPathAbsolute ).join("/"); if (!normalizedPath && !isPathAbsolute) { normalizedPath = "."; } if (normalizedPath && trailingSlash) { normalizedPath += "/"; } return (isPathAbsolute ? "/" : "") + normalizedPath; } __name(normalizePath, "normalizePath"); function isAbsolute(path) { return path.charAt(0) === "/"; } __name(isAbsolute, "isAbsolute"); function join$3(...args) { return normalizePath(args.join("/")); } __name(join$3, "join$3"); function dirname(path) { const result = splitPath(path); const root27 = result[0] || ""; let dir = result[1]; if (!root27 && !dir) { return "."; } if (dir) { dir = dir.slice(0, dir.length - 1); } return root27 + dir; } __name(dirname, "dirname"); function basename(path, ext) { let f2 = splitPath(path)[2] || ""; if (ext && f2.slice(ext.length * -1) === ext) { f2 = f2.slice(0, f2.length - ext.length); } return f2; } __name(basename, "basename"); const INTEGRATION_NAME$d = "RewriteFrames"; const rewriteFramesIntegration = defineIntegration((options4 = {}) => { const root27 = options4.root; const prefix2 = options4.prefix || "app:///"; const isBrowser2 = "window" in GLOBAL_OBJ && GLOBAL_OBJ.window !== void 0; const iteratee = options4.iteratee || generateIteratee({ isBrowser: isBrowser2, root: root27, prefix: prefix2 }); function _processExceptionsEvent(event) { try { return { ...event, exception: { ...event.exception, // The check for this is performed inside `process` call itself, safe to skip here // eslint-disable-next-line @typescript-eslint/no-non-null-assertion values: event.exception.values.map((value4) => ({ ...value4, ...value4.stacktrace && { stacktrace: _processStacktrace(value4.stacktrace) } })) } }; } catch (_oO) { return event; } } __name(_processExceptionsEvent, "_processExceptionsEvent"); function _processStacktrace(stacktrace) { return { ...stacktrace, frames: stacktrace && stacktrace.frames && stacktrace.frames.map((f2) => iteratee(f2)) }; } __name(_processStacktrace, "_processStacktrace"); return { name: INTEGRATION_NAME$d, processEvent(originalEvent) { let processedEvent = originalEvent; if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) { processedEvent = _processExceptionsEvent(processedEvent); } return processedEvent; } }; }); function generateIteratee({ isBrowser: isBrowser2, root: root27, prefix: prefix2 }) { return (frame) => { if (!frame.filename) { return frame; } const isWindowsFrame = /^[a-zA-Z]:\\/.test(frame.filename) || // or the presence of a backslash without a forward slash (which are not allowed on Windows) frame.filename.includes("\\") && !frame.filename.includes("/"); const startsWithSlash = /^\//.test(frame.filename); if (isBrowser2) { if (root27) { const oldFilename = frame.filename; if (oldFilename.indexOf(root27) === 0) { frame.filename = oldFilename.replace(root27, prefix2); } } } else { if (isWindowsFrame || startsWithSlash) { const filename = isWindowsFrame ? frame.filename.replace(/^[a-zA-Z]:/, "").replace(/\\/g, "/") : frame.filename; const base2 = root27 ? relative(root27, filename) : basename(filename); frame.filename = `${prefix2}${base2}`; } } return frame; }; } __name(generateIteratee, "generateIteratee"); const INTEGRATION_NAME$c = "SessionTiming"; const _sessionTimingIntegration = /* @__PURE__ */ __name(() => { const startTime = timestampInSeconds() * 1e3; return { name: INTEGRATION_NAME$c, processEvent(event) { const now2 = timestampInSeconds() * 1e3; return { ...event, extra: { ...event.extra, ["session:start"]: startTime, ["session:duration"]: now2 - startTime, ["session:end"]: now2 } }; } }; }, "_sessionTimingIntegration"); const sessionTimingIntegration = defineIntegration(_sessionTimingIntegration); const DEFAULT_LIMIT$1 = 10; const INTEGRATION_NAME$b = "ZodErrors"; function originalExceptionIsZodError(originalException) { return isError(originalException) && originalException.name === "ZodError" && Array.isArray(originalException.errors); } __name(originalExceptionIsZodError, "originalExceptionIsZodError"); function formatIssueTitle(issue) { return { ...issue, path: "path" in issue && Array.isArray(issue.path) ? issue.path.join(".") : void 0, keys: "keys" in issue ? JSON.stringify(issue.keys) : void 0, unionErrors: "unionErrors" in issue ? JSON.stringify(issue.unionErrors) : void 0 }; } __name(formatIssueTitle, "formatIssueTitle"); function formatIssueMessage(zodError) { const errorKeyMap = /* @__PURE__ */ new Set(); for (const iss of zodError.issues) { if (iss.path && iss.path[0]) { errorKeyMap.add(iss.path[0]); } } const errorKeys = Array.from(errorKeyMap); return `Failed to validate keys: ${truncate(errorKeys.join(", "), 100)}`; } __name(formatIssueMessage, "formatIssueMessage"); function applyZodErrorsToEvent(limit, event, hint) { if (!event.exception || !event.exception.values || !hint || !hint.originalException || !originalExceptionIsZodError(hint.originalException) || hint.originalException.issues.length === 0) { return event; } return { ...event, exception: { ...event.exception, values: [ { ...event.exception.values[0], value: formatIssueMessage(hint.originalException) }, ...event.exception.values.slice(1) ] }, extra: { ...event.extra, "zoderror.issues": hint.originalException.errors.slice(0, limit).map(formatIssueTitle) } }; } __name(applyZodErrorsToEvent, "applyZodErrorsToEvent"); const _zodErrorsIntegration = /* @__PURE__ */ __name((options4 = {}) => { const limit = options4.limit || DEFAULT_LIMIT$1; return { name: INTEGRATION_NAME$b, processEvent(originalEvent, hint) { const processedEvent = applyZodErrorsToEvent(limit, originalEvent, hint); return processedEvent; } }; }, "_zodErrorsIntegration"); const zodErrorsIntegration = defineIntegration(_zodErrorsIntegration); const thirdPartyErrorFilterIntegration = defineIntegration((options4) => { return { name: "ThirdPartyErrorsFilter", setup(client) { client.on("beforeEnvelope", (envelope) => { forEachEnvelopeItem(envelope, (item3, type) => { if (type === "event") { const event = Array.isArray(item3) ? item3[1] : void 0; if (event) { stripMetadataFromStackFrames(event); item3[1] = event; } } }); }); client.on("applyFrameMetadata", (event) => { if (event.type) { return; } const stackParser = client.getOptions().stackParser; addMetadataToStackFrames(stackParser, event); }); }, processEvent(event) { const frameKeys = getBundleKeysForAllFramesWithFilenames(event); if (frameKeys) { const arrayMethod = options4.behaviour === "drop-error-if-contains-third-party-frames" || options4.behaviour === "apply-tag-if-contains-third-party-frames" ? "some" : "every"; const behaviourApplies = frameKeys[arrayMethod]((keys2) => !keys2.some((key) => options4.filterKeys.includes(key))); if (behaviourApplies) { const shouldDrop = options4.behaviour === "drop-error-if-contains-third-party-frames" || options4.behaviour === "drop-error-if-exclusively-contains-third-party-frames"; if (shouldDrop) { return null; } else { event.tags = { ...event.tags, third_party_code: true }; } } } return event; } }; }); function getBundleKeysForAllFramesWithFilenames(event) { const frames = getFramesFromEvent(event); if (!frames) { return void 0; } return frames.filter((frame) => !!frame.filename).map((frame) => { if (frame.module_metadata) { return Object.keys(frame.module_metadata).filter((key) => key.startsWith(BUNDLER_PLUGIN_APP_KEY_PREFIX)).map((key) => key.slice(BUNDLER_PLUGIN_APP_KEY_PREFIX.length)); } return []; }); } __name(getBundleKeysForAllFramesWithFilenames, "getBundleKeysForAllFramesWithFilenames"); const BUNDLER_PLUGIN_APP_KEY_PREFIX = "_sentryBundlerPluginAppKey:"; const COUNTER_METRIC_TYPE = "c"; const GAUGE_METRIC_TYPE = "g"; const SET_METRIC_TYPE = "s"; const DISTRIBUTION_METRIC_TYPE = "d"; const DEFAULT_BROWSER_FLUSH_INTERVAL = 5e3; const DEFAULT_FLUSH_INTERVAL = 1e4; const MAX_WEIGHT = 1e4; function getMetricsAggregatorForClient$1(client, Aggregator) { const globalMetricsAggregators = getGlobalSingleton( "globalMetricsAggregators", () => /* @__PURE__ */ new WeakMap() ); const aggregator = globalMetricsAggregators.get(client); if (aggregator) { return aggregator; } const newAggregator = new Aggregator(client); client.on("flush", () => newAggregator.flush()); client.on("close", () => newAggregator.close()); globalMetricsAggregators.set(client, newAggregator); return newAggregator; } __name(getMetricsAggregatorForClient$1, "getMetricsAggregatorForClient$1"); function addToMetricsAggregator(Aggregator, metricType, name2, value4, data25 = {}) { const client = data25.client || getClient(); if (!client) { return; } const span = getActiveSpan(); const rootSpan = span ? getRootSpan(span) : void 0; const transactionName = rootSpan && spanToJSON(rootSpan).description; const { unit, tags, timestamp: timestamp2 } = data25; const { release, environment } = client.getOptions(); const metricTags = {}; if (release) { metricTags.release = release; } if (environment) { metricTags.environment = environment; } if (transactionName) { metricTags.transaction = transactionName; } DEBUG_BUILD$6 && logger$2.log(`Adding value of ${value4} to ${metricType} metric ${name2}`); const aggregator = getMetricsAggregatorForClient$1(client, Aggregator); aggregator.add(metricType, name2, value4, unit, { ...metricTags, ...tags }, timestamp2); } __name(addToMetricsAggregator, "addToMetricsAggregator"); function increment$2(aggregator, name2, value4 = 1, data25) { addToMetricsAggregator(aggregator, COUNTER_METRIC_TYPE, name2, ensureNumber(value4), data25); } __name(increment$2, "increment$2"); function distribution$2(aggregator, name2, value4, data25) { addToMetricsAggregator(aggregator, DISTRIBUTION_METRIC_TYPE, name2, ensureNumber(value4), data25); } __name(distribution$2, "distribution$2"); function timing$2(aggregator, name2, value4, unit = "second", data25) { if (typeof value4 === "function") { const startTime = timestampInSeconds(); return startSpanManual( { op: "metrics.timing", name: name2, startTime, onlyIfParent: true }, (span) => { return handleCallbackErrors( () => value4(), () => { }, () => { const endTime = timestampInSeconds(); const timeDiff = endTime - startTime; distribution$2(aggregator, name2, timeDiff, { ...data25, unit: "second" }); span.end(endTime); } ); } ); } distribution$2(aggregator, name2, value4, { ...data25, unit }); } __name(timing$2, "timing$2"); function set$7(aggregator, name2, value4, data25) { addToMetricsAggregator(aggregator, SET_METRIC_TYPE, name2, value4, data25); } __name(set$7, "set$7"); function gauge$2(aggregator, name2, value4, data25) { addToMetricsAggregator(aggregator, GAUGE_METRIC_TYPE, name2, ensureNumber(value4), data25); } __name(gauge$2, "gauge$2"); const metrics$1 = { increment: increment$2, distribution: distribution$2, set: set$7, gauge: gauge$2, timing: timing$2, /** * @ignore This is for internal use only. */ getMetricsAggregatorForClient: getMetricsAggregatorForClient$1 }; function ensureNumber(number2) { return typeof number2 === "string" ? parseInt(number2) : number2; } __name(ensureNumber, "ensureNumber"); function isProfilingIntegrationWithProfiler(integration) { return !!integration && typeof integration["_profiler"] !== "undefined" && typeof integration["_profiler"]["start"] === "function" && typeof integration["_profiler"]["stop"] === "function"; } __name(isProfilingIntegrationWithProfiler, "isProfilingIntegrationWithProfiler"); function startProfiler() { const client = getClient(); if (!client) { DEBUG_BUILD$6 && logger$2.warn("No Sentry client available, profiling is not started"); return; } const integration = client.getIntegrationByName("ProfilingIntegration"); if (!integration) { DEBUG_BUILD$6 && logger$2.warn("ProfilingIntegration is not available"); return; } if (!isProfilingIntegrationWithProfiler(integration)) { DEBUG_BUILD$6 && logger$2.warn("Profiler is not available on profiling integration."); return; } integration._profiler.start(); } __name(startProfiler, "startProfiler"); function stopProfiler() { const client = getClient(); if (!client) { DEBUG_BUILD$6 && logger$2.warn("No Sentry client available, profiling is not started"); return; } const integration = client.getIntegrationByName("ProfilingIntegration"); if (!integration) { DEBUG_BUILD$6 && logger$2.warn("ProfilingIntegration is not available"); return; } if (!isProfilingIntegrationWithProfiler(integration)) { DEBUG_BUILD$6 && logger$2.warn("Profiler is not available on profiling integration."); return; } integration._profiler.stop(); } __name(stopProfiler, "stopProfiler"); const profiler = { startProfiler, stopProfiler }; function getBucketKey(metricType, name2, unit, tags) { const stringifiedTags = Object.entries(dropUndefinedKeys(tags)).sort((a2, b2) => a2[0].localeCompare(b2[0])); return `${metricType}${name2}${unit}${stringifiedTags}`; } __name(getBucketKey, "getBucketKey"); function simpleHash(s2) { let rv = 0; for (let i2 = 0; i2 < s2.length; i2++) { const c2 = s2.charCodeAt(i2); rv = (rv << 5) - rv + c2; rv &= rv; } return rv >>> 0; } __name(simpleHash, "simpleHash"); function serializeMetricBuckets(metricBucketItems) { let out = ""; for (const item3 of metricBucketItems) { const tagEntries = Object.entries(item3.tags); const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value4]) => `${key}:${value4}`).join(",")}` : ""; out += `${item3.name}@${item3.unit}:${item3.metric}|${item3.metricType}${maybeTags}|T${item3.timestamp} `; } return out; } __name(serializeMetricBuckets, "serializeMetricBuckets"); function sanitizeUnit(unit) { return unit.replace(/[^\w]+/gi, "_"); } __name(sanitizeUnit, "sanitizeUnit"); function sanitizeMetricKey(key) { return key.replace(/[^\w\-.]+/gi, "_"); } __name(sanitizeMetricKey, "sanitizeMetricKey"); function sanitizeTagKey(key) { return key.replace(/[^\w\-./]+/gi, ""); } __name(sanitizeTagKey, "sanitizeTagKey"); const tagValueReplacements = [ ["\n", "\\n"], ["\r", "\\r"], [" ", "\\t"], ["\\", "\\\\"], ["|", "\\u{7c}"], [",", "\\u{2c}"] ]; function getCharOrReplacement(input) { for (const [search2, replacement] of tagValueReplacements) { if (input === search2) { return replacement; } } return input; } __name(getCharOrReplacement, "getCharOrReplacement"); function sanitizeTagValue(value4) { return [...value4].reduce((acc, char) => acc + getCharOrReplacement(char), ""); } __name(sanitizeTagValue, "sanitizeTagValue"); function sanitizeTags(unsanitizedTags) { const tags = {}; for (const key in unsanitizedTags) { if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) { const sanitizedKey = sanitizeTagKey(key); tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key])); } } return tags; } __name(sanitizeTags, "sanitizeTags"); function captureAggregateMetrics(client, metricBucketItems) { logger$2.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`); const dsn = client.getDsn(); const metadata = client.getSdkMetadata(); const tunnel = client.getOptions().tunnel; const metricsEnvelope = createMetricEnvelope(metricBucketItems, dsn, metadata, tunnel); client.sendEnvelope(metricsEnvelope); } __name(captureAggregateMetrics, "captureAggregateMetrics"); function createMetricEnvelope(metricBucketItems, dsn, metadata, tunnel) { const headers = { sent_at: (/* @__PURE__ */ new Date()).toISOString() }; if (metadata && metadata.sdk) { headers.sdk = { name: metadata.sdk.name, version: metadata.sdk.version }; } if (!!tunnel && dsn) { headers.dsn = dsnToString(dsn); } const item3 = createMetricEnvelopeItem(metricBucketItems); return createEnvelope(headers, [item3]); } __name(createMetricEnvelope, "createMetricEnvelope"); function createMetricEnvelopeItem(metricBucketItems) { const payload = serializeMetricBuckets(metricBucketItems); const metricHeaders = { type: "statsd", length: payload.length }; return [metricHeaders, payload]; } __name(createMetricEnvelopeItem, "createMetricEnvelopeItem"); class CounterMetric { static { __name(this, "CounterMetric"); } constructor(_value) { this._value = _value; } /** @inheritDoc */ get weight() { return 1; } /** @inheritdoc */ add(value4) { this._value += value4; } /** @inheritdoc */ toString() { return `${this._value}`; } } class GaugeMetric { static { __name(this, "GaugeMetric"); } constructor(value4) { this._last = value4; this._min = value4; this._max = value4; this._sum = value4; this._count = 1; } /** @inheritDoc */ get weight() { return 5; } /** @inheritdoc */ add(value4) { this._last = value4; if (value4 < this._min) { this._min = value4; } if (value4 > this._max) { this._max = value4; } this._sum += value4; this._count++; } /** @inheritdoc */ toString() { return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`; } } class DistributionMetric { static { __name(this, "DistributionMetric"); } constructor(first2) { this._value = [first2]; } /** @inheritDoc */ get weight() { return this._value.length; } /** @inheritdoc */ add(value4) { this._value.push(value4); } /** @inheritdoc */ toString() { return this._value.join(":"); } } class SetMetric { static { __name(this, "SetMetric"); } constructor(first2) { this.first = first2; this._value = /* @__PURE__ */ new Set([first2]); } /** @inheritDoc */ get weight() { return this._value.size; } /** @inheritdoc */ add(value4) { this._value.add(value4); } /** @inheritdoc */ toString() { return Array.from(this._value).map((val) => typeof val === "string" ? simpleHash(val) : val).join(":"); } } const METRIC_MAP = { [COUNTER_METRIC_TYPE]: CounterMetric, [GAUGE_METRIC_TYPE]: GaugeMetric, [DISTRIBUTION_METRIC_TYPE]: DistributionMetric, [SET_METRIC_TYPE]: SetMetric }; class MetricsAggregator { static { __name(this, "MetricsAggregator"); } // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets // when the aggregator is garbage collected. // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry // Different metrics have different weights. We use this to limit the number of metrics // that we store in memory. // We adjust the type here to add the `unref()` part, as setInterval can technically return a number or a NodeJS.Timer // SDKs are required to shift the flush interval by random() * rollup_in_seconds. // That shift is determined once per startup to create jittering. // An SDK is required to perform force flushing ahead of scheduled time if the memory // pressure is too high. There is no rule for this other than that SDKs should be tracking // abstract aggregation complexity (eg: a counter only carries a single float, whereas a // distribution is a float per emission). // // Force flush is used on either shutdown, flush() or when we exceed the max weight. constructor(_client) { this._client = _client; this._buckets = /* @__PURE__ */ new Map(); this._bucketsTotalWeight = 0; this._interval = setInterval(() => this._flush(), DEFAULT_FLUSH_INTERVAL); if (this._interval.unref) { this._interval.unref(); } this._flushShift = Math.floor(Math.random() * DEFAULT_FLUSH_INTERVAL / 1e3); this._forceFlush = false; } /** * @inheritDoc */ add(metricType, unsanitizedName, value4, unsanitizedUnit = "none", unsanitizedTags = {}, maybeFloatTimestamp = timestampInSeconds()) { const timestamp2 = Math.floor(maybeFloatTimestamp); const name2 = sanitizeMetricKey(unsanitizedName); const tags = sanitizeTags(unsanitizedTags); const unit = sanitizeUnit(unsanitizedUnit); const bucketKey = getBucketKey(metricType, name2, unit, tags); let bucketItem = this._buckets.get(bucketKey); const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0; if (bucketItem) { bucketItem.metric.add(value4); if (bucketItem.timestamp < timestamp2) { bucketItem.timestamp = timestamp2; } } else { bucketItem = { // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size. metric: new METRIC_MAP[metricType](value4), timestamp: timestamp2, metricType, name: name2, unit, tags }; this._buckets.set(bucketKey, bucketItem); } const val = typeof value4 === "string" ? bucketItem.metric.weight - previousWeight : value4; updateMetricSummaryOnActiveSpan(metricType, name2, val, unit, unsanitizedTags, bucketKey); this._bucketsTotalWeight += bucketItem.metric.weight; if (this._bucketsTotalWeight >= MAX_WEIGHT) { this.flush(); } } /** * Flushes the current metrics to the transport via the transport. */ flush() { this._forceFlush = true; this._flush(); } /** * Shuts down metrics aggregator and clears all metrics. */ close() { this._forceFlush = true; clearInterval(this._interval); this._flush(); } /** * Flushes the buckets according to the internal state of the aggregator. * If it is a force flush, which happens on shutdown, it will flush all buckets. * Otherwise, it will only flush buckets that are older than the flush interval, * and according to the flush shift. * * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties. */ _flush() { if (this._forceFlush) { this._forceFlush = false; this._bucketsTotalWeight = 0; this._captureMetrics(this._buckets); this._buckets.clear(); return; } const cutoffSeconds = Math.floor(timestampInSeconds()) - DEFAULT_FLUSH_INTERVAL / 1e3 - this._flushShift; const flushedBuckets = /* @__PURE__ */ new Map(); for (const [key, bucket] of this._buckets) { if (bucket.timestamp <= cutoffSeconds) { flushedBuckets.set(key, bucket); this._bucketsTotalWeight -= bucket.metric.weight; } } for (const [key] of flushedBuckets) { this._buckets.delete(key); } this._captureMetrics(flushedBuckets); } /** * Only captures a subset of the buckets passed to this function. * @param flushedBuckets */ _captureMetrics(flushedBuckets) { if (flushedBuckets.size > 0) { const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem); captureAggregateMetrics(this._client, buckets); } } } function increment$1(name2, value4 = 1, data25) { metrics$1.increment(MetricsAggregator, name2, value4, data25); } __name(increment$1, "increment$1"); function distribution$1(name2, value4, data25) { metrics$1.distribution(MetricsAggregator, name2, value4, data25); } __name(distribution$1, "distribution$1"); function set$6(name2, value4, data25) { metrics$1.set(MetricsAggregator, name2, value4, data25); } __name(set$6, "set$6"); function gauge$1(name2, value4, data25) { metrics$1.gauge(MetricsAggregator, name2, value4, data25); } __name(gauge$1, "gauge$1"); function timing$1(name2, value4, unit = "second", data25) { return metrics$1.timing(MetricsAggregator, name2, value4, unit, data25); } __name(timing$1, "timing$1"); function getMetricsAggregatorForClient(client) { return metrics$1.getMetricsAggregatorForClient(client, MetricsAggregator); } __name(getMetricsAggregatorForClient, "getMetricsAggregatorForClient"); const metricsDefault = { increment: increment$1, distribution: distribution$1, set: set$6, gauge: gauge$1, timing: timing$1, /** * @ignore This is for internal use only. */ getMetricsAggregatorForClient }; class BrowserMetricsAggregator { static { __name(this, "BrowserMetricsAggregator"); } // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets // when the aggregator is garbage collected. // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry constructor(_client) { this._client = _client; this._buckets = /* @__PURE__ */ new Map(); this._interval = setInterval(() => this.flush(), DEFAULT_BROWSER_FLUSH_INTERVAL); } /** * @inheritDoc */ add(metricType, unsanitizedName, value4, unsanitizedUnit = "none", unsanitizedTags = {}, maybeFloatTimestamp = timestampInSeconds()) { const timestamp2 = Math.floor(maybeFloatTimestamp); const name2 = sanitizeMetricKey(unsanitizedName); const tags = sanitizeTags(unsanitizedTags); const unit = sanitizeUnit(unsanitizedUnit); const bucketKey = getBucketKey(metricType, name2, unit, tags); let bucketItem = this._buckets.get(bucketKey); const previousWeight = bucketItem && metricType === SET_METRIC_TYPE ? bucketItem.metric.weight : 0; if (bucketItem) { bucketItem.metric.add(value4); if (bucketItem.timestamp < timestamp2) { bucketItem.timestamp = timestamp2; } } else { bucketItem = { // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size. metric: new METRIC_MAP[metricType](value4), timestamp: timestamp2, metricType, name: name2, unit, tags }; this._buckets.set(bucketKey, bucketItem); } const val = typeof value4 === "string" ? bucketItem.metric.weight - previousWeight : value4; updateMetricSummaryOnActiveSpan(metricType, name2, val, unit, unsanitizedTags, bucketKey); } /** * @inheritDoc */ flush() { if (this._buckets.size === 0) { return; } const metricBuckets = Array.from(this._buckets.values()); captureAggregateMetrics(this._client, metricBuckets); this._buckets.clear(); } /** * @inheritDoc */ close() { clearInterval(this._interval); this.flush(); } } function instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeaders2, spans, spanOrigin = "auto.http.browser") { if (!handlerData.fetchData) { return void 0; } const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(handlerData.fetchData.url); if (handlerData.endTimestamp && shouldCreateSpanResult) { const spanId = handlerData.fetchData.__span; if (!spanId) return; const span2 = spans[spanId]; if (span2) { endSpan(span2, handlerData); delete spans[spanId]; } return void 0; } const { method, url } = handlerData.fetchData; const fullUrl = getFullURL$1(url); const host = fullUrl ? parseUrl$1(fullUrl).host : void 0; const hasParent = !!getActiveSpan(); const span = shouldCreateSpanResult && hasParent ? startInactiveSpan({ name: `${method} ${url}`, attributes: { url, type: "fetch", "http.method": method, "http.url": fullUrl, "server.address": host, [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin, [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.client" } }) : new SentryNonRecordingSpan(); handlerData.fetchData.__span = span.spanContext().spanId; spans[span.spanContext().spanId] = span; if (shouldAttachHeaders2(handlerData.fetchData.url)) { const request = handlerData.args[0]; const options4 = handlerData.args[1] || {}; const headers = _addTracingHeadersToFetchRequest( request, options4, // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction), // we do not want to use the span as base for the trace headers, // which means that the headers will be generated from the scope and the sampling decision is deferred hasTracingEnabled() && hasParent ? span : void 0 ); if (headers) { handlerData.args[1] = options4; options4.headers = headers; } } return span; } __name(instrumentFetchRequest, "instrumentFetchRequest"); function _addTracingHeadersToFetchRequest(request, fetchOptionsObj, span) { const traceHeaders = getTraceData({ span }); const sentryTrace = traceHeaders["sentry-trace"]; const baggage = traceHeaders.baggage; if (!sentryTrace) { return void 0; } const headers = fetchOptionsObj.headers || (isRequest$1(request) ? request.headers : void 0); if (!headers) { return { ...traceHeaders }; } else if (isHeaders$1(headers)) { const newHeaders = new Headers(headers); newHeaders.set("sentry-trace", sentryTrace); if (baggage) { const prevBaggageHeader = newHeaders.get("baggage"); if (prevBaggageHeader) { const prevHeaderStrippedFromSentryBaggage = stripBaggageHeaderOfSentryBaggageValues(prevBaggageHeader); newHeaders.set( "baggage", // If there are non-sentry entries (i.e. if the stripped string is non-empty/truthy) combine the stripped header and sentry baggage header // otherwise just set the sentry baggage header prevHeaderStrippedFromSentryBaggage ? `${prevHeaderStrippedFromSentryBaggage},${baggage}` : baggage ); } else { newHeaders.set("baggage", baggage); } } return newHeaders; } else if (Array.isArray(headers)) { const newHeaders = [ ...headers.filter((header3) => { return !(Array.isArray(header3) && header3[0] === "sentry-trace"); }).map((header3) => { if (Array.isArray(header3) && header3[0] === "baggage" && typeof header3[1] === "string") { const [headerName, headerValue, ...rest] = header3; return [headerName, stripBaggageHeaderOfSentryBaggageValues(headerValue), ...rest]; } else { return header3; } }), // Attach the new sentry-trace header ["sentry-trace", sentryTrace] ]; if (baggage) { newHeaders.push(["baggage", baggage]); } return newHeaders; } else { const existingBaggageHeader = "baggage" in headers ? headers.baggage : void 0; let newBaggageHeaders = []; if (Array.isArray(existingBaggageHeader)) { newBaggageHeaders = existingBaggageHeader.map( (headerItem) => typeof headerItem === "string" ? stripBaggageHeaderOfSentryBaggageValues(headerItem) : headerItem ).filter((headerItem) => headerItem === ""); } else if (existingBaggageHeader) { newBaggageHeaders.push(stripBaggageHeaderOfSentryBaggageValues(existingBaggageHeader)); } if (baggage) { newBaggageHeaders.push(baggage); } return { ...headers, "sentry-trace": sentryTrace, baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(",") : void 0 }; } } __name(_addTracingHeadersToFetchRequest, "_addTracingHeadersToFetchRequest"); function addTracingHeadersToFetchRequest(request, _client, _scope, fetchOptionsObj, span) { return _addTracingHeadersToFetchRequest(request, fetchOptionsObj, span); } __name(addTracingHeadersToFetchRequest, "addTracingHeadersToFetchRequest"); function getFullURL$1(url) { try { const parsed = new URL(url); return parsed.href; } catch (e2) { return void 0; } } __name(getFullURL$1, "getFullURL$1"); function endSpan(span, handlerData) { if (handlerData.response) { setHttpStatus(span, handlerData.response.status); const contentLength = handlerData.response && handlerData.response.headers && handlerData.response.headers.get("content-length"); if (contentLength) { const contentLengthNum = parseInt(contentLength); if (contentLengthNum > 0) { span.setAttribute("http.response_content_length", contentLengthNum); } } } else if (handlerData.error) { span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" }); } span.end(); } __name(endSpan, "endSpan"); function stripBaggageHeaderOfSentryBaggageValues(baggageHeader) { return baggageHeader.split(",").filter((baggageEntry) => !baggageEntry.split("=")[0].startsWith(SENTRY_BAGGAGE_KEY_PREFIX)).join(","); } __name(stripBaggageHeaderOfSentryBaggageValues, "stripBaggageHeaderOfSentryBaggageValues"); function isRequest$1(request) { return typeof Request !== "undefined" && isInstanceOf(request, Request); } __name(isRequest$1, "isRequest$1"); function isHeaders$1(headers) { return typeof Headers !== "undefined" && isInstanceOf(headers, Headers); } __name(isHeaders$1, "isHeaders$1"); const trpcCaptureContext = { mechanism: { handled: false, data: { function: "trpcMiddleware" } } }; function captureIfError(nextResult) { if (typeof nextResult === "object" && nextResult !== null && "ok" in nextResult && !nextResult.ok && "error" in nextResult) { captureException(nextResult.error, trpcCaptureContext); } } __name(captureIfError, "captureIfError"); function trpcMiddleware(options4 = {}) { return async function(opts) { const { path, type, next: next2, rawInput, getRawInput } = opts; const client = getClient(); const clientOptions = client && client.getOptions(); const trpcContext = { procedure_path: path, procedure_type: type }; if (options4.attachRpcInput !== void 0 ? options4.attachRpcInput : clientOptions && clientOptions.sendDefaultPii) { if (rawInput !== void 0) { trpcContext.input = normalize$2(rawInput); } if (getRawInput !== void 0 && typeof getRawInput === "function") { try { const rawRes = await getRawInput(); trpcContext.input = normalize$2(rawRes); } catch (err) { } } } return withScope((scope) => { scope.setContext("trpc", trpcContext); return startSpanManual( { name: `trpc/${path}`, op: "rpc.server", attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "route", [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.rpc.trpc" } }, async (span) => { try { const nextResult = await next2(); captureIfError(nextResult); span.end(); return nextResult; } catch (e2) { captureException(e2, trpcCaptureContext); span.end(); throw e2; } } ); }); }; } __name(trpcMiddleware, "trpcMiddleware"); function captureFeedback(params, hint = {}, scope = getCurrentScope$1()) { const { message: message3, name: name2, email, url, source, associatedEventId, tags } = params; const feedbackEvent = { contexts: { feedback: dropUndefinedKeys({ contact_email: email, name: name2, message: message3, url, source, associated_event_id: associatedEventId }) }, type: "feedback", level: "info", tags }; const client = scope && scope.getClient() || getClient(); if (client) { client.emit("beforeSendFeedback", feedbackEvent, hint); } const eventId = scope.captureEvent(feedbackEvent, hint); return eventId; } __name(captureFeedback, "captureFeedback"); function getCurrentHubShim() { return { bindClient(client) { const scope = getCurrentScope$1(); scope.setClient(client); }, withScope, getClient: /* @__PURE__ */ __name(() => getClient(), "getClient"), getScope: getCurrentScope$1, getIsolationScope, captureException: /* @__PURE__ */ __name((exception, hint) => { return getCurrentScope$1().captureException(exception, hint); }, "captureException"), captureMessage: /* @__PURE__ */ __name((message3, level, hint) => { return getCurrentScope$1().captureMessage(message3, level, hint); }, "captureMessage"), captureEvent, addBreadcrumb, setUser, setTags, setTag: setTag$5, setExtra, setExtras, setContext, getIntegration(integration) { const client = getClient(); return client && client.getIntegrationByName(integration.id) || null; }, startSession, endSession, captureSession(end) { if (end) { return endSession(); } _sendSessionUpdate(); } }; } __name(getCurrentHubShim, "getCurrentHubShim"); const getCurrentHub = getCurrentHubShim; function _sendSessionUpdate() { const scope = getCurrentScope$1(); const client = getClient(); const session = scope.getSession(); if (client && session) { client.captureSession(session); } } __name(_sendSessionUpdate, "_sendSessionUpdate"); function flatten(input) { const result = []; const flattenHelper = /* @__PURE__ */ __name((input2) => { input2.forEach((el) => { if (Array.isArray(el)) { flattenHelper(el); } else { result.push(el); } }); }, "flattenHelper"); flattenHelper(input); return result; } __name(flatten, "flatten"); function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) { if (statusCode === void 0) { return void 0; } else if (statusCode >= 400 && statusCode < 500) { return "warning"; } else if (statusCode >= 500) { return "error"; } else { return void 0; } } __name(getBreadcrumbLogLevelFromHttpStatusCode, "getBreadcrumbLogLevelFromHttpStatusCode"); const WINDOW$7 = GLOBAL_OBJ; function supportsErrorEvent() { try { new ErrorEvent(""); return true; } catch (e2) { return false; } } __name(supportsErrorEvent, "supportsErrorEvent"); function supportsDOMError() { try { new DOMError(""); return true; } catch (e2) { return false; } } __name(supportsDOMError, "supportsDOMError"); function supportsDOMException() { try { new DOMException(""); return true; } catch (e2) { return false; } } __name(supportsDOMException, "supportsDOMException"); function supportsFetch() { if (!("fetch" in WINDOW$7)) { return false; } try { new Headers(); new Request("http://www.example.com"); new Response(); return true; } catch (e2) { return false; } } __name(supportsFetch, "supportsFetch"); function isNativeFunction(func) { return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); } __name(isNativeFunction, "isNativeFunction"); function supportsNativeFetch() { if (typeof EdgeRuntime === "string") { return true; } if (!supportsFetch()) { return false; } if (isNativeFunction(WINDOW$7.fetch)) { return true; } let result = false; const doc2 = WINDOW$7.document; if (doc2 && typeof doc2.createElement === "function") { try { const sandbox = doc2.createElement("iframe"); sandbox.hidden = true; doc2.head.appendChild(sandbox); if (sandbox.contentWindow && sandbox.contentWindow.fetch) { result = isNativeFunction(sandbox.contentWindow.fetch); } doc2.head.removeChild(sandbox); } catch (err) { DEBUG_BUILD$5 && logger$2.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err); } } return result; } __name(supportsNativeFetch, "supportsNativeFetch"); function supportsReportingObserver() { return "ReportingObserver" in WINDOW$7; } __name(supportsReportingObserver, "supportsReportingObserver"); function supportsReferrerPolicy() { if (!supportsFetch()) { return false; } try { new Request("_", { referrerPolicy: "origin" }); return true; } catch (e2) { return false; } } __name(supportsReferrerPolicy, "supportsReferrerPolicy"); function addFetchInstrumentationHandler(handler6, skipNativeFetchCheck) { const type = "fetch"; addHandler$1(type, handler6); maybeInstrument(type, () => instrumentFetch(void 0, skipNativeFetchCheck)); } __name(addFetchInstrumentationHandler, "addFetchInstrumentationHandler"); function addFetchEndInstrumentationHandler(handler6) { const type = "fetch-body-resolved"; addHandler$1(type, handler6); maybeInstrument(type, () => instrumentFetch(streamHandler)); } __name(addFetchEndInstrumentationHandler, "addFetchEndInstrumentationHandler"); function instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) { if (skipNativeFetchCheck && !supportsNativeFetch()) { return; } fill(GLOBAL_OBJ, "fetch", function(originalFetch) { return function(...args) { const virtualError = new Error(); const { method, url } = parseFetchArgs(args); const handlerData = { args, fetchData: { method, url }, startTimestamp: timestampInSeconds() * 1e3, // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation virtualError }; if (!onFetchResolved) { triggerHandlers$1("fetch", { ...handlerData }); } return originalFetch.apply(GLOBAL_OBJ, args).then( async (response) => { if (onFetchResolved) { onFetchResolved(response); } else { triggerHandlers$1("fetch", { ...handlerData, endTimestamp: timestampInSeconds() * 1e3, response }); } return response; }, (error2) => { triggerHandlers$1("fetch", { ...handlerData, endTimestamp: timestampInSeconds() * 1e3, error: error2 }); if (isError(error2) && error2.stack === void 0) { error2.stack = virtualError.stack; addNonEnumerableProperty(error2, "framesToPop", 1); } throw error2; } ); }; }); } __name(instrumentFetch, "instrumentFetch"); async function resolveResponse(res, onFinishedResolving) { if (res && res.body) { const body = res.body; const responseReader = body.getReader(); const maxFetchDurationTimeout = setTimeout( () => { body.cancel().then(null, () => { }); }, 90 * 1e3 // 90s ); let readingActive = true; while (readingActive) { let chunkTimeout; try { chunkTimeout = setTimeout(() => { body.cancel().then(null, () => { }); }, 5e3); const { done } = await responseReader.read(); clearTimeout(chunkTimeout); if (done) { onFinishedResolving(); readingActive = false; } } catch (error2) { readingActive = false; } finally { clearTimeout(chunkTimeout); } } clearTimeout(maxFetchDurationTimeout); responseReader.releaseLock(); body.cancel().then(null, () => { }); } } __name(resolveResponse, "resolveResponse"); function streamHandler(response) { let clonedResponseForResolving; try { clonedResponseForResolving = response.clone(); } catch (e2) { return; } resolveResponse(clonedResponseForResolving, () => { triggerHandlers$1("fetch-body-resolved", { endTimestamp: timestampInSeconds() * 1e3, response }); }); } __name(streamHandler, "streamHandler"); function hasProp(obj, prop2) { return !!obj && typeof obj === "object" && !!obj[prop2]; } __name(hasProp, "hasProp"); function getUrlFromResource(resource) { if (typeof resource === "string") { return resource; } if (!resource) { return ""; } if (hasProp(resource, "url")) { return resource.url; } if (resource.toString) { return resource.toString(); } return ""; } __name(getUrlFromResource, "getUrlFromResource"); function parseFetchArgs(fetchArgs) { if (fetchArgs.length === 0) { return { method: "GET", url: "" }; } if (fetchArgs.length === 2) { const [url, options4] = fetchArgs; return { url: getUrlFromResource(url), method: hasProp(options4, "method") ? String(options4.method).toUpperCase() : "GET" }; } const arg = fetchArgs[0]; return { url: getUrlFromResource(arg), method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET" }; } __name(parseFetchArgs, "parseFetchArgs"); function isBrowserBundle() { return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__; } __name(isBrowserBundle, "isBrowserBundle"); function getSDKSource() { return "npm"; } __name(getSDKSource, "getSDKSource"); function isNodeEnv() { return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; } __name(isNodeEnv, "isNodeEnv"); function dynamicRequire(mod, request) { return mod.require(request); } __name(dynamicRequire, "dynamicRequire"); function loadModule(moduleName) { let mod; try { mod = dynamicRequire(module, moduleName); } catch (e2) { } if (!mod) { try { const { cwd } = dynamicRequire(module, "process"); mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`); } catch (e2) { } } return mod; } __name(loadModule, "loadModule"); function isBrowser$1() { return typeof window !== "undefined" && (!isNodeEnv() || isElectronNodeRenderer()); } __name(isBrowser$1, "isBrowser$1"); function isElectronNodeRenderer() { const process2 = GLOBAL_OBJ.process; return !!process2 && process2.type === "renderer"; } __name(isElectronNodeRenderer, "isElectronNodeRenderer"); function filenameIsInApp(filename, isNative = false) { const isInternal = isNative || filename && // It's not internal if it's an absolute linux path !filename.startsWith("/") && // It's not internal if it's an absolute windows path !filename.match(/^[A-Z]:/) && // It's not internal if the path is starting with a dot !filename.startsWith(".") && // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//); return !isInternal && filename !== void 0 && !filename.includes("node_modules/"); } __name(filenameIsInApp, "filenameIsInApp"); function node(getModule) { const FILENAME_MATCH = /^\s*[-]{4,}$/; const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; return (line) => { const lineMatch = line.match(FULL_MATCH); if (lineMatch) { 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.slice(0, methodStart); method = functionName.slice(methodStart + 1); const objectEnd = object.indexOf(".Module"); if (objectEnd > 0) { functionName = functionName.slice(objectEnd + 1); object = object.slice(0, objectEnd); } } typeName = void 0; } if (method) { typeName = object; methodName = method; } if (method === "") { methodName = void 0; functionName = void 0; } if (functionName === void 0) { methodName = methodName || UNKNOWN_FUNCTION; functionName = typeName ? `${typeName}.${methodName}` : methodName; } let filename = lineMatch[2] && lineMatch[2].startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2]; const isNative = lineMatch[5] === "native"; if (filename && filename.match(/\/[A-Z]:/)) { filename = filename.slice(1); } if (!filename && lineMatch[5] && !isNative) { filename = lineMatch[5]; } return { filename: filename ? decodeURI(filename) : void 0, module: getModule ? getModule(filename) : void 0, function: functionName, lineno: _parseIntOrUndefined(lineMatch[3]), colno: _parseIntOrUndefined(lineMatch[4]), in_app: filenameIsInApp(filename || "", isNative) }; } if (line.match(FILENAME_MATCH)) { return { filename: line }; } return void 0; }; } __name(node, "node"); function nodeStackLineParser(getModule) { return [90, node(getModule)]; } __name(nodeStackLineParser, "nodeStackLineParser"); function _parseIntOrUndefined(input) { return parseInt(input || "", 10) || void 0; } __name(_parseIntOrUndefined, "_parseIntOrUndefined"); function makeFifoCache(size2) { let evictionOrder = []; let cache2 = {}; return { add(key, value4) { while (evictionOrder.length >= size2) { const evictCandidate = evictionOrder.shift(); if (evictCandidate !== void 0) { delete cache2[evictCandidate]; } } if (cache2[key]) { this.delete(key); } evictionOrder.push(key); cache2[key] = value4; }, clear() { cache2 = {}; evictionOrder = []; }, get(key) { return cache2[key]; }, size() { return evictionOrder.length; }, // Delete cache key and return true if it existed, false otherwise. delete(key) { if (!cache2[key]) { return false; } delete cache2[key]; for (let i2 = 0; i2 < evictionOrder.length; i2++) { if (evictionOrder[i2] === key) { evictionOrder.splice(i2, 1); break; } } return true; } }; } __name(makeFifoCache, "makeFifoCache"); function watchdogTimer(createTimer, pollInterval, anrThreshold, callback) { const timer = createTimer(); let triggered = false; let enabled = true; setInterval(() => { const diffMs = timer.getTimeMs(); if (triggered === false && diffMs > pollInterval + anrThreshold) { triggered = true; if (enabled) { callback(); } } if (diffMs < pollInterval + anrThreshold) { triggered = false; } }, 20); return { poll: /* @__PURE__ */ __name(() => { timer.reset(); }, "poll"), enabled: /* @__PURE__ */ __name((state) => { enabled = state; }, "enabled") }; } __name(watchdogTimer, "watchdogTimer"); function callFrameToStackFrame(frame, url, getModuleFromFilename) { const filename = url ? url.replace(/^file:\/\//, "") : void 0; const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : void 0; const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : void 0; return dropUndefinedKeys({ filename, module: getModuleFromFilename(filename), function: frame.functionName || UNKNOWN_FUNCTION, colno, lineno, in_app: filename ? filenameIsInApp(filename) : void 0 }); } __name(callFrameToStackFrame, "callFrameToStackFrame"); class LRUMap { static { __name(this, "LRUMap"); } constructor(_maxSize) { this._maxSize = _maxSize; this._cache = /* @__PURE__ */ new Map(); } /** Get the current size of the cache */ get size() { return this._cache.size; } /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */ get(key) { const value4 = this._cache.get(key); if (value4 === void 0) { return void 0; } this._cache.delete(key); this._cache.set(key, value4); return value4; } /** Insert an entry and evict an older entry if we've reached maxSize */ set(key, value4) { if (this._cache.size >= this._maxSize) { this._cache.delete(this._cache.keys().next().value); } this._cache.set(key, value4); } /** Remove an entry and return the entry if it was in the cache */ remove(key) { const value4 = this._cache.get(key); if (value4) { this._cache.delete(key); } return value4; } /** Clear all entries */ clear() { this._cache.clear(); } /** Get all the keys */ keys() { return Array.from(this._cache.keys()); } /** Get all the values */ values() { const values = []; this._cache.forEach((value4) => values.push(value4)); return values; } } function vercelWaitUntil(task) { const vercelRequestContextGlobal = ( // @ts-expect-error This is not typed GLOBAL_OBJ[Symbol.for("@vercel/request-context")] ); const ctx = vercelRequestContextGlobal && vercelRequestContextGlobal.get && vercelRequestContextGlobal.get() ? vercelRequestContextGlobal.get() : {}; if (ctx && ctx.waitUntil) { ctx.waitUntil(task); } } __name(vercelWaitUntil, "vercelWaitUntil"); function escapeStringForRegex(regexString) { return regexString.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d"); } __name(escapeStringForRegex, "escapeStringForRegex"); const WINDOW$6 = GLOBAL_OBJ; function supportsHistory() { const chromeVar = WINDOW$6.chrome; const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime; const hasHistoryApi = "history" in WINDOW$6 && !!WINDOW$6.history.pushState && !!WINDOW$6.history.replaceState; return !isChromePackagedApp && hasHistoryApi; } __name(supportsHistory, "supportsHistory"); function _nullishCoalesce(lhs, rhsFn) { return lhs != null ? lhs : rhsFn(); } __name(_nullishCoalesce, "_nullishCoalesce"); async function _asyncNullishCoalesce(lhs, rhsFn) { return _nullishCoalesce(lhs, rhsFn); } __name(_asyncNullishCoalesce, "_asyncNullishCoalesce"); async function _asyncOptionalChain(ops) { let lastAccessLHS = void 0; let value4 = ops[0]; let i2 = 1; while (i2 < ops.length) { const op = ops[i2]; const fn = ops[i2 + 1]; i2 += 2; if ((op === "optionalAccess" || op === "optionalCall") && value4 == null) { return; } if (op === "access" || op === "optionalAccess") { lastAccessLHS = value4; value4 = await fn(value4); } else if (op === "call" || op === "optionalCall") { value4 = await fn((...args) => value4.call(lastAccessLHS, ...args)); lastAccessLHS = void 0; } } return value4; } __name(_asyncOptionalChain, "_asyncOptionalChain"); async function _asyncOptionalChainDelete(ops) { const result = await _asyncOptionalChain(ops); return result == null ? true : result; } __name(_asyncOptionalChainDelete, "_asyncOptionalChainDelete"); function _optionalChain(ops) { let lastAccessLHS = void 0; let value4 = ops[0]; let i2 = 1; while (i2 < ops.length) { const op = ops[i2]; const fn = ops[i2 + 1]; i2 += 2; if ((op === "optionalAccess" || op === "optionalCall") && value4 == null) { return; } if (op === "access" || op === "optionalAccess") { lastAccessLHS = value4; value4 = fn(value4); } else if (op === "call" || op === "optionalCall") { value4 = fn((...args) => value4.call(lastAccessLHS, ...args)); lastAccessLHS = void 0; } } return value4; } __name(_optionalChain, "_optionalChain"); function _optionalChainDelete(ops) { const result = _optionalChain(ops); return result == null ? true : result; } __name(_optionalChainDelete, "_optionalChainDelete"); const WINDOW$5 = GLOBAL_OBJ; let ignoreOnError = 0; function shouldIgnoreOnError() { return ignoreOnError > 0; } __name(shouldIgnoreOnError, "shouldIgnoreOnError"); function ignoreNextOnError() { ignoreOnError++; setTimeout(() => { ignoreOnError--; }); } __name(ignoreNextOnError, "ignoreNextOnError"); function wrap$1(fn, options4 = {}) { function isFunction2(fn2) { return typeof fn2 === "function"; } __name(isFunction2, "isFunction"); if (!isFunction2(fn)) { return fn; } try { const wrapper = fn.__sentry_wrapped__; if (wrapper) { if (typeof wrapper === "function") { return wrapper; } else { return fn; } } if (getOriginalFunction(fn)) { return fn; } } catch (e2) { return fn; } const sentryWrapped = /* @__PURE__ */ __name(function(...args) { try { const wrappedArguments = args.map((arg) => wrap$1(arg, options4)); return fn.apply(this, wrappedArguments); } catch (ex) { ignoreNextOnError(); withScope((scope) => { scope.addEventProcessor((event) => { if (options4.mechanism) { addExceptionTypeValue(event, void 0, void 0); addExceptionMechanism(event, options4.mechanism); } event.extra = { ...event.extra, arguments: args }; return event; }); captureException(ex); }); throw ex; } }, "sentryWrapped"); try { for (const property in fn) { if (Object.prototype.hasOwnProperty.call(fn, property)) { sentryWrapped[property] = fn[property]; } } } catch (e2) { } markFunctionWrapped(sentryWrapped, fn); addNonEnumerableProperty(fn, "__sentry_wrapped__", sentryWrapped); try { const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, "name"); if (descriptor.configurable) { Object.defineProperty(sentryWrapped, "name", { get() { return fn.name; } }); } } catch (e3) { } return sentryWrapped; } __name(wrap$1, "wrap$1"); const DEBUG_BUILD$4 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; function exceptionFromError(stackParser, ex) { const frames = parseStackFrames(stackParser, ex); const exception = { type: extractType(ex), value: extractMessage(ex) }; if (frames.length) { exception.stacktrace = { frames }; } if (exception.type === void 0 && exception.value === "") { exception.value = "Unrecoverable error caught"; } return exception; } __name(exceptionFromError, "exceptionFromError"); function eventFromPlainObject(stackParser, exception, syntheticException, isUnhandledRejection) { const client = getClient(); const normalizeDepth = client && client.getOptions().normalizeDepth; const errorFromProp = getErrorPropertyFromObject(exception); const extra = { __serialized__: normalizeToSize(exception, normalizeDepth) }; if (errorFromProp) { return { exception: { values: [exceptionFromError(stackParser, errorFromProp)] }, extra }; } const event = { exception: { values: [ { type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? "UnhandledRejection" : "Error", value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) } ] }, extra }; if (syntheticException) { const frames = parseStackFrames(stackParser, syntheticException); if (frames.length) { event.exception.values[0].stacktrace = { frames }; } } return event; } __name(eventFromPlainObject, "eventFromPlainObject"); function eventFromError(stackParser, ex) { return { exception: { values: [exceptionFromError(stackParser, ex)] } }; } __name(eventFromError, "eventFromError"); function parseStackFrames(stackParser, ex) { const stacktrace = ex.stacktrace || ex.stack || ""; const skipLines = getSkipFirstStackStringLines(ex); const framesToPop = getPopFirstTopFrames(ex); try { return stackParser(stacktrace, skipLines, framesToPop); } catch (e2) { } return []; } __name(parseStackFrames, "parseStackFrames"); const reactMinifiedRegexp = /Minified React error #\d+;/i; function getSkipFirstStackStringLines(ex) { if (ex && reactMinifiedRegexp.test(ex.message)) { return 1; } return 0; } __name(getSkipFirstStackStringLines, "getSkipFirstStackStringLines"); function getPopFirstTopFrames(ex) { if (typeof ex.framesToPop === "number") { return ex.framesToPop; } return 0; } __name(getPopFirstTopFrames, "getPopFirstTopFrames"); function isWebAssemblyException(exception) { if (typeof WebAssembly !== "undefined" && typeof WebAssembly.Exception !== "undefined") { return exception instanceof WebAssembly.Exception; } else { return false; } } __name(isWebAssemblyException, "isWebAssemblyException"); function extractType(ex) { const name2 = ex && ex.name; if (!name2 && isWebAssemblyException(ex)) { const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2; return hasTypeInMessage ? ex.message[0] : "WebAssembly.Exception"; } return name2; } __name(extractType, "extractType"); function extractMessage(ex) { const message3 = ex && ex.message; if (!message3) { return "No error message"; } if (message3.error && typeof message3.error.message === "string") { return message3.error.message; } if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) { return ex.message[1]; } return message3; } __name(extractMessage, "extractMessage"); function eventFromException(stackParser, exception, hint, attachStacktrace) { const syntheticException = hint && hint.syntheticException || void 0; const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace); addExceptionMechanism(event); event.level = "error"; if (hint && hint.event_id) { event.event_id = hint.event_id; } return resolvedSyncPromise(event); } __name(eventFromException, "eventFromException"); function eventFromMessage(stackParser, message3, level = "info", hint, attachStacktrace) { const syntheticException = hint && hint.syntheticException || void 0; const event = eventFromString(stackParser, message3, syntheticException, attachStacktrace); event.level = level; if (hint && hint.event_id) { event.event_id = hint.event_id; } return resolvedSyncPromise(event); } __name(eventFromMessage, "eventFromMessage"); function eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace, isUnhandledRejection) { let event; if (isErrorEvent$2(exception) && exception.error) { const errorEvent = exception; return eventFromError(stackParser, errorEvent.error); } if (isDOMError(exception) || isDOMException(exception)) { const domException = exception; if ("stack" in exception) { event = eventFromError(stackParser, exception); } else { const name2 = domException.name || (isDOMError(domException) ? "DOMError" : "DOMException"); const message3 = domException.message ? `${name2}: ${domException.message}` : name2; event = eventFromString(stackParser, message3, syntheticException, attachStacktrace); addExceptionTypeValue(event, message3); } if ("code" in domException) { event.tags = { ...event.tags, "DOMException.code": `${domException.code}` }; } return event; } if (isError(exception)) { return eventFromError(stackParser, exception); } if (isPlainObject$5(exception) || isEvent(exception)) { const objectException = exception; event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection); addExceptionMechanism(event, { synthetic: true }); return event; } event = eventFromString(stackParser, exception, syntheticException, attachStacktrace); addExceptionTypeValue(event, `${exception}`, void 0); addExceptionMechanism(event, { synthetic: true }); return event; } __name(eventFromUnknownInput, "eventFromUnknownInput"); function eventFromString(stackParser, message3, syntheticException, attachStacktrace) { const event = {}; if (attachStacktrace && syntheticException) { const frames = parseStackFrames(stackParser, syntheticException); if (frames.length) { event.exception = { values: [{ value: message3, stacktrace: { frames } }] }; } addExceptionMechanism(event, { synthetic: true }); } if (isParameterizedString(message3)) { const { __sentry_template_string__, __sentry_template_values__ } = message3; event.logentry = { message: __sentry_template_string__, params: __sentry_template_values__ }; return event; } event.message = message3; return event; } __name(eventFromString, "eventFromString"); function getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) { const keys2 = extractExceptionKeysForMessage(exception); const captureType = isUnhandledRejection ? "promise rejection" : "exception"; if (isErrorEvent$2(exception)) { return `Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``; } if (isEvent(exception)) { const className = getObjectClassName(exception); return `Event \`${className}\` (type=${exception.type}) captured as ${captureType}`; } return `Object captured as ${captureType} with keys: ${keys2}`; } __name(getNonErrorObjectExceptionValue, "getNonErrorObjectExceptionValue"); function getObjectClassName(obj) { try { const prototype2 = Object.getPrototypeOf(obj); return prototype2 ? prototype2.constructor.name : void 0; } catch (e2) { } } __name(getObjectClassName, "getObjectClassName"); function getErrorPropertyFromObject(obj) { for (const prop2 in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop2)) { const value4 = obj[prop2]; if (value4 instanceof Error) { return value4; } } } return void 0; } __name(getErrorPropertyFromObject, "getErrorPropertyFromObject"); function createUserFeedbackEnvelope(feedback, { metadata, tunnel, dsn }) { const headers = { event_id: feedback.event_id, sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...metadata && metadata.sdk && { sdk: { name: metadata.sdk.name, version: metadata.sdk.version } }, ...!!tunnel && !!dsn && { dsn: dsnToString(dsn) } }; const item3 = createUserFeedbackEnvelopeItem(feedback); return createEnvelope(headers, [item3]); } __name(createUserFeedbackEnvelope, "createUserFeedbackEnvelope"); function createUserFeedbackEnvelopeItem(feedback) { const feedbackHeaders = { type: "user_report" }; return [feedbackHeaders, feedback]; } __name(createUserFeedbackEnvelopeItem, "createUserFeedbackEnvelopeItem"); class BrowserClient extends BaseClient { static { __name(this, "BrowserClient"); } /** * Creates a new Browser SDK instance. * * @param options Configuration options for this SDK. */ constructor(options4) { const opts = { // We default this to true, as it is the safer scenario parentSpanIsAlwaysRootSpan: true, ...options4 }; const sdkSource = WINDOW$5.SENTRY_SDK_SOURCE || getSDKSource(); applySdkMetadata(opts, "browser", ["browser"], sdkSource); super(opts); if (opts.sendClientReports && WINDOW$5.document) { WINDOW$5.document.addEventListener("visibilitychange", () => { if (WINDOW$5.document.visibilityState === "hidden") { this._flushOutcomes(); } }); } } /** * @inheritDoc */ eventFromException(exception, hint) { return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace); } /** * @inheritDoc */ eventFromMessage(message3, level = "info", hint) { return eventFromMessage(this._options.stackParser, message3, level, hint, this._options.attachStacktrace); } /** * Sends user feedback to Sentry. * * @deprecated Use `captureFeedback` instead. */ captureUserFeedback(feedback) { if (!this._isEnabled()) { DEBUG_BUILD$4 && logger$2.warn("SDK not enabled, will not capture user feedback."); return; } const envelope = createUserFeedbackEnvelope(feedback, { metadata: this.getSdkMetadata(), dsn: this.getDsn(), tunnel: this.getOptions().tunnel }); this.sendEnvelope(envelope); } /** * @inheritDoc */ _prepareEvent(event, hint, scope) { event.platform = event.platform || "javascript"; return super._prepareEvent(event, hint, scope); } } const DEBUG_BUILD$3 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; const getRating = /* @__PURE__ */ __name((value4, thresholds) => { if (value4 > thresholds[1]) { return "poor"; } if (value4 > thresholds[0]) { return "needs-improvement"; } return "good"; }, "getRating"); const bindReporter = /* @__PURE__ */ __name((callback, metric, thresholds, reportAllChanges) => { let prevValue; let delta2; return (forceReport) => { if (metric.value >= 0) { if (forceReport || reportAllChanges) { delta2 = metric.value - (prevValue || 0); if (delta2 || prevValue === void 0) { prevValue = metric.value; metric.delta = delta2; metric.rating = getRating(metric.value, thresholds); callback(metric); } } } }; }, "bindReporter"); const WINDOW$4 = GLOBAL_OBJ; const generateUniqueID = /* @__PURE__ */ __name(() => { return `v4-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`; }, "generateUniqueID"); const getNavigationEntry = /* @__PURE__ */ __name((checkResponseStart = true) => { const navigationEntry = WINDOW$4.performance && WINDOW$4.performance.getEntriesByType && WINDOW$4.performance.getEntriesByType("navigation")[0]; if ( // sentry-specific change: // We don't want to check for responseStart for our own use of `getNavigationEntry` !checkResponseStart || navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now() ) { return navigationEntry; } }, "getNavigationEntry"); const getActivationStart = /* @__PURE__ */ __name(() => { const navEntry = getNavigationEntry(); return navEntry && navEntry.activationStart || 0; }, "getActivationStart"); const initMetric = /* @__PURE__ */ __name((name2, value4) => { const navEntry = getNavigationEntry(); let navigationType = "navigate"; if (navEntry) { if (WINDOW$4.document && WINDOW$4.document.prerendering || getActivationStart() > 0) { navigationType = "prerender"; } else if (WINDOW$4.document && WINDOW$4.document.wasDiscarded) { navigationType = "restore"; } else if (navEntry.type) { navigationType = navEntry.type.replace(/_/g, "-"); } } const entries = []; return { name: name2, value: typeof value4 === "undefined" ? -1 : value4, rating: "good", // If needed, will be updated when reported. `const` to keep the type from widening to `string`. delta: 0, entries, id: generateUniqueID(), navigationType }; }, "initMetric"); const observe = /* @__PURE__ */ __name((type, callback, opts) => { try { if (PerformanceObserver.supportedEntryTypes.includes(type)) { const po2 = new PerformanceObserver((list2) => { Promise.resolve().then(() => { callback(list2.getEntries()); }); }); po2.observe( Object.assign( { type, buffered: true }, opts || {} ) ); return po2; } } catch (e2) { } return; }, "observe"); const onHidden = /* @__PURE__ */ __name((cb) => { const onHiddenOrPageHide = /* @__PURE__ */ __name((event) => { if (event.type === "pagehide" || WINDOW$4.document && WINDOW$4.document.visibilityState === "hidden") { cb(event); } }, "onHiddenOrPageHide"); if (WINDOW$4.document) { addEventListener("visibilitychange", onHiddenOrPageHide, true); addEventListener("pagehide", onHiddenOrPageHide, true); } }, "onHidden"); const runOnce = /* @__PURE__ */ __name((cb) => { let called = false; return () => { if (!called) { cb(); called = true; } }; }, "runOnce"); let firstHiddenTime = -1; const initHiddenTime = /* @__PURE__ */ __name(() => { return WINDOW$4.document.visibilityState === "hidden" && !WINDOW$4.document.prerendering ? 0 : Infinity; }, "initHiddenTime"); const onVisibilityUpdate = /* @__PURE__ */ __name((event) => { if (WINDOW$4.document.visibilityState === "hidden" && firstHiddenTime > -1) { firstHiddenTime = event.type === "visibilitychange" ? event.timeStamp : 0; removeChangeListeners(); } }, "onVisibilityUpdate"); const addChangeListeners = /* @__PURE__ */ __name(() => { addEventListener("visibilitychange", onVisibilityUpdate, true); addEventListener("prerenderingchange", onVisibilityUpdate, true); }, "addChangeListeners"); const removeChangeListeners = /* @__PURE__ */ __name(() => { removeEventListener("visibilitychange", onVisibilityUpdate, true); removeEventListener("prerenderingchange", onVisibilityUpdate, true); }, "removeChangeListeners"); const getVisibilityWatcher = /* @__PURE__ */ __name(() => { if (WINDOW$4.document && firstHiddenTime < 0) { firstHiddenTime = initHiddenTime(); addChangeListeners(); } return { get firstHiddenTime() { return firstHiddenTime; } }; }, "getVisibilityWatcher"); const whenActivated = /* @__PURE__ */ __name((callback) => { if (WINDOW$4.document && WINDOW$4.document.prerendering) { addEventListener("prerenderingchange", () => callback(), true); } else { callback(); } }, "whenActivated"); const FCPThresholds = [1800, 3e3]; const onFCP = /* @__PURE__ */ __name((onReport, opts = {}) => { whenActivated(() => { const visibilityWatcher = getVisibilityWatcher(); const metric = initMetric("FCP"); let report; const handleEntries = /* @__PURE__ */ __name((entries) => { entries.forEach((entry) => { if (entry.name === "first-contentful-paint") { po2.disconnect(); if (entry.startTime < visibilityWatcher.firstHiddenTime) { metric.value = Math.max(entry.startTime - getActivationStart(), 0); metric.entries.push(entry); report(true); } } }); }, "handleEntries"); const po2 = observe("paint", handleEntries); if (po2) { report = bindReporter(onReport, metric, FCPThresholds, opts.reportAllChanges); } }); }, "onFCP"); const CLSThresholds = [0.1, 0.25]; const onCLS = /* @__PURE__ */ __name((onReport, opts = {}) => { onFCP( runOnce(() => { const metric = initMetric("CLS", 0); let report; let sessionValue = 0; let sessionEntries = []; const handleEntries = /* @__PURE__ */ __name((entries) => { entries.forEach((entry) => { if (!entry.hadRecentInput) { const firstSessionEntry = sessionEntries[0]; const lastSessionEntry = sessionEntries[sessionEntries.length - 1]; if (sessionValue && firstSessionEntry && lastSessionEntry && entry.startTime - lastSessionEntry.startTime < 1e3 && entry.startTime - firstSessionEntry.startTime < 5e3) { sessionValue += entry.value; sessionEntries.push(entry); } else { sessionValue = entry.value; sessionEntries = [entry]; } } }); if (sessionValue > metric.value) { metric.value = sessionValue; metric.entries = sessionEntries; report(); } }, "handleEntries"); const po2 = observe("layout-shift", handleEntries); if (po2) { report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges); onHidden(() => { handleEntries(po2.takeRecords()); report(true); }); setTimeout(report, 0); } }) ); }, "onCLS"); const FIDThresholds = [100, 300]; const onFID = /* @__PURE__ */ __name((onReport, opts = {}) => { whenActivated(() => { const visibilityWatcher = getVisibilityWatcher(); const metric = initMetric("FID"); let report; const handleEntry = /* @__PURE__ */ __name((entry) => { if (entry.startTime < visibilityWatcher.firstHiddenTime) { metric.value = entry.processingStart - entry.startTime; metric.entries.push(entry); report(true); } }, "handleEntry"); const handleEntries = /* @__PURE__ */ __name((entries) => { entries.forEach(handleEntry); }, "handleEntries"); const po2 = observe("first-input", handleEntries); report = bindReporter(onReport, metric, FIDThresholds, opts.reportAllChanges); if (po2) { onHidden( runOnce(() => { handleEntries(po2.takeRecords()); po2.disconnect(); }) ); } }); }, "onFID"); let interactionCountEstimate = 0; let minKnownInteractionId = Infinity; let maxKnownInteractionId = 0; const updateEstimate = /* @__PURE__ */ __name((entries) => { entries.forEach((e2) => { if (e2.interactionId) { minKnownInteractionId = Math.min(minKnownInteractionId, e2.interactionId); maxKnownInteractionId = Math.max(maxKnownInteractionId, e2.interactionId); interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0; } }); }, "updateEstimate"); let po; const getInteractionCount = /* @__PURE__ */ __name(() => { return po ? interactionCountEstimate : performance.interactionCount || 0; }, "getInteractionCount"); const initInteractionCountPolyfill = /* @__PURE__ */ __name(() => { if ("interactionCount" in performance || po) return; po = observe("event", updateEstimate, { type: "event", buffered: true, durationThreshold: 0 }); }, "initInteractionCountPolyfill"); const longestInteractionList = []; const longestInteractionMap = /* @__PURE__ */ new Map(); const DEFAULT_DURATION_THRESHOLD = 40; let prevInteractionCount = 0; const getInteractionCountForNavigation = /* @__PURE__ */ __name(() => { return getInteractionCount() - prevInteractionCount; }, "getInteractionCountForNavigation"); const estimateP98LongestInteraction = /* @__PURE__ */ __name(() => { const candidateInteractionIndex = Math.min( longestInteractionList.length - 1, Math.floor(getInteractionCountForNavigation() / 50) ); return longestInteractionList[candidateInteractionIndex]; }, "estimateP98LongestInteraction"); const MAX_INTERACTIONS_TO_CONSIDER = 10; const entryPreProcessingCallbacks = []; const processInteractionEntry = /* @__PURE__ */ __name((entry) => { entryPreProcessingCallbacks.forEach((cb) => cb(entry)); if (!(entry.interactionId || entry.entryType === "first-input")) return; const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1]; const existingInteraction = longestInteractionMap.get(entry.interactionId); if (existingInteraction || longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER || minLongestInteraction && entry.duration > minLongestInteraction.latency) { if (existingInteraction) { if (entry.duration > existingInteraction.latency) { existingInteraction.entries = [entry]; existingInteraction.latency = entry.duration; } else if (entry.duration === existingInteraction.latency && entry.startTime === (existingInteraction.entries[0] && existingInteraction.entries[0].startTime)) { existingInteraction.entries.push(entry); } } else { const interaction = { id: entry.interactionId, latency: entry.duration, entries: [entry] }; longestInteractionMap.set(interaction.id, interaction); longestInteractionList.push(interaction); } longestInteractionList.sort((a2, b2) => b2.latency - a2.latency); if (longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) { longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach((i2) => longestInteractionMap.delete(i2.id)); } } }, "processInteractionEntry"); const whenIdle = /* @__PURE__ */ __name((cb) => { const rIC = WINDOW$4.requestIdleCallback || WINDOW$4.setTimeout; let handle = -1; cb = runOnce(cb); if (WINDOW$4.document && WINDOW$4.document.visibilityState === "hidden") { cb(); } else { handle = rIC(cb); onHidden(cb); } return handle; }, "whenIdle"); const INPThresholds = [200, 500]; const onINP = /* @__PURE__ */ __name((onReport, opts = {}) => { if (!("PerformanceEventTiming" in WINDOW$4 && "interactionId" in PerformanceEventTiming.prototype)) { return; } whenActivated(() => { initInteractionCountPolyfill(); const metric = initMetric("INP"); let report; const handleEntries = /* @__PURE__ */ __name((entries) => { whenIdle(() => { entries.forEach(processInteractionEntry); const inp = estimateP98LongestInteraction(); if (inp && inp.latency !== metric.value) { metric.value = inp.latency; metric.entries = inp.entries; report(); } }); }, "handleEntries"); const po2 = observe("event", handleEntries, { // Event Timing entries have their durations rounded to the nearest 8ms, // so a duration of 40ms would be any event that spans 2.5 or more frames // at 60Hz. This threshold is chosen to strike a balance between usefulness // and performance. Running this callback for any interaction that spans // just one or two frames is likely not worth the insight that could be // gained. durationThreshold: opts.durationThreshold != null ? opts.durationThreshold : DEFAULT_DURATION_THRESHOLD }); report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges); if (po2) { po2.observe({ type: "first-input", buffered: true }); onHidden(() => { handleEntries(po2.takeRecords()); report(true); }); } }); }, "onINP"); const LCPThresholds = [2500, 4e3]; const reportedMetricIDs = {}; const onLCP = /* @__PURE__ */ __name((onReport, opts = {}) => { whenActivated(() => { const visibilityWatcher = getVisibilityWatcher(); const metric = initMetric("LCP"); let report; const handleEntries = /* @__PURE__ */ __name((entries) => { if (!opts.reportAllChanges) { entries = entries.slice(-1); } entries.forEach((entry) => { if (entry.startTime < visibilityWatcher.firstHiddenTime) { metric.value = Math.max(entry.startTime - getActivationStart(), 0); metric.entries = [entry]; report(); } }); }, "handleEntries"); const po2 = observe("largest-contentful-paint", handleEntries); if (po2) { report = bindReporter(onReport, metric, LCPThresholds, opts.reportAllChanges); const stopListening = runOnce(() => { if (!reportedMetricIDs[metric.id]) { handleEntries(po2.takeRecords()); po2.disconnect(); reportedMetricIDs[metric.id] = true; report(true); } }); ["keydown", "click"].forEach((type) => { if (WINDOW$4.document) { addEventListener(type, () => whenIdle(stopListening), { once: true, capture: true }); } }); onHidden(stopListening); } }); }, "onLCP"); const TTFBThresholds = [800, 1800]; const whenReady = /* @__PURE__ */ __name((callback) => { if (WINDOW$4.document && WINDOW$4.document.prerendering) { whenActivated(() => whenReady(callback)); } else if (WINDOW$4.document && WINDOW$4.document.readyState !== "complete") { addEventListener("load", () => whenReady(callback), true); } else { setTimeout(callback, 0); } }, "whenReady"); const onTTFB = /* @__PURE__ */ __name((onReport, opts = {}) => { const metric = initMetric("TTFB"); const report = bindReporter(onReport, metric, TTFBThresholds, opts.reportAllChanges); whenReady(() => { const navigationEntry = getNavigationEntry(); if (navigationEntry) { metric.value = Math.max(navigationEntry.responseStart - getActivationStart(), 0); metric.entries = [navigationEntry]; report(true); } }); }, "onTTFB"); const handlers$3 = {}; const instrumented = {}; let _previousCls; let _previousFid; let _previousLcp; let _previousTtfb; let _previousInp; function addClsInstrumentationHandler(callback, stopOnCallback = false) { return addMetricObserver("cls", callback, instrumentCls, _previousCls, stopOnCallback); } __name(addClsInstrumentationHandler, "addClsInstrumentationHandler"); function addLcpInstrumentationHandler(callback, stopOnCallback = false) { return addMetricObserver("lcp", callback, instrumentLcp, _previousLcp, stopOnCallback); } __name(addLcpInstrumentationHandler, "addLcpInstrumentationHandler"); function addFidInstrumentationHandler(callback) { return addMetricObserver("fid", callback, instrumentFid, _previousFid); } __name(addFidInstrumentationHandler, "addFidInstrumentationHandler"); function addTtfbInstrumentationHandler(callback) { return addMetricObserver("ttfb", callback, instrumentTtfb, _previousTtfb); } __name(addTtfbInstrumentationHandler, "addTtfbInstrumentationHandler"); function addInpInstrumentationHandler(callback) { return addMetricObserver("inp", callback, instrumentInp, _previousInp); } __name(addInpInstrumentationHandler, "addInpInstrumentationHandler"); function addPerformanceInstrumentationHandler(type, callback) { addHandler(type, callback); if (!instrumented[type]) { instrumentPerformanceObserver(type); instrumented[type] = true; } return getCleanupCallback(type, callback); } __name(addPerformanceInstrumentationHandler, "addPerformanceInstrumentationHandler"); function triggerHandlers(type, data25) { const typeHandlers = handlers$3[type]; if (!typeHandlers || !typeHandlers.length) { return; } for (const handler6 of typeHandlers) { try { handler6(data25); } catch (e2) { DEBUG_BUILD$3 && logger$2.error( `Error while triggering instrumentation handler. Type: ${type} Name: ${getFunctionName(handler6)} Error:`, e2 ); } } } __name(triggerHandlers, "triggerHandlers"); function instrumentCls() { return onCLS( (metric) => { triggerHandlers("cls", { metric }); _previousCls = metric; }, // We want the callback to be called whenever the CLS value updates. // By default, the callback is only called when the tab goes to the background. { reportAllChanges: true } ); } __name(instrumentCls, "instrumentCls"); function instrumentFid() { return onFID((metric) => { triggerHandlers("fid", { metric }); _previousFid = metric; }); } __name(instrumentFid, "instrumentFid"); function instrumentLcp() { return onLCP( (metric) => { triggerHandlers("lcp", { metric }); _previousLcp = metric; }, // We want the callback to be called whenever the LCP value updates. // By default, the callback is only called when the tab goes to the background. { reportAllChanges: true } ); } __name(instrumentLcp, "instrumentLcp"); function instrumentTtfb() { return onTTFB((metric) => { triggerHandlers("ttfb", { metric }); _previousTtfb = metric; }); } __name(instrumentTtfb, "instrumentTtfb"); function instrumentInp() { return onINP((metric) => { triggerHandlers("inp", { metric }); _previousInp = metric; }); } __name(instrumentInp, "instrumentInp"); function addMetricObserver(type, callback, instrumentFn, previousValue, stopOnCallback = false) { addHandler(type, callback); let stopListening; if (!instrumented[type]) { stopListening = instrumentFn(); instrumented[type] = true; } if (previousValue) { callback({ metric: previousValue }); } return getCleanupCallback(type, callback, stopOnCallback ? stopListening : void 0); } __name(addMetricObserver, "addMetricObserver"); function instrumentPerformanceObserver(type) { const options4 = {}; if (type === "event") { options4.durationThreshold = 0; } observe( type, (entries) => { triggerHandlers(type, { entries }); }, options4 ); } __name(instrumentPerformanceObserver, "instrumentPerformanceObserver"); function addHandler(type, handler6) { handlers$3[type] = handlers$3[type] || []; handlers$3[type].push(handler6); } __name(addHandler, "addHandler"); function getCleanupCallback(type, callback, stopListening) { return () => { if (stopListening) { stopListening(); } const typeHandlers = handlers$3[type]; if (!typeHandlers) { return; } const index2 = typeHandlers.indexOf(callback); if (index2 !== -1) { typeHandlers.splice(index2, 1); } }; } __name(getCleanupCallback, "getCleanupCallback"); function isPerformanceEventTiming(entry) { return "duration" in entry; } __name(isPerformanceEventTiming, "isPerformanceEventTiming"); function isMeasurementValue(value4) { return typeof value4 === "number" && isFinite(value4); } __name(isMeasurementValue, "isMeasurementValue"); function startAndEndSpan(parentSpan, startTimeInSeconds, endTime, { ...ctx }) { const parentStartTime = spanToJSON(parentSpan).start_timestamp; if (parentStartTime && parentStartTime > startTimeInSeconds) { if (typeof parentSpan.updateStartTime === "function") { parentSpan.updateStartTime(startTimeInSeconds); } } return withActiveSpan(parentSpan, () => { const span = startInactiveSpan({ startTime: startTimeInSeconds, ...ctx }); if (span) { span.end(endTime); } return span; }); } __name(startAndEndSpan, "startAndEndSpan"); function startStandaloneWebVitalSpan(options4) { const client = getClient(); if (!client) { return; } const { name: name2, transaction, attributes: passedAttributes, startTime } = options4; const { release, environment } = client.getOptions(); const replay = client.getIntegrationByName("Replay"); const replayId = replay && replay.getReplayId(); const scope = getCurrentScope$1(); const user = scope.getUser(); const userDisplay = user !== void 0 ? user.email || user.id || user.ip_address : void 0; let profileId; try { profileId = scope.getScopeData().contexts.profile.profile_id; } catch (e2) { } const attributes = { release, environment, user: userDisplay || void 0, profile_id: profileId || void 0, replay_id: replayId || void 0, transaction, // Web vital score calculation relies on the user agent to account for different // browsers setting different thresholds for what is considered a good/meh/bad value. // For example: Chrome vs. Chrome Mobile "user_agent.original": WINDOW$4.navigator && WINDOW$4.navigator.userAgent, ...passedAttributes }; return startInactiveSpan({ name: name2, attributes, startTime, experimental: { standalone: true } }); } __name(startStandaloneWebVitalSpan, "startStandaloneWebVitalSpan"); function getBrowserPerformanceAPI() { return WINDOW$4 && WINDOW$4.addEventListener && WINDOW$4.performance; } __name(getBrowserPerformanceAPI, "getBrowserPerformanceAPI"); function msToSec(time) { return time / 1e3; } __name(msToSec, "msToSec"); function trackClsAsStandaloneSpan() { let standaloneCLsValue = 0; let standaloneClsEntry; let pageloadSpanId; if (!supportsLayoutShift()) { return; } let sentSpan = false; function _collectClsOnce() { if (sentSpan) { return; } sentSpan = true; if (pageloadSpanId) { sendStandaloneClsSpan(standaloneCLsValue, standaloneClsEntry, pageloadSpanId); } cleanupClsHandler(); } __name(_collectClsOnce, "_collectClsOnce"); const cleanupClsHandler = addClsInstrumentationHandler(({ metric }) => { const entry = metric.entries[metric.entries.length - 1]; if (!entry) { return; } standaloneCLsValue = metric.value; standaloneClsEntry = entry; }, true); onHidden(() => { _collectClsOnce(); }); setTimeout(() => { const client = getClient(); if (!client) { return; } const unsubscribeStartNavigation = client.on("startNavigationSpan", () => { _collectClsOnce(); unsubscribeStartNavigation && unsubscribeStartNavigation(); }); const activeSpan = getActiveSpan(); const rootSpan = activeSpan && getRootSpan(activeSpan); const spanJSON = rootSpan && spanToJSON(rootSpan); if (spanJSON && spanJSON.op === "pageload") { pageloadSpanId = rootSpan.spanContext().spanId; } }, 0); } __name(trackClsAsStandaloneSpan, "trackClsAsStandaloneSpan"); function sendStandaloneClsSpan(clsValue, entry, pageloadSpanId) { DEBUG_BUILD$3 && logger$2.log(`Sending CLS span (${clsValue})`); const startTime = msToSec((browserPerformanceTimeOrigin || 0) + (entry && entry.startTime || 0)); const routeName = getCurrentScope$1().getScopeData().transactionName; const name2 = entry ? htmlTreeAsString(entry.sources[0] && entry.sources[0].node) : "Layout shift"; const attributes = dropUndefinedKeys({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.cls", [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "ui.webvital.cls", [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry && entry.duration || 0, // attach the pageload span id to the CLS span so that we can link them in the UI "sentry.pageload.span_id": pageloadSpanId }); const span = startStandaloneWebVitalSpan({ name: name2, transaction: routeName, attributes, startTime }); if (span) { span.addEvent("cls", { [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "", [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: clsValue }); span.end(startTime); } } __name(sendStandaloneClsSpan, "sendStandaloneClsSpan"); function supportsLayoutShift() { try { return PerformanceObserver.supportedEntryTypes.includes("layout-shift"); } catch (e2) { return false; } } __name(supportsLayoutShift, "supportsLayoutShift"); const MAX_INT_AS_BYTES = 2147483647; let _performanceCursor = 0; let _measurements = {}; let _lcpEntry; let _clsEntry; function startTrackingWebVitals({ recordClsStandaloneSpans }) { const performance2 = getBrowserPerformanceAPI(); if (performance2 && browserPerformanceTimeOrigin) { if (performance2.mark) { WINDOW$4.performance.mark("sentry-tracing-init"); } const fidCleanupCallback = _trackFID(); const lcpCleanupCallback = _trackLCP(); const ttfbCleanupCallback = _trackTtfb(); const clsCleanupCallback = recordClsStandaloneSpans ? trackClsAsStandaloneSpan() : _trackCLS(); return () => { fidCleanupCallback(); lcpCleanupCallback(); ttfbCleanupCallback(); clsCleanupCallback && clsCleanupCallback(); }; } return () => void 0; } __name(startTrackingWebVitals, "startTrackingWebVitals"); function startTrackingLongTasks() { addPerformanceInstrumentationHandler("longtask", ({ entries }) => { const parent = getActiveSpan(); if (!parent) { return; } const { op: parentOp, start_timestamp: parentStartTimestamp } = spanToJSON(parent); for (const entry of entries) { const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime); const duration = msToSec(entry.duration); if (parentOp === "navigation" && parentStartTimestamp && startTime < parentStartTimestamp) { continue; } startAndEndSpan(parent, startTime, startTime + duration, { name: "Main UI thread blocked", op: "ui.long-task", attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } }); } }); } __name(startTrackingLongTasks, "startTrackingLongTasks"); function startTrackingLongAnimationFrames() { const observer = new PerformanceObserver((list2) => { const parent = getActiveSpan(); if (!parent) { return; } for (const entry of list2.getEntries()) { if (!entry.scripts[0]) { continue; } const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime); const { start_timestamp: parentStartTimestamp, op: parentOp } = spanToJSON(parent); if (parentOp === "navigation" && parentStartTimestamp && startTime < parentStartTimestamp) { continue; } const duration = msToSec(entry.duration); const attributes = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" }; const initialScript = entry.scripts[0]; const { invoker, invokerType, sourceURL, sourceFunctionName, sourceCharPosition } = initialScript; attributes["browser.script.invoker"] = invoker; attributes["browser.script.invoker_type"] = invokerType; if (sourceURL) { attributes["code.filepath"] = sourceURL; } if (sourceFunctionName) { attributes["code.function"] = sourceFunctionName; } if (sourceCharPosition !== -1) { attributes["browser.script.source_char_position"] = sourceCharPosition; } startAndEndSpan(parent, startTime, startTime + duration, { name: "Main UI thread blocked", op: "ui.long-animation-frame", attributes }); } }); observer.observe({ type: "long-animation-frame", buffered: true }); } __name(startTrackingLongAnimationFrames, "startTrackingLongAnimationFrames"); function startTrackingInteractions() { addPerformanceInstrumentationHandler("event", ({ entries }) => { const parent = getActiveSpan(); if (!parent) { return; } for (const entry of entries) { if (entry.name === "click") { const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime); const duration = msToSec(entry.duration); const spanOptions = { name: htmlTreeAsString(entry.target), op: `ui.interaction.${entry.name}`, startTime, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } }; const componentName = getComponentName$1(entry.target); if (componentName) { spanOptions.attributes["ui.component_name"] = componentName; } startAndEndSpan(parent, startTime, startTime + duration, spanOptions); } } }); } __name(startTrackingInteractions, "startTrackingInteractions"); function _trackCLS() { return addClsInstrumentationHandler(({ metric }) => { const entry = metric.entries[metric.entries.length - 1]; if (!entry) { return; } _measurements["cls"] = { value: metric.value, unit: "" }; _clsEntry = entry; }, true); } __name(_trackCLS, "_trackCLS"); function _trackLCP() { return addLcpInstrumentationHandler(({ metric }) => { const entry = metric.entries[metric.entries.length - 1]; if (!entry) { return; } _measurements["lcp"] = { value: metric.value, unit: "millisecond" }; _lcpEntry = entry; }, true); } __name(_trackLCP, "_trackLCP"); function _trackFID() { return addFidInstrumentationHandler(({ metric }) => { const entry = metric.entries[metric.entries.length - 1]; if (!entry) { return; } const timeOrigin = msToSec(browserPerformanceTimeOrigin); const startTime = msToSec(entry.startTime); _measurements["fid"] = { value: metric.value, unit: "millisecond" }; _measurements["mark.fid"] = { value: timeOrigin + startTime, unit: "second" }; }); } __name(_trackFID, "_trackFID"); function _trackTtfb() { return addTtfbInstrumentationHandler(({ metric }) => { const entry = metric.entries[metric.entries.length - 1]; if (!entry) { return; } _measurements["ttfb"] = { value: metric.value, unit: "millisecond" }; }); } __name(_trackTtfb, "_trackTtfb"); function addPerformanceEntries(span, options4) { const performance2 = getBrowserPerformanceAPI(); if (!performance2 || !performance2.getEntries || !browserPerformanceTimeOrigin) { return; } const timeOrigin = msToSec(browserPerformanceTimeOrigin); const performanceEntries = performance2.getEntries(); const { op, start_timestamp: transactionStartTime } = spanToJSON(span); performanceEntries.slice(_performanceCursor).forEach((entry) => { const startTime = msToSec(entry.startTime); const duration = msToSec( // Inexplicably, Chrome sometimes emits a negative duration. We need to work around this. // There is a SO post attempting to explain this, but it leaves one with open questions: https://stackoverflow.com/questions/23191918/peformance-getentries-and-negative-duration-display // The way we clamp the value is probably not accurate, since we have observed this happen for things that may take a while to load, like for example the replay worker. // TODO: Investigate why this happens and how to properly mitigate. For now, this is a workaround to prevent transactions being dropped due to negative duration spans. Math.max(0, entry.duration) ); if (op === "navigation" && transactionStartTime && timeOrigin + startTime < transactionStartTime) { return; } switch (entry.entryType) { case "navigation": { _addNavigationSpans(span, entry, timeOrigin); break; } case "mark": case "paint": case "measure": { _addMeasureSpans(span, entry, startTime, duration, timeOrigin); const firstHidden = getVisibilityWatcher(); const shouldRecord = entry.startTime < firstHidden.firstHiddenTime; if (entry.name === "first-paint" && shouldRecord) { _measurements["fp"] = { value: entry.startTime, unit: "millisecond" }; } if (entry.name === "first-contentful-paint" && shouldRecord) { _measurements["fcp"] = { value: entry.startTime, unit: "millisecond" }; } break; } case "resource": { _addResourceSpans(span, entry, entry.name, startTime, duration, timeOrigin); break; } } }); _performanceCursor = Math.max(performanceEntries.length - 1, 0); _trackNavigator(span); if (op === "pageload") { _addTtfbRequestTimeToMeasurements(_measurements); const fidMark = _measurements["mark.fid"]; if (fidMark && _measurements["fid"]) { startAndEndSpan(span, fidMark.value, fidMark.value + msToSec(_measurements["fid"].value), { name: "first input delay", op: "ui.action", attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } }); delete _measurements["mark.fid"]; } if (!("fcp" in _measurements) || !options4.recordClsOnPageloadSpan) { delete _measurements.cls; } Object.entries(_measurements).forEach(([measurementName, measurement]) => { setMeasurement(measurementName, measurement.value, measurement.unit); }); span.setAttribute("performance.timeOrigin", timeOrigin); span.setAttribute("performance.activationStart", getActivationStart()); _setWebVitalAttributes(span); } _lcpEntry = void 0; _clsEntry = void 0; _measurements = {}; } __name(addPerformanceEntries, "addPerformanceEntries"); function _addMeasureSpans(span, entry, startTime, duration, timeOrigin) { const navEntry = getNavigationEntry(false); const requestTime = msToSec(navEntry ? navEntry.requestStart : 0); const measureStartTimestamp = timeOrigin + Math.max(startTime, requestTime); const startTimeStamp = timeOrigin + startTime; const measureEndTimestamp = startTimeStamp + duration; const attributes = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.resource.browser.metrics" }; if (measureStartTimestamp !== startTimeStamp) { attributes["sentry.browser.measure_happened_before_request"] = true; attributes["sentry.browser.measure_start_time"] = measureStartTimestamp; } startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, { name: entry.name, op: entry.entryType, attributes }); return measureStartTimestamp; } __name(_addMeasureSpans, "_addMeasureSpans"); function _addNavigationSpans(span, entry, timeOrigin) { ["unloadEvent", "redirect", "domContentLoadedEvent", "loadEvent", "connect"].forEach((event) => { _addPerformanceNavigationTiming(span, entry, event, timeOrigin); }); _addPerformanceNavigationTiming(span, entry, "secureConnection", timeOrigin, "TLS/SSL"); _addPerformanceNavigationTiming(span, entry, "fetch", timeOrigin, "cache"); _addPerformanceNavigationTiming(span, entry, "domainLookup", timeOrigin, "DNS"); _addRequest(span, entry, timeOrigin); } __name(_addNavigationSpans, "_addNavigationSpans"); function _addPerformanceNavigationTiming(span, entry, event, timeOrigin, name2 = event) { const eventEnd = _getEndPropertyNameForNavigationTiming(event); const end = entry[eventEnd]; const start2 = entry[`${event}Start`]; if (!start2 || !end) { return; } startAndEndSpan(span, timeOrigin + msToSec(start2), timeOrigin + msToSec(end), { op: `browser.${name2}`, name: entry.name, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } }); } __name(_addPerformanceNavigationTiming, "_addPerformanceNavigationTiming"); function _getEndPropertyNameForNavigationTiming(event) { if (event === "secureConnection") { return "connectEnd"; } if (event === "fetch") { return "domainLookupStart"; } return `${event}End`; } __name(_getEndPropertyNameForNavigationTiming, "_getEndPropertyNameForNavigationTiming"); function _addRequest(span, entry, timeOrigin) { const requestStartTimestamp = timeOrigin + msToSec(entry.requestStart); const responseEndTimestamp = timeOrigin + msToSec(entry.responseEnd); const responseStartTimestamp = timeOrigin + msToSec(entry.responseStart); if (entry.responseEnd) { startAndEndSpan(span, requestStartTimestamp, responseEndTimestamp, { op: "browser.request", name: entry.name, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } }); startAndEndSpan(span, responseStartTimestamp, responseEndTimestamp, { op: "browser.response", name: entry.name, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } }); } } __name(_addRequest, "_addRequest"); function _addResourceSpans(span, entry, resourceUrl, startTime, duration, timeOrigin) { if (entry.initiatorType === "xmlhttprequest" || entry.initiatorType === "fetch") { return; } const parsedUrl = parseUrl$1(resourceUrl); const attributes = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.resource.browser.metrics" }; setResourceEntrySizeData(attributes, entry, "transferSize", "http.response_transfer_size"); setResourceEntrySizeData(attributes, entry, "encodedBodySize", "http.response_content_length"); setResourceEntrySizeData(attributes, entry, "decodedBodySize", "http.decoded_response_content_length"); const deliveryType = entry.deliveryType; if (deliveryType != null) { attributes["http.response_delivery_type"] = deliveryType; } const renderBlockingStatus = entry.renderBlockingStatus; if (renderBlockingStatus) { attributes["resource.render_blocking_status"] = renderBlockingStatus; } if (parsedUrl.protocol) { attributes["url.scheme"] = parsedUrl.protocol.split(":").pop(); } if (parsedUrl.host) { attributes["server.address"] = parsedUrl.host; } attributes["url.same_origin"] = resourceUrl.includes(WINDOW$4.location.origin); const startTimestamp = timeOrigin + startTime; const endTimestamp = startTimestamp + duration; startAndEndSpan(span, startTimestamp, endTimestamp, { name: resourceUrl.replace(WINDOW$4.location.origin, ""), op: entry.initiatorType ? `resource.${entry.initiatorType}` : "resource.other", attributes }); } __name(_addResourceSpans, "_addResourceSpans"); function _trackNavigator(span) { const navigator2 = WINDOW$4.navigator; if (!navigator2) { return; } const connection = navigator2.connection; if (connection) { if (connection.effectiveType) { span.setAttribute("effectiveConnectionType", connection.effectiveType); } if (connection.type) { span.setAttribute("connectionType", connection.type); } if (isMeasurementValue(connection.rtt)) { _measurements["connection.rtt"] = { value: connection.rtt, unit: "millisecond" }; } } if (isMeasurementValue(navigator2.deviceMemory)) { span.setAttribute("deviceMemory", `${navigator2.deviceMemory} GB`); } if (isMeasurementValue(navigator2.hardwareConcurrency)) { span.setAttribute("hardwareConcurrency", String(navigator2.hardwareConcurrency)); } } __name(_trackNavigator, "_trackNavigator"); function _setWebVitalAttributes(span) { if (_lcpEntry) { if (_lcpEntry.element) { span.setAttribute("lcp.element", htmlTreeAsString(_lcpEntry.element)); } if (_lcpEntry.id) { span.setAttribute("lcp.id", _lcpEntry.id); } if (_lcpEntry.url) { span.setAttribute("lcp.url", _lcpEntry.url.trim().slice(0, 200)); } if (_lcpEntry.loadTime != null) { span.setAttribute("lcp.loadTime", _lcpEntry.loadTime); } if (_lcpEntry.renderTime != null) { span.setAttribute("lcp.renderTime", _lcpEntry.renderTime); } span.setAttribute("lcp.size", _lcpEntry.size); } if (_clsEntry && _clsEntry.sources) { _clsEntry.sources.forEach( (source, index2) => span.setAttribute(`cls.source.${index2 + 1}`, htmlTreeAsString(source.node)) ); } } __name(_setWebVitalAttributes, "_setWebVitalAttributes"); function setResourceEntrySizeData(attributes, entry, key, dataKey) { const entryVal = entry[key]; if (entryVal != null && entryVal < MAX_INT_AS_BYTES) { attributes[dataKey] = entryVal; } } __name(setResourceEntrySizeData, "setResourceEntrySizeData"); function _addTtfbRequestTimeToMeasurements(_measurements2) { const navEntry = getNavigationEntry(false); if (!navEntry) { return; } const { responseStart, requestStart } = navEntry; if (requestStart <= responseStart) { _measurements2["ttfb.requestTime"] = { value: responseStart - requestStart, unit: "millisecond" }; } } __name(_addTtfbRequestTimeToMeasurements, "_addTtfbRequestTimeToMeasurements"); const DEBOUNCE_DURATION = 1e3; let debounceTimerID; let lastCapturedEventType; let lastCapturedEventTargetId; function addClickKeypressInstrumentationHandler(handler6) { const type = "dom"; addHandler$1(type, handler6); maybeInstrument(type, instrumentDOM); } __name(addClickKeypressInstrumentationHandler, "addClickKeypressInstrumentationHandler"); function instrumentDOM() { if (!WINDOW$4.document) { return; } const triggerDOMHandler = triggerHandlers$1.bind(null, "dom"); const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); WINDOW$4.document.addEventListener("click", globalDOMEventHandler, false); WINDOW$4.document.addEventListener("keypress", globalDOMEventHandler, false); ["EventTarget", "Node"].forEach((target) => { const globalObject = WINDOW$4; const targetObj = globalObject[target]; const proto = targetObj && targetObj.prototype; if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) { return; } fill(proto, "addEventListener", function(originalAddEventListener) { return function(type, listener, options4) { if (type === "click" || type == "keypress") { try { const handlers2 = this.__sentry_instrumentation_handlers__ = this.__sentry_instrumentation_handlers__ || {}; const handlerForType = handlers2[type] = handlers2[type] || { refCount: 0 }; if (!handlerForType.handler) { const handler6 = makeDOMEventHandler(triggerDOMHandler); handlerForType.handler = handler6; originalAddEventListener.call(this, type, handler6, options4); } handlerForType.refCount++; } catch (e2) { } } return originalAddEventListener.call(this, type, listener, options4); }; }); fill( proto, "removeEventListener", function(originalRemoveEventListener) { return function(type, listener, options4) { if (type === "click" || type == "keypress") { try { const handlers2 = this.__sentry_instrumentation_handlers__ || {}; const handlerForType = handlers2[type]; if (handlerForType) { handlerForType.refCount--; if (handlerForType.refCount <= 0) { originalRemoveEventListener.call(this, type, handlerForType.handler, options4); handlerForType.handler = void 0; delete handlers2[type]; } if (Object.keys(handlers2).length === 0) { delete this.__sentry_instrumentation_handlers__; } } } catch (e2) { } } return originalRemoveEventListener.call(this, type, listener, options4); }; } ); }); } __name(instrumentDOM, "instrumentDOM"); function isSimilarToLastCapturedEvent(event) { if (event.type !== lastCapturedEventType) { return false; } try { if (!event.target || event.target._sentryId !== lastCapturedEventTargetId) { return false; } } catch (e2) { } return true; } __name(isSimilarToLastCapturedEvent, "isSimilarToLastCapturedEvent"); function shouldSkipDOMEvent(eventType, target) { if (eventType !== "keypress") { return false; } if (!target || !target.tagName) { return true; } if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) { return false; } return true; } __name(shouldSkipDOMEvent, "shouldSkipDOMEvent"); function makeDOMEventHandler(handler6, globalListener = false) { return (event) => { if (!event || event["_sentryCaptured"]) { return; } const target = getEventTarget$1(event); if (shouldSkipDOMEvent(event.type, target)) { return; } addNonEnumerableProperty(event, "_sentryCaptured", true); if (target && !target._sentryId) { addNonEnumerableProperty(target, "_sentryId", uuid4()); } const name2 = event.type === "keypress" ? "input" : event.type; if (!isSimilarToLastCapturedEvent(event)) { const handlerData = { event, name: name2, global: globalListener }; handler6(handlerData); lastCapturedEventType = event.type; lastCapturedEventTargetId = target ? target._sentryId : void 0; } clearTimeout(debounceTimerID); debounceTimerID = WINDOW$4.setTimeout(() => { lastCapturedEventTargetId = void 0; lastCapturedEventType = void 0; }, DEBOUNCE_DURATION); }; } __name(makeDOMEventHandler, "makeDOMEventHandler"); function getEventTarget$1(event) { try { return event.target; } catch (e2) { return null; } } __name(getEventTarget$1, "getEventTarget$1"); let lastHref; function addHistoryInstrumentationHandler(handler6) { const type = "history"; addHandler$1(type, handler6); maybeInstrument(type, instrumentHistory); } __name(addHistoryInstrumentationHandler, "addHistoryInstrumentationHandler"); function instrumentHistory() { if (!supportsHistory()) { return; } const oldOnPopState = WINDOW$4.onpopstate; WINDOW$4.onpopstate = function(...args) { const to = WINDOW$4.location.href; const from2 = lastHref; lastHref = to; const handlerData = { from: from2, to }; triggerHandlers$1("history", handlerData); if (oldOnPopState) { try { return oldOnPopState.apply(this, args); } catch (_oO) { } } }; function historyReplacementFunction(originalHistoryFunction) { return function(...args) { const url = args.length > 2 ? args[2] : void 0; if (url) { const from2 = lastHref; const to = String(url); lastHref = to; const handlerData = { from: from2, to }; triggerHandlers$1("history", handlerData); } return originalHistoryFunction.apply(this, args); }; } __name(historyReplacementFunction, "historyReplacementFunction"); fill(WINDOW$4.history, "pushState", historyReplacementFunction); fill(WINDOW$4.history, "replaceState", historyReplacementFunction); } __name(instrumentHistory, "instrumentHistory"); const cachedImplementations$3 = {}; function getNativeImplementation(name2) { const cached = cachedImplementations$3[name2]; if (cached) { return cached; } let impl = WINDOW$4[name2]; if (isNativeFunction(impl)) { return cachedImplementations$3[name2] = impl.bind(WINDOW$4); } const document2 = WINDOW$4.document; if (document2 && typeof document2.createElement === "function") { try { const sandbox = document2.createElement("iframe"); sandbox.hidden = true; document2.head.appendChild(sandbox); const contentWindow = sandbox.contentWindow; if (contentWindow && contentWindow[name2]) { impl = contentWindow[name2]; } document2.head.removeChild(sandbox); } catch (e2) { DEBUG_BUILD$3 && logger$2.warn(`Could not create sandbox iframe for ${name2} check, bailing to window.${name2}: `, e2); } } if (!impl) { return impl; } return cachedImplementations$3[name2] = impl.bind(WINDOW$4); } __name(getNativeImplementation, "getNativeImplementation"); function clearCachedImplementation(name2) { cachedImplementations$3[name2] = void 0; } __name(clearCachedImplementation, "clearCachedImplementation"); function fetch$1(...rest) { return getNativeImplementation("fetch")(...rest); } __name(fetch$1, "fetch$1"); function setTimeout$3(...rest) { return getNativeImplementation("setTimeout")(...rest); } __name(setTimeout$3, "setTimeout$3"); const SENTRY_XHR_DATA_KEY = "__sentry_xhr_v3__"; function addXhrInstrumentationHandler(handler6) { const type = "xhr"; addHandler$1(type, handler6); maybeInstrument(type, instrumentXHR); } __name(addXhrInstrumentationHandler, "addXhrInstrumentationHandler"); function instrumentXHR() { if (!WINDOW$4.XMLHttpRequest) { return; } const xhrproto = XMLHttpRequest.prototype; xhrproto.open = new Proxy(xhrproto.open, { apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) { const virtualError = new Error(); const startTimestamp = timestampInSeconds() * 1e3; const method = isString$8(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : void 0; const url = parseUrl(xhrOpenArgArray[1]); if (!method || !url) { return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray); } xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = { method, url, request_headers: {} }; if (method === "POST" && url.match(/sentry_key/)) { xhrOpenThisArg.__sentry_own_request__ = true; } const onreadystatechangeHandler = /* @__PURE__ */ __name(() => { const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY]; if (!xhrInfo) { return; } if (xhrOpenThisArg.readyState === 4) { try { xhrInfo.status_code = xhrOpenThisArg.status; } catch (e2) { } const handlerData = { endTimestamp: timestampInSeconds() * 1e3, startTimestamp, xhr: xhrOpenThisArg, virtualError }; triggerHandlers$1("xhr", handlerData); } }, "onreadystatechangeHandler"); if ("onreadystatechange" in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === "function") { xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, { apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) { onreadystatechangeHandler(); return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray); } }); } else { xhrOpenThisArg.addEventListener("readystatechange", onreadystatechangeHandler); } xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, { apply(originalSetRequestHeader, setRequestHeaderThisArg, setRequestHeaderArgArray) { const [header3, value4] = setRequestHeaderArgArray; const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY]; if (xhrInfo && isString$8(header3) && isString$8(value4)) { xhrInfo.request_headers[header3.toLowerCase()] = value4; } return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray); } }); return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray); } }); xhrproto.send = new Proxy(xhrproto.send, { apply(originalSend, sendThisArg, sendArgArray) { const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY]; if (!sentryXhrData) { return originalSend.apply(sendThisArg, sendArgArray); } if (sendArgArray[0] !== void 0) { sentryXhrData.body = sendArgArray[0]; } const handlerData = { startTimestamp: timestampInSeconds() * 1e3, xhr: sendThisArg }; triggerHandlers$1("xhr", handlerData); return originalSend.apply(sendThisArg, sendArgArray); } }); } __name(instrumentXHR, "instrumentXHR"); function parseUrl(url) { if (isString$8(url)) { return url; } try { return url.toString(); } catch (e2) { } return void 0; } __name(parseUrl, "parseUrl"); const LAST_INTERACTIONS = []; const INTERACTIONS_SPAN_MAP = /* @__PURE__ */ new Map(); function startTrackingINP() { const performance2 = getBrowserPerformanceAPI(); if (performance2 && browserPerformanceTimeOrigin) { const inpCallback = _trackINP(); return () => { inpCallback(); }; } return () => void 0; } __name(startTrackingINP, "startTrackingINP"); const INP_ENTRY_MAP = { click: "click", pointerdown: "click", pointerup: "click", mousedown: "click", mouseup: "click", touchstart: "click", touchend: "click", mouseover: "hover", mouseout: "hover", mouseenter: "hover", mouseleave: "hover", pointerover: "hover", pointerout: "hover", pointerenter: "hover", pointerleave: "hover", dragstart: "drag", dragend: "drag", drag: "drag", dragenter: "drag", dragleave: "drag", dragover: "drag", drop: "drag", keydown: "press", keyup: "press", keypress: "press", input: "press" }; function _trackINP() { return addInpInstrumentationHandler(({ metric }) => { if (metric.value == void 0) { return; } const entry = metric.entries.find((entry2) => entry2.duration === metric.value && INP_ENTRY_MAP[entry2.name]); if (!entry) { return; } const { interactionId } = entry; const interactionType = INP_ENTRY_MAP[entry.name]; const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime); const duration = msToSec(metric.value); const activeSpan = getActiveSpan(); const rootSpan = activeSpan ? getRootSpan(activeSpan) : void 0; const cachedSpan = interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : void 0; const spanToUse = cachedSpan || rootSpan; const routeName = spanToUse ? spanToJSON(spanToUse).description : getCurrentScope$1().getScopeData().transactionName; const name2 = htmlTreeAsString(entry.target); const attributes = dropUndefinedKeys({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.inp", [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `ui.interaction.${interactionType}`, [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry.duration }); const span = startStandaloneWebVitalSpan({ name: name2, transaction: routeName, attributes, startTime }); if (span) { span.addEvent("inp", { [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "millisecond", [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: metric.value }); span.end(startTime + duration); } }); } __name(_trackINP, "_trackINP"); function registerInpInteractionListener(_latestRoute) { const handleEntries = /* @__PURE__ */ __name(({ entries }) => { const activeSpan = getActiveSpan(); const activeRootSpan = activeSpan && getRootSpan(activeSpan); entries.forEach((entry) => { if (!isPerformanceEventTiming(entry) || !activeRootSpan) { return; } const interactionId = entry.interactionId; if (interactionId == null) { return; } if (INTERACTIONS_SPAN_MAP.has(interactionId)) { return; } if (LAST_INTERACTIONS.length > 10) { const last = LAST_INTERACTIONS.shift(); INTERACTIONS_SPAN_MAP.delete(last); } LAST_INTERACTIONS.push(interactionId); INTERACTIONS_SPAN_MAP.set(interactionId, activeRootSpan); }); }, "handleEntries"); addPerformanceInstrumentationHandler("event", handleEntries); addPerformanceInstrumentationHandler("first-input", handleEntries); } __name(registerInpInteractionListener, "registerInpInteractionListener"); function makeFetchTransport(options4, nativeFetch = getNativeImplementation("fetch")) { let pendingBodySize = 0; let pendingCount = 0; function makeRequest(request) { const requestSize = request.body.length; pendingBodySize += requestSize; pendingCount++; const requestOptions = { body: request.body, method: "POST", referrerPolicy: "origin", headers: options4.headers, // Outgoing requests are usually cancelled when navigating to a different page, causing a "TypeError: Failed to // fetch" error and sending a "network_error" client-outcome - in Chrome, the request status shows "(cancelled)". // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're // frequently sending events right before the user is switching pages (eg. when finishing navigation transactions). // Gotchas: // - `keepalive` isn't supported by Firefox // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch): // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error. // We will therefore only activate the flag when we're below that limit. // There is also a limit of requests that can be open at the same time, so we also limit this to 15 // See https://github.com/getsentry/sentry-javascript/pull/7553 for details keepalive: pendingBodySize <= 6e4 && pendingCount < 15, ...options4.fetchOptions }; if (!nativeFetch) { clearCachedImplementation("fetch"); return rejectedSyncPromise("No fetch implementation available"); } try { return nativeFetch(options4.url, requestOptions).then((response) => { pendingBodySize -= requestSize; pendingCount--; return { statusCode: response.status, headers: { "x-sentry-rate-limits": response.headers.get("X-Sentry-Rate-Limits"), "retry-after": response.headers.get("Retry-After") } }; }); } catch (e2) { clearCachedImplementation("fetch"); pendingBodySize -= requestSize; pendingCount--; return rejectedSyncPromise(e2); } } __name(makeRequest, "makeRequest"); return createTransport(options4, makeRequest); } __name(makeFetchTransport, "makeFetchTransport"); const OPERA10_PRIORITY = 10; const OPERA11_PRIORITY = 20; const CHROME_PRIORITY = 30; const WINJS_PRIORITY = 40; const GECKO_PRIORITY = 50; function createFrame(filename, func, lineno, colno) { const frame = { filename, function: func === "" ? UNKNOWN_FUNCTION : func, in_app: true // All browser frames are considered in_app }; if (lineno !== void 0) { frame.lineno = lineno; } if (colno !== void 0) { frame.colno = colno; } return frame; } __name(createFrame, "createFrame"); const chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i; const chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; const chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/; const chromeStackParserFn = /* @__PURE__ */ __name((line) => { const noFnParts = chromeRegexNoFnName.exec(line); if (noFnParts) { const [, filename, line2, col] = noFnParts; return createFrame(filename, UNKNOWN_FUNCTION, +line2, +col); } const parts2 = chromeRegex.exec(line); if (parts2) { const isEval = parts2[2] && parts2[2].indexOf("eval") === 0; if (isEval) { const subMatch = chromeEvalRegex.exec(parts2[2]); if (subMatch) { parts2[2] = subMatch[1]; parts2[3] = subMatch[2]; parts2[4] = subMatch[3]; } } const [func, filename] = extractSafariExtensionDetails(parts2[1] || UNKNOWN_FUNCTION, parts2[2]); return createFrame(filename, func, parts2[3] ? +parts2[3] : void 0, parts2[4] ? +parts2[4] : void 0); } return; }, "chromeStackParserFn"); const chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn]; const geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i; const geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; const gecko$1 = /* @__PURE__ */ __name((line) => { const parts2 = geckoREgex.exec(line); if (parts2) { const isEval = parts2[3] && parts2[3].indexOf(" > eval") > -1; if (isEval) { const subMatch = geckoEvalRegex.exec(parts2[3]); if (subMatch) { parts2[1] = parts2[1] || "eval"; parts2[3] = subMatch[1]; parts2[4] = subMatch[2]; parts2[5] = ""; } } let filename = parts2[3]; let func = parts2[1] || UNKNOWN_FUNCTION; [func, filename] = extractSafariExtensionDetails(func, filename); return createFrame(filename, func, parts2[4] ? +parts2[4] : void 0, parts2[5] ? +parts2[5] : void 0); } return; }, "gecko$1"); const geckoStackLineParser = [GECKO_PRIORITY, gecko$1]; const winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i; const winjs = /* @__PURE__ */ __name((line) => { const parts2 = winjsRegex.exec(line); return parts2 ? createFrame(parts2[2], parts2[1] || UNKNOWN_FUNCTION, +parts2[3], parts2[4] ? +parts2[4] : void 0) : void 0; }, "winjs"); const winjsStackLineParser = [WINJS_PRIORITY, winjs]; const opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i; const opera10 = /* @__PURE__ */ __name((line) => { const parts2 = opera10Regex.exec(line); return parts2 ? createFrame(parts2[2], parts2[3] || UNKNOWN_FUNCTION, +parts2[1]) : void 0; }, "opera10"); const opera10StackLineParser = [OPERA10_PRIORITY, opera10]; const opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:]+)>|([^)]+))\(.*\))? in (.*):\s*$/i; const opera11 = /* @__PURE__ */ __name((line) => { const parts2 = opera11Regex.exec(line); return parts2 ? createFrame(parts2[5], parts2[3] || parts2[4] || UNKNOWN_FUNCTION, +parts2[1], +parts2[2]) : void 0; }, "opera11"); const opera11StackLineParser = [OPERA11_PRIORITY, opera11]; const defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser]; const defaultStackParser = createStackParser(...defaultStackLineParsers); const extractSafariExtensionDetails = /* @__PURE__ */ __name((func, filename) => { const isSafariExtension = func.indexOf("safari-extension") !== -1; const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1; return isSafariExtension || isSafariWebExtension ? [ func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION, isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}` ] : [func, filename]; }, "extractSafariExtensionDetails"); const MAX_ALLOWED_STRING_LENGTH = 1024; const INTEGRATION_NAME$a = "Breadcrumbs"; const _breadcrumbsIntegration = /* @__PURE__ */ __name((options4 = {}) => { const _options = { console: true, dom: true, fetch: true, history: true, sentry: true, xhr: true, ...options4 }; return { name: INTEGRATION_NAME$a, setup(client) { if (_options.console) { addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client)); } if (_options.dom) { addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom)); } if (_options.xhr) { addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client)); } if (_options.fetch) { addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client)); } if (_options.history) { addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client)); } if (_options.sentry) { client.on("beforeSendEvent", _getSentryBreadcrumbHandler(client)); } } }; }, "_breadcrumbsIntegration"); const breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration); function _getSentryBreadcrumbHandler(client) { return /* @__PURE__ */ __name(function addSentryBreadcrumb(event) { if (getClient() !== client) { return; } addBreadcrumb( { category: `sentry.${event.type === "transaction" ? "transaction" : "event"}`, event_id: event.event_id, level: event.level, message: getEventDescription(event) }, { event } ); }, "addSentryBreadcrumb"); } __name(_getSentryBreadcrumbHandler, "_getSentryBreadcrumbHandler"); function _getDomBreadcrumbHandler(client, dom) { return /* @__PURE__ */ __name(function _innerDomBreadcrumb(handlerData) { if (getClient() !== client) { return; } let target; let componentName; let keyAttrs = typeof dom === "object" ? dom.serializeAttribute : void 0; let maxStringLength = typeof dom === "object" && typeof dom.maxStringLength === "number" ? dom.maxStringLength : void 0; if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) { DEBUG_BUILD$4 && logger$2.warn( `\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.` ); maxStringLength = MAX_ALLOWED_STRING_LENGTH; } if (typeof keyAttrs === "string") { keyAttrs = [keyAttrs]; } try { const event = handlerData.event; const element = _isEvent(event) ? event.target : event; target = htmlTreeAsString(element, { keyAttrs, maxStringLength }); componentName = getComponentName$1(element); } catch (e2) { target = ""; } if (target.length === 0) { return; } const breadcrumb = { category: `ui.${handlerData.name}`, message: target }; if (componentName) { breadcrumb.data = { "ui.component_name": componentName }; } addBreadcrumb(breadcrumb, { event: handlerData.event, name: handlerData.name, global: handlerData.global }); }, "_innerDomBreadcrumb"); } __name(_getDomBreadcrumbHandler, "_getDomBreadcrumbHandler"); function _getConsoleBreadcrumbHandler(client) { return /* @__PURE__ */ __name(function _consoleBreadcrumb(handlerData) { if (getClient() !== client) { return; } const breadcrumb = { category: "console", data: { arguments: handlerData.args, logger: "console" }, level: severityLevelFromString(handlerData.level), message: safeJoin(handlerData.args, " ") }; if (handlerData.level === "assert") { if (handlerData.args[0] === false) { breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), " ") || "console.assert"}`; breadcrumb.data.arguments = handlerData.args.slice(1); } else { return; } } addBreadcrumb(breadcrumb, { input: handlerData.args, level: handlerData.level }); }, "_consoleBreadcrumb"); } __name(_getConsoleBreadcrumbHandler, "_getConsoleBreadcrumbHandler"); function _getXhrBreadcrumbHandler(client) { return /* @__PURE__ */ __name(function _xhrBreadcrumb(handlerData) { if (getClient() !== client) { return; } const { startTimestamp, endTimestamp } = handlerData; const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY]; if (!startTimestamp || !endTimestamp || !sentryXhrData) { return; } const { method, url, status_code, body } = sentryXhrData; const data25 = { method, url, status_code }; const hint = { xhr: handlerData.xhr, input: body, startTimestamp, endTimestamp }; const level = getBreadcrumbLogLevelFromHttpStatusCode(status_code); addBreadcrumb( { category: "xhr", data: data25, type: "http", level }, hint ); }, "_xhrBreadcrumb"); } __name(_getXhrBreadcrumbHandler, "_getXhrBreadcrumbHandler"); function _getFetchBreadcrumbHandler(client) { return /* @__PURE__ */ __name(function _fetchBreadcrumb(handlerData) { if (getClient() !== client) { return; } const { startTimestamp, endTimestamp } = handlerData; if (!endTimestamp) { return; } if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === "POST") { return; } if (handlerData.error) { const data25 = handlerData.fetchData; const hint = { data: handlerData.error, input: handlerData.args, startTimestamp, endTimestamp }; addBreadcrumb( { category: "fetch", data: data25, level: "error", type: "http" }, hint ); } else { const response = handlerData.response; const data25 = { ...handlerData.fetchData, status_code: response && response.status }; const hint = { input: handlerData.args, response, startTimestamp, endTimestamp }; const level = getBreadcrumbLogLevelFromHttpStatusCode(data25.status_code); addBreadcrumb( { category: "fetch", data: data25, type: "http", level }, hint ); } }, "_fetchBreadcrumb"); } __name(_getFetchBreadcrumbHandler, "_getFetchBreadcrumbHandler"); function _getHistoryBreadcrumbHandler(client) { return /* @__PURE__ */ __name(function _historyBreadcrumb(handlerData) { if (getClient() !== client) { return; } let from2 = handlerData.from; let to = handlerData.to; const parsedLoc = parseUrl$1(WINDOW$5.location.href); let parsedFrom = from2 ? parseUrl$1(from2) : void 0; const parsedTo = parseUrl$1(to); if (!parsedFrom || !parsedFrom.path) { parsedFrom = parsedLoc; } if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) { to = parsedTo.relative; } if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) { from2 = parsedFrom.relative; } addBreadcrumb({ category: "navigation", data: { from: from2, to } }); }, "_historyBreadcrumb"); } __name(_getHistoryBreadcrumbHandler, "_getHistoryBreadcrumbHandler"); function _isEvent(event) { return !!event && !!event.target; } __name(_isEvent, "_isEvent"); const DEFAULT_EVENT_TARGET = [ "EventTarget", "Window", "Node", "ApplicationCache", "AudioTrackList", "BroadcastChannel", "ChannelMergerNode", "CryptoOperation", "EventSource", "FileReader", "HTMLUnknownElement", "IDBDatabase", "IDBRequest", "IDBTransaction", "KeyOperation", "MediaController", "MessagePort", "ModalWindow", "Notification", "SVGElementInstance", "Screen", "SharedWorker", "TextTrack", "TextTrackCue", "TextTrackList", "WebSocket", "WebSocketWorker", "Worker", "XMLHttpRequest", "XMLHttpRequestEventTarget", "XMLHttpRequestUpload" ]; const INTEGRATION_NAME$9 = "BrowserApiErrors"; const _browserApiErrorsIntegration = /* @__PURE__ */ __name((options4 = {}) => { const _options = { XMLHttpRequest: true, eventTarget: true, requestAnimationFrame: true, setInterval: true, setTimeout: true, ...options4 }; return { name: INTEGRATION_NAME$9, // TODO: This currently only works for the first client this is setup // We may want to adjust this to check for client etc. setupOnce() { if (_options.setTimeout) { fill(WINDOW$5, "setTimeout", _wrapTimeFunction); } if (_options.setInterval) { fill(WINDOW$5, "setInterval", _wrapTimeFunction); } if (_options.requestAnimationFrame) { fill(WINDOW$5, "requestAnimationFrame", _wrapRAF); } if (_options.XMLHttpRequest && "XMLHttpRequest" in WINDOW$5) { fill(XMLHttpRequest.prototype, "send", _wrapXHR$1); } const eventTargetOption = _options.eventTarget; if (eventTargetOption) { const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET; eventTarget.forEach(_wrapEventTarget); } } }; }, "_browserApiErrorsIntegration"); const browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration); function _wrapTimeFunction(original) { return function(...args) { const originalCallback = args[0]; args[0] = wrap$1(originalCallback, { mechanism: { data: { function: getFunctionName(original) }, handled: false, type: "instrument" } }); return original.apply(this, args); }; } __name(_wrapTimeFunction, "_wrapTimeFunction"); function _wrapRAF(original) { return function(callback) { return original.apply(this, [ wrap$1(callback, { mechanism: { data: { function: "requestAnimationFrame", handler: getFunctionName(original) }, handled: false, type: "instrument" } }) ]); }; } __name(_wrapRAF, "_wrapRAF"); function _wrapXHR$1(originalSend) { return function(...args) { const xhr = this; const xmlHttpRequestProps = ["onload", "onerror", "onprogress", "onreadystatechange"]; xmlHttpRequestProps.forEach((prop2) => { if (prop2 in xhr && typeof xhr[prop2] === "function") { fill(xhr, prop2, function(original) { const wrapOptions = { mechanism: { data: { function: prop2, handler: getFunctionName(original) }, handled: false, type: "instrument" } }; const originalFunction = getOriginalFunction(original); if (originalFunction) { wrapOptions.mechanism.data.handler = getFunctionName(originalFunction); } return wrap$1(original, wrapOptions); }); } }); return originalSend.apply(this, args); }; } __name(_wrapXHR$1, "_wrapXHR$1"); function _wrapEventTarget(target) { const globalObject = WINDOW$5; const targetObj = globalObject[target]; const proto = targetObj && targetObj.prototype; if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) { return; } fill(proto, "addEventListener", function(original) { return function(eventName, fn, options4) { try { if (isEventListenerObject(fn)) { fn.handleEvent = wrap$1(fn.handleEvent, { mechanism: { data: { function: "handleEvent", handler: getFunctionName(fn), target }, handled: false, type: "instrument" } }); } } catch (e2) { } return original.apply(this, [ eventName, wrap$1(fn, { mechanism: { data: { function: "addEventListener", handler: getFunctionName(fn), target }, handled: false, type: "instrument" } }), options4 ]); }; }); fill(proto, "removeEventListener", function(originalRemoveEventListener) { return function(eventName, fn, options4) { try { const originalEventHandler = fn.__sentry_wrapped__; if (originalEventHandler) { originalRemoveEventListener.call(this, eventName, originalEventHandler, options4); } } catch (e2) { } return originalRemoveEventListener.call(this, eventName, fn, options4); }; }); } __name(_wrapEventTarget, "_wrapEventTarget"); function isEventListenerObject(obj) { return typeof obj.handleEvent === "function"; } __name(isEventListenerObject, "isEventListenerObject"); const browserSessionIntegration = defineIntegration(() => { return { name: "BrowserSession", setupOnce() { if (typeof WINDOW$5.document === "undefined") { DEBUG_BUILD$4 && logger$2.warn("Using the `browserSessionIntegration` in non-browser environments is not supported."); return; } startSession({ ignoreDuration: true }); captureSession(); addHistoryInstrumentationHandler(({ from: from2, to }) => { if (from2 !== void 0 && from2 !== to) { startSession({ ignoreDuration: true }); captureSession(); } }); } }; }); const INTEGRATION_NAME$8 = "GlobalHandlers"; const _globalHandlersIntegration = /* @__PURE__ */ __name((options4 = {}) => { const _options = { onerror: true, onunhandledrejection: true, ...options4 }; return { name: INTEGRATION_NAME$8, setupOnce() { Error.stackTraceLimit = 50; }, setup(client) { if (_options.onerror) { _installGlobalOnErrorHandler(client); globalHandlerLog("onerror"); } if (_options.onunhandledrejection) { _installGlobalOnUnhandledRejectionHandler(client); globalHandlerLog("onunhandledrejection"); } } }; }, "_globalHandlersIntegration"); const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration); function _installGlobalOnErrorHandler(client) { addGlobalErrorInstrumentationHandler((data25) => { const { stackParser, attachStacktrace } = getOptions(); if (getClient() !== client || shouldIgnoreOnError()) { return; } const { msg, url, line, column, error: error2 } = data25; const event = _enhanceEventWithInitialFrame( eventFromUnknownInput(stackParser, error2 || msg, void 0, attachStacktrace, false), url, line, column ); event.level = "error"; captureEvent(event, { originalException: error2, mechanism: { handled: false, type: "onerror" } }); }); } __name(_installGlobalOnErrorHandler, "_installGlobalOnErrorHandler"); function _installGlobalOnUnhandledRejectionHandler(client) { addGlobalUnhandledRejectionInstrumentationHandler((e2) => { const { stackParser, attachStacktrace } = getOptions(); if (getClient() !== client || shouldIgnoreOnError()) { return; } const error2 = _getUnhandledRejectionError(e2); const event = isPrimitive(error2) ? _eventFromRejectionWithPrimitive(error2) : eventFromUnknownInput(stackParser, error2, void 0, attachStacktrace, true); event.level = "error"; captureEvent(event, { originalException: error2, mechanism: { handled: false, type: "onunhandledrejection" } }); }); } __name(_installGlobalOnUnhandledRejectionHandler, "_installGlobalOnUnhandledRejectionHandler"); function _getUnhandledRejectionError(error2) { if (isPrimitive(error2)) { return error2; } try { if ("reason" in error2) { return error2.reason; } if ("detail" in error2 && "reason" in error2.detail) { return error2.detail.reason; } } catch (e2) { } return error2; } __name(_getUnhandledRejectionError, "_getUnhandledRejectionError"); function _eventFromRejectionWithPrimitive(reason) { return { exception: { values: [ { type: "UnhandledRejection", // String() is needed because the Primitive type includes symbols (which can't be automatically stringified) value: `Non-Error promise rejection captured with value: ${String(reason)}` } ] } }; } __name(_eventFromRejectionWithPrimitive, "_eventFromRejectionWithPrimitive"); function _enhanceEventWithInitialFrame(event, url, line, column) { const e2 = event.exception = event.exception || {}; const ev = e2.values = e2.values || []; const ev0 = ev[0] = ev[0] || {}; const ev0s = ev0.stacktrace = ev0.stacktrace || {}; const ev0sf = ev0s.frames = ev0s.frames || []; const colno = column; const lineno = line; const filename = isString$8(url) && url.length > 0 ? url : getLocationHref(); if (ev0sf.length === 0) { ev0sf.push({ colno, filename, function: UNKNOWN_FUNCTION, in_app: true, lineno }); } return event; } __name(_enhanceEventWithInitialFrame, "_enhanceEventWithInitialFrame"); function globalHandlerLog(type) { DEBUG_BUILD$4 && logger$2.log(`Global Handler attached: ${type}`); } __name(globalHandlerLog, "globalHandlerLog"); function getOptions() { const client = getClient(); const options4 = client && client.getOptions() || { stackParser: /* @__PURE__ */ __name(() => [], "stackParser"), attachStacktrace: false }; return options4; } __name(getOptions, "getOptions"); const httpContextIntegration = defineIntegration(() => { return { name: "HttpContext", preprocessEvent(event) { if (!WINDOW$5.navigator && !WINDOW$5.location && !WINDOW$5.document) { return; } const url = event.request && event.request.url || WINDOW$5.location && WINDOW$5.location.href; const { referrer } = WINDOW$5.document || {}; const { userAgent } = WINDOW$5.navigator || {}; const headers = { ...event.request && event.request.headers, ...referrer && { Referer: referrer }, ...userAgent && { "User-Agent": userAgent } }; const request = { ...event.request, ...url && { url }, headers }; event.request = request; } }; }); const DEFAULT_KEY = "cause"; const DEFAULT_LIMIT = 5; const INTEGRATION_NAME$7 = "LinkedErrors"; const _linkedErrorsIntegration = /* @__PURE__ */ __name((options4 = {}) => { const limit = options4.limit || DEFAULT_LIMIT; const key = options4.key || DEFAULT_KEY; return { name: INTEGRATION_NAME$7, preprocessEvent(event, hint, client) { const options5 = client.getOptions(); applyAggregateErrorsToEvent( // This differs from the LinkedErrors integration in core by using a different exceptionFromError function exceptionFromError, options5.stackParser, options5.maxValueLength, key, limit, event, hint ); } }; }, "_linkedErrorsIntegration"); const linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration); function getDefaultIntegrations(options4) { const integrations = [ inboundFiltersIntegration(), functionToStringIntegration(), browserApiErrorsIntegration(), breadcrumbsIntegration(), globalHandlersIntegration(), linkedErrorsIntegration(), dedupeIntegration(), httpContextIntegration() ]; if (options4.autoSessionTracking !== false) { integrations.push(browserSessionIntegration()); } return integrations; } __name(getDefaultIntegrations, "getDefaultIntegrations"); function applyDefaultOptions(optionsArg = {}) { const defaultOptions2 = { defaultIntegrations: getDefaultIntegrations(optionsArg), release: typeof __SENTRY_RELEASE__ === "string" ? __SENTRY_RELEASE__ : WINDOW$5.SENTRY_RELEASE && WINDOW$5.SENTRY_RELEASE.id ? WINDOW$5.SENTRY_RELEASE.id : void 0, autoSessionTracking: true, sendClientReports: true }; if (optionsArg.defaultIntegrations == null) { delete optionsArg.defaultIntegrations; } return { ...defaultOptions2, ...optionsArg }; } __name(applyDefaultOptions, "applyDefaultOptions"); function shouldShowBrowserExtensionError() { const windowWithMaybeExtension = typeof WINDOW$5.window !== "undefined" && WINDOW$5; if (!windowWithMaybeExtension) { return false; } const extensionKey = windowWithMaybeExtension.chrome ? "chrome" : "browser"; const extensionObject = windowWithMaybeExtension[extensionKey]; const runtimeId = extensionObject && extensionObject.runtime && extensionObject.runtime.id; const href = WINDOW$5.location && WINDOW$5.location.href || ""; const extensionProtocols = ["chrome-extension:", "moz-extension:", "ms-browser-extension:", "safari-web-extension:"]; const isDedicatedExtensionPage = !!runtimeId && WINDOW$5 === WINDOW$5.top && extensionProtocols.some((protocol) => href.startsWith(`${protocol}//`)); const isNWjs = typeof windowWithMaybeExtension.nw !== "undefined"; return !!runtimeId && !isDedicatedExtensionPage && !isNWjs; } __name(shouldShowBrowserExtensionError, "shouldShowBrowserExtensionError"); function init$4(browserOptions = {}) { const options4 = applyDefaultOptions(browserOptions); if (!options4.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) { consoleSandbox(() => { console.error( "[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/" ); }); return; } if (DEBUG_BUILD$4) { if (!supportsFetch()) { logger$2.warn( "No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill." ); } } const clientOptions = { ...options4, stackParser: stackParserFromStackParserOptions(options4.stackParser || defaultStackParser), integrations: getIntegrationsToSetup(options4), transport: options4.transport || makeFetchTransport }; return initAndBind(BrowserClient, clientOptions); } __name(init$4, "init$4"); function showReportDialog(options4 = {}) { if (!WINDOW$5.document) { DEBUG_BUILD$4 && logger$2.error("Global document not defined in showReportDialog call"); return; } const scope = getCurrentScope$1(); const client = scope.getClient(); const dsn = client && client.getDsn(); if (!dsn) { DEBUG_BUILD$4 && logger$2.error("DSN not configured for showReportDialog call"); return; } if (scope) { options4.user = { ...scope.getUser(), ...options4.user }; } if (!options4.eventId) { const eventId = lastEventId(); if (eventId) { options4.eventId = eventId; } } const script2 = WINDOW$5.document.createElement("script"); script2.async = true; script2.crossOrigin = "anonymous"; script2.src = getReportDialogEndpoint(dsn, options4); if (options4.onLoad) { script2.onload = options4.onLoad; } const { onClose } = options4; if (onClose) { const reportDialogClosedMessageHandler = /* @__PURE__ */ __name((event) => { if (event.data === "__sentry_reportdialog_closed__") { try { onClose(); } finally { WINDOW$5.removeEventListener("message", reportDialogClosedMessageHandler); } } }, "reportDialogClosedMessageHandler"); WINDOW$5.addEventListener("message", reportDialogClosedMessageHandler); } const injectionPoint = WINDOW$5.document.head || WINDOW$5.document.body; if (injectionPoint) { injectionPoint.appendChild(script2); } else { DEBUG_BUILD$4 && logger$2.error("Not injecting report dialog. No injection point found in HTML"); } } __name(showReportDialog, "showReportDialog"); function forceLoad() { } __name(forceLoad, "forceLoad"); function onLoad(callback) { callback(); } __name(onLoad, "onLoad"); function captureUserFeedback(feedback) { const client = getClient(); if (client) { client.captureUserFeedback(feedback); } } __name(captureUserFeedback, "captureUserFeedback"); const LazyLoadableIntegrations = { replayIntegration: "replay", replayCanvasIntegration: "replay-canvas", feedbackIntegration: "feedback", feedbackModalIntegration: "feedback-modal", feedbackScreenshotIntegration: "feedback-screenshot", captureConsoleIntegration: "captureconsole", contextLinesIntegration: "contextlines", linkedErrorsIntegration: "linkederrors", debugIntegration: "debug", dedupeIntegration: "dedupe", extraErrorDataIntegration: "extraerrordata", httpClientIntegration: "httpclient", reportingObserverIntegration: "reportingobserver", rewriteFramesIntegration: "rewriteframes", sessionTimingIntegration: "sessiontiming", browserProfilingIntegration: "browserprofiling", moduleMetadataIntegration: "modulemetadata" }; const WindowWithMaybeIntegration = WINDOW$5; async function lazyLoadIntegration(name2, scriptNonce) { const bundle = LazyLoadableIntegrations[name2]; const sentryOnWindow = WindowWithMaybeIntegration.Sentry = WindowWithMaybeIntegration.Sentry || {}; if (!bundle) { throw new Error(`Cannot lazy load integration: ${name2}`); } const existing = sentryOnWindow[name2]; if (typeof existing === "function" && !("_isShim" in existing)) { return existing; } const url = getScriptURL(bundle); const script2 = WINDOW$5.document.createElement("script"); script2.src = url; script2.crossOrigin = "anonymous"; script2.referrerPolicy = "origin"; if (scriptNonce) { script2.setAttribute("nonce", scriptNonce); } const waitForLoad = new Promise((resolve2, reject3) => { script2.addEventListener("load", () => resolve2()); script2.addEventListener("error", reject3); }); const currentScript = WINDOW$5.document.currentScript; const parent = WINDOW$5.document.body || WINDOW$5.document.head || currentScript && currentScript.parentElement; if (parent) { parent.appendChild(script2); } else { throw new Error(`Could not find parent element to insert lazy-loaded ${name2} script`); } try { await waitForLoad; } catch (e2) { throw new Error(`Error when loading integration: ${name2}`); } const integrationFn = sentryOnWindow[name2]; if (typeof integrationFn !== "function") { throw new Error(`Could not load integration: ${name2}`); } return integrationFn; } __name(lazyLoadIntegration, "lazyLoadIntegration"); function getScriptURL(bundle) { const client = getClient(); const options4 = client && client.getOptions(); const baseURL = options4 && options4.cdnBaseUrl || "https://browser.sentry-cdn.com"; return new URL(`/${SDK_VERSION}/${bundle}.min.js`, baseURL).toString(); } __name(getScriptURL, "getScriptURL"); const WINDOW$3 = GLOBAL_OBJ; const INTEGRATION_NAME$6 = "ReportingObserver"; const SETUP_CLIENTS = /* @__PURE__ */ new WeakMap(); const _reportingObserverIntegration = /* @__PURE__ */ __name((options4 = {}) => { const types = options4.types || ["crash", "deprecation", "intervention"]; function handler6(reports) { if (!SETUP_CLIENTS.has(getClient())) { return; } for (const report of reports) { withScope((scope) => { scope.setExtra("url", report.url); const label5 = `ReportingObserver [${report.type}]`; let details = "No details available"; if (report.body) { const plainBody = {}; for (const prop2 in report.body) { plainBody[prop2] = report.body[prop2]; } scope.setExtra("body", plainBody); if (report.type === "crash") { const body = report.body; details = [body.crashId || "", body.reason || ""].join(" ").trim() || details; } else { const body = report.body; details = body.message || details; } } captureMessage(`${label5}: ${details}`); }); } } __name(handler6, "handler"); return { name: INTEGRATION_NAME$6, setupOnce() { if (!supportsReportingObserver()) { return; } const observer = new WINDOW$3.ReportingObserver( handler6, { buffered: true, types } ); observer.observe(); }, setup(client) { SETUP_CLIENTS.set(client, true); } }; }, "_reportingObserverIntegration"); const reportingObserverIntegration = defineIntegration(_reportingObserverIntegration); const INTEGRATION_NAME$5 = "HttpClient"; const _httpClientIntegration = /* @__PURE__ */ __name((options4 = {}) => { const _options = { failedRequestStatusCodes: [[500, 599]], failedRequestTargets: [/.*/], ...options4 }; return { name: INTEGRATION_NAME$5, setup(client) { _wrapFetch(client, _options); _wrapXHR(client, _options); } }; }, "_httpClientIntegration"); const httpClientIntegration = defineIntegration(_httpClientIntegration); function _fetchResponseHandler(options4, requestInfo, response, requestInit, error2) { if (_shouldCaptureResponse(options4, response.status, response.url)) { const request = _getRequest(requestInfo, requestInit); let requestHeaders, responseHeaders, requestCookies, responseCookies; if (_shouldSendDefaultPii()) { [requestHeaders, requestCookies] = _parseCookieHeaders("Cookie", request); [responseHeaders, responseCookies] = _parseCookieHeaders("Set-Cookie", response); } const event = _createEvent({ url: request.url, method: request.method, status: response.status, requestHeaders, responseHeaders, requestCookies, responseCookies, error: error2 }); captureEvent(event); } } __name(_fetchResponseHandler, "_fetchResponseHandler"); function _parseCookieHeaders(cookieHeader, obj) { const headers = _extractFetchHeaders(obj.headers); let cookies2; try { const cookieString = headers[cookieHeader] || headers[cookieHeader.toLowerCase()] || void 0; if (cookieString) { cookies2 = _parseCookieString(cookieString); } } catch (e2) { } return [headers, cookies2]; } __name(_parseCookieHeaders, "_parseCookieHeaders"); function _xhrResponseHandler(options4, xhr, method, headers, error2) { if (_shouldCaptureResponse(options4, xhr.status, xhr.responseURL)) { let requestHeaders, responseCookies, responseHeaders; if (_shouldSendDefaultPii()) { try { const cookieString = xhr.getResponseHeader("Set-Cookie") || xhr.getResponseHeader("set-cookie") || void 0; if (cookieString) { responseCookies = _parseCookieString(cookieString); } } catch (e3) { } try { responseHeaders = _getXHRResponseHeaders(xhr); } catch (e4) { } requestHeaders = headers; } const event = _createEvent({ url: xhr.responseURL, method, status: xhr.status, requestHeaders, // Can't access request cookies from XHR responseHeaders, responseCookies, error: error2 }); captureEvent(event); } } __name(_xhrResponseHandler, "_xhrResponseHandler"); function _getResponseSizeFromHeaders(headers) { if (headers) { const contentLength = headers["Content-Length"] || headers["content-length"]; if (contentLength) { return parseInt(contentLength, 10); } } return void 0; } __name(_getResponseSizeFromHeaders, "_getResponseSizeFromHeaders"); function _parseCookieString(cookieString) { return cookieString.split("; ").reduce((acc, cookie) => { const [key, value4] = cookie.split("="); if (key && value4) { acc[key] = value4; } return acc; }, {}); } __name(_parseCookieString, "_parseCookieString"); function _extractFetchHeaders(headers) { const result = {}; headers.forEach((value4, key) => { result[key] = value4; }); return result; } __name(_extractFetchHeaders, "_extractFetchHeaders"); function _getXHRResponseHeaders(xhr) { const headers = xhr.getAllResponseHeaders(); if (!headers) { return {}; } return headers.split("\r\n").reduce((acc, line) => { const [key, value4] = line.split(": "); if (key && value4) { acc[key] = value4; } return acc; }, {}); } __name(_getXHRResponseHeaders, "_getXHRResponseHeaders"); function _isInGivenRequestTargets(failedRequestTargets, target) { return failedRequestTargets.some((givenRequestTarget) => { if (typeof givenRequestTarget === "string") { return target.includes(givenRequestTarget); } return givenRequestTarget.test(target); }); } __name(_isInGivenRequestTargets, "_isInGivenRequestTargets"); function _isInGivenStatusRanges(failedRequestStatusCodes, status) { return failedRequestStatusCodes.some((range2) => { if (typeof range2 === "number") { return range2 === status; } return status >= range2[0] && status <= range2[1]; }); } __name(_isInGivenStatusRanges, "_isInGivenStatusRanges"); function _wrapFetch(client, options4) { if (!supportsNativeFetch()) { return; } addFetchInstrumentationHandler((handlerData) => { if (getClient() !== client) { return; } const { response, args, error: error2, virtualError } = handlerData; const [requestInfo, requestInit] = args; if (!response) { return; } _fetchResponseHandler(options4, requestInfo, response, requestInit, error2 || virtualError); }, false); } __name(_wrapFetch, "_wrapFetch"); function _wrapXHR(client, options4) { if (!("XMLHttpRequest" in GLOBAL_OBJ)) { return; } addXhrInstrumentationHandler((handlerData) => { if (getClient() !== client) { return; } const { error: error2, virtualError } = handlerData; const xhr = handlerData.xhr; const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY]; if (!sentryXhrData) { return; } const { method, request_headers: headers } = sentryXhrData; try { _xhrResponseHandler(options4, xhr, method, headers, error2 || virtualError); } catch (e2) { DEBUG_BUILD$4 && logger$2.warn("Error while extracting response event form XHR response", e2); } }); } __name(_wrapXHR, "_wrapXHR"); function _shouldCaptureResponse(options4, status, url) { return _isInGivenStatusRanges(options4.failedRequestStatusCodes, status) && _isInGivenRequestTargets(options4.failedRequestTargets, url) && !isSentryRequestUrl(url, getClient()); } __name(_shouldCaptureResponse, "_shouldCaptureResponse"); function _createEvent(data25) { const client = getClient(); const virtualStackTrace = client && data25.error && data25.error instanceof Error ? data25.error.stack : void 0; const stack2 = virtualStackTrace && client ? client.getOptions().stackParser(virtualStackTrace, 0, 1) : void 0; const message3 = `HTTP Client Error with status code: ${data25.status}`; const event = { message: message3, exception: { values: [ { type: "Error", value: message3, stacktrace: stack2 ? { frames: stack2 } : void 0 } ] }, request: { url: data25.url, method: data25.method, headers: data25.requestHeaders, cookies: data25.requestCookies }, contexts: { response: { status_code: data25.status, headers: data25.responseHeaders, cookies: data25.responseCookies, body_size: _getResponseSizeFromHeaders(data25.responseHeaders) } } }; addExceptionMechanism(event, { type: "http.client", handled: false }); return event; } __name(_createEvent, "_createEvent"); function _getRequest(requestInfo, requestInit) { if (!requestInit && requestInfo instanceof Request) { return requestInfo; } if (requestInfo instanceof Request && requestInfo.bodyUsed) { return requestInfo; } return new Request(requestInfo, requestInit); } __name(_getRequest, "_getRequest"); function _shouldSendDefaultPii() { const client = getClient(); return client ? Boolean(client.getOptions().sendDefaultPii) : false; } __name(_shouldSendDefaultPii, "_shouldSendDefaultPii"); const WINDOW$2 = GLOBAL_OBJ; const DEFAULT_LINES_OF_CONTEXT = 7; const INTEGRATION_NAME$4 = "ContextLines"; const _contextLinesIntegration = /* @__PURE__ */ __name((options4 = {}) => { const contextLines = options4.frameContextLines != null ? options4.frameContextLines : DEFAULT_LINES_OF_CONTEXT; return { name: INTEGRATION_NAME$4, processEvent(event) { return addSourceContext(event, contextLines); } }; }, "_contextLinesIntegration"); const contextLinesIntegration = defineIntegration(_contextLinesIntegration); function addSourceContext(event, contextLines) { const doc2 = WINDOW$2.document; const htmlFilename = WINDOW$2.location && stripUrlQueryAndFragment(WINDOW$2.location.href); if (!doc2 || !htmlFilename) { return event; } const exceptions = event.exception && event.exception.values; if (!exceptions || !exceptions.length) { return event; } const html = doc2.documentElement.innerHTML; if (!html) { return event; } const htmlLines = ["", "", ...html.split("\n"), ""]; exceptions.forEach((exception) => { const stacktrace = exception.stacktrace; if (stacktrace && stacktrace.frames) { stacktrace.frames = stacktrace.frames.map( (frame) => applySourceContextToFrame(frame, htmlLines, htmlFilename, contextLines) ); } }); return event; } __name(addSourceContext, "addSourceContext"); function applySourceContextToFrame(frame, htmlLines, htmlFilename, linesOfContext) { if (frame.filename !== htmlFilename || !frame.lineno || !htmlLines.length) { return frame; } addContextToFrame(htmlLines, frame, linesOfContext); return frame; } __name(applySourceContextToFrame, "applySourceContextToFrame"); const WINDOW$1 = GLOBAL_OBJ; const REPLAY_SESSION_KEY = "sentryReplaySession"; const REPLAY_EVENT_NAME = "replay_event"; const UNABLE_TO_SEND_REPLAY = "Unable to send Replay"; const SESSION_IDLE_PAUSE_DURATION = 3e5; const SESSION_IDLE_EXPIRE_DURATION = 9e5; const DEFAULT_FLUSH_MIN_DELAY = 5e3; const DEFAULT_FLUSH_MAX_DELAY = 5500; const BUFFER_CHECKOUT_TIME = 6e4; const RETRY_BASE_INTERVAL = 5e3; const RETRY_MAX_COUNT = 3; const NETWORK_BODY_MAX_SIZE = 15e4; const CONSOLE_ARG_MAX_SIZE = 5e3; const SLOW_CLICK_THRESHOLD = 3e3; const SLOW_CLICK_SCROLL_TIMEOUT = 300; const REPLAY_MAX_EVENT_BUFFER_SIZE = 2e7; const MIN_REPLAY_DURATION = 4999; const MIN_REPLAY_DURATION_LIMIT = 15e3; const MAX_REPLAY_DURATION = 36e5; function _nullishCoalesce$1(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } __name(_nullishCoalesce$1, "_nullishCoalesce$1"); function _optionalChain$5(ops) { let lastAccessLHS = void 0; let value4 = ops[0]; let i2 = 1; while (i2 < ops.length) { const op = ops[i2]; const fn = ops[i2 + 1]; i2 += 2; if ((op === "optionalAccess" || op === "optionalCall") && value4 == null) { return void 0; } if (op === "access" || op === "optionalAccess") { lastAccessLHS = value4; value4 = fn(value4); } else if (op === "call" || op === "optionalCall") { value4 = fn((...args) => value4.call(lastAccessLHS, ...args)); lastAccessLHS = void 0; } } return value4; } __name(_optionalChain$5, "_optionalChain$5"); var NodeType$3; (function(NodeType3) { NodeType3[NodeType3["Document"] = 0] = "Document"; NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType"; NodeType3[NodeType3["Element"] = 2] = "Element"; NodeType3[NodeType3["Text"] = 3] = "Text"; NodeType3[NodeType3["CDATA"] = 4] = "CDATA"; NodeType3[NodeType3["Comment"] = 5] = "Comment"; })(NodeType$3 || (NodeType$3 = {})); function isElement$1(n2) { return n2.nodeType === n2.ELEMENT_NODE; } __name(isElement$1, "isElement$1"); function isShadowRoot(n2) { const host = _optionalChain$5([n2, "optionalAccess", (_2) => _2.host]); return Boolean(_optionalChain$5([host, "optionalAccess", (_2) => _2.shadowRoot]) === n2); } __name(isShadowRoot, "isShadowRoot"); function isNativeShadowDom(shadowRoot) { return Object.prototype.toString.call(shadowRoot) === "[object ShadowRoot]"; } __name(isNativeShadowDom, "isNativeShadowDom"); function fixBrowserCompatibilityIssuesInCSS(cssText) { if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) { cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;"); } return cssText; } __name(fixBrowserCompatibilityIssuesInCSS, "fixBrowserCompatibilityIssuesInCSS"); function escapeImportStatement(rule) { const { cssText } = rule; if (cssText.split('"').length < 3) return cssText; const statement = ["@import", `url(${JSON.stringify(rule.href)})`]; if (rule.layerName === "") { statement.push(`layer`); } else if (rule.layerName) { statement.push(`layer(${rule.layerName})`); } if (rule.supportsText) { statement.push(`supports(${rule.supportsText})`); } if (rule.media.length) { statement.push(rule.media.mediaText); } return statement.join(" ") + ";"; } __name(escapeImportStatement, "escapeImportStatement"); function stringifyStylesheet(s2) { try { const rules = s2.rules || s2.cssRules; return rules ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join("")) : null; } catch (error2) { return null; } } __name(stringifyStylesheet, "stringifyStylesheet"); function fixAllCssProperty(rule) { let styles = ""; for (let i2 = 0; i2 < rule.style.length; i2++) { const styleDeclaration = rule.style; const attribute2 = styleDeclaration[i2]; const isImportant = styleDeclaration.getPropertyPriority(attribute2); styles += `${attribute2}:${styleDeclaration.getPropertyValue(attribute2)}${isImportant ? ` !important` : ""};`; } return `${rule.selectorText} { ${styles} }`; } __name(fixAllCssProperty, "fixAllCssProperty"); function stringifyRule(rule) { let importStringified; if (isCSSImportRule(rule)) { try { importStringified = stringifyStylesheet(rule.styleSheet) || escapeImportStatement(rule); } catch (error2) { } } else if (isCSSStyleRule(rule)) { let cssText = rule.cssText; const needsSafariColonFix = rule.selectorText.includes(":"); const needsAllFix = typeof rule.style["all"] === "string" && rule.style["all"]; if (needsAllFix) { cssText = fixAllCssProperty(rule); } if (needsSafariColonFix) { cssText = fixSafariColons(cssText); } if (needsSafariColonFix || needsAllFix) { return cssText; } } return importStringified || rule.cssText; } __name(stringifyRule, "stringifyRule"); function fixSafariColons(cssStringified) { const regex2 = /(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm; return cssStringified.replace(regex2, "$1\\$2"); } __name(fixSafariColons, "fixSafariColons"); function isCSSImportRule(rule) { return "styleSheet" in rule; } __name(isCSSImportRule, "isCSSImportRule"); function isCSSStyleRule(rule) { return "selectorText" in rule; } __name(isCSSStyleRule, "isCSSStyleRule"); class Mirror { static { __name(this, "Mirror"); } constructor() { this.idNodeMap = /* @__PURE__ */ new Map(); this.nodeMetaMap = /* @__PURE__ */ new WeakMap(); } getId(n2) { if (!n2) return -1; const id3 = _optionalChain$5([this, "access", (_3) => _3.getMeta, "call", (_4) => _4(n2), "optionalAccess", (_5) => _5.id]); return _nullishCoalesce$1(id3, () => -1); } getNode(id3) { return this.idNodeMap.get(id3) || null; } getIds() { return Array.from(this.idNodeMap.keys()); } getMeta(n2) { return this.nodeMetaMap.get(n2) || null; } removeNodeFromMap(n2) { const id3 = this.getId(n2); this.idNodeMap.delete(id3); if (n2.childNodes) { n2.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode)); } } has(id3) { return this.idNodeMap.has(id3); } hasNode(node3) { return this.nodeMetaMap.has(node3); } add(n2, meta) { const id3 = meta.id; this.idNodeMap.set(id3, n2); this.nodeMetaMap.set(n2, meta); } replace(id3, n2) { const oldNode = this.getNode(id3); if (oldNode) { const meta = this.nodeMetaMap.get(oldNode); if (meta) this.nodeMetaMap.set(n2, meta); } this.idNodeMap.set(id3, n2); } reset() { this.idNodeMap = /* @__PURE__ */ new Map(); this.nodeMetaMap = /* @__PURE__ */ new WeakMap(); } } function createMirror() { return new Mirror(); } __name(createMirror, "createMirror"); function shouldMaskInput({ maskInputOptions, tagName, type }) { if (tagName === "OPTION") { tagName = "SELECT"; } return Boolean(maskInputOptions[tagName.toLowerCase()] || type && maskInputOptions[type] || type === "password" || tagName === "INPUT" && !type && maskInputOptions["text"]); } __name(shouldMaskInput, "shouldMaskInput"); function maskInputValue({ isMasked: isMasked2, element, value: value4, maskInputFn }) { let text2 = value4 || ""; if (!isMasked2) { return text2; } if (maskInputFn) { text2 = maskInputFn(text2, element); } return "*".repeat(text2.length); } __name(maskInputValue, "maskInputValue"); function toLowerCase(str) { return str.toLowerCase(); } __name(toLowerCase, "toLowerCase"); function toUpperCase(str) { return str.toUpperCase(); } __name(toUpperCase, "toUpperCase"); const ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__"; function is2DCanvasBlank(canvas) { const ctx = canvas.getContext("2d"); if (!ctx) return true; const chunkSize = 50; for (let x2 = 0; x2 < canvas.width; x2 += chunkSize) { for (let y2 = 0; y2 < canvas.height; y2 += chunkSize) { const getImageData = ctx.getImageData; const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData; const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x2, y2, Math.min(chunkSize, canvas.width - x2), Math.min(chunkSize, canvas.height - y2)).data.buffer); if (pixelBuffer.some((pixel) => pixel !== 0)) return false; } } return true; } __name(is2DCanvasBlank, "is2DCanvasBlank"); function getInputType(element) { const type = element.type; return element.hasAttribute("data-rr-is-password") ? "password" : type ? toLowerCase(type) : null; } __name(getInputType, "getInputType"); function getInputValue(el, tagName, type) { if (tagName === "INPUT" && (type === "radio" || type === "checkbox")) { return el.getAttribute("value") || ""; } return el.value; } __name(getInputValue, "getInputValue"); function extractFileExtension(path, baseURL) { let url; try { url = new URL(path, _nullishCoalesce$1(baseURL, () => window.location.href)); } catch (err) { return null; } const regex2 = /\.([0-9a-z]+)(?:$)/i; const match2 = url.pathname.match(regex2); return _nullishCoalesce$1(_optionalChain$5([match2, "optionalAccess", (_6) => _6[1]]), () => null); } __name(extractFileExtension, "extractFileExtension"); const cachedImplementations$1 = {}; function getImplementation$1(name2) { const cached = cachedImplementations$1[name2]; if (cached) { return cached; } const document2 = window.document; let impl = window[name2]; if (document2 && typeof document2.createElement === "function") { try { const sandbox = document2.createElement("iframe"); sandbox.hidden = true; document2.head.appendChild(sandbox); const contentWindow = sandbox.contentWindow; if (contentWindow && contentWindow[name2]) { impl = contentWindow[name2]; } document2.head.removeChild(sandbox); } catch (e2) { } } return cachedImplementations$1[name2] = impl.bind(window); } __name(getImplementation$1, "getImplementation$1"); function setTimeout$2(...rest) { return getImplementation$1("setTimeout")(...rest); } __name(setTimeout$2, "setTimeout$2"); function clearTimeout$2(...rest) { return getImplementation$1("clearTimeout")(...rest); } __name(clearTimeout$2, "clearTimeout$2"); function getIframeContentDocument(iframe) { try { return iframe.contentDocument; } catch (e2) { } } __name(getIframeContentDocument, "getIframeContentDocument"); let _id$2 = 1; const tagNameRegex = new RegExp("[^a-z0-9-_:]"); const IGNORED_NODE = -2; function genId() { return _id$2++; } __name(genId, "genId"); function getValidTagName(element) { if (element instanceof HTMLFormElement) { return "form"; } const processedTagName = toLowerCase(element.tagName); if (tagNameRegex.test(processedTagName)) { return "div"; } return processedTagName; } __name(getValidTagName, "getValidTagName"); function extractOrigin(url) { let origin2 = ""; if (url.indexOf("//") > -1) { origin2 = url.split("/").slice(0, 3).join("/"); } else { origin2 = url.split("/")[0]; } origin2 = origin2.split("?")[0]; return origin2; } __name(extractOrigin, "extractOrigin"); let canvasService; let canvasCtx; const URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm; const URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i; const URL_WWW_MATCH = /^www\..*/i; const DATA_URI = /^(data:)([^,]*),(.*)/i; function absoluteToStylesheet(cssText, href) { return (cssText || "").replace(URL_IN_CSS_REF, (origin2, quote1, path1, quote2, path2, path3) => { const filePath = path1 || path2 || path3; const maybeQuote = quote1 || quote2 || ""; if (!filePath) { return origin2; } if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) { return `url(${maybeQuote}${filePath}${maybeQuote})`; } if (DATA_URI.test(filePath)) { return `url(${maybeQuote}${filePath}${maybeQuote})`; } if (filePath[0] === "/") { return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`; } const stack2 = href.split("/"); const parts2 = filePath.split("/"); stack2.pop(); for (const part of parts2) { if (part === ".") { continue; } else if (part === "..") { stack2.pop(); } else { stack2.push(part); } } return `url(${maybeQuote}${stack2.join("/")}${maybeQuote})`; }); } __name(absoluteToStylesheet, "absoluteToStylesheet"); const SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/; const SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/; function getAbsoluteSrcsetString(doc2, attributeValue) { if (attributeValue.trim() === "") { return attributeValue; } let pos2 = 0; function collectCharacters(regEx) { let chars2; const match2 = regEx.exec(attributeValue.substring(pos2)); if (match2) { chars2 = match2[0]; pos2 += chars2.length; return chars2; } return ""; } __name(collectCharacters, "collectCharacters"); const output = []; while (true) { collectCharacters(SRCSET_COMMAS_OR_SPACES); if (pos2 >= attributeValue.length) { break; } let url = collectCharacters(SRCSET_NOT_SPACES); if (url.slice(-1) === ",") { url = absoluteToDoc(doc2, url.substring(0, url.length - 1)); output.push(url); } else { let descriptorsStr = ""; url = absoluteToDoc(doc2, url); let inParens = false; while (true) { const c2 = attributeValue.charAt(pos2); if (c2 === "") { output.push((url + descriptorsStr).trim()); break; } else if (!inParens) { if (c2 === ",") { pos2 += 1; output.push((url + descriptorsStr).trim()); break; } else if (c2 === "(") { inParens = true; } } else { if (c2 === ")") { inParens = false; } } descriptorsStr += c2; pos2 += 1; } } } return output.join(", "); } __name(getAbsoluteSrcsetString, "getAbsoluteSrcsetString"); const cachedDocument = /* @__PURE__ */ new WeakMap(); function absoluteToDoc(doc2, attributeValue) { if (!attributeValue || attributeValue.trim() === "") { return attributeValue; } return getHref(doc2, attributeValue); } __name(absoluteToDoc, "absoluteToDoc"); function isSVGElement(el) { return Boolean(el.tagName === "svg" || el.ownerSVGElement); } __name(isSVGElement, "isSVGElement"); function getHref(doc2, customHref) { let a2 = cachedDocument.get(doc2); if (!a2) { a2 = doc2.createElement("a"); cachedDocument.set(doc2, a2); } if (!customHref) { customHref = ""; } else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) { return customHref; } a2.setAttribute("href", customHref); return a2.href; } __name(getHref, "getHref"); function transformAttribute(doc2, tagName, name2, value4, element, maskAttributeFn) { if (!value4) { return value4; } if (name2 === "src" || name2 === "href" && !(tagName === "use" && value4[0] === "#")) { return absoluteToDoc(doc2, value4); } else if (name2 === "xlink:href" && value4[0] !== "#") { return absoluteToDoc(doc2, value4); } else if (name2 === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) { return absoluteToDoc(doc2, value4); } else if (name2 === "srcset") { return getAbsoluteSrcsetString(doc2, value4); } else if (name2 === "style") { return absoluteToStylesheet(value4, getHref(doc2)); } else if (tagName === "object" && name2 === "data") { return absoluteToDoc(doc2, value4); } if (typeof maskAttributeFn === "function") { return maskAttributeFn(name2, value4, element); } return value4; } __name(transformAttribute, "transformAttribute"); function ignoreAttribute(tagName, name2, _value) { return (tagName === "video" || tagName === "audio") && name2 === "autoplay"; } __name(ignoreAttribute, "ignoreAttribute"); function _isBlockedElement(element, blockClass, blockSelector, unblockSelector) { try { if (unblockSelector && element.matches(unblockSelector)) { return false; } if (typeof blockClass === "string") { if (element.classList.contains(blockClass)) { return true; } } else { for (let eIndex = element.classList.length; eIndex--; ) { const className = element.classList[eIndex]; if (blockClass.test(className)) { return true; } } } if (blockSelector) { return element.matches(blockSelector); } } catch (e2) { } return false; } __name(_isBlockedElement, "_isBlockedElement"); function elementClassMatchesRegex$1(el, regex2) { for (let eIndex = el.classList.length; eIndex--; ) { const className = el.classList[eIndex]; if (regex2.test(className)) { return true; } } return false; } __name(elementClassMatchesRegex$1, "elementClassMatchesRegex$1"); function distanceToMatch$1(node3, matchPredicate, limit = Infinity, distance2 = 0) { if (!node3) return -1; if (node3.nodeType !== node3.ELEMENT_NODE) return -1; if (distance2 > limit) return -1; if (matchPredicate(node3)) return distance2; return distanceToMatch$1(node3.parentNode, matchPredicate, limit, distance2 + 1); } __name(distanceToMatch$1, "distanceToMatch$1"); function createMatchPredicate$1(className, selector) { return (node3) => { const el = node3; if (el === null) return false; try { if (className) { if (typeof className === "string") { if (el.matches(`.${className}`)) return true; } else if (elementClassMatchesRegex$1(el, className)) { return true; } } if (selector && el.matches(selector)) return true; return false; } catch (e2) { return false; } }; } __name(createMatchPredicate$1, "createMatchPredicate$1"); function needMaskingText(node3, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) { try { const el = node3.nodeType === node3.ELEMENT_NODE ? node3 : node3.parentElement; if (el === null) return false; if (el.tagName === "INPUT") { const autocomplete = el.getAttribute("autocomplete"); const disallowedAutocompleteValues = [ "current-password", "new-password", "cc-number", "cc-exp", "cc-exp-month", "cc-exp-year", "cc-csc" ]; if (disallowedAutocompleteValues.includes(autocomplete)) { return true; } } let maskDistance = -1; let unmaskDistance = -1; if (maskAllText) { unmaskDistance = distanceToMatch$1(el, createMatchPredicate$1(unmaskTextClass, unmaskTextSelector)); if (unmaskDistance < 0) { return true; } maskDistance = distanceToMatch$1(el, createMatchPredicate$1(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity); } else { maskDistance = distanceToMatch$1(el, createMatchPredicate$1(maskTextClass, maskTextSelector)); if (maskDistance < 0) { return false; } unmaskDistance = distanceToMatch$1(el, createMatchPredicate$1(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity); } return maskDistance >= 0 ? unmaskDistance >= 0 ? maskDistance <= unmaskDistance : true : unmaskDistance >= 0 ? false : !!maskAllText; } catch (e2) { } return !!maskAllText; } __name(needMaskingText, "needMaskingText"); function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) { const win = iframeEl.contentWindow; if (!win) { return; } let fired = false; let readyState; try { readyState = win.document.readyState; } catch (error2) { return; } if (readyState !== "complete") { const timer = setTimeout$2(() => { if (!fired) { listener(); fired = true; } }, iframeLoadTimeout); iframeEl.addEventListener("load", () => { clearTimeout$2(timer); fired = true; listener(); }); return; } const blankUrl = "about:blank"; if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") { setTimeout$2(listener, 0); return iframeEl.addEventListener("load", listener); } iframeEl.addEventListener("load", listener); } __name(onceIframeLoaded, "onceIframeLoaded"); function onceStylesheetLoaded(link2, listener, styleSheetLoadTimeout) { let fired = false; let styleSheetLoaded; try { styleSheetLoaded = link2.sheet; } catch (error2) { return; } if (styleSheetLoaded) return; const timer = setTimeout$2(() => { if (!fired) { listener(); fired = true; } }, styleSheetLoadTimeout); link2.addEventListener("load", () => { clearTimeout$2(timer); fired = true; listener(); }); } __name(onceStylesheetLoaded, "onceStylesheetLoaded"); function serializeNode(n2, options4) { const { doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false } = options4; const rootId = getRootId(doc2, mirror2); switch (n2.nodeType) { case n2.DOCUMENT_NODE: if (n2.compatMode !== "CSS1Compat") { return { type: NodeType$3.Document, childNodes: [], compatMode: n2.compatMode }; } else { return { type: NodeType$3.Document, childNodes: [] }; } case n2.DOCUMENT_TYPE_NODE: return { type: NodeType$3.DocumentType, name: n2.name, publicId: n2.publicId, systemId: n2.systemId, rootId }; case n2.ELEMENT_NODE: return serializeElementNode(n2, { doc: doc2, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskAttributeFn, maskInputOptions, maskInputFn, dataURLOptions, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector }); case n2.TEXT_NODE: return serializeTextNode(n2, { doc: doc2, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId }); case n2.CDATA_SECTION_NODE: return { type: NodeType$3.CDATA, textContent: "", rootId }; case n2.COMMENT_NODE: return { type: NodeType$3.Comment, textContent: n2.textContent || "", rootId }; default: return false; } } __name(serializeNode, "serializeNode"); function getRootId(doc2, mirror2) { if (!mirror2.hasNode(doc2)) return void 0; const docId = mirror2.getId(doc2); return docId === 1 ? void 0 : docId; } __name(getRootId, "getRootId"); function serializeTextNode(n2, options4) { const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId } = options4; const parentTagName = n2.parentNode && n2.parentNode.tagName; let textContent = n2.textContent; const isStyle = parentTagName === "STYLE" ? true : void 0; const isScript = parentTagName === "SCRIPT" ? true : void 0; const isTextarea = parentTagName === "TEXTAREA" ? true : void 0; if (isStyle && textContent) { try { if (n2.nextSibling || n2.previousSibling) { } else if (_optionalChain$5([n2, "access", (_7) => _7.parentNode, "access", (_8) => _8.sheet, "optionalAccess", (_9) => _9.cssRules])) { textContent = stringifyStylesheet(n2.parentNode.sheet); } } catch (err) { console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n2); } textContent = absoluteToStylesheet(textContent, getHref(options4.doc)); } if (isScript) { textContent = "SCRIPT_PLACEHOLDER"; } const forceMask = needMaskingText(n2, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText); if (!isStyle && !isScript && !isTextarea && textContent && forceMask) { textContent = maskTextFn ? maskTextFn(textContent, n2.parentElement) : textContent.replace(/[\S]/g, "*"); } if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) { textContent = maskInputFn ? maskInputFn(textContent, n2.parentNode) : textContent.replace(/[\S]/g, "*"); } if (parentTagName === "OPTION" && textContent) { const isInputMasked = shouldMaskInput({ type: null, tagName: parentTagName, maskInputOptions }); textContent = maskInputValue({ isMasked: needMaskingText(n2, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked), element: n2, value: textContent, maskInputFn }); } return { type: NodeType$3.Text, textContent: textContent || "", isStyle, rootId }; } __name(serializeTextNode, "serializeTextNode"); function serializeElementNode(n2, options4) { const { doc: doc2, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector } = options4; const needBlock = _isBlockedElement(n2, blockClass, blockSelector, unblockSelector); const tagName = getValidTagName(n2); let attributes = {}; const len = n2.attributes.length; for (let i2 = 0; i2 < len; i2++) { const attr = n2.attributes[i2]; if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) { attributes[attr.name] = transformAttribute(doc2, tagName, toLowerCase(attr.name), attr.value, n2, maskAttributeFn); } } if (tagName === "link" && inlineStylesheet) { const stylesheet = Array.from(doc2.styleSheets).find((s2) => { return s2.href === n2.href; }); let cssText = null; if (stylesheet) { cssText = stringifyStylesheet(stylesheet); } if (cssText) { attributes.rel = null; attributes.href = null; attributes.crossorigin = null; attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href); } } if (tagName === "style" && n2.sheet && !(n2.innerText || n2.textContent || "").trim().length) { const cssText = stringifyStylesheet(n2.sheet); if (cssText) { attributes._cssText = absoluteToStylesheet(cssText, getHref(doc2)); } } if (tagName === "input" || tagName === "textarea" || tagName === "select" || tagName === "option") { const el = n2; const type = getInputType(el); const value4 = getInputValue(el, toUpperCase(tagName), type); const checked4 = el.checked; if (type !== "submit" && type !== "button" && value4) { const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({ type, tagName: toUpperCase(tagName), maskInputOptions })); attributes.value = maskInputValue({ isMasked: forceMask, element: el, value: value4, maskInputFn }); } if (checked4) { attributes.checked = checked4; } } if (tagName === "option") { if (n2.selected && !maskInputOptions["select"]) { attributes.selected = true; } else { delete attributes.selected; } } if (tagName === "canvas" && recordCanvas) { if (n2.__context === "2d") { if (!is2DCanvasBlank(n2)) { attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality); } } else if (!("__context" in n2)) { const canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality); const blankCanvas = doc2.createElement("canvas"); blankCanvas.width = n2.width; blankCanvas.height = n2.height; const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality); if (canvasDataURL !== blankCanvasDataURL) { attributes.rr_dataURL = canvasDataURL; } } } if (tagName === "img" && inlineImages) { if (!canvasService) { canvasService = doc2.createElement("canvas"); canvasCtx = canvasService.getContext("2d"); } const image2 = n2; const imageSrc = image2.currentSrc || image2.getAttribute("src") || ""; const priorCrossOrigin = image2.crossOrigin; const recordInlineImage = /* @__PURE__ */ __name(() => { image2.removeEventListener("load", recordInlineImage); try { canvasService.width = image2.naturalWidth; canvasService.height = image2.naturalHeight; canvasCtx.drawImage(image2, 0, 0); attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality); } catch (err) { if (image2.crossOrigin !== "anonymous") { image2.crossOrigin = "anonymous"; if (image2.complete && image2.naturalWidth !== 0) recordInlineImage(); else image2.addEventListener("load", recordInlineImage); return; } else { console.warn(`Cannot inline img src=${imageSrc}! Error: ${err}`); } } if (image2.crossOrigin === "anonymous") { priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image2.removeAttribute("crossorigin"); } }, "recordInlineImage"); if (image2.complete && image2.naturalWidth !== 0) recordInlineImage(); else image2.addEventListener("load", recordInlineImage); } if (tagName === "audio" || tagName === "video") { attributes.rr_mediaState = n2.paused ? "paused" : "played"; attributes.rr_mediaCurrentTime = n2.currentTime; } if (!newlyAddedElement) { if (n2.scrollLeft) { attributes.rr_scrollLeft = n2.scrollLeft; } if (n2.scrollTop) { attributes.rr_scrollTop = n2.scrollTop; } } if (needBlock) { const { width: width2, height } = n2.getBoundingClientRect(); attributes = { class: attributes.class, rr_width: `${width2}px`, rr_height: `${height}px` }; } if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) { if (!needBlock && !getIframeContentDocument(n2)) { attributes.rr_src = attributes.src; } delete attributes.src; } let isCustomElement; try { if (customElements.get(tagName)) isCustomElement = true; } catch (e2) { } return { type: NodeType$3.Element, tagName, attributes, childNodes: [], isSVG: isSVGElement(n2) || void 0, needBlock, rootId, isCustom: isCustomElement }; } __name(serializeElementNode, "serializeElementNode"); function lowerIfExists(maybeAttr) { if (maybeAttr === void 0 || maybeAttr === null) { return ""; } else { return maybeAttr.toLowerCase(); } } __name(lowerIfExists, "lowerIfExists"); function slimDOMExcluded(sn, slimDOMOptions) { if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) { return true; } else if (sn.type === NodeType$3.Element) { if (slimDOMOptions.script && (sn.tagName === "script" || sn.tagName === "link" && (sn.attributes.rel === "preload" || sn.attributes.rel === "modulepreload") || sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) { return true; } else if (slimDOMOptions.headFavicon && (sn.tagName === "link" && sn.attributes.rel === "shortcut icon" || sn.tagName === "meta" && (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) || lowerIfExists(sn.attributes.name) === "application-name" || lowerIfExists(sn.attributes.rel) === "icon" || lowerIfExists(sn.attributes.rel) === "apple-touch-icon" || lowerIfExists(sn.attributes.rel) === "shortcut icon"))) { return true; } else if (sn.tagName === "meta") { if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) { return true; } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) { return true; } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) { return true; } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) { return true; } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === "author" || lowerIfExists(sn.attributes.name) === "generator" || lowerIfExists(sn.attributes.name) === "framework" || lowerIfExists(sn.attributes.name) === "publisher" || lowerIfExists(sn.attributes.name) === "progid" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) { return true; } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === "google-site-verification" || lowerIfExists(sn.attributes.name) === "yandex-verification" || lowerIfExists(sn.attributes.name) === "csrf-token" || lowerIfExists(sn.attributes.name) === "p:domain_verify" || lowerIfExists(sn.attributes.name) === "verify-v1" || lowerIfExists(sn.attributes.name) === "verification" || lowerIfExists(sn.attributes.name) === "shopify-checkout-api-token")) { return true; } } } return false; } __name(slimDOMExcluded, "slimDOMExcluded"); function serializeNodeWithId(n2, options4) { const { doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5e3, onStylesheetLoad, stylesheetLoadTimeout = 5e3, keepIframeSrcFn = /* @__PURE__ */ __name(() => false, "keepIframeSrcFn"), newlyAddedElement = false } = options4; let { preserveWhiteSpace = true } = options4; const _serializedNode = serializeNode(n2, { doc: doc2, mirror: mirror2, blockClass, blockSelector, maskAllText, unblockSelector, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions, maskAttributeFn, maskTextFn, maskInputFn, dataURLOptions, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement }); if (!_serializedNode) { console.warn(n2, "not serialized"); return null; } let id3; if (mirror2.hasNode(n2)) { id3 = mirror2.getId(n2); } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.isStyle && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) { id3 = IGNORED_NODE; } else { id3 = genId(); } const serializedNode = Object.assign(_serializedNode, { id: id3 }); mirror2.add(n2, serializedNode); if (id3 === IGNORED_NODE) { return null; } if (onSerialize) { onSerialize(n2); } let recordChild = !skipChild; if (serializedNode.type === NodeType$3.Element) { recordChild = recordChild && !serializedNode.needBlock; delete serializedNode.needBlock; const shadowRoot = n2.shadowRoot; if (shadowRoot && isNativeShadowDom(shadowRoot)) serializedNode.isShadowHost = true; } if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) { if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") { preserveWhiteSpace = false; } const bypassOptions = { doc: doc2, mirror: mirror2, blockClass, blockSelector, maskAllText, unblockSelector, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild, inlineStylesheet, maskInputOptions, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions, inlineImages, recordCanvas, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn }; for (const childN of Array.from(n2.childNodes)) { const serializedChildNode = serializeNodeWithId(childN, bypassOptions); if (serializedChildNode) { serializedNode.childNodes.push(serializedChildNode); } } if (isElement$1(n2) && n2.shadowRoot) { for (const childN of Array.from(n2.shadowRoot.childNodes)) { const serializedChildNode = serializeNodeWithId(childN, bypassOptions); if (serializedChildNode) { isNativeShadowDom(n2.shadowRoot) && (serializedChildNode.isShadow = true); serializedNode.childNodes.push(serializedChildNode); } } } } if (n2.parentNode && isShadowRoot(n2.parentNode) && isNativeShadowDom(n2.parentNode)) { serializedNode.isShadow = true; } if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") { onceIframeLoaded(n2, () => { const iframeDoc = getIframeContentDocument(n2); if (iframeDoc && onIframeLoad) { const serializedIframeNode = serializeNodeWithId(iframeDoc, { doc: iframeDoc, mirror: mirror2, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild: false, inlineStylesheet, maskInputOptions, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions, inlineImages, recordCanvas, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn }); if (serializedIframeNode) { onIframeLoad(n2, serializedIframeNode); } } }, iframeLoadTimeout); } if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "link" && typeof serializedNode.attributes.rel === "string" && (serializedNode.attributes.rel === "stylesheet" || serializedNode.attributes.rel === "preload" && typeof serializedNode.attributes.href === "string" && extractFileExtension(serializedNode.attributes.href) === "css")) { onceStylesheetLoaded(n2, () => { if (onStylesheetLoad) { const serializedLinkNode = serializeNodeWithId(n2, { doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild: false, inlineStylesheet, maskInputOptions, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions, inlineImages, recordCanvas, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn }); if (serializedLinkNode) { onStylesheetLoad(n2, serializedLinkNode); } } }, stylesheetLoadTimeout); } return serializedNode; } __name(serializeNodeWithId, "serializeNodeWithId"); function snapshot(n2, options4) { const { mirror: mirror2 = new Mirror(), blockClass = "rr-block", blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = "rr-mask", unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = /* @__PURE__ */ __name(() => false, "keepIframeSrcFn") } = options4 || {}; const maskInputOptions = maskAllInputs === true ? { color: true, date: true, "datetime-local": true, email: true, month: true, number: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true, textarea: true, select: true } : maskAllInputs === false ? {} : maskAllInputs; const slimDOMOptions = slimDOM === true || slimDOM === "all" ? { script: true, comment: true, headFavicon: true, headWhitespace: true, headMetaDescKeywords: slimDOM === "all", headMetaSocial: true, headMetaRobots: true, headMetaHttpEquiv: true, headMetaAuthorship: true, headMetaVerification: true } : slimDOM === false ? {} : slimDOM; return serializeNodeWithId(n2, { doc: n2, mirror: mirror2, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild: false, inlineStylesheet, maskInputOptions, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions, inlineImages, recordCanvas, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn, newlyAddedElement: false }); } __name(snapshot, "snapshot"); function _optionalChain$4(ops) { let lastAccessLHS = void 0; let value4 = ops[0]; let i2 = 1; while (i2 < ops.length) { const op = ops[i2]; const fn = ops[i2 + 1]; i2 += 2; if ((op === "optionalAccess" || op === "optionalCall") && value4 == null) { return void 0; } if (op === "access" || op === "optionalAccess") { lastAccessLHS = value4; value4 = fn(value4); } else if (op === "call" || op === "optionalCall") { value4 = fn((...args) => value4.call(lastAccessLHS, ...args)); lastAccessLHS = void 0; } } return value4; } __name(_optionalChain$4, "_optionalChain$4"); function on(type, fn, target = document) { const options4 = { capture: true, passive: true }; target.addEventListener(type, fn, options4); return () => target.removeEventListener(type, fn, options4); } __name(on, "on"); const DEPARTED_MIRROR_ACCESS_WARNING$1 = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording."; let _mirror$1 = { map: {}, getId() { console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); return -1; }, getNode() { console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); return null; }, removeNodeFromMap() { console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); }, has() { console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); return false; }, reset() { console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); } }; if (typeof window !== "undefined" && window.Proxy && window.Reflect) { _mirror$1 = new Proxy(_mirror$1, { get(target, prop2, receiver) { if (prop2 === "map") { console.error(DEPARTED_MIRROR_ACCESS_WARNING$1); } return Reflect.get(target, prop2, receiver); } }); } function throttle$1(func, wait, options4 = {}) { let timeout = null; let previous = 0; return function(...args) { const now2 = Date.now(); if (!previous && options4.leading === false) { previous = now2; } const remaining = wait - (now2 - previous); const context = this; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout$1(timeout); timeout = null; } previous = now2; func.apply(context, args); } else if (!timeout && options4.trailing !== false) { timeout = setTimeout$1$1(() => { previous = options4.leading === false ? 0 : Date.now(); timeout = null; func.apply(context, args); }, remaining); } }; } __name(throttle$1, "throttle$1"); function hookSetter$1(target, key, d2, isRevoked, win = window) { const original = win.Object.getOwnPropertyDescriptor(target, key); win.Object.defineProperty(target, key, isRevoked ? d2 : { set(value4) { setTimeout$1$1(() => { d2.set.call(this, value4); }, 0); if (original && original.set) { original.set.call(this, value4); } } }); return () => hookSetter$1(target, key, original || {}, true); } __name(hookSetter$1, "hookSetter$1"); function patch$2(source, name2, replacement) { try { if (!(name2 in source)) { return () => { }; } const original = source[name2]; const wrapped = replacement(original); if (typeof wrapped === "function") { wrapped.prototype = wrapped.prototype || {}; Object.defineProperties(wrapped, { __rrweb_original__: { enumerable: false, value: original } }); } source[name2] = wrapped; return () => { source[name2] = original; }; } catch (e2) { return () => { }; } } __name(patch$2, "patch$2"); let nowTimestamp = Date.now; if (!/[1-9][0-9]{12}/.test(Date.now().toString())) { nowTimestamp = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).getTime(), "nowTimestamp"); } function getWindowScroll(win) { const doc2 = win.document; return { left: doc2.scrollingElement ? doc2.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : _optionalChain$4([doc2, "optionalAccess", (_2) => _2.documentElement, "access", (_2) => _2.scrollLeft]) || _optionalChain$4([doc2, "optionalAccess", (_3) => _3.body, "optionalAccess", (_4) => _4.parentElement, "optionalAccess", (_5) => _5.scrollLeft]) || _optionalChain$4([doc2, "optionalAccess", (_6) => _6.body, "optionalAccess", (_7) => _7.scrollLeft]) || 0, top: doc2.scrollingElement ? doc2.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : _optionalChain$4([doc2, "optionalAccess", (_8) => _8.documentElement, "access", (_9) => _9.scrollTop]) || _optionalChain$4([doc2, "optionalAccess", (_10) => _10.body, "optionalAccess", (_11) => _11.parentElement, "optionalAccess", (_12) => _12.scrollTop]) || _optionalChain$4([doc2, "optionalAccess", (_13) => _13.body, "optionalAccess", (_14) => _14.scrollTop]) || 0 }; } __name(getWindowScroll, "getWindowScroll"); function getWindowHeight() { return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight; } __name(getWindowHeight, "getWindowHeight"); function getWindowWidth() { return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth; } __name(getWindowWidth, "getWindowWidth"); function closestElementOfNode$1(node3) { if (!node3) { return null; } const el = node3.nodeType === node3.ELEMENT_NODE ? node3 : node3.parentElement; return el; } __name(closestElementOfNode$1, "closestElementOfNode$1"); function isBlocked$1(node3, blockClass, blockSelector, unblockSelector, checkAncestors) { if (!node3) { return false; } const el = closestElementOfNode$1(node3); if (!el) { return false; } const blockedPredicate = createMatchPredicate$1(blockClass, blockSelector); if (!checkAncestors) { const isUnblocked = unblockSelector && el.matches(unblockSelector); return blockedPredicate(el) && !isUnblocked; } const blockDistance = distanceToMatch$1(el, blockedPredicate); let unblockDistance = -1; if (blockDistance < 0) { return false; } if (unblockSelector) { unblockDistance = distanceToMatch$1(el, createMatchPredicate$1(null, unblockSelector)); } if (blockDistance > -1 && unblockDistance < 0) { return true; } return blockDistance < unblockDistance; } __name(isBlocked$1, "isBlocked$1"); function isSerialized(n2, mirror2) { return mirror2.getId(n2) !== -1; } __name(isSerialized, "isSerialized"); function isIgnored(n2, mirror2) { return mirror2.getId(n2) === IGNORED_NODE; } __name(isIgnored, "isIgnored"); function isAncestorRemoved(target, mirror2) { if (isShadowRoot(target)) { return false; } const id3 = mirror2.getId(target); if (!mirror2.has(id3)) { return true; } if (target.parentNode && target.parentNode.nodeType === target.DOCUMENT_NODE) { return false; } if (!target.parentNode) { return true; } return isAncestorRemoved(target.parentNode, mirror2); } __name(isAncestorRemoved, "isAncestorRemoved"); function legacy_isTouchEvent(event) { return Boolean(event.changedTouches); } __name(legacy_isTouchEvent, "legacy_isTouchEvent"); function polyfill(win = window) { if ("NodeList" in win && !win.NodeList.prototype.forEach) { win.NodeList.prototype.forEach = Array.prototype.forEach; } if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) { win.DOMTokenList.prototype.forEach = Array.prototype.forEach; } if (!Node.prototype.contains) { Node.prototype.contains = (...args) => { let node3 = args[0]; if (!(0 in args)) { throw new TypeError("1 argument is required"); } do { if (this === node3) { return true; } } while (node3 = node3 && node3.parentNode); return false; }; } } __name(polyfill, "polyfill"); function isSerializedIframe(n2, mirror2) { return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2)); } __name(isSerializedIframe, "isSerializedIframe"); function isSerializedStylesheet(n2, mirror2) { return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2)); } __name(isSerializedStylesheet, "isSerializedStylesheet"); function hasShadowRoot(n2) { return Boolean(_optionalChain$4([n2, "optionalAccess", (_18) => _18.shadowRoot])); } __name(hasShadowRoot, "hasShadowRoot"); class StyleSheetMirror { static { __name(this, "StyleSheetMirror"); } constructor() { this.id = 1; this.styleIDMap = /* @__PURE__ */ new WeakMap(); this.idStyleMap = /* @__PURE__ */ new Map(); } getId(stylesheet) { return _nullishCoalesce(this.styleIDMap.get(stylesheet), () => -1); } has(stylesheet) { return this.styleIDMap.has(stylesheet); } add(stylesheet, id3) { if (this.has(stylesheet)) return this.getId(stylesheet); let newId; if (id3 === void 0) { newId = this.id++; } else newId = id3; this.styleIDMap.set(stylesheet, newId); this.idStyleMap.set(newId, stylesheet); return newId; } getStyle(id3) { return this.idStyleMap.get(id3) || null; } reset() { this.styleIDMap = /* @__PURE__ */ new WeakMap(); this.idStyleMap = /* @__PURE__ */ new Map(); this.id = 1; } generateId() { return this.id++; } } function getShadowHost(n2) { let shadowHost = null; if (_optionalChain$4([n2, "access", (_19) => _19.getRootNode, "optionalCall", (_20) => _20(), "optionalAccess", (_21) => _21.nodeType]) === Node.DOCUMENT_FRAGMENT_NODE && n2.getRootNode().host) shadowHost = n2.getRootNode().host; return shadowHost; } __name(getShadowHost, "getShadowHost"); function getRootShadowHost(n2) { let rootShadowHost = n2; let shadowHost; while (shadowHost = getShadowHost(rootShadowHost)) rootShadowHost = shadowHost; return rootShadowHost; } __name(getRootShadowHost, "getRootShadowHost"); function shadowHostInDom(n2) { const doc2 = n2.ownerDocument; if (!doc2) return false; const shadowHost = getRootShadowHost(n2); return doc2.contains(shadowHost); } __name(shadowHostInDom, "shadowHostInDom"); function inDom(n2) { const doc2 = n2.ownerDocument; if (!doc2) return false; return doc2.contains(n2) || shadowHostInDom(n2); } __name(inDom, "inDom"); const cachedImplementations$2 = {}; function getImplementation$2(name2) { const cached = cachedImplementations$2[name2]; if (cached) { return cached; } const document2 = window.document; let impl = window[name2]; if (document2 && typeof document2.createElement === "function") { try { const sandbox = document2.createElement("iframe"); sandbox.hidden = true; document2.head.appendChild(sandbox); const contentWindow = sandbox.contentWindow; if (contentWindow && contentWindow[name2]) { impl = contentWindow[name2]; } document2.head.removeChild(sandbox); } catch (e2) { } } return cachedImplementations$2[name2] = impl.bind(window); } __name(getImplementation$2, "getImplementation$2"); function onRequestAnimationFrame$1(...rest) { return getImplementation$2("requestAnimationFrame")(...rest); } __name(onRequestAnimationFrame$1, "onRequestAnimationFrame$1"); function setTimeout$1$1(...rest) { return getImplementation$2("setTimeout")(...rest); } __name(setTimeout$1$1, "setTimeout$1$1"); function clearTimeout$1(...rest) { return getImplementation$2("clearTimeout")(...rest); } __name(clearTimeout$1, "clearTimeout$1"); var EventType = /* @__PURE__ */ ((EventType2) => { EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded"; EventType2[EventType2["Load"] = 1] = "Load"; EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot"; EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot"; EventType2[EventType2["Meta"] = 4] = "Meta"; EventType2[EventType2["Custom"] = 5] = "Custom"; EventType2[EventType2["Plugin"] = 6] = "Plugin"; return EventType2; })(EventType || {}); var IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => { IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation"; IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove"; IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction"; IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll"; IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize"; IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input"; IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove"; IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction"; IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule"; IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation"; IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font"; IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log"; IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag"; IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration"; IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection"; IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet"; IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement"; return IncrementalSource2; })(IncrementalSource || {}); var MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => { MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp"; MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown"; MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click"; MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu"; MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick"; MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus"; MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur"; MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart"; MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed"; MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd"; MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel"; return MouseInteractions2; })(MouseInteractions || {}); var PointerTypes = /* @__PURE__ */ ((PointerTypes2) => { PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse"; PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen"; PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch"; return PointerTypes2; })(PointerTypes || {}); var NodeType$1$1; (function(NodeType3) { NodeType3[NodeType3["Document"] = 0] = "Document"; NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType"; NodeType3[NodeType3["Element"] = 2] = "Element"; NodeType3[NodeType3["Text"] = 3] = "Text"; NodeType3[NodeType3["CDATA"] = 4] = "CDATA"; NodeType3[NodeType3["Comment"] = 5] = "Comment"; })(NodeType$1$1 || (NodeType$1$1 = {})); var NodeType$2$1; (function(NodeType3) { NodeType3[NodeType3["PLACEHOLDER"] = 0] = "PLACEHOLDER"; NodeType3[NodeType3["ELEMENT_NODE"] = 1] = "ELEMENT_NODE"; NodeType3[NodeType3["ATTRIBUTE_NODE"] = 2] = "ATTRIBUTE_NODE"; NodeType3[NodeType3["TEXT_NODE"] = 3] = "TEXT_NODE"; NodeType3[NodeType3["CDATA_SECTION_NODE"] = 4] = "CDATA_SECTION_NODE"; NodeType3[NodeType3["ENTITY_REFERENCE_NODE"] = 5] = "ENTITY_REFERENCE_NODE"; NodeType3[NodeType3["ENTITY_NODE"] = 6] = "ENTITY_NODE"; NodeType3[NodeType3["PROCESSING_INSTRUCTION_NODE"] = 7] = "PROCESSING_INSTRUCTION_NODE"; NodeType3[NodeType3["COMMENT_NODE"] = 8] = "COMMENT_NODE"; NodeType3[NodeType3["DOCUMENT_NODE"] = 9] = "DOCUMENT_NODE"; NodeType3[NodeType3["DOCUMENT_TYPE_NODE"] = 10] = "DOCUMENT_TYPE_NODE"; NodeType3[NodeType3["DOCUMENT_FRAGMENT_NODE"] = 11] = "DOCUMENT_FRAGMENT_NODE"; })(NodeType$2$1 || (NodeType$2$1 = {})); function getIFrameContentDocument(iframe) { try { return iframe.contentDocument; } catch (e2) { } } __name(getIFrameContentDocument, "getIFrameContentDocument"); function getIFrameContentWindow(iframe) { try { return iframe.contentWindow; } catch (e2) { } } __name(getIFrameContentWindow, "getIFrameContentWindow"); function _optionalChain$3(ops) { let lastAccessLHS = void 0; let value4 = ops[0]; let i2 = 1; while (i2 < ops.length) { const op = ops[i2]; const fn = ops[i2 + 1]; i2 += 2; if ((op === "optionalAccess" || op === "optionalCall") && value4 == null) { return void 0; } if (op === "access" || op === "optionalAccess") { lastAccessLHS = value4; value4 = fn(value4); } else if (op === "call" || op === "optionalCall") { value4 = fn((...args) => value4.call(lastAccessLHS, ...args)); lastAccessLHS = void 0; } } return value4; } __name(_optionalChain$3, "_optionalChain$3"); function isNodeInLinkedList(n2) { return "__ln" in n2; } __name(isNodeInLinkedList, "isNodeInLinkedList"); class DoubleLinkedList { static { __name(this, "DoubleLinkedList"); } constructor() { this.length = 0; this.head = null; this.tail = null; } get(position3) { if (position3 >= this.length) { throw new Error("Position outside of list range"); } let current = this.head; for (let index2 = 0; index2 < position3; index2++) { current = _optionalChain$3([current, "optionalAccess", (_2) => _2.next]) || null; } return current; } addNode(n2) { const node3 = { value: n2, previous: null, next: null }; n2.__ln = node3; if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) { const current = n2.previousSibling.__ln.next; node3.next = current; node3.previous = n2.previousSibling.__ln; n2.previousSibling.__ln.next = node3; if (current) { current.previous = node3; } } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) { const current = n2.nextSibling.__ln.previous; node3.previous = current; node3.next = n2.nextSibling.__ln; n2.nextSibling.__ln.previous = node3; if (current) { current.next = node3; } } else { if (this.head) { this.head.previous = node3; } node3.next = this.head; this.head = node3; } if (node3.next === null) { this.tail = node3; } this.length++; } removeNode(n2) { const current = n2.__ln; if (!this.head) { return; } if (!current.previous) { this.head = current.next; if (this.head) { this.head.previous = null; } else { this.tail = null; } } else { current.previous.next = current.next; if (current.next) { current.next.previous = current.previous; } else { this.tail = current.previous; } } if (n2.__ln) { delete n2.__ln; } this.length--; } } const moveKey = /* @__PURE__ */ __name((id3, parentId) => `${id3}@${parentId}`, "moveKey"); class MutationBuffer { static { __name(this, "MutationBuffer"); } constructor() { this.frozen = false; this.locked = false; this.texts = []; this.attributes = []; this.attributeMap = /* @__PURE__ */ new WeakMap(); this.removes = []; this.mapRemoves = []; this.movedMap = {}; this.addedSet = /* @__PURE__ */ new Set(); this.movedSet = /* @__PURE__ */ new Set(); this.droppedSet = /* @__PURE__ */ new Set(); this.processMutations = (mutations) => { mutations.forEach(this.processMutation); this.emit(); }; this.emit = () => { if (this.frozen || this.locked) { return; } const adds = []; const addedIds = /* @__PURE__ */ new Set(); const addList = new DoubleLinkedList(); const getNextId = /* @__PURE__ */ __name((n2) => { let ns = n2; let nextId = IGNORED_NODE; while (nextId === IGNORED_NODE) { ns = ns && ns.nextSibling; nextId = ns && this.mirror.getId(ns); } return nextId; }, "getNextId"); const pushAdd = /* @__PURE__ */ __name((n2) => { if (!n2.parentNode || !inDom(n2)) { return; } const parentId = isShadowRoot(n2.parentNode) ? this.mirror.getId(getShadowHost(n2)) : this.mirror.getId(n2.parentNode); const nextId = getNextId(n2); if (parentId === -1 || nextId === -1) { return addList.addNode(n2); } const sn = serializeNodeWithId(n2, { doc: this.doc, mirror: this.mirror, blockClass: this.blockClass, blockSelector: this.blockSelector, maskAllText: this.maskAllText, unblockSelector: this.unblockSelector, maskTextClass: this.maskTextClass, unmaskTextClass: this.unmaskTextClass, maskTextSelector: this.maskTextSelector, unmaskTextSelector: this.unmaskTextSelector, skipChild: true, newlyAddedElement: true, inlineStylesheet: this.inlineStylesheet, maskInputOptions: this.maskInputOptions, maskAttributeFn: this.maskAttributeFn, maskTextFn: this.maskTextFn, maskInputFn: this.maskInputFn, slimDOMOptions: this.slimDOMOptions, dataURLOptions: this.dataURLOptions, recordCanvas: this.recordCanvas, inlineImages: this.inlineImages, onSerialize: /* @__PURE__ */ __name((currentN) => { if (isSerializedIframe(currentN, this.mirror) && !isBlocked$1(currentN, this.blockClass, this.blockSelector, this.unblockSelector, false)) { this.iframeManager.addIframe(currentN); } if (isSerializedStylesheet(currentN, this.mirror)) { this.stylesheetManager.trackLinkElement(currentN); } if (hasShadowRoot(n2)) { this.shadowDomManager.addShadowRoot(n2.shadowRoot, this.doc); } }, "onSerialize"), onIframeLoad: /* @__PURE__ */ __name((iframe, childSn) => { if (isBlocked$1(iframe, this.blockClass, this.blockSelector, this.unblockSelector, false)) { return; } this.iframeManager.attachIframe(iframe, childSn); if (iframe.contentWindow) { this.canvasManager.addWindow(iframe.contentWindow); } this.shadowDomManager.observeAttachShadow(iframe); }, "onIframeLoad"), onStylesheetLoad: /* @__PURE__ */ __name((link2, childSn) => { this.stylesheetManager.attachLinkElement(link2, childSn); }, "onStylesheetLoad") }); if (sn) { adds.push({ parentId, nextId, node: sn }); addedIds.add(sn.id); } }, "pushAdd"); while (this.mapRemoves.length) { this.mirror.removeNodeFromMap(this.mapRemoves.shift()); } for (const n2 of this.movedSet) { if (isParentRemoved(this.removes, n2, this.mirror) && !this.movedSet.has(n2.parentNode)) { continue; } pushAdd(n2); } for (const n2 of this.addedSet) { if (!isAncestorInSet(this.droppedSet, n2) && !isParentRemoved(this.removes, n2, this.mirror)) { pushAdd(n2); } else if (isAncestorInSet(this.movedSet, n2)) { pushAdd(n2); } else { this.droppedSet.add(n2); } } let candidate = null; while (addList.length) { let node3 = null; if (candidate) { const parentId = this.mirror.getId(candidate.value.parentNode); const nextId = getNextId(candidate.value); if (parentId !== -1 && nextId !== -1) { node3 = candidate; } } if (!node3) { let tailNode = addList.tail; while (tailNode) { const _node = tailNode; tailNode = tailNode.previous; if (_node) { const parentId = this.mirror.getId(_node.value.parentNode); const nextId = getNextId(_node.value); if (nextId === -1) continue; else if (parentId !== -1) { node3 = _node; break; } else { const unhandledNode = _node.value; if (unhandledNode.parentNode && unhandledNode.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { const shadowHost = unhandledNode.parentNode.host; const parentId2 = this.mirror.getId(shadowHost); if (parentId2 !== -1) { node3 = _node; break; } } } } } } if (!node3) { while (addList.head) { addList.removeNode(addList.head.value); } break; } candidate = node3.previous; addList.removeNode(node3.value); pushAdd(node3.value); } const payload = { texts: this.texts.map((text2) => ({ id: this.mirror.getId(text2.node), value: text2.value })).filter((text2) => !addedIds.has(text2.id)).filter((text2) => this.mirror.has(text2.id)), attributes: this.attributes.map((attribute2) => { const { attributes } = attribute2; if (typeof attributes.style === "string") { const diffAsStr = JSON.stringify(attribute2.styleDiff); const unchangedAsStr = JSON.stringify(attribute2._unchangedStyles); if (diffAsStr.length < attributes.style.length) { if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) { attributes.style = attribute2.styleDiff; } } } return { id: this.mirror.getId(attribute2.node), attributes }; }).filter((attribute2) => !addedIds.has(attribute2.id)).filter((attribute2) => this.mirror.has(attribute2.id)), removes: this.removes, adds }; if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) { return; } this.texts = []; this.attributes = []; this.attributeMap = /* @__PURE__ */ new WeakMap(); this.removes = []; this.addedSet = /* @__PURE__ */ new Set(); this.movedSet = /* @__PURE__ */ new Set(); this.droppedSet = /* @__PURE__ */ new Set(); this.movedMap = {}; this.mutationCb(payload); }; this.processMutation = (m2) => { if (isIgnored(m2.target, this.mirror)) { return; } switch (m2.type) { case "characterData": { const value4 = m2.target.textContent; if (!isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, false) && value4 !== m2.oldValue) { this.texts.push({ value: needMaskingText(m2.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value4 ? this.maskTextFn ? this.maskTextFn(value4, closestElementOfNode$1(m2.target)) : value4.replace(/[\S]/g, "*") : value4, node: m2.target }); } break; } case "attributes": { const target = m2.target; let attributeName = m2.attributeName; let value4 = m2.target.getAttribute(attributeName); if (attributeName === "value") { const type = getInputType(target); const tagName = target.tagName; value4 = getInputValue(target, tagName, type); const isInputMasked = shouldMaskInput({ maskInputOptions: this.maskInputOptions, tagName, type }); const forceMask = needMaskingText(m2.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked); value4 = maskInputValue({ isMasked: forceMask, element: target, value: value4, maskInputFn: this.maskInputFn }); } if (isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, false) || value4 === m2.oldValue) { return; } let item3 = this.attributeMap.get(m2.target); if (target.tagName === "IFRAME" && attributeName === "src" && !this.keepIframeSrcFn(value4)) { const iframeDoc = getIFrameContentDocument(target); if (!iframeDoc) { attributeName = "rr_src"; } else { return; } } if (!item3) { item3 = { node: m2.target, attributes: {}, styleDiff: {}, _unchangedStyles: {} }; this.attributes.push(item3); this.attributeMap.set(m2.target, item3); } if (attributeName === "type" && target.tagName === "INPUT" && (m2.oldValue || "").toLowerCase() === "password") { target.setAttribute("data-rr-is-password", "true"); } if (!ignoreAttribute(target.tagName, attributeName)) { item3.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value4, target, this.maskAttributeFn); if (attributeName === "style") { if (!this.unattachedDoc) { try { this.unattachedDoc = document.implementation.createHTMLDocument(); } catch (e2) { this.unattachedDoc = this.doc; } } const old = this.unattachedDoc.createElement("span"); if (m2.oldValue) { old.setAttribute("style", m2.oldValue); } for (const pname of Array.from(target.style)) { const newValue2 = target.style.getPropertyValue(pname); const newPriority = target.style.getPropertyPriority(pname); if (newValue2 !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) { if (newPriority === "") { item3.styleDiff[pname] = newValue2; } else { item3.styleDiff[pname] = [newValue2, newPriority]; } } else { item3._unchangedStyles[pname] = [newValue2, newPriority]; } } for (const pname of Array.from(old.style)) { if (target.style.getPropertyValue(pname) === "") { item3.styleDiff[pname] = false; } } } } break; } case "childList": { if (isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) { return; } m2.addedNodes.forEach((n2) => this.genAdds(n2, m2.target)); m2.removedNodes.forEach((n2) => { const nodeId = this.mirror.getId(n2); const parentId = isShadowRoot(m2.target) ? this.mirror.getId(m2.target.host) : this.mirror.getId(m2.target); if (isBlocked$1(m2.target, this.blockClass, this.blockSelector, this.unblockSelector, false) || isIgnored(n2, this.mirror) || !isSerialized(n2, this.mirror)) { return; } if (this.addedSet.has(n2)) { deepDelete(this.addedSet, n2); this.droppedSet.add(n2); } else if (this.addedSet.has(m2.target) && nodeId === -1) ; else if (isAncestorRemoved(m2.target, this.mirror)) ; else if (this.movedSet.has(n2) && this.movedMap[moveKey(nodeId, parentId)]) { deepDelete(this.movedSet, n2); } else { this.removes.push({ parentId, id: nodeId, isShadow: isShadowRoot(m2.target) && isNativeShadowDom(m2.target) ? true : void 0 }); } this.mapRemoves.push(n2); }); break; } } }; this.genAdds = (n2, target) => { if (this.processedNodeManager.inOtherBuffer(n2, this)) return; if (this.addedSet.has(n2) || this.movedSet.has(n2)) return; if (this.mirror.hasNode(n2)) { if (isIgnored(n2, this.mirror)) { return; } this.movedSet.add(n2); let targetId = null; if (target && this.mirror.hasNode(target)) { targetId = this.mirror.getId(target); } if (targetId && targetId !== -1) { this.movedMap[moveKey(this.mirror.getId(n2), targetId)] = true; } } else { this.addedSet.add(n2); this.droppedSet.delete(n2); } if (!isBlocked$1(n2, this.blockClass, this.blockSelector, this.unblockSelector, false)) { n2.childNodes.forEach((childN) => this.genAdds(childN)); if (hasShadowRoot(n2)) { n2.shadowRoot.childNodes.forEach((childN) => { this.processedNodeManager.add(childN, this); this.genAdds(childN, n2); }); } } }; } init(options4) { [ "mutationCb", "blockClass", "blockSelector", "unblockSelector", "maskAllText", "maskTextClass", "unmaskTextClass", "maskTextSelector", "unmaskTextSelector", "inlineStylesheet", "maskInputOptions", "maskAttributeFn", "maskTextFn", "maskInputFn", "keepIframeSrcFn", "recordCanvas", "inlineImages", "slimDOMOptions", "dataURLOptions", "doc", "mirror", "iframeManager", "stylesheetManager", "shadowDomManager", "canvasManager", "processedNodeManager" ].forEach((key) => { this[key] = options4[key]; }); } freeze() { this.frozen = true; this.canvasManager.freeze(); } unfreeze() { this.frozen = false; this.canvasManager.unfreeze(); this.emit(); } isFrozen() { return this.frozen; } lock() { this.locked = true; this.canvasManager.lock(); } unlock() { this.locked = false; this.canvasManager.unlock(); this.emit(); } reset() { this.shadowDomManager.reset(); this.canvasManager.reset(); } } function deepDelete(addsSet, n2) { addsSet.delete(n2); n2.childNodes.forEach((childN) => deepDelete(addsSet, childN)); } __name(deepDelete, "deepDelete"); function isParentRemoved(removes, n2, mirror2) { if (removes.length === 0) return false; return _isParentRemoved(removes, n2, mirror2); } __name(isParentRemoved, "isParentRemoved"); function _isParentRemoved(removes, n2, mirror2) { let node3 = n2.parentNode; while (node3) { const parentId = mirror2.getId(node3); if (removes.some((r2) => r2.id === parentId)) { return true; } node3 = node3.parentNode; } return false; } __name(_isParentRemoved, "_isParentRemoved"); function isAncestorInSet(set3, n2) { if (set3.size === 0) return false; return _isAncestorInSet(set3, n2); } __name(isAncestorInSet, "isAncestorInSet"); function _isAncestorInSet(set3, n2) { const { parentNode: parentNode2 } = n2; if (!parentNode2) { return false; } if (set3.has(parentNode2)) { return true; } return _isAncestorInSet(set3, parentNode2); } __name(_isAncestorInSet, "_isAncestorInSet"); let errorHandler$1; function registerErrorHandler$1(handler6) { errorHandler$1 = handler6; } __name(registerErrorHandler$1, "registerErrorHandler$1"); function unregisterErrorHandler() { errorHandler$1 = void 0; } __name(unregisterErrorHandler, "unregisterErrorHandler"); const callbackWrapper$1 = /* @__PURE__ */ __name((cb) => { if (!errorHandler$1) { return cb; } const rrwebWrapped = /* @__PURE__ */ __name((...rest) => { try { return cb(...rest); } catch (error2) { if (errorHandler$1 && errorHandler$1(error2) === true) { return () => { }; } throw error2; } }, "rrwebWrapped"); return rrwebWrapped; }, "callbackWrapper$1"); function _optionalChain$2(ops) { let lastAccessLHS = void 0; let value4 = ops[0]; let i2 = 1; while (i2 < ops.length) { const op = ops[i2]; const fn = ops[i2 + 1]; i2 += 2; if ((op === "optionalAccess" || op === "optionalCall") && value4 == null) { return void 0; } if (op === "access" || op === "optionalAccess") { lastAccessLHS = value4; value4 = fn(value4); } else if (op === "call" || op === "optionalCall") { value4 = fn((...args) => value4.call(lastAccessLHS, ...args)); lastAccessLHS = void 0; } } return value4; } __name(_optionalChain$2, "_optionalChain$2"); const mutationBuffers = []; function getEventTarget(event) { try { if ("composedPath" in event) { const path = event.composedPath(); if (path.length) { return path[0]; } } else if ("path" in event && event.path.length) { return event.path[0]; } } catch (e2) { } return event && event.target; } __name(getEventTarget, "getEventTarget"); function initMutationObserver(options4, rootEl) { const mutationBuffer = new MutationBuffer(); mutationBuffers.push(mutationBuffer); mutationBuffer.init(options4); let mutationObserverCtor = window.MutationObserver || window.__rrMutationObserver; const angularZoneSymbol = _optionalChain$2([window, "optionalAccess", (_2) => _2.Zone, "optionalAccess", (_2) => _2.__symbol__, "optionalCall", (_3) => _3("MutationObserver")]); if (angularZoneSymbol && window[angularZoneSymbol]) { mutationObserverCtor = window[angularZoneSymbol]; } const observer = new mutationObserverCtor(callbackWrapper$1((mutations) => { if (options4.onMutation && options4.onMutation(mutations) === false) { return; } mutationBuffer.processMutations.bind(mutationBuffer)(mutations); })); observer.observe(rootEl, { attributes: true, attributeOldValue: true, characterData: true, characterDataOldValue: true, childList: true, subtree: true }); return observer; } __name(initMutationObserver, "initMutationObserver"); function initMoveObserver({ mousemoveCb, sampling, doc: doc2, mirror: mirror2 }) { if (sampling.mousemove === false) { return () => { }; } const threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50; const callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500; let positions = []; let timeBaseline; const wrappedCb = throttle$1(callbackWrapper$1((source) => { const totalOffset = Date.now() - timeBaseline; mousemoveCb(positions.map((p2) => { p2.timeOffset -= totalOffset; return p2; }), source); positions = []; timeBaseline = null; }), callbackThreshold); const updatePosition = callbackWrapper$1(throttle$1(callbackWrapper$1((evt) => { const target = getEventTarget(evt); const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt; if (!timeBaseline) { timeBaseline = nowTimestamp(); } positions.push({ x: clientX, y: clientY, id: mirror2.getId(target), timeOffset: nowTimestamp() - timeBaseline }); wrappedCb(typeof DragEvent !== "undefined" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove); }), threshold, { trailing: false })); const handlers2 = [ on("mousemove", updatePosition, doc2), on("touchmove", updatePosition, doc2), on("drag", updatePosition, doc2) ]; return callbackWrapper$1(() => { handlers2.forEach((h2) => h2()); }); } __name(initMoveObserver, "initMoveObserver"); function initMouseInteractionObserver({ mouseInteractionCb, doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, sampling }) { if (sampling.mouseInteraction === false) { return () => { }; } const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction; const handlers2 = []; let currentPointerType = null; const getHandler = /* @__PURE__ */ __name((eventKey) => { return (event) => { const target = getEventTarget(event); if (isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) { return; } let pointerType = null; let thisEventKey = eventKey; if ("pointerType" in event) { switch (event.pointerType) { case "mouse": pointerType = PointerTypes.Mouse; break; case "touch": pointerType = PointerTypes.Touch; break; case "pen": pointerType = PointerTypes.Pen; break; } if (pointerType === PointerTypes.Touch) { if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) { thisEventKey = "TouchStart"; } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) { thisEventKey = "TouchEnd"; } } else if (pointerType === PointerTypes.Pen) ; } else if (legacy_isTouchEvent(event)) { pointerType = PointerTypes.Touch; } if (pointerType !== null) { currentPointerType = pointerType; if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) { pointerType = null; } } else if (MouseInteractions[eventKey] === MouseInteractions.Click) { pointerType = currentPointerType; currentPointerType = null; } const e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event; if (!e2) { return; } const id3 = mirror2.getId(target); const { clientX, clientY } = e2; callbackWrapper$1(mouseInteractionCb)({ type: MouseInteractions[thisEventKey], id: id3, x: clientX, y: clientY, ...pointerType !== null && { pointerType } }); }; }, "getHandler"); Object.keys(MouseInteractions).filter((key) => Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false).forEach((eventKey) => { let eventName = toLowerCase(eventKey); const handler6 = getHandler(eventKey); if (window.PointerEvent) { switch (MouseInteractions[eventKey]) { case MouseInteractions.MouseDown: case MouseInteractions.MouseUp: eventName = eventName.replace("mouse", "pointer"); break; case MouseInteractions.TouchStart: case MouseInteractions.TouchEnd: return; } } handlers2.push(on(eventName, handler6, doc2)); }); return callbackWrapper$1(() => { handlers2.forEach((h2) => h2()); }); } __name(initMouseInteractionObserver, "initMouseInteractionObserver"); function initScrollObserver({ scrollCb, doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, sampling }) { const updatePosition = callbackWrapper$1(throttle$1(callbackWrapper$1((evt) => { const target = getEventTarget(evt); if (!target || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) { return; } const id3 = mirror2.getId(target); if (target === doc2 && doc2.defaultView) { const scrollLeftTop = getWindowScroll(doc2.defaultView); scrollCb({ id: id3, x: scrollLeftTop.left, y: scrollLeftTop.top }); } else { scrollCb({ id: id3, x: target.scrollLeft, y: target.scrollTop }); } }), sampling.scroll || 100)); return on("scroll", updatePosition, doc2); } __name(initScrollObserver, "initScrollObserver"); function initViewportResizeObserver({ viewportResizeCb }, { win }) { let lastH = -1; let lastW = -1; const updateDimension = callbackWrapper$1(throttle$1(callbackWrapper$1(() => { const height = getWindowHeight(); const width2 = getWindowWidth(); if (lastH !== height || lastW !== width2) { viewportResizeCb({ width: Number(width2), height: Number(height) }); lastH = height; lastW = width2; } }), 200)); return on("resize", updateDimension, win); } __name(initViewportResizeObserver, "initViewportResizeObserver"); const INPUT_TAGS = ["INPUT", "TEXTAREA", "SELECT"]; const lastInputValueMap = /* @__PURE__ */ new WeakMap(); function initInputObserver({ inputCb, doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector }) { function eventHandler(event) { let target = getEventTarget(event); const userTriggered = event.isTrusted; const tagName = target && toUpperCase(target.tagName); if (tagName === "OPTION") target = target.parentElement; if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) { return; } const el = target; if (el.classList.contains(ignoreClass) || ignoreSelector && el.matches(ignoreSelector)) { return; } const type = getInputType(target); let text2 = getInputValue(el, tagName, type); let isChecked2 = false; const isInputMasked = shouldMaskInput({ maskInputOptions, tagName, type }); const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked); if (type === "radio" || type === "checkbox") { isChecked2 = target.checked; } text2 = maskInputValue({ isMasked: forceMask, element: target, value: text2, maskInputFn }); cbWithDedup(target, userTriggeredOnInput ? { text: text2, isChecked: isChecked2, userTriggered } : { text: text2, isChecked: isChecked2 }); const name2 = target.name; if (type === "radio" && name2 && isChecked2) { doc2.querySelectorAll(`input[type="radio"][name="${name2}"]`).forEach((el2) => { if (el2 !== target) { const text3 = maskInputValue({ isMasked: forceMask, element: el2, value: getInputValue(el2, tagName, type), maskInputFn }); cbWithDedup(el2, userTriggeredOnInput ? { text: text3, isChecked: !isChecked2, userTriggered: false } : { text: text3, isChecked: !isChecked2 }); } }); } } __name(eventHandler, "eventHandler"); function cbWithDedup(target, v2) { const lastInputValue = lastInputValueMap.get(target); if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) { lastInputValueMap.set(target, v2); const id3 = mirror2.getId(target); callbackWrapper$1(inputCb)({ ...v2, id: id3 }); } } __name(cbWithDedup, "cbWithDedup"); const events2 = sampling.input === "last" ? ["change"] : ["input", "change"]; const handlers2 = events2.map((eventName) => on(eventName, callbackWrapper$1(eventHandler), doc2)); const currentWindow = doc2.defaultView; if (!currentWindow) { return () => { handlers2.forEach((h2) => h2()); }; } const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value"); const hookProperties = [ [currentWindow.HTMLInputElement.prototype, "value"], [currentWindow.HTMLInputElement.prototype, "checked"], [currentWindow.HTMLSelectElement.prototype, "value"], [currentWindow.HTMLTextAreaElement.prototype, "value"], [currentWindow.HTMLSelectElement.prototype, "selectedIndex"], [currentWindow.HTMLOptionElement.prototype, "selected"] ]; if (propertyDescriptor && propertyDescriptor.set) { handlers2.push(...hookProperties.map((p2) => hookSetter$1(p2[0], p2[1], { set() { callbackWrapper$1(eventHandler)({ target: this, isTrusted: false }); } }, false, currentWindow))); } return callbackWrapper$1(() => { handlers2.forEach((h2) => h2()); }); } __name(initInputObserver, "initInputObserver"); function getNestedCSSRulePositions(rule) { const positions = []; function recurse(childRule, pos2) { if (hasNestedCSSRule("CSSGroupingRule") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule("CSSMediaRule") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule("CSSSupportsRule") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule("CSSConditionRule") && childRule.parentRule instanceof CSSConditionRule) { const rules = Array.from(childRule.parentRule.cssRules); const index2 = rules.indexOf(childRule); pos2.unshift(index2); } else if (childRule.parentStyleSheet) { const rules = Array.from(childRule.parentStyleSheet.cssRules); const index2 = rules.indexOf(childRule); pos2.unshift(index2); } return pos2; } __name(recurse, "recurse"); return recurse(rule, positions); } __name(getNestedCSSRulePositions, "getNestedCSSRulePositions"); function getIdAndStyleId(sheet, mirror2, styleMirror) { let id3, styleId; if (!sheet) return {}; if (sheet.ownerNode) id3 = mirror2.getId(sheet.ownerNode); else styleId = styleMirror.getId(sheet); return { styleId, id: id3 }; } __name(getIdAndStyleId, "getIdAndStyleId"); function initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) { if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) { return () => { }; } const insertRule = win.CSSStyleSheet.prototype.insertRule; win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [rule, index2] = argumentsList; const { id: id3, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleSheetRuleCb({ id: id3, styleId, adds: [{ rule, index: index2 }] }); } return target.apply(thisArg, argumentsList); }) }); const deleteRule = win.CSSStyleSheet.prototype.deleteRule; win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [index2] = argumentsList; const { id: id3, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleSheetRuleCb({ id: id3, styleId, removes: [{ index: index2 }] }); } return target.apply(thisArg, argumentsList); }) }); let replace2; if (win.CSSStyleSheet.prototype.replace) { replace2 = win.CSSStyleSheet.prototype.replace; win.CSSStyleSheet.prototype.replace = new Proxy(replace2, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [text2] = argumentsList; const { id: id3, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleSheetRuleCb({ id: id3, styleId, replace: text2 }); } return target.apply(thisArg, argumentsList); }) }); } let replaceSync; if (win.CSSStyleSheet.prototype.replaceSync) { replaceSync = win.CSSStyleSheet.prototype.replaceSync; win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [text2] = argumentsList; const { id: id3, styleId } = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleSheetRuleCb({ id: id3, styleId, replaceSync: text2 }); } return target.apply(thisArg, argumentsList); }) }); } const supportedNestedCSSRuleTypes = {}; if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) { supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule; } else { if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) { supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule; } if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) { supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule; } if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) { supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule; } } const unmodifiedFunctions = {}; Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => { unmodifiedFunctions[typeKey] = { insertRule: type.prototype.insertRule, deleteRule: type.prototype.deleteRule }; type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [rule, index2] = argumentsList; const { id: id3, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleSheetRuleCb({ id: id3, styleId, adds: [ { rule, index: [ ...getNestedCSSRulePositions(thisArg), index2 || 0 ] } ] }); } return target.apply(thisArg, argumentsList); }) }); type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [index2] = argumentsList; const { id: id3, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleSheetRuleCb({ id: id3, styleId, removes: [ { index: [...getNestedCSSRulePositions(thisArg), index2] } ] }); } return target.apply(thisArg, argumentsList); }) }); }); return callbackWrapper$1(() => { win.CSSStyleSheet.prototype.insertRule = insertRule; win.CSSStyleSheet.prototype.deleteRule = deleteRule; replace2 && (win.CSSStyleSheet.prototype.replace = replace2); replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync); Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => { type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule; type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule; }); }); } __name(initStyleSheetObserver, "initStyleSheetObserver"); function initAdoptedStyleSheetObserver({ mirror: mirror2, stylesheetManager }, host) { let hostId = null; if (host.nodeName === "#document") hostId = mirror2.getId(host); else hostId = mirror2.getId(host.host); const patchTarget = host.nodeName === "#document" ? _optionalChain$2([host, "access", (_4) => _4.defaultView, "optionalAccess", (_5) => _5.Document]) : _optionalChain$2([host, "access", (_6) => _6.ownerDocument, "optionalAccess", (_7) => _7.defaultView, "optionalAccess", (_8) => _8.ShadowRoot]); const originalPropertyDescriptor = _optionalChain$2([patchTarget, "optionalAccess", (_9) => _9.prototype]) ? Object.getOwnPropertyDescriptor(_optionalChain$2([patchTarget, "optionalAccess", (_10) => _10.prototype]), "adoptedStyleSheets") : void 0; if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return () => { }; Object.defineProperty(host, "adoptedStyleSheets", { configurable: originalPropertyDescriptor.configurable, enumerable: originalPropertyDescriptor.enumerable, get() { return _optionalChain$2([originalPropertyDescriptor, "access", (_11) => _11.get, "optionalAccess", (_12) => _12.call, "call", (_13) => _13(this)]); }, set(sheets) { const result = _optionalChain$2([originalPropertyDescriptor, "access", (_14) => _14.set, "optionalAccess", (_15) => _15.call, "call", (_16) => _16(this, sheets)]); if (hostId !== null && hostId !== -1) { try { stylesheetManager.adoptStyleSheets(sheets, hostId); } catch (e2) { } } return result; } }); return callbackWrapper$1(() => { Object.defineProperty(host, "adoptedStyleSheets", { configurable: originalPropertyDescriptor.configurable, enumerable: originalPropertyDescriptor.enumerable, get: originalPropertyDescriptor.get, set: originalPropertyDescriptor.set }); }); } __name(initAdoptedStyleSheetObserver, "initAdoptedStyleSheetObserver"); function initStyleDeclarationObserver({ styleDeclarationCb, mirror: mirror2, ignoreCSSAttributes, stylesheetManager }, { win }) { const setProperty2 = win.CSSStyleDeclaration.prototype.setProperty; win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty2, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [property, value4, priority] = argumentsList; if (ignoreCSSAttributes.has(property)) { return setProperty2.apply(thisArg, [property, value4, priority]); } const { id: id3, styleId } = getIdAndStyleId(_optionalChain$2([thisArg, "access", (_17) => _17.parentRule, "optionalAccess", (_18) => _18.parentStyleSheet]), mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleDeclarationCb({ id: id3, styleId, set: { property, value: value4, priority }, index: getNestedCSSRulePositions(thisArg.parentRule) }); } return target.apply(thisArg, argumentsList); }) }); const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty; win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, { apply: callbackWrapper$1((target, thisArg, argumentsList) => { const [property] = argumentsList; if (ignoreCSSAttributes.has(property)) { return removeProperty.apply(thisArg, [property]); } const { id: id3, styleId } = getIdAndStyleId(_optionalChain$2([thisArg, "access", (_19) => _19.parentRule, "optionalAccess", (_20) => _20.parentStyleSheet]), mirror2, stylesheetManager.styleMirror); if (id3 && id3 !== -1 || styleId && styleId !== -1) { styleDeclarationCb({ id: id3, styleId, remove: { property }, index: getNestedCSSRulePositions(thisArg.parentRule) }); } return target.apply(thisArg, argumentsList); }) }); return callbackWrapper$1(() => { win.CSSStyleDeclaration.prototype.setProperty = setProperty2; win.CSSStyleDeclaration.prototype.removeProperty = removeProperty; }); } __name(initStyleDeclarationObserver, "initStyleDeclarationObserver"); function initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror: mirror2, sampling, doc: doc2 }) { const handler6 = callbackWrapper$1((type) => throttle$1(callbackWrapper$1((event) => { const target = getEventTarget(event); if (!target || isBlocked$1(target, blockClass, blockSelector, unblockSelector, true)) { return; } const { currentTime, volume, muted, playbackRate } = target; mediaInteractionCb({ type, id: mirror2.getId(target), currentTime, volume, muted, playbackRate }); }), sampling.media || 500)); const handlers2 = [ on("play", handler6(0), doc2), on("pause", handler6(1), doc2), on("seeked", handler6(2), doc2), on("volumechange", handler6(3), doc2), on("ratechange", handler6(4), doc2) ]; return callbackWrapper$1(() => { handlers2.forEach((h2) => h2()); }); } __name(initMediaInteractionObserver, "initMediaInteractionObserver"); function initFontObserver({ fontCb, doc: doc2 }) { const win = doc2.defaultView; if (!win) { return () => { }; } const handlers2 = []; const fontMap = /* @__PURE__ */ new WeakMap(); const originalFontFace = win.FontFace; win.FontFace = /* @__PURE__ */ __name(function FontFace(family, source, descriptors2) { const fontFace = new originalFontFace(family, source, descriptors2); fontMap.set(fontFace, { family, buffer: typeof source !== "string", descriptors: descriptors2, fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source))) }); return fontFace; }, "FontFace"); const restoreHandler = patch$2(doc2.fonts, "add", function(original) { return function(fontFace) { setTimeout$1$1(callbackWrapper$1(() => { const p2 = fontMap.get(fontFace); if (p2) { fontCb(p2); fontMap.delete(fontFace); } }), 0); return original.apply(this, [fontFace]); }; }); handlers2.push(() => { win.FontFace = originalFontFace; }); handlers2.push(restoreHandler); return callbackWrapper$1(() => { handlers2.forEach((h2) => h2()); }); } __name(initFontObserver, "initFontObserver"); function initSelectionObserver(param) { const { doc: doc2, mirror: mirror2, blockClass, blockSelector, unblockSelector, selectionCb } = param; let collapsed2 = true; const updateSelection2 = callbackWrapper$1(() => { const selection = doc2.getSelection(); if (!selection || collapsed2 && _optionalChain$2([selection, "optionalAccess", (_21) => _21.isCollapsed])) return; collapsed2 = selection.isCollapsed || false; const ranges = []; const count = selection.rangeCount || 0; for (let i2 = 0; i2 < count; i2++) { const range2 = selection.getRangeAt(i2); const { startContainer, startOffset, endContainer, endOffset } = range2; const blocked2 = isBlocked$1(startContainer, blockClass, blockSelector, unblockSelector, true) || isBlocked$1(endContainer, blockClass, blockSelector, unblockSelector, true); if (blocked2) continue; ranges.push({ start: mirror2.getId(startContainer), startOffset, end: mirror2.getId(endContainer), endOffset }); } selectionCb({ ranges }); }); updateSelection2(); return on("selectionchange", updateSelection2); } __name(initSelectionObserver, "initSelectionObserver"); function initCustomElementObserver({ doc: doc2, customElementCb }) { const win = doc2.defaultView; if (!win || !win.customElements) return () => { }; const restoreHandler = patch$2(win.customElements, "define", function(original) { return function(name2, constructor, options4) { try { customElementCb({ define: { name: name2 } }); } catch (e2) { } return original.apply(this, [name2, constructor, options4]); }; }); return restoreHandler; } __name(initCustomElementObserver, "initCustomElementObserver"); function initObservers(o2, _hooks = {}) { const currentWindow = o2.doc.defaultView; if (!currentWindow) { return () => { }; } let mutationObserver; if (o2.recordDOM) { mutationObserver = initMutationObserver(o2, o2.doc); } const mousemoveHandler = initMoveObserver(o2); const mouseInteractionHandler = initMouseInteractionObserver(o2); const scrollHandler = initScrollObserver(o2); const viewportResizeHandler = initViewportResizeObserver(o2, { win: currentWindow }); const inputHandler = initInputObserver(o2); const mediaInteractionHandler = initMediaInteractionObserver(o2); let styleSheetObserver = /* @__PURE__ */ __name(() => { }, "styleSheetObserver"); let adoptedStyleSheetObserver = /* @__PURE__ */ __name(() => { }, "adoptedStyleSheetObserver"); let styleDeclarationObserver = /* @__PURE__ */ __name(() => { }, "styleDeclarationObserver"); let fontObserver = /* @__PURE__ */ __name(() => { }, "fontObserver"); if (o2.recordDOM) { styleSheetObserver = initStyleSheetObserver(o2, { win: currentWindow }); adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc); styleDeclarationObserver = initStyleDeclarationObserver(o2, { win: currentWindow }); if (o2.collectFonts) { fontObserver = initFontObserver(o2); } } const selectionObserver = initSelectionObserver(o2); const customElementObserver = initCustomElementObserver(o2); const pluginHandlers = []; for (const plugin of o2.plugins) { pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options)); } return callbackWrapper$1(() => { mutationBuffers.forEach((b2) => b2.reset()); _optionalChain$2([mutationObserver, "optionalAccess", (_22) => _22.disconnect, "call", (_23) => _23()]); mousemoveHandler(); mouseInteractionHandler(); scrollHandler(); viewportResizeHandler(); inputHandler(); mediaInteractionHandler(); styleSheetObserver(); adoptedStyleSheetObserver(); styleDeclarationObserver(); fontObserver(); selectionObserver(); customElementObserver(); pluginHandlers.forEach((h2) => h2()); }); } __name(initObservers, "initObservers"); function hasNestedCSSRule(prop2) { return typeof window[prop2] !== "undefined"; } __name(hasNestedCSSRule, "hasNestedCSSRule"); function canMonkeyPatchNestedCSSRule(prop2) { return Boolean(typeof window[prop2] !== "undefined" && window[prop2].prototype && "insertRule" in window[prop2].prototype && "deleteRule" in window[prop2].prototype); } __name(canMonkeyPatchNestedCSSRule, "canMonkeyPatchNestedCSSRule"); class CrossOriginIframeMirror { static { __name(this, "CrossOriginIframeMirror"); } constructor(generateIdFn) { this.generateIdFn = generateIdFn; this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap(); this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap(); } getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) { const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe); const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe); let id3 = idToRemoteIdMap.get(remoteId); if (!id3) { id3 = this.generateIdFn(); idToRemoteIdMap.set(remoteId, id3); remoteIdToIdMap.set(id3, remoteId); } return id3; } getIds(iframe, remoteId) { const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe); const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe); return remoteId.map((id3) => this.getId(iframe, id3, idToRemoteIdMap, remoteIdToIdMap)); } getRemoteId(iframe, id3, map3) { const remoteIdToIdMap = map3 || this.getRemoteIdToIdMap(iframe); if (typeof id3 !== "number") return id3; const remoteId = remoteIdToIdMap.get(id3); if (!remoteId) return -1; return remoteId; } getRemoteIds(iframe, ids) { const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe); return ids.map((id3) => this.getRemoteId(iframe, id3, remoteIdToIdMap)); } reset(iframe) { if (!iframe) { this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap(); this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap(); return; } this.iframeIdToRemoteIdMap.delete(iframe); this.iframeRemoteIdToIdMap.delete(iframe); } getIdToRemoteIdMap(iframe) { let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe); if (!idToRemoteIdMap) { idToRemoteIdMap = /* @__PURE__ */ new Map(); this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap); } return idToRemoteIdMap; } getRemoteIdToIdMap(iframe) { let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe); if (!remoteIdToIdMap) { remoteIdToIdMap = /* @__PURE__ */ new Map(); this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap); } return remoteIdToIdMap; } } function _optionalChain$1(ops) { let lastAccessLHS = void 0; let value4 = ops[0]; let i2 = 1; while (i2 < ops.length) { const op = ops[i2]; const fn = ops[i2 + 1]; i2 += 2; if ((op === "optionalAccess" || op === "optionalCall") && value4 == null) { return void 0; } if (op === "access" || op === "optionalAccess") { lastAccessLHS = value4; value4 = fn(value4); } else if (op === "call" || op === "optionalCall") { value4 = fn((...args) => value4.call(lastAccessLHS, ...args)); lastAccessLHS = void 0; } } return value4; } __name(_optionalChain$1, "_optionalChain$1"); class IframeManagerNoop { static { __name(this, "IframeManagerNoop"); } constructor() { this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId); this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap(); } addIframe() { } addLoadListener() { } attachIframe() { } } class IframeManager { static { __name(this, "IframeManager"); } constructor(options4) { this.iframes = /* @__PURE__ */ new WeakMap(); this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap(); this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId); this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap(); this.mutationCb = options4.mutationCb; this.wrappedEmit = options4.wrappedEmit; this.stylesheetManager = options4.stylesheetManager; this.recordCrossOriginIframes = options4.recordCrossOriginIframes; this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)); this.mirror = options4.mirror; if (this.recordCrossOriginIframes) { window.addEventListener("message", this.handleMessage.bind(this)); } } addIframe(iframeEl) { this.iframes.set(iframeEl, true); if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl); } addLoadListener(cb) { this.loadListener = cb; } attachIframe(iframeEl, childSn) { this.mutationCb({ adds: [ { parentId: this.mirror.getId(iframeEl), nextId: null, node: childSn } ], removes: [], texts: [], attributes: [], isAttachIframe: true }); _optionalChain$1([this, "access", (_2) => _2.loadListener, "optionalCall", (_2) => _2(iframeEl)]); const iframeDoc = getIFrameContentDocument(iframeEl); if (iframeDoc && iframeDoc.adoptedStyleSheets && iframeDoc.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeDoc.adoptedStyleSheets, this.mirror.getId(iframeDoc)); } handleMessage(message3) { const crossOriginMessageEvent = message3; if (crossOriginMessageEvent.data.type !== "rrweb" || crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return; const iframeSourceWindow = message3.source; if (!iframeSourceWindow) return; const iframeEl = this.crossOriginIframeMap.get(message3.source); if (!iframeEl) return; const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event); if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout); } transformCrossOriginEvent(iframeEl, e2) { switch (e2.type) { case EventType.FullSnapshot: { this.crossOriginIframeMirror.reset(iframeEl); this.crossOriginIframeStyleMirror.reset(iframeEl); this.replaceIdOnNode(e2.data.node, iframeEl); const rootId = e2.data.node.id; this.crossOriginIframeRootIdMap.set(iframeEl, rootId); this.patchRootIdOnNode(e2.data.node, rootId); return { timestamp: e2.timestamp, type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.Mutation, adds: [ { parentId: this.mirror.getId(iframeEl), nextId: null, node: e2.data.node } ], removes: [], texts: [], attributes: [], isAttachIframe: true } }; } case EventType.Meta: case EventType.Load: case EventType.DomContentLoaded: { return false; } case EventType.Plugin: { return e2; } case EventType.Custom: { this.replaceIds(e2.data.payload, iframeEl, ["id", "parentId", "previousId", "nextId"]); return e2; } case EventType.IncrementalSnapshot: { switch (e2.data.source) { case IncrementalSource.Mutation: { e2.data.adds.forEach((n2) => { this.replaceIds(n2, iframeEl, [ "parentId", "nextId", "previousId" ]); this.replaceIdOnNode(n2.node, iframeEl); const rootId = this.crossOriginIframeRootIdMap.get(iframeEl); rootId && this.patchRootIdOnNode(n2.node, rootId); }); e2.data.removes.forEach((n2) => { this.replaceIds(n2, iframeEl, ["parentId", "id"]); }); e2.data.attributes.forEach((n2) => { this.replaceIds(n2, iframeEl, ["id"]); }); e2.data.texts.forEach((n2) => { this.replaceIds(n2, iframeEl, ["id"]); }); return e2; } case IncrementalSource.Drag: case IncrementalSource.TouchMove: case IncrementalSource.MouseMove: { e2.data.positions.forEach((p2) => { this.replaceIds(p2, iframeEl, ["id"]); }); return e2; } case IncrementalSource.ViewportResize: { return false; } case IncrementalSource.MediaInteraction: case IncrementalSource.MouseInteraction: case IncrementalSource.Scroll: case IncrementalSource.CanvasMutation: case IncrementalSource.Input: { this.replaceIds(e2.data, iframeEl, ["id"]); return e2; } case IncrementalSource.StyleSheetRule: case IncrementalSource.StyleDeclaration: { this.replaceIds(e2.data, iframeEl, ["id"]); this.replaceStyleIds(e2.data, iframeEl, ["styleId"]); return e2; } case IncrementalSource.Font: { return e2; } case IncrementalSource.Selection: { e2.data.ranges.forEach((range2) => { this.replaceIds(range2, iframeEl, ["start", "end"]); }); return e2; } case IncrementalSource.AdoptedStyleSheet: { this.replaceIds(e2.data, iframeEl, ["id"]); this.replaceStyleIds(e2.data, iframeEl, ["styleIds"]); _optionalChain$1([e2, "access", (_3) => _3.data, "access", (_4) => _4.styles, "optionalAccess", (_5) => _5.forEach, "call", (_6) => _6((style2) => { this.replaceStyleIds(style2, iframeEl, ["styleId"]); })]); return e2; } } } } return false; } replace(iframeMirror, obj, iframeEl, keys2) { for (const key of keys2) { if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue; if (Array.isArray(obj[key])) { obj[key] = iframeMirror.getIds(iframeEl, obj[key]); } else { obj[key] = iframeMirror.getId(iframeEl, obj[key]); } } return obj; } replaceIds(obj, iframeEl, keys2) { return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys2); } replaceStyleIds(obj, iframeEl, keys2) { return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys2); } replaceIdOnNode(node3, iframeEl) { this.replaceIds(node3, iframeEl, ["id", "rootId"]); if ("childNodes" in node3) { node3.childNodes.forEach((child) => { this.replaceIdOnNode(child, iframeEl); }); } } patchRootIdOnNode(node3, rootId) { if (node3.type !== NodeType$3.Document && !node3.rootId) node3.rootId = rootId; if ("childNodes" in node3) { node3.childNodes.forEach((child) => { this.patchRootIdOnNode(child, rootId); }); } } } class ShadowDomManagerNoop { static { __name(this, "ShadowDomManagerNoop"); } init() { } addShadowRoot() { } observeAttachShadow() { } reset() { } } class ShadowDomManager { static { __name(this, "ShadowDomManager"); } constructor(options4) { this.shadowDoms = /* @__PURE__ */ new WeakSet(); this.restoreHandlers = []; this.mutationCb = options4.mutationCb; this.scrollCb = options4.scrollCb; this.bypassOptions = options4.bypassOptions; this.mirror = options4.mirror; this.init(); } init() { this.reset(); this.patchAttachShadow(Element, document); } addShadowRoot(shadowRoot, doc2) { if (!isNativeShadowDom(shadowRoot)) return; if (this.shadowDoms.has(shadowRoot)) return; this.shadowDoms.add(shadowRoot); this.bypassOptions.canvasManager.addShadowRoot(shadowRoot); const observer = initMutationObserver({ ...this.bypassOptions, doc: doc2, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }, shadowRoot); this.restoreHandlers.push(() => observer.disconnect()); this.restoreHandlers.push(initScrollObserver({ ...this.bypassOptions, scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror })); setTimeout$1$1(() => { if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0) this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host)); this.restoreHandlers.push(initAdoptedStyleSheetObserver({ mirror: this.mirror, stylesheetManager: this.bypassOptions.stylesheetManager }, shadowRoot)); }, 0); } observeAttachShadow(iframeElement) { const iframeDoc = getIFrameContentDocument(iframeElement); const iframeWindow = getIFrameContentWindow(iframeElement); if (!iframeDoc || !iframeWindow) return; this.patchAttachShadow(iframeWindow.Element, iframeDoc); } patchAttachShadow(element, doc2) { const manager = this; this.restoreHandlers.push(patch$2(element.prototype, "attachShadow", function(original) { return function(option3) { const shadowRoot = original.call(this, option3); if (this.shadowRoot && inDom(this)) manager.addShadowRoot(this.shadowRoot, doc2); return shadowRoot; }; })); } reset() { this.restoreHandlers.forEach((handler6) => { try { handler6(); } catch (e2) { } }); this.restoreHandlers = []; this.shadowDoms = /* @__PURE__ */ new WeakSet(); this.bypassOptions.canvasManager.resetShadowRoots(); } } class CanvasManagerNoop { static { __name(this, "CanvasManagerNoop"); } reset() { } freeze() { } unfreeze() { } lock() { } unlock() { } snapshot() { } addWindow() { } addShadowRoot() { } resetShadowRoots() { } } class StylesheetManager { static { __name(this, "StylesheetManager"); } constructor(options4) { this.trackedLinkElements = /* @__PURE__ */ new WeakSet(); this.styleMirror = new StyleSheetMirror(); this.mutationCb = options4.mutationCb; this.adoptedStyleSheetCb = options4.adoptedStyleSheetCb; } attachLinkElement(linkEl, childSn) { if ("_cssText" in childSn.attributes) this.mutationCb({ adds: [], removes: [], texts: [], attributes: [ { id: childSn.id, attributes: childSn.attributes } ] }); this.trackLinkElement(linkEl); } trackLinkElement(linkEl) { if (this.trackedLinkElements.has(linkEl)) return; this.trackedLinkElements.add(linkEl); this.trackStylesheetInLinkElement(linkEl); } adoptStyleSheets(sheets, hostId) { if (sheets.length === 0) return; const adoptedStyleSheetData = { id: hostId, styleIds: [] }; const styles = []; for (const sheet of sheets) { let styleId; if (!this.styleMirror.has(sheet)) { styleId = this.styleMirror.add(sheet); styles.push({ styleId, rules: Array.from(sheet.rules || CSSRule, (r2, index2) => ({ rule: stringifyRule(r2), index: index2 })) }); } else styleId = this.styleMirror.getId(sheet); adoptedStyleSheetData.styleIds.push(styleId); } if (styles.length > 0) adoptedStyleSheetData.styles = styles; this.adoptedStyleSheetCb(adoptedStyleSheetData); } reset() { this.styleMirror.reset(); this.trackedLinkElements = /* @__PURE__ */ new WeakSet(); } trackStylesheetInLinkElement(linkEl) { } } class ProcessedNodeManager { static { __name(this, "ProcessedNodeManager"); } constructor() { this.nodeMap = /* @__PURE__ */ new WeakMap(); this.active = false; } inOtherBuffer(node3, thisBuffer) { const buffers = this.nodeMap.get(node3); return buffers && Array.from(buffers).some((buffer2) => buffer2 !== thisBuffer); } add(node3, buffer2) { if (!this.active) { this.active = true; onRequestAnimationFrame$1(() => { this.nodeMap = /* @__PURE__ */ new WeakMap(); this.active = false; }); } this.nodeMap.set(node3, (this.nodeMap.get(node3) || /* @__PURE__ */ new Set()).add(buffer2)); } destroy() { } } let wrappedEmit; let _takeFullSnapshot; try { if (Array.from([1], (x2) => x2 * 2)[0] !== 2) { const cleanFrame = document.createElement("iframe"); document.body.appendChild(cleanFrame); Array.from = _optionalChain([cleanFrame, "access", (_2) => _2.contentWindow, "optionalAccess", (_2) => _2.Array, "access", (_3) => _3.from]) || Array.from; document.body.removeChild(cleanFrame); } } catch (err) { console.debug("Unable to override Array.from", err); } const mirror = createMirror(); function record(options4 = {}) { const { emit: emit2, checkoutEveryNms, checkoutEveryNth, blockClass = "rr-block", blockSelector = null, unblockSelector = null, ignoreClass = "rr-ignore", ignoreSelector = null, maskAllText = false, maskTextClass = "rr-mask", unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordDOM = true, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options4.recordAfter === "DOMContentLoaded" ? options4.recordAfter : "load", userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = /* @__PURE__ */ __name(() => false, "keepIframeSrcFn"), ignoreCSSAttributes = /* @__PURE__ */ new Set([]), errorHandler: errorHandler2, onMutation, getCanvasManager } = options4; registerErrorHandler$1(errorHandler2); const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true; let passEmitsToParent = false; if (!inEmittingFrame) { try { if (window.parent.document) { passEmitsToParent = false; } } catch (e2) { passEmitsToParent = true; } } if (inEmittingFrame && !emit2) { throw new Error("emit function is required"); } if (!inEmittingFrame && !passEmitsToParent) { return () => { }; } if (mousemoveWait !== void 0 && sampling.mousemove === void 0) { sampling.mousemove = mousemoveWait; } mirror.reset(); const maskInputOptions = maskAllInputs === true ? { color: true, date: true, "datetime-local": true, email: true, month: true, number: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true, textarea: true, select: true, radio: true, checkbox: true } : _maskInputOptions !== void 0 ? _maskInputOptions : {}; const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? { script: true, comment: true, headFavicon: true, headWhitespace: true, headMetaSocial: true, headMetaRobots: true, headMetaHttpEquiv: true, headMetaVerification: true, headMetaAuthorship: _slimDOMOptions === "all", headMetaDescKeywords: _slimDOMOptions === "all" } : _slimDOMOptions ? _slimDOMOptions : {}; polyfill(); let lastFullSnapshotEvent; let incrementalSnapshotCount = 0; const eventProcessor = /* @__PURE__ */ __name((e2) => { for (const plugin of plugins || []) { if (plugin.eventProcessor) { e2 = plugin.eventProcessor(e2); } } if (packFn && !passEmitsToParent) { e2 = packFn(e2); } return e2; }, "eventProcessor"); wrappedEmit = /* @__PURE__ */ __name((r2, isCheckout) => { const e2 = r2; e2.timestamp = nowTimestamp(); if (_optionalChain([mutationBuffers, "access", (_4) => _4[0], "optionalAccess", (_5) => _5.isFrozen, "call", (_6) => _6()]) && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) { mutationBuffers.forEach((buf) => buf.unfreeze()); } if (inEmittingFrame) { _optionalChain([emit2, "optionalCall", (_7) => _7(eventProcessor(e2), isCheckout)]); } else if (passEmitsToParent) { const message3 = { type: "rrweb", event: eventProcessor(e2), origin: window.location.origin, isCheckout }; window.parent.postMessage(message3, "*"); } if (e2.type === EventType.FullSnapshot) { lastFullSnapshotEvent = e2; incrementalSnapshotCount = 0; } else if (e2.type === EventType.IncrementalSnapshot) { if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) { return; } incrementalSnapshotCount++; const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth; const exceedTime = checkoutEveryNms && lastFullSnapshotEvent && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms; if (exceedCount || exceedTime) { takeFullSnapshot2(true); } } }, "wrappedEmit"); const wrappedMutationEmit = /* @__PURE__ */ __name((m2) => { wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.Mutation, ...m2 } }); }, "wrappedMutationEmit"); const wrappedScrollEmit = /* @__PURE__ */ __name((p2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.Scroll, ...p2 } }), "wrappedScrollEmit"); const wrappedCanvasMutationEmit = /* @__PURE__ */ __name((p2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.CanvasMutation, ...p2 } }), "wrappedCanvasMutationEmit"); const wrappedAdoptedStyleSheetEmit = /* @__PURE__ */ __name((a2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.AdoptedStyleSheet, ...a2 } }), "wrappedAdoptedStyleSheetEmit"); const stylesheetManager = new StylesheetManager({ mutationCb: wrappedMutationEmit, adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit }); const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === "boolean" && __RRWEB_EXCLUDE_IFRAME__ ? new IframeManagerNoop() : new IframeManager({ mirror, mutationCb: wrappedMutationEmit, stylesheetManager, recordCrossOriginIframes, wrappedEmit }); for (const plugin of plugins || []) { if (plugin.getMirror) plugin.getMirror({ nodeMirror: mirror, crossOriginIframeMirror: iframeManager.crossOriginIframeMirror, crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror }); } const processedNodeManager = new ProcessedNodeManager(); const canvasManager = _getCanvasManager(getCanvasManager, { mirror, win: window, mutationCb: /* @__PURE__ */ __name((p2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.CanvasMutation, ...p2 } }), "mutationCb"), recordCanvas, blockClass, blockSelector, unblockSelector, maxCanvasSize, sampling: sampling["canvas"], dataURLOptions, errorHandler: errorHandler2 }); const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === "boolean" && __RRWEB_EXCLUDE_SHADOW_DOM__ ? new ShadowDomManagerNoop() : new ShadowDomManager({ mutationCb: wrappedMutationEmit, scrollCb: wrappedScrollEmit, bypassOptions: { onMutation, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions, dataURLOptions, maskAttributeFn, maskTextFn, maskInputFn, recordCanvas, inlineImages, sampling, slimDOMOptions, iframeManager, stylesheetManager, canvasManager, keepIframeSrcFn, processedNodeManager }, mirror }); const takeFullSnapshot2 = /* @__PURE__ */ __name((isCheckout = false) => { if (!recordDOM) { return; } wrappedEmit({ type: EventType.Meta, data: { href: window.location.href, width: getWindowWidth(), height: getWindowHeight() } }, isCheckout); stylesheetManager.reset(); shadowDomManager.init(); mutationBuffers.forEach((buf) => buf.lock()); const node3 = snapshot(document, { mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskAllInputs: maskInputOptions, maskAttributeFn, maskInputFn, maskTextFn, slimDOM: slimDOMOptions, dataURLOptions, recordCanvas, inlineImages, onSerialize: /* @__PURE__ */ __name((n2) => { if (isSerializedIframe(n2, mirror)) { iframeManager.addIframe(n2); } if (isSerializedStylesheet(n2, mirror)) { stylesheetManager.trackLinkElement(n2); } if (hasShadowRoot(n2)) { shadowDomManager.addShadowRoot(n2.shadowRoot, document); } }, "onSerialize"), onIframeLoad: /* @__PURE__ */ __name((iframe, childSn) => { iframeManager.attachIframe(iframe, childSn); if (iframe.contentWindow) { canvasManager.addWindow(iframe.contentWindow); } shadowDomManager.observeAttachShadow(iframe); }, "onIframeLoad"), onStylesheetLoad: /* @__PURE__ */ __name((linkEl, childSn) => { stylesheetManager.attachLinkElement(linkEl, childSn); }, "onStylesheetLoad"), keepIframeSrcFn }); if (!node3) { return console.warn("Failed to snapshot the document"); } wrappedEmit({ type: EventType.FullSnapshot, data: { node: node3, initialOffset: getWindowScroll(window) } }); mutationBuffers.forEach((buf) => buf.unlock()); if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document)); }, "takeFullSnapshot"); _takeFullSnapshot = takeFullSnapshot2; try { const handlers2 = []; const observe2 = /* @__PURE__ */ __name((doc2) => { return callbackWrapper$1(initObservers)({ onMutation, mutationCb: wrappedMutationEmit, mousemoveCb: /* @__PURE__ */ __name((positions, source) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source, positions } }), "mousemoveCb"), mouseInteractionCb: /* @__PURE__ */ __name((d2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.MouseInteraction, ...d2 } }), "mouseInteractionCb"), scrollCb: wrappedScrollEmit, viewportResizeCb: /* @__PURE__ */ __name((d2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.ViewportResize, ...d2 } }), "viewportResizeCb"), inputCb: /* @__PURE__ */ __name((v2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.Input, ...v2 } }), "inputCb"), mediaInteractionCb: /* @__PURE__ */ __name((p2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.MediaInteraction, ...p2 } }), "mediaInteractionCb"), styleSheetRuleCb: /* @__PURE__ */ __name((r2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.StyleSheetRule, ...r2 } }), "styleSheetRuleCb"), styleDeclarationCb: /* @__PURE__ */ __name((r2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.StyleDeclaration, ...r2 } }), "styleDeclarationCb"), canvasMutationCb: wrappedCanvasMutationEmit, fontCb: /* @__PURE__ */ __name((p2) => wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.Font, ...p2 } }), "fontCb"), selectionCb: /* @__PURE__ */ __name((p2) => { wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.Selection, ...p2 } }); }, "selectionCb"), customElementCb: /* @__PURE__ */ __name((c2) => { wrappedEmit({ type: EventType.IncrementalSnapshot, data: { source: IncrementalSource.CustomElement, ...c2 } }); }, "customElementCb"), blockClass, ignoreClass, ignoreSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskInputOptions, inlineStylesheet, sampling, recordDOM, recordCanvas, inlineImages, userTriggeredOnInput, collectFonts, doc: doc2, maskAttributeFn, maskInputFn, maskTextFn, keepIframeSrcFn, blockSelector, unblockSelector, slimDOMOptions, dataURLOptions, mirror, iframeManager, stylesheetManager, shadowDomManager, processedNodeManager, canvasManager, ignoreCSSAttributes, plugins: _optionalChain([ plugins, "optionalAccess", (_8) => _8.filter, "call", (_9) => _9((p2) => p2.observer), "optionalAccess", (_10) => _10.map, "call", (_11) => _11((p2) => ({ observer: p2.observer, options: p2.options, callback: /* @__PURE__ */ __name((payload) => wrappedEmit({ type: EventType.Plugin, data: { plugin: p2.name, payload } }), "callback") })) ]) || [] }, {}); }, "observe"); iframeManager.addLoadListener((iframeEl) => { try { handlers2.push(observe2(iframeEl.contentDocument)); } catch (error2) { console.warn(error2); } }); const init3 = /* @__PURE__ */ __name(() => { takeFullSnapshot2(); handlers2.push(observe2(document)); }, "init"); if (document.readyState === "interactive" || document.readyState === "complete") { init3(); } else { handlers2.push(on("DOMContentLoaded", () => { wrappedEmit({ type: EventType.DomContentLoaded, data: {} }); if (recordAfter === "DOMContentLoaded") init3(); })); handlers2.push(on("load", () => { wrappedEmit({ type: EventType.Load, data: {} }); if (recordAfter === "load") init3(); }, window)); } return () => { handlers2.forEach((h2) => h2()); processedNodeManager.destroy(); _takeFullSnapshot = void 0; unregisterErrorHandler(); }; } catch (error2) { console.warn(error2); } } __name(record, "record"); function takeFullSnapshot(isCheckout) { if (!_takeFullSnapshot) { throw new Error("please take full snapshot after start recording"); } _takeFullSnapshot(isCheckout); } __name(takeFullSnapshot, "takeFullSnapshot"); record.mirror = mirror; record.takeFullSnapshot = takeFullSnapshot; function _getCanvasManager(getCanvasManagerFn, options4) { try { return getCanvasManagerFn ? getCanvasManagerFn(options4) : new CanvasManagerNoop(); } catch (e2) { console.warn("Unable to initialize CanvasManager"); return new CanvasManagerNoop(); } } __name(_getCanvasManager, "_getCanvasManager"); const ReplayEventTypeIncrementalSnapshot = 3; const ReplayEventTypeCustom = 5; function timestampToMs(timestamp2) { const isMs = timestamp2 > 9999999999; return isMs ? timestamp2 : timestamp2 * 1e3; } __name(timestampToMs, "timestampToMs"); function timestampToS(timestamp2) { const isMs = timestamp2 > 9999999999; return isMs ? timestamp2 / 1e3 : timestamp2; } __name(timestampToS, "timestampToS"); function addBreadcrumbEvent(replay, breadcrumb) { if (breadcrumb.category === "sentry.transaction") { return; } if (["ui.click", "ui.input"].includes(breadcrumb.category)) { replay.triggerUserActivity(); } else { replay.checkAndHandleExpiredSession(); } replay.addUpdate(() => { replay.throttledAddEvent({ type: EventType.Custom, // TODO: We were converting from ms to seconds for breadcrumbs, spans, // but maybe we should just keep them as milliseconds timestamp: (breadcrumb.timestamp || 0) * 1e3, data: { tag: "breadcrumb", // normalize to max. 10 depth and 1_000 properties per object payload: normalize$2(breadcrumb, 10, 1e3) } }); return breadcrumb.category === "console"; }); } __name(addBreadcrumbEvent, "addBreadcrumbEvent"); const INTERACTIVE_SELECTOR = "button,a"; function getClosestInteractive(element) { const closestInteractive = element.closest(INTERACTIVE_SELECTOR); return closestInteractive || element; } __name(getClosestInteractive, "getClosestInteractive"); function getClickTargetNode(event) { const target = getTargetNode(event); if (!target || !(target instanceof Element)) { return target; } return getClosestInteractive(target); } __name(getClickTargetNode, "getClickTargetNode"); function getTargetNode(event) { if (isEventWithTarget(event)) { return event.target; } return event; } __name(getTargetNode, "getTargetNode"); function isEventWithTarget(event) { return typeof event === "object" && !!event && "target" in event; } __name(isEventWithTarget, "isEventWithTarget"); let handlers$2; function onWindowOpen(cb) { if (!handlers$2) { handlers$2 = []; monkeyPatchWindowOpen(); } handlers$2.push(cb); return () => { const pos2 = handlers$2 ? handlers$2.indexOf(cb) : -1; if (pos2 > -1) { handlers$2.splice(pos2, 1); } }; } __name(onWindowOpen, "onWindowOpen"); function monkeyPatchWindowOpen() { fill(WINDOW$1, "open", function(originalWindowOpen) { return function(...args) { if (handlers$2) { try { handlers$2.forEach((handler6) => handler6()); } catch (e2) { } } return originalWindowOpen.apply(WINDOW$1, args); }; }); } __name(monkeyPatchWindowOpen, "monkeyPatchWindowOpen"); const IncrementalMutationSources = /* @__PURE__ */ new Set([ IncrementalSource.Mutation, IncrementalSource.StyleSheetRule, IncrementalSource.StyleDeclaration, IncrementalSource.AdoptedStyleSheet, IncrementalSource.CanvasMutation, IncrementalSource.Selection, IncrementalSource.MediaInteraction ]); function handleClick$1(clickDetector, clickBreadcrumb, node3) { clickDetector.handleClick(clickBreadcrumb, node3); } __name(handleClick$1, "handleClick$1"); class ClickDetector { static { __name(this, "ClickDetector"); } // protected for testing constructor(replay, slowClickConfig, _addBreadcrumbEvent = addBreadcrumbEvent) { this._lastMutation = 0; this._lastScroll = 0; this._clicks = []; this._timeout = slowClickConfig.timeout / 1e3; this._threshold = slowClickConfig.threshold / 1e3; this._scrollTimeout = slowClickConfig.scrollTimeout / 1e3; this._replay = replay; this._ignoreSelector = slowClickConfig.ignoreSelector; this._addBreadcrumbEvent = _addBreadcrumbEvent; } /** Register click detection handlers on mutation or scroll. */ addListeners() { const cleanupWindowOpen = onWindowOpen(() => { this._lastMutation = nowInSeconds(); }); this._teardown = () => { cleanupWindowOpen(); this._clicks = []; this._lastMutation = 0; this._lastScroll = 0; }; } /** Clean up listeners. */ removeListeners() { if (this._teardown) { this._teardown(); } if (this._checkClickTimeout) { clearTimeout(this._checkClickTimeout); } } /** @inheritDoc */ handleClick(breadcrumb, node3) { if (ignoreElement(node3, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) { return; } const newClick = { timestamp: timestampToS(breadcrumb.timestamp), clickBreadcrumb: breadcrumb, // Set this to 0 so we know it originates from the click breadcrumb clickCount: 0, node: node3 }; if (this._clicks.some((click2) => click2.node === newClick.node && Math.abs(click2.timestamp - newClick.timestamp) < 1)) { return; } this._clicks.push(newClick); if (this._clicks.length === 1) { this._scheduleCheckClicks(); } } /** @inheritDoc */ registerMutation(timestamp2 = Date.now()) { this._lastMutation = timestampToS(timestamp2); } /** @inheritDoc */ registerScroll(timestamp2 = Date.now()) { this._lastScroll = timestampToS(timestamp2); } /** @inheritDoc */ registerClick(element) { const node3 = getClosestInteractive(element); this._handleMultiClick(node3); } /** Count multiple clicks on elements. */ _handleMultiClick(node3) { this._getClicks(node3).forEach((click2) => { click2.clickCount++; }); } /** Get all pending clicks for a given node. */ _getClicks(node3) { return this._clicks.filter((click2) => click2.node === node3); } /** Check the clicks that happened. */ _checkClicks() { const timedOutClicks = []; const now2 = nowInSeconds(); this._clicks.forEach((click2) => { if (!click2.mutationAfter && this._lastMutation) { click2.mutationAfter = click2.timestamp <= this._lastMutation ? this._lastMutation - click2.timestamp : void 0; } if (!click2.scrollAfter && this._lastScroll) { click2.scrollAfter = click2.timestamp <= this._lastScroll ? this._lastScroll - click2.timestamp : void 0; } if (click2.timestamp + this._timeout <= now2) { timedOutClicks.push(click2); } }); for (const click2 of timedOutClicks) { const pos2 = this._clicks.indexOf(click2); if (pos2 > -1) { this._generateBreadcrumbs(click2); this._clicks.splice(pos2, 1); } } if (this._clicks.length) { this._scheduleCheckClicks(); } } /** Generate matching breadcrumb(s) for the click. */ _generateBreadcrumbs(click2) { const replay = this._replay; const hadScroll = click2.scrollAfter && click2.scrollAfter <= this._scrollTimeout; const hadMutation = click2.mutationAfter && click2.mutationAfter <= this._threshold; const isSlowClick = !hadScroll && !hadMutation; const { clickCount, clickBreadcrumb } = click2; if (isSlowClick) { const timeAfterClickMs = Math.min(click2.mutationAfter || this._timeout, this._timeout) * 1e3; const endReason = timeAfterClickMs < this._timeout * 1e3 ? "mutation" : "timeout"; const breadcrumb = { type: "default", message: clickBreadcrumb.message, timestamp: clickBreadcrumb.timestamp, category: "ui.slowClickDetected", data: { ...clickBreadcrumb.data, url: WINDOW$1.location.href, route: replay.getCurrentRoute(), timeAfterClickMs, endReason, // If clickCount === 0, it means multiClick was not correctly captured here // - we still want to send 1 in this case clickCount: clickCount || 1 } }; this._addBreadcrumbEvent(replay, breadcrumb); return; } if (clickCount > 1) { const breadcrumb = { type: "default", message: clickBreadcrumb.message, timestamp: clickBreadcrumb.timestamp, category: "ui.multiClick", data: { ...clickBreadcrumb.data, url: WINDOW$1.location.href, route: replay.getCurrentRoute(), clickCount, metric: true } }; this._addBreadcrumbEvent(replay, breadcrumb); } } /** Schedule to check current clicks. */ _scheduleCheckClicks() { if (this._checkClickTimeout) { clearTimeout(this._checkClickTimeout); } this._checkClickTimeout = setTimeout$3(() => this._checkClicks(), 1e3); } } const SLOW_CLICK_TAGS = ["A", "BUTTON", "INPUT"]; function ignoreElement(node3, ignoreSelector) { if (!SLOW_CLICK_TAGS.includes(node3.tagName)) { return true; } if (node3.tagName === "INPUT" && !["submit", "button"].includes(node3.getAttribute("type") || "")) { return true; } if (node3.tagName === "A" && (node3.hasAttribute("download") || node3.hasAttribute("target") && node3.getAttribute("target") !== "_self")) { return true; } if (ignoreSelector && node3.matches(ignoreSelector)) { return true; } return false; } __name(ignoreElement, "ignoreElement"); function isClickBreadcrumb(breadcrumb) { return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === "number" && breadcrumb.timestamp); } __name(isClickBreadcrumb, "isClickBreadcrumb"); function nowInSeconds() { return Date.now() / 1e3; } __name(nowInSeconds, "nowInSeconds"); function updateClickDetectorForRecordingEvent(clickDetector, event) { try { if (!isIncrementalEvent(event)) { return; } const { source } = event.data; if (IncrementalMutationSources.has(source)) { clickDetector.registerMutation(event.timestamp); } if (source === IncrementalSource.Scroll) { clickDetector.registerScroll(event.timestamp); } if (isIncrementalMouseInteraction(event)) { const { type, id: id3 } = event.data; const node3 = record.mirror.getNode(id3); if (node3 instanceof HTMLElement && type === MouseInteractions.Click) { clickDetector.registerClick(node3); } } } catch (e2) { } } __name(updateClickDetectorForRecordingEvent, "updateClickDetectorForRecordingEvent"); function isIncrementalEvent(event) { return event.type === ReplayEventTypeIncrementalSnapshot; } __name(isIncrementalEvent, "isIncrementalEvent"); function isIncrementalMouseInteraction(event) { return event.data.source === IncrementalSource.MouseInteraction; } __name(isIncrementalMouseInteraction, "isIncrementalMouseInteraction"); function createBreadcrumb(breadcrumb) { return { timestamp: Date.now() / 1e3, type: "default", ...breadcrumb }; } __name(createBreadcrumb, "createBreadcrumb"); var NodeType$4; (function(NodeType3) { NodeType3[NodeType3["Document"] = 0] = "Document"; NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType"; NodeType3[NodeType3["Element"] = 2] = "Element"; NodeType3[NodeType3["Text"] = 3] = "Text"; NodeType3[NodeType3["CDATA"] = 4] = "CDATA"; NodeType3[NodeType3["Comment"] = 5] = "Comment"; })(NodeType$4 || (NodeType$4 = {})); const ATTRIBUTES_TO_RECORD = /* @__PURE__ */ new Set([ "id", "class", "aria-label", "role", "name", "alt", "title", "data-test-id", "data-testid", "disabled", "aria-disabled", "data-sentry-component" ]); function getAttributesToRecord(attributes) { const obj = {}; if (!attributes["data-sentry-component"] && attributes["data-sentry-element"]) { attributes["data-sentry-component"] = attributes["data-sentry-element"]; } for (const key in attributes) { if (ATTRIBUTES_TO_RECORD.has(key)) { let normalizedKey = key; if (key === "data-testid" || key === "data-test-id") { normalizedKey = "testId"; } obj[normalizedKey] = attributes[key]; } } return obj; } __name(getAttributesToRecord, "getAttributesToRecord"); const handleDomListener = /* @__PURE__ */ __name((replay) => { return (handlerData) => { if (!replay.isEnabled()) { return; } const result = handleDom(handlerData); if (!result) { return; } const isClick = handlerData.name === "click"; const event = isClick ? handlerData.event : void 0; if (isClick && replay.clickDetector && event && event.target && !event.altKey && !event.metaKey && !event.ctrlKey && !event.shiftKey) { handleClick$1( replay.clickDetector, result, getClickTargetNode(handlerData.event) ); } addBreadcrumbEvent(replay, result); }; }, "handleDomListener"); function getBaseDomBreadcrumb(target, message3) { const nodeId = record.mirror.getId(target); const node3 = nodeId && record.mirror.getNode(nodeId); const meta = node3 && record.mirror.getMeta(node3); const element = meta && isElement$2(meta) ? meta : null; return { message: message3, data: element ? { nodeId, node: { id: nodeId, tagName: element.tagName, textContent: Array.from(element.childNodes).map((node4) => node4.type === NodeType$4.Text && node4.textContent).filter(Boolean).map((text2) => text2.trim()).join(""), attributes: getAttributesToRecord(element.attributes) } } : {} }; } __name(getBaseDomBreadcrumb, "getBaseDomBreadcrumb"); function handleDom(handlerData) { const { target, message: message3 } = getDomTarget(handlerData); return createBreadcrumb({ category: `ui.${handlerData.name}`, ...getBaseDomBreadcrumb(target, message3) }); } __name(handleDom, "handleDom"); function getDomTarget(handlerData) { const isClick = handlerData.name === "click"; let message3; let target = null; try { target = isClick ? getClickTargetNode(handlerData.event) : getTargetNode(handlerData.event); message3 = htmlTreeAsString(target, { maxStringLength: 200 }) || ""; } catch (e2) { message3 = ""; } return { target, message: message3 }; } __name(getDomTarget, "getDomTarget"); function isElement$2(node3) { return node3.type === NodeType$4.Element; } __name(isElement$2, "isElement$2"); function handleKeyboardEvent(replay, event) { if (!replay.isEnabled()) { return; } replay.updateUserActivity(); const breadcrumb = getKeyboardBreadcrumb(event); if (!breadcrumb) { return; } addBreadcrumbEvent(replay, breadcrumb); } __name(handleKeyboardEvent, "handleKeyboardEvent"); function getKeyboardBreadcrumb(event) { const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event; if (!target || isInputElement(target) || !key) { return null; } const hasModifierKey = metaKey || ctrlKey || altKey; const isCharacterKey = key.length === 1; if (!hasModifierKey && isCharacterKey) { return null; } const message3 = htmlTreeAsString(target, { maxStringLength: 200 }) || ""; const baseBreadcrumb = getBaseDomBreadcrumb(target, message3); return createBreadcrumb({ category: "ui.keyDown", message: message3, data: { ...baseBreadcrumb.data, metaKey, shiftKey, ctrlKey, altKey, key } }); } __name(getKeyboardBreadcrumb, "getKeyboardBreadcrumb"); function isInputElement(target) { return target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable; } __name(isInputElement, "isInputElement"); const ENTRY_TYPES = { // @ts-expect-error TODO: entry type does not fit the create* functions entry type resource: createResourceEntry, paint: createPaintEntry, // @ts-expect-error TODO: entry type does not fit the create* functions entry type navigation: createNavigationEntry }; function webVitalHandler(getter, replay) { return ({ metric }) => void replay.replayPerformanceEntries.push(getter(metric)); } __name(webVitalHandler, "webVitalHandler"); function createPerformanceEntries(entries) { return entries.map(createPerformanceEntry).filter(Boolean); } __name(createPerformanceEntries, "createPerformanceEntries"); function createPerformanceEntry(entry) { const entryType = ENTRY_TYPES[entry.entryType]; if (!entryType) { return null; } return entryType(entry); } __name(createPerformanceEntry, "createPerformanceEntry"); function getAbsoluteTime$1(time) { return ((browserPerformanceTimeOrigin || WINDOW$1.performance.timeOrigin) + time) / 1e3; } __name(getAbsoluteTime$1, "getAbsoluteTime$1"); function createPaintEntry(entry) { const { duration, entryType, name: name2, startTime } = entry; const start2 = getAbsoluteTime$1(startTime); return { type: entryType, name: name2, start: start2, end: start2 + duration, data: void 0 }; } __name(createPaintEntry, "createPaintEntry"); function createNavigationEntry(entry) { const { entryType, name: name2, decodedBodySize, duration, domComplete, encodedBodySize, domContentLoadedEventStart, domContentLoadedEventEnd, domInteractive, loadEventStart, loadEventEnd, redirectCount, startTime, transferSize, type } = entry; if (duration === 0) { return null; } return { type: `${entryType}.${type}`, start: getAbsoluteTime$1(startTime), end: getAbsoluteTime$1(domComplete), name: name2, data: { size: transferSize, decodedBodySize, encodedBodySize, duration, domInteractive, domContentLoadedEventStart, domContentLoadedEventEnd, loadEventStart, loadEventEnd, domComplete, redirectCount } }; } __name(createNavigationEntry, "createNavigationEntry"); function createResourceEntry(entry) { const { entryType, initiatorType, name: name2, responseEnd, startTime, decodedBodySize, encodedBodySize, responseStatus, transferSize } = entry; if (["fetch", "xmlhttprequest"].includes(initiatorType)) { return null; } return { type: `${entryType}.${initiatorType}`, start: getAbsoluteTime$1(startTime), end: getAbsoluteTime$1(responseEnd), name: name2, data: { size: transferSize, statusCode: responseStatus, decodedBodySize, encodedBodySize } }; } __name(createResourceEntry, "createResourceEntry"); function getLargestContentfulPaint(metric) { const lastEntry = metric.entries[metric.entries.length - 1]; const node3 = lastEntry && lastEntry.element ? [lastEntry.element] : void 0; return getWebVital(metric, "largest-contentful-paint", node3); } __name(getLargestContentfulPaint, "getLargestContentfulPaint"); function isLayoutShift(entry) { return entry.sources !== void 0; } __name(isLayoutShift, "isLayoutShift"); function getCumulativeLayoutShift(metric) { const layoutShifts = []; const nodes = []; for (const entry of metric.entries) { if (isLayoutShift(entry)) { const nodeIds = []; for (const source of entry.sources) { if (source.node) { nodes.push(source.node); const nodeId = record.mirror.getId(source.node); if (nodeId) { nodeIds.push(nodeId); } } } layoutShifts.push({ value: entry.value, nodeIds: nodeIds.length ? nodeIds : void 0 }); } } return getWebVital(metric, "cumulative-layout-shift", nodes, layoutShifts); } __name(getCumulativeLayoutShift, "getCumulativeLayoutShift"); function getFirstInputDelay(metric) { const lastEntry = metric.entries[metric.entries.length - 1]; const node3 = lastEntry && lastEntry.target ? [lastEntry.target] : void 0; return getWebVital(metric, "first-input-delay", node3); } __name(getFirstInputDelay, "getFirstInputDelay"); function getInteractionToNextPaint(metric) { const lastEntry = metric.entries[metric.entries.length - 1]; const node3 = lastEntry && lastEntry.target ? [lastEntry.target] : void 0; return getWebVital(metric, "interaction-to-next-paint", node3); } __name(getInteractionToNextPaint, "getInteractionToNextPaint"); function getWebVital(metric, name2, nodes, attributions) { const value4 = metric.value; const rating = metric.rating; const end = getAbsoluteTime$1(value4); return { type: "web-vital", name: name2, start: end, end, data: { value: value4, size: value4, rating, nodeIds: nodes ? nodes.map((node3) => record.mirror.getId(node3)) : void 0, attributions } }; } __name(getWebVital, "getWebVital"); function setupPerformanceObserver(replay) { function addPerformanceEntry(entry) { if (!replay.performanceEntries.includes(entry)) { replay.performanceEntries.push(entry); } } __name(addPerformanceEntry, "addPerformanceEntry"); function onEntries({ entries }) { entries.forEach(addPerformanceEntry); } __name(onEntries, "onEntries"); const clearCallbacks = []; ["navigation", "paint", "resource"].forEach((type) => { clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries)); }); clearCallbacks.push( addLcpInstrumentationHandler(webVitalHandler(getLargestContentfulPaint, replay)), addClsInstrumentationHandler(webVitalHandler(getCumulativeLayoutShift, replay)), addFidInstrumentationHandler(webVitalHandler(getFirstInputDelay, replay)), addInpInstrumentationHandler(webVitalHandler(getInteractionToNextPaint, replay)) ); return () => { clearCallbacks.forEach((clearCallback) => clearCallback()); }; } __name(setupPerformanceObserver, "setupPerformanceObserver"); const DEBUG_BUILD$2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; const r$3 = `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a>h]=l}else for(o=new n(i),a=0;a>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],a=0;ad&&(d=o[a].s);var g=new n(d+1),w=A(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<e))break;p+=m-(1<>=y;p>0;){var M=o[a].s;g[M]=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}},L=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},O=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=C[s-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!w)){p=U(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},j=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},q=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&j(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}},B=function(t){return 10+(t.filename?t.filename.length+1:0)},G=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(O(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();var H=function(){function t(t,n){this.c=L(),this.v=1,G.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),G.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=O(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=L();i.p(n.dictionary),j(t,2,i.d())}}(r,this.o),this.v=0),n&&j(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),J="undefined"!=typeof TextEncoder&&new TextEncoder,K="undefined"!=typeof TextDecoder&&new TextDecoder;try{K.decode(F,{stream:!0})}catch(t){}var N=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(P(t),this.d=n||!1)},t}();function P(n,r){if(J)return J.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),a=0,s=function(t){i[a++]=t},o=0;oi.length){var f=new t(a+8+(e-o<<1));f.set(i),i=f}var h=n.charCodeAt(o);h<128||r?s(h):h<2048?(s(192|h>>6),s(128|63&h)):h>55295&&h<57344?(s(240|(h=65536+(1047552&h)|1023&n.charCodeAt(++o))>>18),s(128|h>>12&63),s(128|h>>6&63),s(128|63&h)):(s(224|h>>12),s(128|h>>6&63),s(128|63&h))}return b(i,0,a)}function Q(t){return function(t,n){n||(n={});var r=S(),e=t.length;r.p(t);var i=O(t,n,B(n),8),a=i.length;return q(i,n),j(i,a-8,r.d()),j(i,a-4,e),i}(P(t))}const R=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n{this._deflatedData.push(t)},this.stream=new N(((t,n)=>{this.deflate.push(t,n)})),this.stream.push("[")}},V={clear:()=>{R.clear()},addEvent:t=>R.addEvent(t),finish:()=>R.finish(),compress:t=>Q(t)};addEventListener("message",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in V&&"function"==typeof V[n])try{const t=V[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});`; function e$1() { const e2 = new Blob([r$3]); return URL.createObjectURL(e2); } __name(e$1, "e$1"); const CONSOLE_LEVELS = ["info", "warn", "error", "log"]; const PREFIX$1 = "[Replay] "; function _addBreadcrumb(message3, level = "info") { addBreadcrumb( { category: "console", data: { logger: "replay" }, level, message: `${PREFIX$1}${message3}` }, { level } ); } __name(_addBreadcrumb, "_addBreadcrumb"); function makeReplayLogger() { let _capture = false; let _trace = false; const _logger = { exception: /* @__PURE__ */ __name(() => void 0, "exception"), infoTick: /* @__PURE__ */ __name(() => void 0, "infoTick"), setConfig: /* @__PURE__ */ __name((opts) => { _capture = opts.captureExceptions; _trace = opts.traceInternals; }, "setConfig") }; if (DEBUG_BUILD$2) { CONSOLE_LEVELS.forEach((name2) => { _logger[name2] = (...args) => { logger$2[name2](PREFIX$1, ...args); if (_trace) { _addBreadcrumb(args.join(""), severityLevelFromString(name2)); } }; }); _logger.exception = (error2, ...message3) => { if (message3.length && _logger.error) { _logger.error(...message3); } logger$2.error(PREFIX$1, error2); if (_capture) { captureException(error2); } else if (_trace) { _addBreadcrumb(error2, "error"); } }; _logger.infoTick = (...args) => { logger$2.info(PREFIX$1, ...args); if (_trace) { setTimeout(() => _addBreadcrumb(args[0]), 0); } }; } else { CONSOLE_LEVELS.forEach((name2) => { _logger[name2] = () => void 0; }); } return _logger; } __name(makeReplayLogger, "makeReplayLogger"); const logger$1 = makeReplayLogger(); class EventBufferSizeExceededError extends Error { static { __name(this, "EventBufferSizeExceededError"); } constructor() { super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`); } } class EventBufferArray { static { __name(this, "EventBufferArray"); } /** All the events that are buffered to be sent. */ /** @inheritdoc */ /** @inheritdoc */ constructor() { this.events = []; this._totalSize = 0; this.hasCheckout = false; this.waitForCheckout = false; } /** @inheritdoc */ get hasEvents() { return this.events.length > 0; } /** @inheritdoc */ get type() { return "sync"; } /** @inheritdoc */ destroy() { this.events = []; } /** @inheritdoc */ async addEvent(event) { const eventSize = JSON.stringify(event).length; this._totalSize += eventSize; if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) { throw new EventBufferSizeExceededError(); } this.events.push(event); } /** @inheritdoc */ finish() { return new Promise((resolve2) => { const eventsRet = this.events; this.clear(); resolve2(JSON.stringify(eventsRet)); }); } /** @inheritdoc */ clear() { this.events = []; this._totalSize = 0; this.hasCheckout = false; } /** @inheritdoc */ getEarliestTimestamp() { const timestamp2 = this.events.map((event) => event.timestamp).sort()[0]; if (!timestamp2) { return null; } return timestampToMs(timestamp2); } } class WorkerHandler { static { __name(this, "WorkerHandler"); } constructor(worker) { this._worker = worker; this._id = 0; } /** * Ensure the worker is ready (or not). * This will either resolve when the worker is ready, or reject if an error occurred. */ ensureReady() { if (this._ensureReadyPromise) { return this._ensureReadyPromise; } this._ensureReadyPromise = new Promise((resolve2, reject3) => { this._worker.addEventListener( "message", ({ data: data25 }) => { if (data25.success) { resolve2(); } else { reject3(); } }, { once: true } ); this._worker.addEventListener( "error", (error2) => { reject3(error2); }, { once: true } ); }); return this._ensureReadyPromise; } /** * Destroy the worker. */ destroy() { DEBUG_BUILD$2 && logger$1.info("Destroying compression worker"); this._worker.terminate(); } /** * Post message to worker and wait for response before resolving promise. */ postMessage(method, arg) { const id3 = this._getAndIncrementId(); return new Promise((resolve2, reject3) => { const listener = /* @__PURE__ */ __name(({ data: data25 }) => { const response = data25; if (response.method !== method) { return; } if (response.id !== id3) { return; } this._worker.removeEventListener("message", listener); if (!response.success) { DEBUG_BUILD$2 && logger$1.error("Error in compression worker: ", response.response); reject3(new Error("Error in compression worker")); return; } resolve2(response.response); }, "listener"); this._worker.addEventListener("message", listener); this._worker.postMessage({ id: id3, method, arg }); }); } /** Get the current ID and increment it for the next call. */ _getAndIncrementId() { return this._id++; } } class EventBufferCompressionWorker { static { __name(this, "EventBufferCompressionWorker"); } /** @inheritdoc */ /** @inheritdoc */ constructor(worker) { this._worker = new WorkerHandler(worker); this._earliestTimestamp = null; this._totalSize = 0; this.hasCheckout = false; this.waitForCheckout = false; } /** @inheritdoc */ get hasEvents() { return !!this._earliestTimestamp; } /** @inheritdoc */ get type() { return "worker"; } /** * Ensure the worker is ready (or not). * This will either resolve when the worker is ready, or reject if an error occurred. */ ensureReady() { return this._worker.ensureReady(); } /** * Destroy the event buffer. */ destroy() { this._worker.destroy(); } /** * Add an event to the event buffer. * * Returns true if event was successfully received and processed by worker. */ addEvent(event) { const timestamp2 = timestampToMs(event.timestamp); if (!this._earliestTimestamp || timestamp2 < this._earliestTimestamp) { this._earliestTimestamp = timestamp2; } const data25 = JSON.stringify(event); this._totalSize += data25.length; if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) { return Promise.reject(new EventBufferSizeExceededError()); } return this._sendEventToWorker(data25); } /** * Finish the event buffer and return the compressed data. */ finish() { return this._finishRequest(); } /** @inheritdoc */ clear() { this._earliestTimestamp = null; this._totalSize = 0; this.hasCheckout = false; this._worker.postMessage("clear").then(null, (e2) => { DEBUG_BUILD$2 && logger$1.exception(e2, 'Sending "clear" message to worker failed', e2); }); } /** @inheritdoc */ getEarliestTimestamp() { return this._earliestTimestamp; } /** * Send the event to the worker. */ _sendEventToWorker(data25) { return this._worker.postMessage("addEvent", data25); } /** * Finish the request and return the compressed data from the worker. */ async _finishRequest() { const response = await this._worker.postMessage("finish"); this._earliestTimestamp = null; this._totalSize = 0; return response; } } class EventBufferProxy { static { __name(this, "EventBufferProxy"); } constructor(worker) { this._fallback = new EventBufferArray(); this._compression = new EventBufferCompressionWorker(worker); this._used = this._fallback; this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded(); } /** @inheritdoc */ get waitForCheckout() { return this._used.waitForCheckout; } /** @inheritdoc */ get type() { return this._used.type; } /** @inheritDoc */ get hasEvents() { return this._used.hasEvents; } /** @inheritdoc */ get hasCheckout() { return this._used.hasCheckout; } /** @inheritdoc */ set hasCheckout(value4) { this._used.hasCheckout = value4; } /** @inheritdoc */ // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures set waitForCheckout(value4) { this._used.waitForCheckout = value4; } /** @inheritDoc */ destroy() { this._fallback.destroy(); this._compression.destroy(); } /** @inheritdoc */ clear() { return this._used.clear(); } /** @inheritdoc */ getEarliestTimestamp() { return this._used.getEarliestTimestamp(); } /** * Add an event to the event buffer. * * Returns true if event was successfully added. */ addEvent(event) { return this._used.addEvent(event); } /** @inheritDoc */ async finish() { await this.ensureWorkerIsLoaded(); return this._used.finish(); } /** Ensure the worker has loaded. */ ensureWorkerIsLoaded() { return this._ensureWorkerIsLoadedPromise; } /** Actually check if the worker has been loaded. */ async _ensureWorkerIsLoaded() { try { await this._compression.ensureReady(); } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to load the compression worker, falling back to simple buffer"); return; } await this._switchToCompressionWorker(); } /** Switch the used buffer to the compression worker. */ async _switchToCompressionWorker() { const { events: events2, hasCheckout, waitForCheckout } = this._fallback; const addEventPromises = []; for (const event of events2) { addEventPromises.push(this._compression.addEvent(event)); } this._compression.hasCheckout = hasCheckout; this._compression.waitForCheckout = waitForCheckout; this._used = this._compression; try { await Promise.all(addEventPromises); this._fallback.clear(); } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to add events when switching buffers."); } } } function createEventBuffer({ useCompression, workerUrl: customWorkerUrl }) { if (useCompression && // eslint-disable-next-line no-restricted-globals window.Worker) { const worker = _loadWorker(customWorkerUrl); if (worker) { return worker; } } DEBUG_BUILD$2 && logger$1.info("Using simple buffer"); return new EventBufferArray(); } __name(createEventBuffer, "createEventBuffer"); function _loadWorker(customWorkerUrl) { try { const workerUrl = customWorkerUrl || _getWorkerUrl(); if (!workerUrl) { return; } DEBUG_BUILD$2 && logger$1.info(`Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ""}`); const worker = new Worker(workerUrl); return new EventBufferProxy(worker); } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to create compression worker"); } } __name(_loadWorker, "_loadWorker"); function _getWorkerUrl() { if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === "undefined" || !__SENTRY_EXCLUDE_REPLAY_WORKER__) { return e$1(); } return ""; } __name(_getWorkerUrl, "_getWorkerUrl"); function hasSessionStorage() { try { return "sessionStorage" in WINDOW$1 && !!WINDOW$1.sessionStorage; } catch (e2) { return false; } } __name(hasSessionStorage, "hasSessionStorage"); function clearSession(replay) { deleteSession(); replay.session = void 0; } __name(clearSession, "clearSession"); function deleteSession() { if (!hasSessionStorage()) { return; } try { WINDOW$1.sessionStorage.removeItem(REPLAY_SESSION_KEY); } catch (e2) { } } __name(deleteSession, "deleteSession"); function isSampled(sampleRate) { if (sampleRate === void 0) { return false; } return Math.random() < sampleRate; } __name(isSampled, "isSampled"); function makeSession(session) { const now2 = Date.now(); const id3 = session.id || uuid4(); const started = session.started || now2; const lastActivity = session.lastActivity || now2; const segmentId = session.segmentId || 0; const sampled = session.sampled; const previousSessionId = session.previousSessionId; return { id: id3, started, lastActivity, segmentId, sampled, previousSessionId }; } __name(makeSession, "makeSession"); function saveSession(session) { if (!hasSessionStorage()) { return; } try { WINDOW$1.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session)); } catch (e2) { } } __name(saveSession, "saveSession"); function getSessionSampleType(sessionSampleRate, allowBuffering) { return isSampled(sessionSampleRate) ? "session" : allowBuffering ? "buffer" : false; } __name(getSessionSampleType, "getSessionSampleType"); function createSession({ sessionSampleRate, allowBuffering, stickySession = false }, { previousSessionId } = {}) { const sampled = getSessionSampleType(sessionSampleRate, allowBuffering); const session = makeSession({ sampled, previousSessionId }); if (stickySession) { saveSession(session); } return session; } __name(createSession, "createSession"); function fetchSession() { if (!hasSessionStorage()) { return null; } try { const sessionStringFromStorage = WINDOW$1.sessionStorage.getItem(REPLAY_SESSION_KEY); if (!sessionStringFromStorage) { return null; } const sessionObj = JSON.parse(sessionStringFromStorage); DEBUG_BUILD$2 && logger$1.infoTick("Loading existing session"); return makeSession(sessionObj); } catch (e2) { return null; } } __name(fetchSession, "fetchSession"); function isExpired(initialTime, expiry, targetTime = +/* @__PURE__ */ new Date()) { if (initialTime === null || expiry === void 0 || expiry < 0) { return true; } if (expiry === 0) { return false; } return initialTime + expiry <= targetTime; } __name(isExpired, "isExpired"); function isSessionExpired(session, { maxReplayDuration, sessionIdleExpire, targetTime = Date.now() }) { return ( // First, check that maximum session length has not been exceeded isExpired(session.started, maxReplayDuration, targetTime) || // check that the idle timeout has not been exceeded (i.e. user has // performed an action within the last `sessionIdleExpire` ms) isExpired(session.lastActivity, sessionIdleExpire, targetTime) ); } __name(isSessionExpired, "isSessionExpired"); function shouldRefreshSession(session, { sessionIdleExpire, maxReplayDuration }) { if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) { return false; } if (session.sampled === "buffer" && session.segmentId === 0) { return false; } return true; } __name(shouldRefreshSession, "shouldRefreshSession"); function loadOrCreateSession({ sessionIdleExpire, maxReplayDuration, previousSessionId }, sessionOptions) { const existingSession = sessionOptions.stickySession && fetchSession(); if (!existingSession) { DEBUG_BUILD$2 && logger$1.infoTick("Creating new session"); return createSession(sessionOptions, { previousSessionId }); } if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) { return existingSession; } DEBUG_BUILD$2 && logger$1.infoTick("Session in sessionStorage is expired, creating new one..."); return createSession(sessionOptions, { previousSessionId: existingSession.id }); } __name(loadOrCreateSession, "loadOrCreateSession"); function isCustomEvent(event) { return event.type === EventType.Custom; } __name(isCustomEvent, "isCustomEvent"); function addEventSync(replay, event, isCheckout) { if (!shouldAddEvent(replay, event)) { return false; } _addEvent(replay, event, isCheckout); return true; } __name(addEventSync, "addEventSync"); function addEvent(replay, event, isCheckout) { if (!shouldAddEvent(replay, event)) { return Promise.resolve(null); } return _addEvent(replay, event, isCheckout); } __name(addEvent, "addEvent"); async function _addEvent(replay, event, isCheckout) { const { eventBuffer } = replay; if (!eventBuffer || eventBuffer.waitForCheckout && !isCheckout) { return null; } const isBufferMode = replay.recordingMode === "buffer"; try { if (isCheckout && isBufferMode) { eventBuffer.clear(); } if (isCheckout) { eventBuffer.hasCheckout = true; eventBuffer.waitForCheckout = false; } const replayOptions = replay.getOptions(); const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent); if (!eventAfterPossibleCallback) { return; } return await eventBuffer.addEvent(eventAfterPossibleCallback); } catch (error2) { const isExceeded = error2 && error2 instanceof EventBufferSizeExceededError; const reason = isExceeded ? "addEventSizeExceeded" : "addEvent"; if (isExceeded && isBufferMode) { eventBuffer.clear(); eventBuffer.waitForCheckout = true; return null; } replay.handleException(error2); await replay.stop({ reason }); const client = getClient(); if (client) { client.recordDroppedEvent("internal_sdk_error", "replay"); } } } __name(_addEvent, "_addEvent"); function shouldAddEvent(replay, event) { if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) { return false; } const timestampInMs = timestampToMs(event.timestamp); if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) { return false; } if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) { DEBUG_BUILD$2 && logger$1.infoTick(`Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`); return false; } return true; } __name(shouldAddEvent, "shouldAddEvent"); function maybeApplyCallback(event, callback) { try { if (typeof callback === "function" && isCustomEvent(event)) { return callback(event); } } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "An error occurred in the `beforeAddRecordingEvent` callback, skipping the event..."); return null; } return event; } __name(maybeApplyCallback, "maybeApplyCallback"); function isErrorEvent(event) { return !event.type; } __name(isErrorEvent, "isErrorEvent"); function isTransactionEvent(event) { return event.type === "transaction"; } __name(isTransactionEvent, "isTransactionEvent"); function isReplayEvent(event) { return event.type === "replay_event"; } __name(isReplayEvent, "isReplayEvent"); function isFeedbackEvent(event) { return event.type === "feedback"; } __name(isFeedbackEvent, "isFeedbackEvent"); function handleAfterSendEvent(replay) { return (event, sendResponse) => { if (!replay.isEnabled() || !isErrorEvent(event) && !isTransactionEvent(event)) { return; } const statusCode = sendResponse && sendResponse.statusCode; if (!statusCode || statusCode < 200 || statusCode >= 300) { return; } if (isTransactionEvent(event)) { handleTransactionEvent(replay, event); return; } handleErrorEvent(replay, event); }; } __name(handleAfterSendEvent, "handleAfterSendEvent"); function handleTransactionEvent(replay, event) { const replayContext = replay.getContext(); if (event.contexts && event.contexts.trace && event.contexts.trace.trace_id && replayContext.traceIds.size < 100) { replayContext.traceIds.add(event.contexts.trace.trace_id); } } __name(handleTransactionEvent, "handleTransactionEvent"); function handleErrorEvent(replay, event) { const replayContext = replay.getContext(); if (event.event_id && replayContext.errorIds.size < 100) { replayContext.errorIds.add(event.event_id); } if (replay.recordingMode !== "buffer" || !event.tags || !event.tags.replayId) { return; } const { beforeErrorSampling } = replay.getOptions(); if (typeof beforeErrorSampling === "function" && !beforeErrorSampling(event)) { return; } setTimeout$3(async () => { try { await replay.sendBufferedReplayOrFlush(); } catch (err) { replay.handleException(err); } }); } __name(handleErrorEvent, "handleErrorEvent"); function handleBeforeSendEvent(replay) { return (event) => { if (!replay.isEnabled() || !isErrorEvent(event)) { return; } handleHydrationError(replay, event); }; } __name(handleBeforeSendEvent, "handleBeforeSendEvent"); function handleHydrationError(replay, event) { const exceptionValue = event.exception && event.exception.values && event.exception.values[0] && event.exception.values[0].value; if (typeof exceptionValue !== "string") { return; } if ( // Only matches errors in production builds of react-dom // Example https://reactjs.org/docs/error-decoder.html?invariant=423 // With newer React versions, the messages changed to a different website https://react.dev/errors/418 exceptionValue.match( /(reactjs\.org\/docs\/error-decoder\.html\?invariant=|react\.dev\/errors\/)(418|419|422|423|425)/ ) || // Development builds of react-dom // Error 1: Hydration failed because the initial UI does not match what was rendered on the server. // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match. exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i) ) { const breadcrumb = createBreadcrumb({ category: "replay.hydrate-error", data: { url: getLocationHref() } }); addBreadcrumbEvent(replay, breadcrumb); } } __name(handleHydrationError, "handleHydrationError"); function handleBreadcrumbs(replay) { const client = getClient(); if (!client) { return; } client.on("beforeAddBreadcrumb", (breadcrumb) => beforeAddBreadcrumb(replay, breadcrumb)); } __name(handleBreadcrumbs, "handleBreadcrumbs"); function beforeAddBreadcrumb(replay, breadcrumb) { if (!replay.isEnabled() || !isBreadcrumbWithCategory(breadcrumb)) { return; } const result = normalizeBreadcrumb(breadcrumb); if (result) { addBreadcrumbEvent(replay, result); } } __name(beforeAddBreadcrumb, "beforeAddBreadcrumb"); function normalizeBreadcrumb(breadcrumb) { if (!isBreadcrumbWithCategory(breadcrumb) || [ // fetch & xhr are handled separately,in handleNetworkBreadcrumbs "fetch", "xhr", // These two are breadcrumbs for emitted sentry events, we don't care about them "sentry.event", "sentry.transaction" ].includes(breadcrumb.category) || // We capture UI breadcrumbs separately breadcrumb.category.startsWith("ui.")) { return null; } if (breadcrumb.category === "console") { return normalizeConsoleBreadcrumb(breadcrumb); } return createBreadcrumb(breadcrumb); } __name(normalizeBreadcrumb, "normalizeBreadcrumb"); function normalizeConsoleBreadcrumb(breadcrumb) { const args = breadcrumb.data && breadcrumb.data.arguments; if (!Array.isArray(args) || args.length === 0) { return createBreadcrumb(breadcrumb); } let isTruncated = false; const normalizedArgs = args.map((arg) => { if (!arg) { return arg; } if (typeof arg === "string") { if (arg.length > CONSOLE_ARG_MAX_SIZE) { isTruncated = true; return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`; } return arg; } if (typeof arg === "object") { try { const normalizedArg = normalize$2(arg, 7); const stringified = JSON.stringify(normalizedArg); if (stringified.length > CONSOLE_ARG_MAX_SIZE) { isTruncated = true; return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`; } return normalizedArg; } catch (e2) { } } return arg; }); return createBreadcrumb({ ...breadcrumb, data: { ...breadcrumb.data, arguments: normalizedArgs, ...isTruncated ? { _meta: { warnings: ["CONSOLE_ARG_TRUNCATED"] } } : {} } }); } __name(normalizeConsoleBreadcrumb, "normalizeConsoleBreadcrumb"); function isBreadcrumbWithCategory(breadcrumb) { return !!breadcrumb.category; } __name(isBreadcrumbWithCategory, "isBreadcrumbWithCategory"); function isRrwebError(event, hint) { if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) { return false; } if (hint.originalException && hint.originalException.__rrweb__) { return true; } return false; } __name(isRrwebError, "isRrwebError"); function resetReplayIdOnDynamicSamplingContext() { const dsc = getCurrentScope$1().getPropagationContext().dsc; if (dsc) { delete dsc.replay_id; } const activeSpan = getActiveSpan(); if (activeSpan) { const dsc2 = getDynamicSamplingContextFromSpan(activeSpan); delete dsc2.replay_id; } } __name(resetReplayIdOnDynamicSamplingContext, "resetReplayIdOnDynamicSamplingContext"); function addFeedbackBreadcrumb(replay, event) { replay.triggerUserActivity(); replay.addUpdate(() => { if (!event.timestamp) { return true; } replay.throttledAddEvent({ type: EventType.Custom, timestamp: event.timestamp * 1e3, data: { tag: "breadcrumb", payload: { timestamp: event.timestamp, type: "default", category: "sentry.feedback", data: { feedbackId: event.event_id } } } }); return false; }); } __name(addFeedbackBreadcrumb, "addFeedbackBreadcrumb"); function shouldSampleForBufferEvent(replay, event) { if (replay.recordingMode !== "buffer") { return false; } if (event.message === UNABLE_TO_SEND_REPLAY) { return false; } if (!event.exception || event.type) { return false; } return isSampled(replay.getOptions().errorSampleRate); } __name(shouldSampleForBufferEvent, "shouldSampleForBufferEvent"); function handleGlobalEventListener(replay) { return Object.assign( (event, hint) => { if (!replay.isEnabled() || replay.isPaused()) { return event; } if (isReplayEvent(event)) { delete event.breadcrumbs; return event; } if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) { return event; } const isSessionActive = replay.checkAndHandleExpiredSession(); if (!isSessionActive) { resetReplayIdOnDynamicSamplingContext(); return event; } if (isFeedbackEvent(event)) { replay.flush(); event.contexts.feedback.replay_id = replay.getSessionId(); addFeedbackBreadcrumb(replay, event); return event; } if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) { DEBUG_BUILD$2 && logger$1.log("Ignoring error from rrweb internals", event); return null; } const isErrorEventSampled = shouldSampleForBufferEvent(replay, event); const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === "session"; if (shouldTagReplayId) { event.tags = { ...event.tags, replayId: replay.getSessionId() }; } return event; }, { id: "Replay" } ); } __name(handleGlobalEventListener, "handleGlobalEventListener"); function createPerformanceSpans(replay, entries) { return entries.map(({ type, start: start2, end, name: name2, data: data25 }) => { const response = replay.throttledAddEvent({ type: EventType.Custom, timestamp: start2, data: { tag: "performanceSpan", payload: { op: type, description: name2, startTimestamp: start2, endTimestamp: end, data: data25 } } }); return typeof response === "string" ? Promise.resolve(null) : response; }); } __name(createPerformanceSpans, "createPerformanceSpans"); function handleHistory(handlerData) { const { from: from2, to } = handlerData; const now2 = Date.now() / 1e3; return { type: "navigation.push", start: now2, end: now2, name: to, data: { previous: from2 } }; } __name(handleHistory, "handleHistory"); function handleHistorySpanListener(replay) { return (handlerData) => { if (!replay.isEnabled()) { return; } const result = handleHistory(handlerData); if (result === null) { return; } replay.getContext().urls.push(result.name); replay.triggerUserActivity(); replay.addUpdate(() => { createPerformanceSpans(replay, [result]); return false; }); }; } __name(handleHistorySpanListener, "handleHistorySpanListener"); function shouldFilterRequest(replay, url) { if (DEBUG_BUILD$2 && replay.getOptions()._experiments.traceInternals) { return false; } return isSentryRequestUrl(url, getClient()); } __name(shouldFilterRequest, "shouldFilterRequest"); function addNetworkBreadcrumb(replay, result) { if (!replay.isEnabled()) { return; } if (result === null) { return; } if (shouldFilterRequest(replay, result.name)) { return; } replay.addUpdate(() => { createPerformanceSpans(replay, [result]); return true; }); } __name(addNetworkBreadcrumb, "addNetworkBreadcrumb"); function getBodySize(body) { if (!body) { return void 0; } const textEncoder = new TextEncoder(); try { if (typeof body === "string") { return textEncoder.encode(body).length; } if (body instanceof URLSearchParams) { return textEncoder.encode(body.toString()).length; } if (body instanceof FormData) { const formDataStr = _serializeFormData(body); return textEncoder.encode(formDataStr).length; } if (body instanceof Blob) { return body.size; } if (body instanceof ArrayBuffer) { return body.byteLength; } } catch (e2) { } return void 0; } __name(getBodySize, "getBodySize"); function parseContentLengthHeader(header3) { if (!header3) { return void 0; } const size2 = parseInt(header3, 10); return isNaN(size2) ? void 0 : size2; } __name(parseContentLengthHeader, "parseContentLengthHeader"); function getBodyString(body) { try { if (typeof body === "string") { return [body]; } if (body instanceof URLSearchParams) { return [body.toString()]; } if (body instanceof FormData) { return [_serializeFormData(body)]; } if (!body) { return [void 0]; } } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to serialize body", body); return [void 0, "BODY_PARSE_ERROR"]; } DEBUG_BUILD$2 && logger$1.info("Skipping network body because of body type", body); return [void 0, "UNPARSEABLE_BODY_TYPE"]; } __name(getBodyString, "getBodyString"); function mergeWarning(info, warning) { if (!info) { return { headers: {}, size: void 0, _meta: { warnings: [warning] } }; } const newMeta = { ...info._meta }; const existingWarnings = newMeta.warnings || []; newMeta.warnings = [...existingWarnings, warning]; info._meta = newMeta; return info; } __name(mergeWarning, "mergeWarning"); function makeNetworkReplayBreadcrumb(type, data25) { if (!data25) { return null; } const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data25; const result = { type, start: startTimestamp / 1e3, end: endTimestamp / 1e3, name: url, data: dropUndefinedKeys({ method, statusCode, request, response }) }; return result; } __name(makeNetworkReplayBreadcrumb, "makeNetworkReplayBreadcrumb"); function buildSkippedNetworkRequestOrResponse(bodySize) { return { headers: {}, size: bodySize, _meta: { warnings: ["URL_SKIPPED"] } }; } __name(buildSkippedNetworkRequestOrResponse, "buildSkippedNetworkRequestOrResponse"); function buildNetworkRequestOrResponse(headers, bodySize, body) { if (!bodySize && Object.keys(headers).length === 0) { return void 0; } if (!bodySize) { return { headers }; } if (!body) { return { headers, size: bodySize }; } const info = { headers, size: bodySize }; const { body: normalizedBody, warnings } = normalizeNetworkBody(body); info.body = normalizedBody; if (warnings && warnings.length > 0) { info._meta = { warnings }; } return info; } __name(buildNetworkRequestOrResponse, "buildNetworkRequestOrResponse"); function getAllowedHeaders(headers, allowedHeaders) { return Object.entries(headers).reduce((filteredHeaders, [key, value4]) => { const normalizedKey = key.toLowerCase(); if (allowedHeaders.includes(normalizedKey) && headers[key]) { filteredHeaders[normalizedKey] = value4; } return filteredHeaders; }, {}); } __name(getAllowedHeaders, "getAllowedHeaders"); function _serializeFormData(formData) { return new URLSearchParams(formData).toString(); } __name(_serializeFormData, "_serializeFormData"); function normalizeNetworkBody(body) { if (!body || typeof body !== "string") { return { body }; } const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE; const isProbablyJson = _strIsProbablyJson(body); if (exceedsSizeLimit) { const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE); if (isProbablyJson) { return { body: truncatedBody, warnings: ["MAYBE_JSON_TRUNCATED"] }; } return { body: `${truncatedBody}…`, warnings: ["TEXT_TRUNCATED"] }; } if (isProbablyJson) { try { const jsonBody = JSON.parse(body); return { body: jsonBody }; } catch (e2) { } } return { body }; } __name(normalizeNetworkBody, "normalizeNetworkBody"); function _strIsProbablyJson(str) { const first2 = str[0]; const last = str[str.length - 1]; return first2 === "[" && last === "]" || first2 === "{" && last === "}"; } __name(_strIsProbablyJson, "_strIsProbablyJson"); function urlMatches(url, urls) { const fullUrl = getFullUrl(url); return stringMatchesSomePattern(fullUrl, urls); } __name(urlMatches, "urlMatches"); function getFullUrl(url, baseURI = WINDOW$1.document.baseURI) { if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith(WINDOW$1.location.origin)) { return url; } const fixedUrl = new URL(url, baseURI); if (fixedUrl.origin !== new URL(baseURI).origin) { return url; } const fullUrl = fixedUrl.href; if (!url.endsWith("/") && fullUrl.endsWith("/")) { return fullUrl.slice(0, -1); } return fullUrl; } __name(getFullUrl, "getFullUrl"); async function captureFetchBreadcrumbToReplay(breadcrumb, hint, options4) { try { const data25 = await _prepareFetchData(breadcrumb, hint, options4); const result = makeNetworkReplayBreadcrumb("resource.fetch", data25); addNetworkBreadcrumb(options4.replay, result); } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to capture fetch breadcrumb"); } } __name(captureFetchBreadcrumbToReplay, "captureFetchBreadcrumbToReplay"); function enrichFetchBreadcrumb(breadcrumb, hint) { const { input, response } = hint; const body = input ? _getFetchRequestArgBody(input) : void 0; const reqSize = getBodySize(body); const resSize = response ? parseContentLengthHeader(response.headers.get("content-length")) : void 0; if (reqSize !== void 0) { breadcrumb.data.request_body_size = reqSize; } if (resSize !== void 0) { breadcrumb.data.response_body_size = resSize; } } __name(enrichFetchBreadcrumb, "enrichFetchBreadcrumb"); async function _prepareFetchData(breadcrumb, hint, options4) { const now2 = Date.now(); const { startTimestamp = now2, endTimestamp = now2 } = hint; const { url, method, status_code: statusCode = 0, request_body_size: requestBodySize, response_body_size: responseBodySize } = breadcrumb.data; const captureDetails = urlMatches(url, options4.networkDetailAllowUrls) && !urlMatches(url, options4.networkDetailDenyUrls); const request = captureDetails ? _getRequestInfo(options4, hint.input, requestBodySize) : buildSkippedNetworkRequestOrResponse(requestBodySize); const response = await _getResponseInfo(captureDetails, options4, hint.response, responseBodySize); return { startTimestamp, endTimestamp, url, method, statusCode, request, response }; } __name(_prepareFetchData, "_prepareFetchData"); function _getRequestInfo({ networkCaptureBodies, networkRequestHeaders }, input, requestBodySize) { const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {}; if (!networkCaptureBodies) { return buildNetworkRequestOrResponse(headers, requestBodySize, void 0); } const requestBody = _getFetchRequestArgBody(input); const [bodyStr, warning] = getBodyString(requestBody); const data25 = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr); if (warning) { return mergeWarning(data25, warning); } return data25; } __name(_getRequestInfo, "_getRequestInfo"); async function _getResponseInfo(captureDetails, { networkCaptureBodies, networkResponseHeaders }, response, responseBodySize) { if (!captureDetails && responseBodySize !== void 0) { return buildSkippedNetworkRequestOrResponse(responseBodySize); } const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {}; if (!response || !networkCaptureBodies && responseBodySize !== void 0) { return buildNetworkRequestOrResponse(headers, responseBodySize, void 0); } const [bodyText, warning] = await _parseFetchResponseBody(response); const result = getResponseData(bodyText, { networkCaptureBodies, responseBodySize, captureDetails, headers }); if (warning) { return mergeWarning(result, warning); } return result; } __name(_getResponseInfo, "_getResponseInfo"); function getResponseData(bodyText, { networkCaptureBodies, responseBodySize, captureDetails, headers }) { try { const size2 = bodyText && bodyText.length && responseBodySize === void 0 ? getBodySize(bodyText) : responseBodySize; if (!captureDetails) { return buildSkippedNetworkRequestOrResponse(size2); } if (networkCaptureBodies) { return buildNetworkRequestOrResponse(headers, size2, bodyText); } return buildNetworkRequestOrResponse(headers, size2, void 0); } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to serialize response body"); return buildNetworkRequestOrResponse(headers, responseBodySize, void 0); } } __name(getResponseData, "getResponseData"); async function _parseFetchResponseBody(response) { const res = _tryCloneResponse(response); if (!res) { return [void 0, "BODY_PARSE_ERROR"]; } try { const text2 = await _tryGetResponseText(res); return [text2]; } catch (error2) { if (error2 instanceof Error && error2.message.indexOf("Timeout") > -1) { DEBUG_BUILD$2 && logger$1.warn("Parsing text body from response timed out"); return [void 0, "BODY_PARSE_TIMEOUT"]; } DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to get text body from response"); return [void 0, "BODY_PARSE_ERROR"]; } } __name(_parseFetchResponseBody, "_parseFetchResponseBody"); function _getFetchRequestArgBody(fetchArgs = []) { if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== "object") { return void 0; } return fetchArgs[1].body; } __name(_getFetchRequestArgBody, "_getFetchRequestArgBody"); function getAllHeaders(headers, allowedHeaders) { const allHeaders = {}; allowedHeaders.forEach((header3) => { if (headers.get(header3)) { allHeaders[header3] = headers.get(header3); } }); return allHeaders; } __name(getAllHeaders, "getAllHeaders"); function getRequestHeaders(fetchArgs, allowedHeaders) { if (fetchArgs.length === 1 && typeof fetchArgs[0] !== "string") { return getHeadersFromOptions(fetchArgs[0], allowedHeaders); } if (fetchArgs.length === 2) { return getHeadersFromOptions(fetchArgs[1], allowedHeaders); } return {}; } __name(getRequestHeaders, "getRequestHeaders"); function getHeadersFromOptions(input, allowedHeaders) { if (!input) { return {}; } const headers = input.headers; if (!headers) { return {}; } if (headers instanceof Headers) { return getAllHeaders(headers, allowedHeaders); } if (Array.isArray(headers)) { return {}; } return getAllowedHeaders(headers, allowedHeaders); } __name(getHeadersFromOptions, "getHeadersFromOptions"); function _tryCloneResponse(response) { try { return response.clone(); } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to clone response body"); } } __name(_tryCloneResponse, "_tryCloneResponse"); function _tryGetResponseText(response) { return new Promise((resolve2, reject3) => { const timeout = setTimeout$3(() => reject3(new Error("Timeout while trying to read response body")), 500); _getResponseText(response).then( (txt) => resolve2(txt), (reason) => reject3(reason) ).finally(() => clearTimeout(timeout)); }); } __name(_tryGetResponseText, "_tryGetResponseText"); async function _getResponseText(response) { return await response.text(); } __name(_getResponseText, "_getResponseText"); async function captureXhrBreadcrumbToReplay(breadcrumb, hint, options4) { try { const data25 = _prepareXhrData(breadcrumb, hint, options4); const result = makeNetworkReplayBreadcrumb("resource.xhr", data25); addNetworkBreadcrumb(options4.replay, result); } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to capture xhr breadcrumb"); } } __name(captureXhrBreadcrumbToReplay, "captureXhrBreadcrumbToReplay"); function enrichXhrBreadcrumb(breadcrumb, hint) { const { xhr, input } = hint; if (!xhr) { return; } const reqSize = getBodySize(input); const resSize = xhr.getResponseHeader("content-length") ? parseContentLengthHeader(xhr.getResponseHeader("content-length")) : _getBodySize(xhr.response, xhr.responseType); if (reqSize !== void 0) { breadcrumb.data.request_body_size = reqSize; } if (resSize !== void 0) { breadcrumb.data.response_body_size = resSize; } } __name(enrichXhrBreadcrumb, "enrichXhrBreadcrumb"); function _prepareXhrData(breadcrumb, hint, options4) { const now2 = Date.now(); const { startTimestamp = now2, endTimestamp = now2, input, xhr } = hint; const { url, method, status_code: statusCode = 0, request_body_size: requestBodySize, response_body_size: responseBodySize } = breadcrumb.data; if (!url) { return null; } if (!xhr || !urlMatches(url, options4.networkDetailAllowUrls) || urlMatches(url, options4.networkDetailDenyUrls)) { const request2 = buildSkippedNetworkRequestOrResponse(requestBodySize); const response2 = buildSkippedNetworkRequestOrResponse(responseBodySize); return { startTimestamp, endTimestamp, url, method, statusCode, request: request2, response: response2 }; } const xhrInfo = xhr[SENTRY_XHR_DATA_KEY]; const networkRequestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options4.networkRequestHeaders) : {}; const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options4.networkResponseHeaders); const [requestBody, requestWarning] = options4.networkCaptureBodies ? getBodyString(input) : [void 0]; const [responseBody, responseWarning] = options4.networkCaptureBodies ? _getXhrResponseBody(xhr) : [void 0]; const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody); const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody); return { startTimestamp, endTimestamp, url, method, statusCode, request: requestWarning ? mergeWarning(request, requestWarning) : request, response: responseWarning ? mergeWarning(response, responseWarning) : response }; } __name(_prepareXhrData, "_prepareXhrData"); function getResponseHeaders(xhr) { const headers = xhr.getAllResponseHeaders(); if (!headers) { return {}; } return headers.split("\r\n").reduce((acc, line) => { const [key, value4] = line.split(": "); if (value4) { acc[key.toLowerCase()] = value4; } return acc; }, {}); } __name(getResponseHeaders, "getResponseHeaders"); function _getXhrResponseBody(xhr) { const errors2 = []; try { return [xhr.responseText]; } catch (e2) { errors2.push(e2); } try { return _parseXhrResponse(xhr.response, xhr.responseType); } catch (e2) { errors2.push(e2); } DEBUG_BUILD$2 && logger$1.warn("Failed to get xhr response body", ...errors2); return [void 0]; } __name(_getXhrResponseBody, "_getXhrResponseBody"); function _parseXhrResponse(body, responseType) { try { if (typeof body === "string") { return [body]; } if (body instanceof Document) { return [body.body.outerHTML]; } if (responseType === "json" && body && typeof body === "object") { return [JSON.stringify(body)]; } if (!body) { return [void 0]; } } catch (error2) { DEBUG_BUILD$2 && logger$1.exception(error2, "Failed to serialize body", body); return [void 0, "BODY_PARSE_ERROR"]; } DEBUG_BUILD$2 && logger$1.info("Skipping network body because of body type", body); return [void 0, "UNPARSEABLE_BODY_TYPE"]; } __name(_parseXhrResponse, "_parseXhrResponse"); function _getBodySize(body, responseType) { try { const bodyStr = responseType === "json" && body && typeof body === "object" ? JSON.stringify(body) : body; return getBodySize(bodyStr); } catch (e2) { return void 0; } } __name(_getBodySize, "_getBodySize"); function handleNetworkBreadcrumbs(replay) { const client = getClient(); try { const { networkDetailAllowUrls, networkDetailDenyUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders } = replay.getOptions(); const options4 = { replay, networkDetailAllowUrls, networkDetailDenyUrls, networkCaptureBodies, networkRequestHeaders, networkResponseHeaders }; if (client) { client.on("beforeAddBreadcrumb", (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options4, breadcrumb, hint)); } } catch (e2) { } } __name(handleNetworkBreadcrumbs, "handleNetworkBreadcrumbs"); function beforeAddNetworkBreadcrumb(options4, breadcrumb, hint) { if (!breadcrumb.data) { return; } try { if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) { enrichXhrBreadcrumb(breadcrumb, hint); captureXhrBreadcrumbToReplay(breadcrumb, hint, options4); } if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) { enrichFetchBreadcrumb(breadcrumb, hint); captureFetchBreadcrumbToReplay(breadcrumb, hint, options4); } } catch (e2) { DEBUG_BUILD$2 && logger$1.exception(e2, "Error when enriching network breadcrumb"); } } __name(beforeAddNetworkBreadcrumb, "beforeAddNetworkBreadcrumb"); function _isXhrBreadcrumb(breadcrumb) { return breadcrumb.category === "xhr"; } __name(_isXhrBreadcrumb, "_isXhrBreadcrumb"); function _isFetchBreadcrumb(breadcrumb) { return breadcrumb.category === "fetch"; } __name(_isFetchBreadcrumb, "_isFetchBreadcrumb"); function _isXhrHint(hint) { return hint && hint.xhr; } __name(_isXhrHint, "_isXhrHint"); function _isFetchHint(hint) { return hint && hint.response; } __name(_isFetchHint, "_isFetchHint"); function addGlobalListeners(replay) { const client = getClient(); addClickKeypressInstrumentationHandler(handleDomListener(replay)); addHistoryInstrumentationHandler(handleHistorySpanListener(replay)); handleBreadcrumbs(replay); handleNetworkBreadcrumbs(replay); const eventProcessor = handleGlobalEventListener(replay); addEventProcessor(eventProcessor); if (client) { client.on("beforeSendEvent", handleBeforeSendEvent(replay)); client.on("afterSendEvent", handleAfterSendEvent(replay)); client.on("createDsc", (dsc) => { const replayId = replay.getSessionId(); if (replayId && replay.isEnabled() && replay.recordingMode === "session") { const isSessionActive = replay.checkAndHandleExpiredSession(); if (isSessionActive) { dsc.replay_id = replayId; } } }); client.on("spanStart", (span) => { replay.lastActiveSpan = span; }); client.on("spanEnd", (span) => { replay.lastActiveSpan = span; }); client.on("beforeSendFeedback", (feedbackEvent, options4) => { const replayId = replay.getSessionId(); if (options4 && options4.includeReplay && replay.isEnabled() && replayId) { if (feedbackEvent.contexts && feedbackEvent.contexts.feedback) { feedbackEvent.contexts.feedback.replay_id = replayId; } } }); } } __name(addGlobalListeners, "addGlobalListeners"); async function addMemoryEntry(replay) { try { return Promise.all( createPerformanceSpans(replay, [ // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above) createMemoryEntry(WINDOW$1.performance.memory) ]) ); } catch (error2) { return []; } } __name(addMemoryEntry, "addMemoryEntry"); function createMemoryEntry(memoryEntry) { const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry; const time = Date.now() / 1e3; return { type: "memory", name: "memory", start: time, end: time, data: { memory: { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } } }; } __name(createMemoryEntry, "createMemoryEntry"); function debounce(func, wait, options4) { let callbackReturnValue; let timerId; let maxTimerId; const maxWait = options4 && options4.maxWait ? Math.max(options4.maxWait, wait) : 0; function invokeFunc() { cancelTimers(); callbackReturnValue = func(); return callbackReturnValue; } __name(invokeFunc, "invokeFunc"); function cancelTimers() { timerId !== void 0 && clearTimeout(timerId); maxTimerId !== void 0 && clearTimeout(maxTimerId); timerId = maxTimerId = void 0; } __name(cancelTimers, "cancelTimers"); function flush2() { if (timerId !== void 0 || maxTimerId !== void 0) { return invokeFunc(); } return callbackReturnValue; } __name(flush2, "flush"); function debounced() { if (timerId) { clearTimeout(timerId); } timerId = setTimeout$3(invokeFunc, wait); if (maxWait && maxTimerId === void 0) { maxTimerId = setTimeout$3(invokeFunc, maxWait); } return callbackReturnValue; } __name(debounced, "debounced"); debounced.cancel = cancelTimers; debounced.flush = flush2; return debounced; } __name(debounce, "debounce"); function getHandleRecordingEmit(replay) { let hadFirstEvent = false; return (event, _isCheckout) => { if (!replay.checkAndHandleExpiredSession()) { DEBUG_BUILD$2 && logger$1.warn("Received replay event after session expired."); return; } const isCheckout = _isCheckout || !hadFirstEvent; hadFirstEvent = true; if (replay.clickDetector) { updateClickDetectorForRecordingEvent(replay.clickDetector, event); } replay.addUpdate(() => { if (replay.recordingMode === "buffer" && isCheckout) { replay.setInitialState(); } if (!addEventSync(replay, event, isCheckout)) { return true; } if (!isCheckout) { return false; } const session = replay.session; addSettingsEvent(replay, isCheckout); if (replay.recordingMode === "buffer" && session && replay.eventBuffer) { const earliestEvent = replay.eventBuffer.getEarliestTimestamp(); if (earliestEvent) { DEBUG_BUILD$2 && logger$1.info(`Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`); session.started = earliestEvent; if (replay.getOptions().stickySession) { saveSession(session); } } } if (session && session.previousSessionId) { return true; } if (replay.recordingMode === "session") { void replay.flush(); } return true; }); }; } __name(getHandleRecordingEmit, "getHandleRecordingEmit"); function createOptionsEvent(replay) { const options4 = replay.getOptions(); return { type: EventType.Custom, timestamp: Date.now(), data: { tag: "options", payload: { shouldRecordCanvas: replay.isRecordingCanvas(), sessionSampleRate: options4.sessionSampleRate, errorSampleRate: options4.errorSampleRate, useCompressionOption: options4.useCompression, blockAllMedia: options4.blockAllMedia, maskAllText: options4.maskAllText, maskAllInputs: options4.maskAllInputs, useCompression: replay.eventBuffer ? replay.eventBuffer.type === "worker" : false, networkDetailHasUrls: options4.networkDetailAllowUrls.length > 0, networkCaptureBodies: options4.networkCaptureBodies, networkRequestHasHeaders: options4.networkRequestHeaders.length > 0, networkResponseHasHeaders: options4.networkResponseHeaders.length > 0 } } }; } __name(createOptionsEvent, "createOptionsEvent"); function addSettingsEvent(replay, isCheckout) { if (!isCheckout || !replay.session || replay.session.segmentId !== 0) { return; } addEventSync(replay, createOptionsEvent(replay), false); } __name(addSettingsEvent, "addSettingsEvent"); function createReplayEnvelope(replayEvent, recordingData, dsn, tunnel) { return createEnvelope( createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn), [ [{ type: "replay_event" }, replayEvent], [ { type: "replay_recording", // If string then we need to encode to UTF8, otherwise will have // wrong size. TextEncoder has similar browser support to // MutationObserver, although it does not accept IE11. length: typeof recordingData === "string" ? new TextEncoder().encode(recordingData).length : recordingData.length }, recordingData ] ] ); } __name(createReplayEnvelope, "createReplayEnvelope"); function prepareRecordingData({ recordingData, headers }) { let payloadWithSequence; const replayHeaders = `${JSON.stringify(headers)} `; if (typeof recordingData === "string") { payloadWithSequence = `${replayHeaders}${recordingData}`; } else { const enc = new TextEncoder(); const sequence = enc.encode(replayHeaders); payloadWithSequence = new Uint8Array(sequence.length + recordingData.length); payloadWithSequence.set(sequence); payloadWithSequence.set(recordingData, sequence.length); } return payloadWithSequence; } __name(prepareRecordingData, "prepareRecordingData"); async function prepareReplayEvent({ client, scope, replayId: event_id, event }) { const integrations = typeof client._integrations === "object" && client._integrations !== null && !Array.isArray(client._integrations) ? Object.keys(client._integrations) : void 0; const eventHint = { event_id, integrations }; client.emit("preprocessEvent", event, eventHint); const preparedEvent = await prepareEvent( client.getOptions(), event, eventHint, scope, client, getIsolationScope() ); if (!preparedEvent) { return null; } preparedEvent.platform = preparedEvent.platform || "javascript"; const metadata = client.getSdkMetadata(); const { name: name2, version: version2 } = metadata && metadata.sdk || {}; preparedEvent.sdk = { ...preparedEvent.sdk, name: name2 || "sentry.javascript.unknown", version: version2 || "0.0.0" }; return preparedEvent; } __name(prepareReplayEvent, "prepareReplayEvent"); async function sendReplayRequest({ recordingData, replayId, segmentId: segment_id, eventContext, timestamp: timestamp2, session }) { const preparedRecordingData = prepareRecordingData({ recordingData, headers: { segment_id } }); const { urls, errorIds, traceIds, initialTimestamp } = eventContext; const client = getClient(); const scope = getCurrentScope$1(); const transport = client && client.getTransport(); const dsn = client && client.getDsn(); if (!client || !transport || !dsn || !session.sampled) { return resolvedSyncPromise({}); } const baseEvent = { type: REPLAY_EVENT_NAME, replay_start_timestamp: initialTimestamp / 1e3, timestamp: timestamp2 / 1e3, error_ids: errorIds, trace_ids: traceIds, urls, replay_id: replayId, segment_id, replay_type: session.sampled }; const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent }); if (!replayEvent) { client.recordDroppedEvent("event_processor", "replay", baseEvent); DEBUG_BUILD$2 && logger$1.info("An event processor returned `null`, will not send event."); return resolvedSyncPromise({}); } delete replayEvent.sdkProcessingMetadata; const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel); let response; try { response = await transport.send(envelope); } catch (err) { const error2 = new Error(UNABLE_TO_SEND_REPLAY); try { error2.cause = err; } catch (e2) { } throw error2; } if (typeof response.statusCode === "number" && (response.statusCode < 200 || response.statusCode >= 300)) { throw new TransportStatusCodeError(response.statusCode); } const rateLimits = updateRateLimits({}, response); if (isRateLimited(rateLimits, "replay")) { throw new RateLimitError(rateLimits); } return response; } __name(sendReplayRequest, "sendReplayRequest"); class TransportStatusCodeError extends Error { static { __name(this, "TransportStatusCodeError"); } constructor(statusCode) { super(`Transport returned status code ${statusCode}`); } } class RateLimitError extends Error { static { __name(this, "RateLimitError"); } constructor(rateLimits) { super("Rate limit hit"); this.rateLimits = rateLimits; } } async function sendReplay(replayData, retryConfig = { count: 0, interval: RETRY_BASE_INTERVAL }) { const { recordingData, onError } = replayData; if (!recordingData.length) { return; } try { await sendReplayRequest(replayData); return true; } catch (err) { if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) { throw err; } setContext("Replays", { _retryCount: retryConfig.count }); if (onError) { onError(err); } if (retryConfig.count >= RETRY_MAX_COUNT) { const error2 = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`); try { error2.cause = err; } catch (e2) { } throw error2; } retryConfig.interval *= ++retryConfig.count; return new Promise((resolve2, reject3) => { setTimeout$3(async () => { try { await sendReplay(replayData, retryConfig); resolve2(true); } catch (err2) { reject3(err2); } }, retryConfig.interval); }); } } __name(sendReplay, "sendReplay"); const THROTTLED = "__THROTTLED"; const SKIPPED = "__SKIPPED"; function throttle$2(fn, maxCount, durationSeconds) { const counter = /* @__PURE__ */ new Map(); const _cleanup = /* @__PURE__ */ __name((now2) => { const threshold = now2 - durationSeconds; counter.forEach((_value, key) => { if (key < threshold) { counter.delete(key); } }); }, "_cleanup"); const _getTotalCount = /* @__PURE__ */ __name(() => { return [...counter.values()].reduce((a2, b2) => a2 + b2, 0); }, "_getTotalCount"); let isThrottled = false; return (...rest) => { const now2 = Math.floor(Date.now() / 1e3); _cleanup(now2); if (_getTotalCount() >= maxCount) { const wasThrottled = isThrottled; isThrottled = true; return wasThrottled ? SKIPPED : THROTTLED; } isThrottled = false; const count = counter.get(now2) || 0; counter.set(now2, count + 1); return fn(...rest); }; } __name(throttle$2, "throttle$2"); class ReplayContainer { static { __name(this, "ReplayContainer"); } /** * Recording can happen in one of two modes: * - session: Record the whole session, sending it continuously * - buffer: Always keep the last 60s of recording, requires: * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs * - or calling `flush()` to send the replay */ /** * The current or last active span. * This is only available when performance is enabled. */ /** * These are here so we can overwrite them in tests etc. * @hidden */ /** The replay has to be manually started, because no sample rate (neither session or error) was provided. */ /** * Options to pass to `rrweb.record()` */ /** * Timestamp of the last user activity. This lives across sessions. */ /** * Is the integration currently active? */ /** * Paused is a state where: * - DOM Recording is not listening at all * - Nothing will be added to event buffer (e.g. core SDK events) */ /** * Have we attached listeners to the core SDK? * Note we have to track this as there is no way to remove instrumentation handlers. */ /** * Function to stop recording */ /** * Internal use for canvas recording options */ constructor({ options: options4, recordingOptions }) { ReplayContainer.prototype.__init.call(this); ReplayContainer.prototype.__init2.call(this); ReplayContainer.prototype.__init3.call(this); ReplayContainer.prototype.__init4.call(this); ReplayContainer.prototype.__init5.call(this); ReplayContainer.prototype.__init6.call(this); this.eventBuffer = null; this.performanceEntries = []; this.replayPerformanceEntries = []; this.recordingMode = "session"; this.timeouts = { sessionIdlePause: SESSION_IDLE_PAUSE_DURATION, sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION }; this._lastActivity = Date.now(); this._isEnabled = false; this._isPaused = false; this._requiresManualStart = false; this._hasInitializedCoreListeners = false; this._context = { errorIds: /* @__PURE__ */ new Set(), traceIds: /* @__PURE__ */ new Set(), urls: [], initialTimestamp: Date.now(), initialUrl: "" }; this._recordingOptions = recordingOptions; this._options = options4; this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, { maxWait: this._options.flushMaxDelay }); this._throttledAddEvent = throttle$2( (event, isCheckout) => addEvent(this, event, isCheckout), // Max 300 events... 300, // ... per 5s 5 ); const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions(); const slowClickConfig = slowClickTimeout ? { threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout), timeout: slowClickTimeout, scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT, ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(",") : "" } : void 0; if (slowClickConfig) { this.clickDetector = new ClickDetector(this, slowClickConfig); } if (DEBUG_BUILD$2) { const experiments = options4._experiments; logger$1.setConfig({ captureExceptions: !!experiments.captureExceptions, traceInternals: !!experiments.traceInternals }); } } /** Get the event context. */ getContext() { return this._context; } /** If recording is currently enabled. */ isEnabled() { return this._isEnabled; } /** If recording is currently paused. */ isPaused() { return this._isPaused; } /** * Determine if canvas recording is enabled */ isRecordingCanvas() { return Boolean(this._canvas); } /** Get the replay integration options. */ getOptions() { return this._options; } /** A wrapper to conditionally capture exceptions. */ handleException(error2) { DEBUG_BUILD$2 && logger$1.exception(error2); if (this._options.onError) { this._options.onError(error2); } } /** * Initializes the plugin based on sampling configuration. Should not be * called outside of constructor. */ initializeSampling(previousSessionId) { const { errorSampleRate, sessionSampleRate } = this._options; const requiresManualStart = errorSampleRate <= 0 && sessionSampleRate <= 0; this._requiresManualStart = requiresManualStart; if (requiresManualStart) { return; } this._initializeSessionForSampling(previousSessionId); if (!this.session) { DEBUG_BUILD$2 && logger$1.exception(new Error("Unable to initialize and create session")); return; } if (this.session.sampled === false) { return; } this.recordingMode = this.session.sampled === "buffer" && this.session.segmentId === 0 ? "buffer" : "session"; DEBUG_BUILD$2 && logger$1.infoTick(`Starting replay in ${this.recordingMode} mode`); this._initializeRecording(); } /** * Start a replay regardless of sampling rate. Calling this will always * create a new session. Will log a message if replay is already in progress. * * Creates or loads a session, attaches listeners to varying events (DOM, * _performanceObserver, Recording, Sentry SDK, etc) */ start() { if (this._isEnabled && this.recordingMode === "session") { DEBUG_BUILD$2 && logger$1.info("Recording is already in progress"); return; } if (this._isEnabled && this.recordingMode === "buffer") { DEBUG_BUILD$2 && logger$1.info("Buffering is in progress, call `flush()` to save the replay"); return; } DEBUG_BUILD$2 && logger$1.infoTick("Starting replay in session mode"); this._updateUserActivity(); const session = loadOrCreateSession( { maxReplayDuration: this._options.maxReplayDuration, sessionIdleExpire: this.timeouts.sessionIdleExpire }, { stickySession: this._options.stickySession, // This is intentional: create a new session-based replay when calling `start()` sessionSampleRate: 1, allowBuffering: false } ); this.session = session; this._initializeRecording(); } /** * Start replay buffering. Buffers until `flush()` is called or, if * `replaysOnErrorSampleRate` > 0, an error occurs. */ startBuffering() { if (this._isEnabled) { DEBUG_BUILD$2 && logger$1.info("Buffering is in progress, call `flush()` to save the replay"); return; } DEBUG_BUILD$2 && logger$1.infoTick("Starting replay in buffer mode"); const session = loadOrCreateSession( { sessionIdleExpire: this.timeouts.sessionIdleExpire, maxReplayDuration: this._options.maxReplayDuration }, { stickySession: this._options.stickySession, sessionSampleRate: 0, allowBuffering: true } ); this.session = session; this.recordingMode = "buffer"; this._initializeRecording(); } /** * Start recording. * * Note that this will cause a new DOM checkout */ startRecording() { try { const canvasOptions = this._canvas; this._stopRecording = record({ ...this._recordingOptions, // When running in error sampling mode, we need to overwrite `checkoutEveryNms` // Without this, it would record forever, until an error happens, which we don't want // instead, we'll always keep the last 60 seconds of replay before an error happened ...this.recordingMode === "buffer" ? { checkoutEveryNms: BUFFER_CHECKOUT_TIME } : ( // Otherwise, use experimental option w/ min checkout time of 6 minutes // This is to improve playback seeking as there could potentially be // less mutations to process in the worse cases. // // checkout by "N" events is probably ideal, but means we have less // control about the number of checkouts we make (which generally // increases replay size) this._options._experiments.continuousCheckout && { // Minimum checkout time is 6 minutes checkoutEveryNms: Math.max(36e4, this._options._experiments.continuousCheckout) } ), emit: getHandleRecordingEmit(this), onMutation: this._onMutationHandler, ...canvasOptions ? { recordCanvas: canvasOptions.recordCanvas, getCanvasManager: canvasOptions.getCanvasManager, sampling: canvasOptions.sampling, dataURLOptions: canvasOptions.dataURLOptions } : {} }); } catch (err) { this.handleException(err); } } /** * Stops the recording, if it was running. * * Returns true if it was previously stopped, or is now stopped, * otherwise false. */ stopRecording() { try { if (this._stopRecording) { this._stopRecording(); this._stopRecording = void 0; } return true; } catch (err) { this.handleException(err); return false; } } /** * Currently, this needs to be manually called (e.g. for tests). Sentry SDK * does not support a teardown */ async stop({ forceFlush = false, reason } = {}) { if (!this._isEnabled) { return; } this._isEnabled = false; try { DEBUG_BUILD$2 && logger$1.info(`Stopping Replay${reason ? ` triggered by ${reason}` : ""}`); resetReplayIdOnDynamicSamplingContext(); this._removeListeners(); this.stopRecording(); this._debouncedFlush.cancel(); if (forceFlush) { await this._flush({ force: true }); } this.eventBuffer && this.eventBuffer.destroy(); this.eventBuffer = null; clearSession(this); } catch (err) { this.handleException(err); } } /** * Pause some replay functionality. See comments for `_isPaused`. * This differs from stop as this only stops DOM recording, it is * not as thorough of a shutdown as `stop()`. */ pause() { if (this._isPaused) { return; } this._isPaused = true; this.stopRecording(); DEBUG_BUILD$2 && logger$1.info("Pausing replay"); } /** * Resumes recording, see notes for `pause(). * * Note that calling `startRecording()` here will cause a * new DOM checkout.` */ resume() { if (!this._isPaused || !this._checkSession()) { return; } this._isPaused = false; this.startRecording(); DEBUG_BUILD$2 && logger$1.info("Resuming replay"); } /** * If not in "session" recording mode, flush event buffer which will create a new replay. * Unless `continueRecording` is false, the replay will continue to record and * behave as a "session"-based replay. * * Otherwise, queue up a flush. */ async sendBufferedReplayOrFlush({ continueRecording = true } = {}) { if (this.recordingMode === "session") { return this.flushImmediate(); } const activityTime = Date.now(); DEBUG_BUILD$2 && logger$1.info("Converting buffer to session"); await this.flushImmediate(); const hasStoppedRecording = this.stopRecording(); if (!continueRecording || !hasStoppedRecording) { return; } if (this.recordingMode === "session") { return; } this.recordingMode = "session"; if (this.session) { this._updateUserActivity(activityTime); this._updateSessionActivity(activityTime); this._maybeSaveSession(); } this.startRecording(); } /** * We want to batch uploads of replay events. Save events only if * `` milliseconds have elapsed since the last event * *OR* if `` milliseconds have elapsed. * * Accepts a callback to perform side-effects and returns true to stop batch * processing and hand back control to caller. */ addUpdate(cb) { const cbResult = cb(); if (this.recordingMode === "buffer") { return; } if (cbResult === true) { return; } this._debouncedFlush(); } /** * Updates the user activity timestamp and resumes recording. This should be * called in an event handler for a user action that we consider as the user * being "active" (e.g. a mouse click). */ triggerUserActivity() { this._updateUserActivity(); if (!this._stopRecording) { if (!this._checkSession()) { return; } this.resume(); return; } this.checkAndHandleExpiredSession(); this._updateSessionActivity(); } /** * Updates the user activity timestamp *without* resuming * recording. Some user events (e.g. keydown) can be create * low-value replays that only contain the keypress as a * breadcrumb. Instead this would require other events to * create a new replay after a session has expired. */ updateUserActivity() { this._updateUserActivity(); this._updateSessionActivity(); } /** * Only flush if `this.recordingMode === 'session'` */ conditionalFlush() { if (this.recordingMode === "buffer") { return Promise.resolve(); } return this.flushImmediate(); } /** * Flush using debounce flush */ flush() { return this._debouncedFlush(); } /** * Always flush via `_debouncedFlush` so that we do not have flushes triggered * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be * cases of multiple flushes happening closely together. */ flushImmediate() { this._debouncedFlush(); return this._debouncedFlush.flush(); } /** * Cancels queued up flushes. */ cancelFlush() { this._debouncedFlush.cancel(); } /** Get the current session (=replay) ID */ getSessionId() { return this.session && this.session.id; } /** * Checks if recording should be stopped due to user inactivity. Otherwise * check if session is expired and create a new session if so. Triggers a new * full snapshot on new session. * * Returns true if session is not expired, false otherwise. * @hidden */ checkAndHandleExpiredSession() { if (this._lastActivity && isExpired(this._lastActivity, this.timeouts.sessionIdlePause) && this.session && this.session.sampled === "session") { this.pause(); return; } if (!this._checkSession()) { return false; } return true; } /** * Capture some initial state that can change throughout the lifespan of the * replay. This is required because otherwise they would be captured at the * first flush. */ setInitialState() { const urlPath = `${WINDOW$1.location.pathname}${WINDOW$1.location.hash}${WINDOW$1.location.search}`; const url = `${WINDOW$1.location.origin}${urlPath}`; this.performanceEntries = []; this.replayPerformanceEntries = []; this._clearContext(); this._context.initialUrl = url; this._context.initialTimestamp = Date.now(); this._context.urls.push(url); } /** * Add a breadcrumb event, that may be throttled. * If it was throttled, we add a custom breadcrumb to indicate that. */ throttledAddEvent(event, isCheckout) { const res = this._throttledAddEvent(event, isCheckout); if (res === THROTTLED) { const breadcrumb = createBreadcrumb({ category: "replay.throttled" }); this.addUpdate(() => { return !addEventSync(this, { type: ReplayEventTypeCustom, timestamp: breadcrumb.timestamp || 0, data: { tag: "breadcrumb", payload: breadcrumb, metric: true } }); }); } return res; } /** * This will get the parametrized route name of the current page. * This is only available if performance is enabled, and if an instrumented router is used. */ getCurrentRoute() { const lastActiveSpan = this.lastActiveSpan || getActiveSpan(); const lastRootSpan = lastActiveSpan && getRootSpan(lastActiveSpan); const attributes = lastRootSpan && spanToJSON(lastRootSpan).data || {}; const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; if (!lastRootSpan || !source || !["route", "custom"].includes(source)) { return void 0; } return spanToJSON(lastRootSpan).description; } /** * Initialize and start all listeners to varying events (DOM, * Performance Observer, Recording, Sentry SDK, etc) */ _initializeRecording() { this.setInitialState(); this._updateSessionActivity(); this.eventBuffer = createEventBuffer({ useCompression: this._options.useCompression, workerUrl: this._options.workerUrl }); this._removeListeners(); this._addListeners(); this._isEnabled = true; this._isPaused = false; this.startRecording(); } /** * Loads (or refreshes) the current session. */ _initializeSessionForSampling(previousSessionId) { const allowBuffering = this._options.errorSampleRate > 0; const session = loadOrCreateSession( { sessionIdleExpire: this.timeouts.sessionIdleExpire, maxReplayDuration: this._options.maxReplayDuration, previousSessionId }, { stickySession: this._options.stickySession, sessionSampleRate: this._options.sessionSampleRate, allowBuffering } ); this.session = session; } /** * Checks and potentially refreshes the current session. * Returns false if session is not recorded. */ _checkSession() { if (!this.session) { return false; } const currentSession = this.session; if (shouldRefreshSession(currentSession, { sessionIdleExpire: this.timeouts.sessionIdleExpire, maxReplayDuration: this._options.maxReplayDuration })) { this._refreshSession(currentSession); return false; } return true; } /** * Refresh a session with a new one. * This stops the current session (without forcing a flush, as that would never work since we are expired), * and then does a new sampling based on the refreshed session. */ async _refreshSession(session) { if (!this._isEnabled) { return; } await this.stop({ reason: "refresh session" }); this.initializeSampling(session.id); } /** * Adds listeners to record events for the replay */ _addListeners() { try { WINDOW$1.document.addEventListener("visibilitychange", this._handleVisibilityChange); WINDOW$1.addEventListener("blur", this._handleWindowBlur); WINDOW$1.addEventListener("focus", this._handleWindowFocus); WINDOW$1.addEventListener("keydown", this._handleKeyboardEvent); if (this.clickDetector) { this.clickDetector.addListeners(); } if (!this._hasInitializedCoreListeners) { addGlobalListeners(this); this._hasInitializedCoreListeners = true; } } catch (err) { this.handleException(err); } this._performanceCleanupCallback = setupPerformanceObserver(this); } /** * Cleans up listeners that were created in `_addListeners` */ _removeListeners() { try { WINDOW$1.document.removeEventListener("visibilitychange", this._handleVisibilityChange); WINDOW$1.removeEventListener("blur", this._handleWindowBlur); WINDOW$1.removeEventListener("focus", this._handleWindowFocus); WINDOW$1.removeEventListener("keydown", this._handleKeyboardEvent); if (this.clickDetector) { this.clickDetector.removeListeners(); } if (this._performanceCleanupCallback) { this._performanceCleanupCallback(); } } catch (err) { this.handleException(err); } } /** * Handle when visibility of the page content changes. Opening a new tab will * cause the state to change to hidden because of content of current page will * be hidden. Likewise, moving a different window to cover the contents of the * page will also trigger a change to a hidden state. */ __init() { this._handleVisibilityChange = () => { if (WINDOW$1.document.visibilityState === "visible") { this._doChangeToForegroundTasks(); } else { this._doChangeToBackgroundTasks(); } }; } /** * Handle when page is blurred */ __init2() { this._handleWindowBlur = () => { const breadcrumb = createBreadcrumb({ category: "ui.blur" }); this._doChangeToBackgroundTasks(breadcrumb); }; } /** * Handle when page is focused */ __init3() { this._handleWindowFocus = () => { const breadcrumb = createBreadcrumb({ category: "ui.focus" }); this._doChangeToForegroundTasks(breadcrumb); }; } /** Ensure page remains active when a key is pressed. */ __init4() { this._handleKeyboardEvent = (event) => { handleKeyboardEvent(this, event); }; } /** * Tasks to run when we consider a page to be hidden (via blurring and/or visibility) */ _doChangeToBackgroundTasks(breadcrumb) { if (!this.session) { return; } const expired = isSessionExpired(this.session, { maxReplayDuration: this._options.maxReplayDuration, sessionIdleExpire: this.timeouts.sessionIdleExpire }); if (expired) { return; } if (breadcrumb) { this._createCustomBreadcrumb(breadcrumb); } void this.conditionalFlush(); } /** * Tasks to run when we consider a page to be visible (via focus and/or visibility) */ _doChangeToForegroundTasks(breadcrumb) { if (!this.session) { return; } const isSessionActive = this.checkAndHandleExpiredSession(); if (!isSessionActive) { DEBUG_BUILD$2 && logger$1.info("Document has become active, but session has expired"); return; } if (breadcrumb) { this._createCustomBreadcrumb(breadcrumb); } } /** * Update user activity (across session lifespans) */ _updateUserActivity(_lastActivity = Date.now()) { this._lastActivity = _lastActivity; } /** * Updates the session's last activity timestamp */ _updateSessionActivity(_lastActivity = Date.now()) { if (this.session) { this.session.lastActivity = _lastActivity; this._maybeSaveSession(); } } /** * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb */ _createCustomBreadcrumb(breadcrumb) { this.addUpdate(() => { this.throttledAddEvent({ type: EventType.Custom, timestamp: breadcrumb.timestamp || 0, data: { tag: "breadcrumb", payload: breadcrumb } }); }); } /** * Observed performance events are added to `this.performanceEntries`. These * are included in the replay event before it is finished and sent to Sentry. */ _addPerformanceEntries() { let performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries); this.performanceEntries = []; this.replayPerformanceEntries = []; if (this._requiresManualStart) { const initialTimestampInSeconds = this._context.initialTimestamp / 1e3; performanceEntries = performanceEntries.filter((entry) => entry.start >= initialTimestampInSeconds); } return Promise.all(createPerformanceSpans(this, performanceEntries)); } /** * Clear _context */ _clearContext() { this._context.errorIds.clear(); this._context.traceIds.clear(); this._context.urls = []; } /** Update the initial timestamp based on the buffer content. */ _updateInitialTimestampFromEventBuffer() { const { session, eventBuffer } = this; if (!session || !eventBuffer || this._requiresManualStart) { return; } if (session.segmentId) { return; } const earliestEvent = eventBuffer.getEarliestTimestamp(); if (earliestEvent && earliestEvent < this._context.initialTimestamp) { this._context.initialTimestamp = earliestEvent; } } /** * Return and clear _context */ _popEventContext() { const _context = { initialTimestamp: this._context.initialTimestamp, initialUrl: this._context.initialUrl, errorIds: Array.from(this._context.errorIds), traceIds: Array.from(this._context.traceIds), urls: this._context.urls }; this._clearContext(); return _context; } /** * Flushes replay event buffer to Sentry. * * Performance events are only added right before flushing - this is * due to the buffered performance observer events. * * Should never be called directly, only by `flush` */ async _runFlush() { const replayId = this.getSessionId(); if (!this.session || !this.eventBuffer || !replayId) { DEBUG_BUILD$2 && logger$1.error("No session or eventBuffer found to flush."); return; } await this._addPerformanceEntries(); if (!this.eventBuffer || !this.eventBuffer.hasEvents) { return; } await addMemoryEntry(this); if (!this.eventBuffer) { return; } if (replayId !== this.getSessionId()) { return; } try { this._updateInitialTimestampFromEventBuffer(); const timestamp2 = Date.now(); if (timestamp2 - this._context.initialTimestamp > this._options.maxReplayDuration + 3e4) { throw new Error("Session is too long, not sending replay"); } const eventContext = this._popEventContext(); const segmentId = this.session.segmentId++; this._maybeSaveSession(); const recordingData = await this.eventBuffer.finish(); await sendReplay({ replayId, recordingData, segmentId, eventContext, session: this.session, timestamp: timestamp2, onError: /* @__PURE__ */ __name((err) => this.handleException(err), "onError") }); } catch (err) { this.handleException(err); this.stop({ reason: "sendReplay" }); const client = getClient(); if (client) { const dropReason = err instanceof RateLimitError ? "ratelimit_backoff" : "send_error"; client.recordDroppedEvent(dropReason, "replay"); } } } /** * Flush recording data to Sentry. Creates a lock so that only a single flush * can be active at a time. Do not call this directly. */ __init5() { this._flush = async ({ force = false } = {}) => { if (!this._isEnabled && !force) { return; } if (!this.checkAndHandleExpiredSession()) { DEBUG_BUILD$2 && logger$1.error("Attempting to finish replay event after session expired."); return; } if (!this.session) { return; } const start2 = this.session.started; const now2 = Date.now(); const duration = now2 - start2; this._debouncedFlush.cancel(); const tooShort = duration < this._options.minReplayDuration; const tooLong = duration > this._options.maxReplayDuration + 5e3; if (tooShort || tooLong) { DEBUG_BUILD$2 && logger$1.info( `Session duration (${Math.floor(duration / 1e3)}s) is too ${tooShort ? "short" : "long"}, not sending replay.` ); if (tooShort) { this._debouncedFlush(); } return; } const eventBuffer = this.eventBuffer; if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) { DEBUG_BUILD$2 && logger$1.info("Flushing initial segment without checkout."); } const _flushInProgress = !!this._flushLock; if (!this._flushLock) { this._flushLock = this._runFlush(); } try { await this._flushLock; } catch (err) { this.handleException(err); } finally { this._flushLock = void 0; if (_flushInProgress) { this._debouncedFlush(); } } }; } /** Save the session, if it is sticky */ _maybeSaveSession() { if (this.session && this._options.stickySession) { saveSession(this.session); } } /** Handler for rrweb.record.onMutation */ __init6() { this._onMutationHandler = (mutations) => { const count = mutations.length; const mutationLimit = this._options.mutationLimit; const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit; const overMutationLimit = mutationLimit && count > mutationLimit; if (count > mutationBreadcrumbLimit || overMutationLimit) { const breadcrumb = createBreadcrumb({ category: "replay.mutations", data: { count, limit: overMutationLimit } }); this._createCustomBreadcrumb(breadcrumb); } if (overMutationLimit) { this.stop({ reason: "mutationLimit", forceFlush: this.recordingMode === "session" }); return false; } return true; }; } } function getOption(selectors, defaultSelectors) { return [ ...selectors, // sentry defaults ...defaultSelectors ].join(","); } __name(getOption, "getOption"); function getPrivacyOptions({ mask: mask3, unmask, block: block3, unblock: unblock2, ignore }) { const defaultBlockedElements = ["base", "iframe[srcdoc]:not([src])"]; const maskSelector = getOption(mask3, [".sentry-mask", "[data-sentry-mask]"]); const unmaskSelector = getOption(unmask, []); const options4 = { // We are making the decision to make text and input selectors the same maskTextSelector: maskSelector, unmaskTextSelector: unmaskSelector, blockSelector: getOption(block3, [".sentry-block", "[data-sentry-block]", ...defaultBlockedElements]), unblockSelector: getOption(unblock2, []), ignoreSelector: getOption(ignore, [".sentry-ignore", "[data-sentry-ignore]", 'input[type="file"]']) }; return options4; } __name(getPrivacyOptions, "getPrivacyOptions"); function maskAttribute({ el, key, maskAttributes, maskAllText, privacyOptions, value: value4 }) { if (!maskAllText) { return value4; } if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) { return value4; } if (maskAttributes.includes(key) || // Need to mask `value` attribute for `` if it's a button-like // type key === "value" && el.tagName === "INPUT" && ["submit", "button"].includes(el.getAttribute("type") || "")) { return value4.replace(/[\S]/g, "*"); } return value4; } __name(maskAttribute, "maskAttribute"); const MEDIA_SELECTORS = 'img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]'; const DEFAULT_NETWORK_HEADERS = ["content-length", "content-type", "accept"]; let _initialized = false; const replayIntegration = /* @__PURE__ */ __name((options4) => { return new Replay(options4); }, "replayIntegration"); class Replay { static { __name(this, "Replay"); } /** * @inheritDoc */ static __initStatic() { this.id = "Replay"; } /** * @inheritDoc */ /** * Options to pass to `rrweb.record()` */ /** * Initial options passed to the replay integration, merged with default values. * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they * can only be finally set when setupOnce() is called. * * @private */ constructor({ flushMinDelay = DEFAULT_FLUSH_MIN_DELAY, flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY, minReplayDuration = MIN_REPLAY_DURATION, maxReplayDuration = MAX_REPLAY_DURATION, stickySession = true, useCompression = true, workerUrl, _experiments = {}, maskAllText = true, maskAllInputs = true, blockAllMedia = true, mutationBreadcrumbLimit = 750, mutationLimit = 1e4, slowClickTimeout = 7e3, slowClickIgnoreSelectors = [], networkDetailAllowUrls = [], networkDetailDenyUrls = [], networkCaptureBodies = true, networkRequestHeaders = [], networkResponseHeaders = [], mask: mask3 = [], maskAttributes = ["title", "placeholder"], unmask = [], block: block3 = [], unblock: unblock2 = [], ignore = [], maskFn, beforeAddRecordingEvent, beforeErrorSampling, onError } = {}) { this.name = Replay.id; const privacyOptions = getPrivacyOptions({ mask: mask3, unmask, block: block3, unblock: unblock2, ignore }); this._recordingOptions = { maskAllInputs, maskAllText, maskInputOptions: { password: true }, maskTextFn: maskFn, maskInputFn: maskFn, maskAttributeFn: /* @__PURE__ */ __name((key, value4, el) => maskAttribute({ maskAttributes, maskAllText, privacyOptions, key, value: value4, el }), "maskAttributeFn"), ...privacyOptions, // Our defaults slimDOMOptions: "all", inlineStylesheet: true, // Disable inline images as it will increase segment/replay size inlineImages: false, // collect fonts, but be aware that `sentry.io` needs to be an allowed // origin for playback collectFonts: true, errorHandler: /* @__PURE__ */ __name((err) => { try { err.__rrweb__ = true; } catch (error2) { } }, "errorHandler") }; this._initialOptions = { flushMinDelay, flushMaxDelay, minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT), maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION), stickySession, useCompression, workerUrl, blockAllMedia, maskAllInputs, maskAllText, mutationBreadcrumbLimit, mutationLimit, slowClickTimeout, slowClickIgnoreSelectors, networkDetailAllowUrls, networkDetailDenyUrls, networkCaptureBodies, networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders), networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders), beforeAddRecordingEvent, beforeErrorSampling, onError, _experiments }; if (this._initialOptions.blockAllMedia) { this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector ? MEDIA_SELECTORS : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`; } if (this._isInitialized && isBrowser$1()) { throw new Error("Multiple Sentry Session Replay instances are not supported"); } this._isInitialized = true; } /** If replay has already been initialized */ get _isInitialized() { return _initialized; } /** Update _isInitialized */ set _isInitialized(value4) { _initialized = value4; } /** * Setup and initialize replay container */ afterAllSetup(client) { if (!isBrowser$1() || this._replay) { return; } this._setup(client); this._initialize(client); } /** * Start a replay regardless of sampling rate. Calling this will always * create a new session. Will log a message if replay is already in progress. * * Creates or loads a session, attaches listeners to varying events (DOM, * PerformanceObserver, Recording, Sentry SDK, etc) */ start() { if (!this._replay) { return; } this._replay.start(); } /** * Start replay buffering. Buffers until `flush()` is called or, if * `replaysOnErrorSampleRate` > 0, until an error occurs. */ startBuffering() { if (!this._replay) { return; } this._replay.startBuffering(); } /** * Currently, this needs to be manually called (e.g. for tests). Sentry SDK * does not support a teardown */ stop() { if (!this._replay) { return Promise.resolve(); } return this._replay.stop({ forceFlush: this._replay.recordingMode === "session" }); } /** * If not in "session" recording mode, flush event buffer which will create a new replay. * If replay is not enabled, a new session replay is started. * Unless `continueRecording` is false, the replay will continue to record and * behave as a "session"-based replay. * * Otherwise, queue up a flush. */ flush(options4) { if (!this._replay) { return Promise.resolve(); } if (!this._replay.isEnabled()) { this._replay.start(); return Promise.resolve(); } return this._replay.sendBufferedReplayOrFlush(options4); } /** * Get the current session ID. */ getReplayId() { if (!this._replay || !this._replay.isEnabled()) { return; } return this._replay.getSessionId(); } /** * Get the current recording mode. This can be either `session` or `buffer`. * * `session`: Recording the whole session, sending it continuously * `buffer`: Always keeping the last 60s of recording, requires: * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs * - or calling `flush()` to send the replay */ getRecordingMode() { if (!this._replay || !this._replay.isEnabled()) { return; } return this._replay.recordingMode; } /** * Initializes replay. */ _initialize(client) { if (!this._replay) { return; } this._maybeLoadFromReplayCanvasIntegration(client); this._replay.initializeSampling(); } /** Setup the integration. */ _setup(client) { const finalOptions = loadReplayOptionsFromClient(this._initialOptions, client); this._replay = new ReplayContainer({ options: finalOptions, recordingOptions: this._recordingOptions }); } /** Get canvas options from ReplayCanvas integration, if it is also added. */ _maybeLoadFromReplayCanvasIntegration(client) { try { const canvasIntegration = client.getIntegrationByName("ReplayCanvas"); if (!canvasIntegration) { return; } this._replay["_canvas"] = canvasIntegration.getOptions(); } catch (e2) { } } } Replay.__initStatic(); function loadReplayOptionsFromClient(initialOptions, client) { const opt = client.getOptions(); const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) }; const replaysSessionSampleRate = parseSampleRate(opt.replaysSessionSampleRate); const replaysOnErrorSampleRate = parseSampleRate(opt.replaysOnErrorSampleRate); if (replaysSessionSampleRate == null && replaysOnErrorSampleRate == null) { consoleSandbox(() => { console.warn( "Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set." ); }); } if (replaysSessionSampleRate != null) { finalOptions.sessionSampleRate = replaysSessionSampleRate; } if (replaysOnErrorSampleRate != null) { finalOptions.errorSampleRate = replaysOnErrorSampleRate; } return finalOptions; } __name(loadReplayOptionsFromClient, "loadReplayOptionsFromClient"); function _getMergedNetworkHeaders(headers) { return [...DEFAULT_NETWORK_HEADERS, ...headers.map((header3) => header3.toLowerCase())]; } __name(_getMergedNetworkHeaders, "_getMergedNetworkHeaders"); function getReplay() { const client = getClient(); return client && client.getIntegrationByName("Replay"); } __name(getReplay, "getReplay"); var NodeType$2; (function(NodeType3) { NodeType3[NodeType3["Document"] = 0] = "Document"; NodeType3[NodeType3["DocumentType"] = 1] = "DocumentType"; NodeType3[NodeType3["Element"] = 2] = "Element"; NodeType3[NodeType3["Text"] = 3] = "Text"; NodeType3[NodeType3["CDATA"] = 4] = "CDATA"; NodeType3[NodeType3["Comment"] = 5] = "Comment"; })(NodeType$2 || (NodeType$2 = {})); function elementClassMatchesRegex(el, regex2) { for (let eIndex = el.classList.length; eIndex--; ) { const className = el.classList[eIndex]; if (regex2.test(className)) { return true; } } return false; } __name(elementClassMatchesRegex, "elementClassMatchesRegex"); function distanceToMatch(node3, matchPredicate, limit = Infinity, distance2 = 0) { if (!node3) return -1; if (node3.nodeType !== node3.ELEMENT_NODE) return -1; if (distance2 > limit) return -1; if (matchPredicate(node3)) return distance2; return distanceToMatch(node3.parentNode, matchPredicate, limit, distance2 + 1); } __name(distanceToMatch, "distanceToMatch"); function createMatchPredicate(className, selector) { return (node3) => { const el = node3; if (el === null) return false; try { if (className) { if (typeof className === "string") { if (el.matches(`.${className}`)) return true; } else if (elementClassMatchesRegex(el, className)) { return true; } } if (selector && el.matches(selector)) return true; return false; } catch (e2) { return false; } }; } __name(createMatchPredicate, "createMatchPredicate"); const DEPARTED_MIRROR_ACCESS_WARNING = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording."; let _mirror = { map: {}, getId() { console.error(DEPARTED_MIRROR_ACCESS_WARNING); return -1; }, getNode() { console.error(DEPARTED_MIRROR_ACCESS_WARNING); return null; }, removeNodeFromMap() { console.error(DEPARTED_MIRROR_ACCESS_WARNING); }, has() { console.error(DEPARTED_MIRROR_ACCESS_WARNING); return false; }, reset() { console.error(DEPARTED_MIRROR_ACCESS_WARNING); } }; if (typeof window !== "undefined" && window.Proxy && window.Reflect) { _mirror = new Proxy(_mirror, { get(target, prop2, receiver) { if (prop2 === "map") { console.error(DEPARTED_MIRROR_ACCESS_WARNING); } return Reflect.get(target, prop2, receiver); } }); } function hookSetter(target, key, d2, isRevoked, win = window) { const original = win.Object.getOwnPropertyDescriptor(target, key); win.Object.defineProperty(target, key, isRevoked ? d2 : { set(value4) { setTimeout$1(() => { d2.set.call(this, value4); }, 0); if (original && original.set) { original.set.call(this, value4); } } }); return () => hookSetter(target, key, original || {}, true); } __name(hookSetter, "hookSetter"); function patch$1(source, name2, replacement) { try { if (!(name2 in source)) { return () => { }; } const original = source[name2]; const wrapped = replacement(original); if (typeof wrapped === "function") { wrapped.prototype = wrapped.prototype || {}; Object.defineProperties(wrapped, { __rrweb_original__: { enumerable: false, value: original } }); } source[name2] = wrapped; return () => { source[name2] = original; }; } catch (e2) { return () => { }; } } __name(patch$1, "patch$1"); if (!/[1-9][0-9]{12}/.test(Date.now().toString())) ; function closestElementOfNode(node3) { if (!node3) { return null; } const el = node3.nodeType === node3.ELEMENT_NODE ? node3 : node3.parentElement; return el; } __name(closestElementOfNode, "closestElementOfNode"); function isBlocked(node3, blockClass, blockSelector, unblockSelector, checkAncestors) { if (!node3) { return false; } const el = closestElementOfNode(node3); if (!el) { return false; } const blockedPredicate = createMatchPredicate(blockClass, blockSelector); const blockDistance = distanceToMatch(el, blockedPredicate); let unblockDistance = -1; if (blockDistance < 0) { return false; } if (unblockSelector) { unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector)); } if (blockDistance > -1 && unblockDistance < 0) { return true; } return blockDistance < unblockDistance; } __name(isBlocked, "isBlocked"); const cachedImplementations = {}; function getImplementation(name2) { const cached = cachedImplementations[name2]; if (cached) { return cached; } const document2 = window.document; let impl = window[name2]; if (document2 && typeof document2.createElement === "function") { try { const sandbox = document2.createElement("iframe"); sandbox.hidden = true; document2.head.appendChild(sandbox); const contentWindow = sandbox.contentWindow; if (contentWindow && contentWindow[name2]) { impl = contentWindow[name2]; } document2.head.removeChild(sandbox); } catch (e2) { } } return cachedImplementations[name2] = impl.bind(window); } __name(getImplementation, "getImplementation"); function onRequestAnimationFrame(...rest) { return getImplementation("requestAnimationFrame")(...rest); } __name(onRequestAnimationFrame, "onRequestAnimationFrame"); function setTimeout$1(...rest) { return getImplementation("setTimeout")(...rest); } __name(setTimeout$1, "setTimeout$1"); var CanvasContext = /* @__PURE__ */ ((CanvasContext2) => { CanvasContext2[CanvasContext2["2D"] = 0] = "2D"; CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL"; CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2"; return CanvasContext2; })(CanvasContext || {}); let errorHandler; function registerErrorHandler(handler6) { errorHandler = handler6; } __name(registerErrorHandler, "registerErrorHandler"); const callbackWrapper = /* @__PURE__ */ __name((cb) => { if (!errorHandler) { return cb; } const rrwebWrapped = /* @__PURE__ */ __name((...rest) => { try { return cb(...rest); } catch (error2) { if (errorHandler && errorHandler(error2) === true) { return () => { }; } throw error2; } }, "rrwebWrapped"); return rrwebWrapped; }, "callbackWrapper"); var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256); for (var i$3 = 0; i$3 < chars.length; i$3++) { lookup[chars.charCodeAt(i$3)] = i$3; } var encode$5 = /* @__PURE__ */ __name(function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = ""; for (i2 = 0; i2 < len; i2 += 3) { base64 += chars[bytes[i2] >> 2]; base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4]; base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6]; base64 += chars[bytes[i2 + 2] & 63]; } if (len % 3 === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }, "encode$5"); const canvasVarMap = /* @__PURE__ */ new Map(); function variableListFor(ctx, ctor) { let contextMap = canvasVarMap.get(ctx); if (!contextMap) { contextMap = /* @__PURE__ */ new Map(); canvasVarMap.set(ctx, contextMap); } if (!contextMap.has(ctor)) { contextMap.set(ctor, []); } return contextMap.get(ctor); } __name(variableListFor, "variableListFor"); const saveWebGLVar = /* @__PURE__ */ __name((value4, win, ctx) => { if (!value4 || !(isInstanceOfWebGLObject(value4, win) || typeof value4 === "object")) return; const name2 = value4.constructor.name; const list2 = variableListFor(ctx, name2); let index2 = list2.indexOf(value4); if (index2 === -1) { index2 = list2.length; list2.push(value4); } return index2; }, "saveWebGLVar"); function serializeArg(value4, win, ctx) { if (value4 instanceof Array) { return value4.map((arg) => serializeArg(arg, win, ctx)); } else if (value4 === null) { return value4; } else if (value4 instanceof Float32Array || value4 instanceof Float64Array || value4 instanceof Int32Array || value4 instanceof Uint32Array || value4 instanceof Uint8Array || value4 instanceof Uint16Array || value4 instanceof Int16Array || value4 instanceof Int8Array || value4 instanceof Uint8ClampedArray) { const name2 = value4.constructor.name; return { rr_type: name2, args: [Object.values(value4)] }; } else if (value4 instanceof ArrayBuffer) { const name2 = value4.constructor.name; const base64 = encode$5(value4); return { rr_type: name2, base64 }; } else if (value4 instanceof DataView) { const name2 = value4.constructor.name; return { rr_type: name2, args: [ serializeArg(value4.buffer, win, ctx), value4.byteOffset, value4.byteLength ] }; } else if (value4 instanceof HTMLImageElement) { const name2 = value4.constructor.name; const { src } = value4; return { rr_type: name2, src }; } else if (value4 instanceof HTMLCanvasElement) { const name2 = "HTMLImageElement"; const src = value4.toDataURL(); return { rr_type: name2, src }; } else if (value4 instanceof ImageData) { const name2 = value4.constructor.name; return { rr_type: name2, args: [serializeArg(value4.data, win, ctx), value4.width, value4.height] }; } else if (isInstanceOfWebGLObject(value4, win) || typeof value4 === "object") { const name2 = value4.constructor.name; const index2 = saveWebGLVar(value4, win, ctx); return { rr_type: name2, index: index2 }; } return value4; } __name(serializeArg, "serializeArg"); const serializeArgs = /* @__PURE__ */ __name((args, win, ctx) => { return args.map((arg) => serializeArg(arg, win, ctx)); }, "serializeArgs"); const isInstanceOfWebGLObject = /* @__PURE__ */ __name((value4, win) => { const webGLConstructorNames = [ "WebGLActiveInfo", "WebGLBuffer", "WebGLFramebuffer", "WebGLProgram", "WebGLRenderbuffer", "WebGLShader", "WebGLShaderPrecisionFormat", "WebGLTexture", "WebGLUniformLocation", "WebGLVertexArrayObject", "WebGLVertexArrayObjectOES" ]; const supportedWebGLConstructorNames = webGLConstructorNames.filter((name2) => typeof win[name2] === "function"); return Boolean(supportedWebGLConstructorNames.find((name2) => value4 instanceof win[name2])); }, "isInstanceOfWebGLObject"); function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector, unblockSelector) { const handlers2 = []; const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype); for (const prop2 of props2D) { try { if (typeof win.CanvasRenderingContext2D.prototype[prop2] !== "function") { continue; } const restoreHandler = patch$1(win.CanvasRenderingContext2D.prototype, prop2, function(original) { return function(...args) { if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector, true)) { setTimeout$1(() => { const recordArgs = serializeArgs(args, win, this); cb(this.canvas, { type: CanvasContext["2D"], property: prop2, args: recordArgs }); }, 0); } return original.apply(this, args); }; }); handlers2.push(restoreHandler); } catch (e2) { const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop2, { set(v2) { cb(this.canvas, { type: CanvasContext["2D"], property: prop2, args: [v2], setter: true }); } }); handlers2.push(hookHandler); } } return () => { handlers2.forEach((h2) => h2()); }; } __name(initCanvas2DMutationObserver, "initCanvas2DMutationObserver"); function getNormalizedContextName(contextType) { return contextType === "experimental-webgl" ? "webgl" : contextType; } __name(getNormalizedContextName, "getNormalizedContextName"); function initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, setPreserveDrawingBufferToTrue) { const handlers2 = []; try { const restoreHandler = patch$1(win.HTMLCanvasElement.prototype, "getContext", function(original) { return function(contextType, ...args) { if (!isBlocked(this, blockClass, blockSelector, unblockSelector, true)) { const ctxName = getNormalizedContextName(contextType); if (!("__context" in this)) this.__context = ctxName; if (setPreserveDrawingBufferToTrue && ["webgl", "webgl2"].includes(ctxName)) { if (args[0] && typeof args[0] === "object") { const contextAttributes = args[0]; if (!contextAttributes.preserveDrawingBuffer) { contextAttributes.preserveDrawingBuffer = true; } } else { args.splice(0, 1, { preserveDrawingBuffer: true }); } } } return original.apply(this, [contextType, ...args]); }; }); handlers2.push(restoreHandler); } catch (e2) { console.error("failed to patch HTMLCanvasElement.prototype.getContext"); } return () => { handlers2.forEach((h2) => h2()); }; } __name(initCanvasContextObserver, "initCanvasContextObserver"); function patchGLPrototype(prototype2, type, cb, blockClass, blockSelector, unblockSelector, mirror2, win) { const handlers2 = []; const props = Object.getOwnPropertyNames(prototype2); for (const prop2 of props) { if ([ "isContextLost", "canvas", "drawingBufferWidth", "drawingBufferHeight" ].includes(prop2)) { continue; } try { if (typeof prototype2[prop2] !== "function") { continue; } const restoreHandler = patch$1(prototype2, prop2, function(original) { return function(...args) { const result = original.apply(this, args); saveWebGLVar(result, win, this); if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, unblockSelector, true)) { const recordArgs = serializeArgs(args, win, this); const mutation = { type, property: prop2, args: recordArgs }; cb(this.canvas, mutation); } return result; }; }); handlers2.push(restoreHandler); } catch (e2) { const hookHandler = hookSetter(prototype2, prop2, { set(v2) { cb(this.canvas, { type, property: prop2, args: [v2], setter: true }); } }); handlers2.push(hookHandler); } } return handlers2; } __name(patchGLPrototype, "patchGLPrototype"); function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, unblockSelector, mirror2) { const handlers2 = []; handlers2.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, unblockSelector, mirror2, win)); if (typeof win.WebGL2RenderingContext !== "undefined") { handlers2.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, unblockSelector, mirror2, win)); } return () => { handlers2.forEach((h2) => h2()); }; } __name(initCanvasWebGLMutationObserver, "initCanvasWebGLMutationObserver"); var r$2 = `for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="undefined"==typeof Uint8Array?[]:new Uint8Array(256),a=0;a<64;a++)t[e.charCodeAt(a)]=a;var n=function(t){var a,n=new Uint8Array(t),r=n.length,s="";for(a=0;a>2],s+=e[(3&n[a])<<4|n[a+1]>>4],s+=e[(15&n[a+1])<<2|n[a+2]>>6],s+=e[63&n[a+2]];return r%3==2?s=s.substring(0,s.length-1)+"=":r%3==1&&(s=s.substring(0,s.length-2)+"=="),s};const r=new Map,s=new Map;const i=self;i.onmessage=async function(e){if(!("OffscreenCanvas"in globalThis))return i.postMessage({id:e.data.id});{const{id:t,bitmap:a,width:o,height:f,maxCanvasSize:c,dataURLOptions:g}=e.data,u=async function(e,t,a){const r=e+"-"+t;if("OffscreenCanvas"in globalThis){if(s.has(r))return s.get(r);const i=new OffscreenCanvas(e,t);i.getContext("2d");const o=await i.convertToBlob(a),f=await o.arrayBuffer(),c=n(f);return s.set(r,c),c}return""}(o,f,g),[h,d]=function(e,t,a){if(!a)return[e,t];const[n,r]=a;if(e<=n&&t<=r)return[e,t];let s=e,i=t;return s>n&&(i=Math.floor(n*t/e),s=n),i>r&&(s=Math.floor(r*e/t),i=r),[s,i]}(o,f,c),l=new OffscreenCanvas(h,d),w=l.getContext("bitmaprenderer"),p=h===o&&d===f?a:await createImageBitmap(a,{resizeWidth:h,resizeHeight:d,resizeQuality:"low"});w.transferFromImageBitmap(p),a.close();const y=await l.convertToBlob(g),v=y.type,b=await y.arrayBuffer(),m=n(b);if(p.close(),!r.has(t)&&await u===m)return r.set(t,m),i.postMessage({id:t});if(r.get(t)===m)return i.postMessage({id:t});i.postMessage({id:t,type:v,base64:m,width:o,height:f}),r.set(t,m)}};`; function t$2() { const t2 = new Blob([r$2]); return URL.createObjectURL(t2); } __name(t$2, "t$2"); class CanvasManager { static { __name(this, "CanvasManager"); } reset() { this.pendingCanvasMutations.clear(); this.restoreHandlers.forEach((handler6) => { try { handler6(); } catch (e2) { } }); this.restoreHandlers = []; this.windowsSet = /* @__PURE__ */ new WeakSet(); this.windows = []; this.shadowDoms = /* @__PURE__ */ new Set(); _optionalChain([this, "access", (_2) => _2.worker, "optionalAccess", (_2) => _2.terminate, "call", (_3) => _3()]); this.worker = null; this.snapshotInProgressMap = /* @__PURE__ */ new Map(); } freeze() { this.frozen = true; } unfreeze() { this.frozen = false; } lock() { this.locked = true; } unlock() { this.locked = false; } constructor(options4) { this.pendingCanvasMutations = /* @__PURE__ */ new Map(); this.rafStamps = { latestId: 0, invokeId: null }; this.shadowDoms = /* @__PURE__ */ new Set(); this.windowsSet = /* @__PURE__ */ new WeakSet(); this.windows = []; this.restoreHandlers = []; this.frozen = false; this.locked = false; this.snapshotInProgressMap = /* @__PURE__ */ new Map(); this.worker = null; this.processMutation = (target, mutation) => { const newFrame = this.rafStamps.invokeId && this.rafStamps.latestId !== this.rafStamps.invokeId; if (newFrame || !this.rafStamps.invokeId) this.rafStamps.invokeId = this.rafStamps.latestId; if (!this.pendingCanvasMutations.has(target)) { this.pendingCanvasMutations.set(target, []); } this.pendingCanvasMutations.get(target).push(mutation); }; const { sampling = "all", win, blockClass, blockSelector, unblockSelector, maxCanvasSize, recordCanvas, dataURLOptions, errorHandler: errorHandler2 } = options4; this.mutationCb = options4.mutationCb; this.mirror = options4.mirror; this.options = options4; if (errorHandler2) { registerErrorHandler(errorHandler2); } if (recordCanvas && typeof sampling === "number" || options4.enableManualSnapshot) { this.worker = this.initFPSWorker(); } this.addWindow(win); if (options4.enableManualSnapshot) { return; } callbackWrapper(() => { if (recordCanvas && sampling === "all") { this.startRAFTimestamping(); this.startPendingCanvasMutationFlusher(); } if (recordCanvas && typeof sampling === "number") { this.initCanvasFPSObserver(sampling, blockClass, blockSelector, unblockSelector, maxCanvasSize, { dataURLOptions }); } })(); } addWindow(win) { const { sampling = "all", blockClass, blockSelector, unblockSelector, recordCanvas, enableManualSnapshot } = this.options; if (this.windowsSet.has(win)) return; if (enableManualSnapshot) { this.windowsSet.add(win); this.windows.push(new WeakRef(win)); return; } callbackWrapper(() => { if (recordCanvas && sampling === "all") { this.initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector); } if (recordCanvas && typeof sampling === "number") { const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, true); this.restoreHandlers.push(() => { canvasContextReset(); }); } })(); this.windowsSet.add(win); this.windows.push(new WeakRef(win)); } addShadowRoot(shadowRoot) { this.shadowDoms.add(new WeakRef(shadowRoot)); } resetShadowRoots() { this.shadowDoms = /* @__PURE__ */ new Set(); } initFPSWorker() { const worker = new Worker(t$2()); worker.onmessage = (e2) => { const data25 = e2.data; const { id: id3 } = data25; this.snapshotInProgressMap.set(id3, false); if (!("base64" in data25)) return; const { base64, type, width: width2, height } = data25; this.mutationCb({ id: id3, type: CanvasContext["2D"], commands: [ { property: "clearRect", args: [0, 0, width2, height] }, { property: "drawImage", args: [ { rr_type: "ImageBitmap", args: [ { rr_type: "Blob", data: [{ rr_type: "ArrayBuffer", base64 }], type } ] }, 0, 0, width2, height ] } ] }); }; return worker; } initCanvasFPSObserver(fps, blockClass, blockSelector, unblockSelector, maxCanvasSize, options4) { const rafId = this.takeSnapshot(false, fps, blockClass, blockSelector, unblockSelector, maxCanvasSize, options4.dataURLOptions); this.restoreHandlers.push(() => { cancelAnimationFrame(rafId); }); } initCanvasMutationObserver(win, blockClass, blockSelector, unblockSelector) { const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector, false); const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector); const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror); this.restoreHandlers.push(() => { canvasContextReset(); canvas2DReset(); canvasWebGL1and2Reset(); }); } snapshot(canvasElement) { const { options: options4 } = this; const rafId = this.takeSnapshot(true, options4.sampling === "all" ? 2 : options4.sampling || 2, options4.blockClass, options4.blockSelector, options4.unblockSelector, options4.maxCanvasSize, options4.dataURLOptions, canvasElement); this.restoreHandlers.push(() => { cancelAnimationFrame(rafId); }); } takeSnapshot(isManualSnapshot, fps, blockClass, blockSelector, unblockSelector, maxCanvasSize, dataURLOptions, canvasElement) { const timeBetweenSnapshots = 1e3 / fps; let lastSnapshotTime = 0; let rafId; const getCanvas = /* @__PURE__ */ __name((canvasElement2) => { if (canvasElement2) { return [canvasElement2]; } const matchedCanvas = []; const searchCanvas = /* @__PURE__ */ __name((root27) => { root27.querySelectorAll("canvas").forEach((canvas) => { if (!isBlocked(canvas, blockClass, blockSelector, unblockSelector)) { matchedCanvas.push(canvas); } }); }, "searchCanvas"); for (const item3 of this.windows) { const window2 = item3.deref(); if (window2) { searchCanvas(window2.document); } } for (const item3 of this.shadowDoms) { const shadowRoot = item3.deref(); if (shadowRoot) { searchCanvas(shadowRoot); } } return matchedCanvas; }, "getCanvas"); const takeCanvasSnapshots = /* @__PURE__ */ __name((timestamp2) => { if (!this.windows.length) { return; } if (lastSnapshotTime && timestamp2 - lastSnapshotTime < timeBetweenSnapshots) { rafId = onRequestAnimationFrame(takeCanvasSnapshots); return; } lastSnapshotTime = timestamp2; getCanvas(canvasElement).forEach((canvas) => { if (!this.mirror.hasNode(canvas)) { return; } const id3 = this.mirror.getId(canvas); if (this.snapshotInProgressMap.get(id3)) return; if (!canvas.width || !canvas.height) return; this.snapshotInProgressMap.set(id3, true); if (!isManualSnapshot && ["webgl", "webgl2"].includes(canvas.__context)) { const context = canvas.getContext(canvas.__context); if (_optionalChain([context, "optionalAccess", (_4) => _4.getContextAttributes, "call", (_5) => _5(), "optionalAccess", (_6) => _6.preserveDrawingBuffer]) === false) { context.clear(context.COLOR_BUFFER_BIT); } } createImageBitmap(canvas).then((bitmap) => { _optionalChain([this, "access", (_7) => _7.worker, "optionalAccess", (_8) => _8.postMessage, "call", (_9) => _9({ id: id3, bitmap, width: canvas.width, height: canvas.height, dataURLOptions, maxCanvasSize }, [bitmap])]); }).catch((error2) => { callbackWrapper(() => { throw error2; })(); }); }); if (!isManualSnapshot) { rafId = onRequestAnimationFrame(takeCanvasSnapshots); } }, "takeCanvasSnapshots"); rafId = onRequestAnimationFrame(takeCanvasSnapshots); return rafId; } startPendingCanvasMutationFlusher() { onRequestAnimationFrame(() => this.flushPendingCanvasMutations()); } startRAFTimestamping() { const setLatestRAFTimestamp = /* @__PURE__ */ __name((timestamp2) => { this.rafStamps.latestId = timestamp2; onRequestAnimationFrame(setLatestRAFTimestamp); }, "setLatestRAFTimestamp"); onRequestAnimationFrame(setLatestRAFTimestamp); } flushPendingCanvasMutations() { this.pendingCanvasMutations.forEach((values, canvas) => { const id3 = this.mirror.getId(canvas); this.flushPendingCanvasMutationFor(canvas, id3); }); onRequestAnimationFrame(() => this.flushPendingCanvasMutations()); } flushPendingCanvasMutationFor(canvas, id3) { if (this.frozen || this.locked) { return; } const valuesWithType = this.pendingCanvasMutations.get(canvas); if (!valuesWithType || id3 === -1) return; const values = valuesWithType.map((value4) => { const { type: type2, ...rest } = value4; return rest; }); const { type } = valuesWithType[0]; this.mutationCb({ id: id3, type, commands: values }); this.pendingCanvasMutations.delete(canvas); } } const CANVAS_QUALITY = { low: { sampling: { canvas: 1 }, dataURLOptions: { type: "image/webp", quality: 0.25 } }, medium: { sampling: { canvas: 2 }, dataURLOptions: { type: "image/webp", quality: 0.4 } }, high: { sampling: { canvas: 4 }, dataURLOptions: { type: "image/webp", quality: 0.5 } } }; const INTEGRATION_NAME$3 = "ReplayCanvas"; const DEFAULT_MAX_CANVAS_SIZE = 1280; const _replayCanvasIntegration = /* @__PURE__ */ __name((options4 = {}) => { const [maxCanvasWidth, maxCanvasHeight] = options4.maxCanvasSize || []; const _canvasOptions = { quality: options4.quality || "medium", enableManualSnapshot: options4.enableManualSnapshot, maxCanvasSize: [ maxCanvasWidth ? Math.min(maxCanvasWidth, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE, maxCanvasHeight ? Math.min(maxCanvasHeight, DEFAULT_MAX_CANVAS_SIZE) : DEFAULT_MAX_CANVAS_SIZE ] }; let canvasManagerResolve; const _canvasManager = new Promise((resolve2) => canvasManagerResolve = resolve2); return { name: INTEGRATION_NAME$3, getOptions() { const { quality, enableManualSnapshot, maxCanvasSize } = _canvasOptions; return { enableManualSnapshot, recordCanvas: true, getCanvasManager: /* @__PURE__ */ __name((getCanvasManagerOptions) => { const manager = new CanvasManager({ ...getCanvasManagerOptions, enableManualSnapshot, maxCanvasSize, errorHandler: /* @__PURE__ */ __name((err) => { try { if (typeof err === "object") { err.__rrweb__ = true; } } catch (error2) { } }, "errorHandler") }); canvasManagerResolve(manager); return manager; }, "getCanvasManager"), ...CANVAS_QUALITY[quality || "medium"] || CANVAS_QUALITY.medium }; }, async snapshot(canvasElement) { const canvasManager = await _canvasManager; canvasManager.snapshot(canvasElement); } }; }, "_replayCanvasIntegration"); const replayCanvasIntegration = defineIntegration( _replayCanvasIntegration ); const WINDOW = GLOBAL_OBJ; const DOCUMENT = WINDOW.document; const NAVIGATOR = WINDOW.navigator; const TRIGGER_LABEL = "Report a Bug"; const CANCEL_BUTTON_LABEL = "Cancel"; const SUBMIT_BUTTON_LABEL = "Send Bug Report"; const CONFIRM_BUTTON_LABEL = "Confirm"; const FORM_TITLE = "Report a Bug"; const EMAIL_PLACEHOLDER = "your.email@example.org"; const EMAIL_LABEL = "Email"; const MESSAGE_PLACEHOLDER = "What's the bug? What did you expect?"; const MESSAGE_LABEL = "Description"; const NAME_PLACEHOLDER = "Your Name"; const NAME_LABEL = "Name"; const SUCCESS_MESSAGE_TEXT = "Thank you for your report!"; const IS_REQUIRED_LABEL = "(required)"; const ADD_SCREENSHOT_LABEL = "Add a screenshot"; const REMOVE_SCREENSHOT_LABEL = "Remove screenshot"; const FEEDBACK_WIDGET_SOURCE = "widget"; const FEEDBACK_API_SOURCE = "api"; const SUCCESS_MESSAGE_TIMEOUT = 5e3; const sendFeedback = /* @__PURE__ */ __name((params, hint = { includeReplay: true }) => { if (!params.message) { throw new Error("Unable to submit feedback with empty message"); } const client = getClient(); if (!client) { throw new Error("No client setup, cannot send feedback."); } if (params.tags && Object.keys(params.tags).length) { getCurrentScope$1().setTags(params.tags); } const eventId = captureFeedback( { source: FEEDBACK_API_SOURCE, url: getLocationHref(), ...params }, hint ); return new Promise((resolve2, reject3) => { const timeout = setTimeout(() => reject3("Unable to determine if Feedback was correctly sent."), 5e3); const cleanup = client.on("afterSendEvent", (event, response) => { if (event.event_id !== eventId) { return; } clearTimeout(timeout); cleanup(); if (response && typeof response.statusCode === "number" && response.statusCode >= 200 && response.statusCode < 300) { return resolve2(eventId); } if (response && typeof response.statusCode === "number" && response.statusCode === 0) { return reject3( "Unable to send Feedback. This is because of network issues, or because you are using an ad-blocker." ); } if (response && typeof response.statusCode === "number" && response.statusCode === 403) { return reject3( "Unable to send Feedback. This could be because this domain is not in your list of allowed domains." ); } return reject3( "Unable to send Feedback. This could be because of network issues, or because you are using an ad-blocker" ); }); }); }, "sendFeedback"); const DEBUG_BUILD$1 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; function isScreenshotSupported() { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(NAVIGATOR.userAgent)) { return false; } if (/Macintosh/i.test(NAVIGATOR.userAgent) && NAVIGATOR.maxTouchPoints && NAVIGATOR.maxTouchPoints > 1) { return false; } if (!isSecureContext) { return false; } return true; } __name(isScreenshotSupported, "isScreenshotSupported"); function mergeOptions$2(defaultOptions2, optionOverrides) { return { ...defaultOptions2, ...optionOverrides, tags: { ...defaultOptions2.tags, ...optionOverrides.tags }, onFormOpen: /* @__PURE__ */ __name(() => { optionOverrides.onFormOpen && optionOverrides.onFormOpen(); defaultOptions2.onFormOpen && defaultOptions2.onFormOpen(); }, "onFormOpen"), onFormClose: /* @__PURE__ */ __name(() => { optionOverrides.onFormClose && optionOverrides.onFormClose(); defaultOptions2.onFormClose && defaultOptions2.onFormClose(); }, "onFormClose"), onSubmitSuccess: /* @__PURE__ */ __name((data25) => { optionOverrides.onSubmitSuccess && optionOverrides.onSubmitSuccess(data25); defaultOptions2.onSubmitSuccess && defaultOptions2.onSubmitSuccess(data25); }, "onSubmitSuccess"), onSubmitError: /* @__PURE__ */ __name((error2) => { optionOverrides.onSubmitError && optionOverrides.onSubmitError(error2); defaultOptions2.onSubmitError && defaultOptions2.onSubmitError(error2); }, "onSubmitError"), onFormSubmitted: /* @__PURE__ */ __name(() => { optionOverrides.onFormSubmitted && optionOverrides.onFormSubmitted(); defaultOptions2.onFormSubmitted && defaultOptions2.onFormSubmitted(); }, "onFormSubmitted"), themeDark: { ...defaultOptions2.themeDark, ...optionOverrides.themeDark }, themeLight: { ...defaultOptions2.themeLight, ...optionOverrides.themeLight } }; } __name(mergeOptions$2, "mergeOptions$2"); function createActorStyles(styleNonce) { const style2 = DOCUMENT.createElement("style"); style2.textContent = ` .widget__actor { position: fixed; z-index: var(--z-index); margin: var(--page-margin); inset: var(--actor-inset); display: flex; align-items: center; gap: 8px; padding: 16px; font-family: inherit; font-size: var(--font-size); font-weight: 600; line-height: 1.14em; text-decoration: none; background: var(--actor-background, var(--background)); border-radius: var(--actor-border-radius, 1.7em/50%); border: var(--actor-border, var(--border)); box-shadow: var(--actor-box-shadow, var(--box-shadow)); color: var(--actor-color, var(--foreground)); fill: var(--actor-color, var(--foreground)); cursor: pointer; opacity: 1; transition: transform 0.2s ease-in-out; transform: translate(0, 0) scale(1); } .widget__actor[aria-hidden="true"] { opacity: 0; pointer-events: none; visibility: hidden; transform: translate(0, 16px) scale(0.98); } .widget__actor:hover { background: var(--actor-hover-background, var(--background)); filter: var(--interactive-filter); } .widget__actor svg { width: 1.14em; height: 1.14em; } @media (max-width: 600px) { .widget__actor span { display: none; } } `; if (styleNonce) { style2.setAttribute("nonce", styleNonce); } return style2; } __name(createActorStyles, "createActorStyles"); function setAttributesNS(el, attributes) { Object.entries(attributes).forEach(([key, val]) => { el.setAttributeNS(null, key, val); }); return el; } __name(setAttributesNS, "setAttributesNS"); const SIZE$1 = 20; const XMLNS$2 = "http://www.w3.org/2000/svg"; function FeedbackIcon() { const createElementNS = /* @__PURE__ */ __name((tagName) => WINDOW.document.createElementNS(XMLNS$2, tagName), "createElementNS"); const svg = setAttributesNS(createElementNS("svg"), { width: `${SIZE$1}`, height: `${SIZE$1}`, viewBox: `0 0 ${SIZE$1} ${SIZE$1}`, fill: "var(--actor-color, var(--foreground))" }); const g2 = setAttributesNS(createElementNS("g"), { clipPath: "url(#clip0_57_80)" }); const path = setAttributesNS(createElementNS("path"), { ["fill-rule"]: "evenodd", ["clip-rule"]: "evenodd", d: "M15.6622 15H12.3997C12.2129 14.9959 12.031 14.9396 11.8747 14.8375L8.04965 12.2H7.49956V19.1C7.4875 19.3348 7.3888 19.5568 7.22256 19.723C7.05632 19.8892 6.83435 19.9879 6.59956 20H2.04956C1.80193 19.9968 1.56535 19.8969 1.39023 19.7218C1.21511 19.5467 1.1153 19.3101 1.11206 19.0625V12.2H0.949652C0.824431 12.2017 0.700142 12.1783 0.584123 12.1311C0.468104 12.084 0.362708 12.014 0.274155 11.9255C0.185602 11.8369 0.115689 11.7315 0.0685419 11.6155C0.0213952 11.4995 -0.00202913 11.3752 -0.00034808 11.25V3.75C-0.00900498 3.62067 0.0092504 3.49095 0.0532651 3.36904C0.0972798 3.24712 0.166097 3.13566 0.255372 3.04168C0.344646 2.94771 0.452437 2.87327 0.571937 2.82307C0.691437 2.77286 0.82005 2.74798 0.949652 2.75H8.04965L11.8747 0.1625C12.031 0.0603649 12.2129 0.00407221 12.3997 0H15.6622C15.9098 0.00323746 16.1464 0.103049 16.3215 0.278167C16.4966 0.453286 16.5964 0.689866 16.5997 0.9375V3.25269C17.3969 3.42959 18.1345 3.83026 18.7211 4.41679C19.5322 5.22788 19.9878 6.32796 19.9878 7.47502C19.9878 8.62209 19.5322 9.72217 18.7211 10.5333C18.1345 11.1198 17.3969 11.5205 16.5997 11.6974V14.0125C16.6047 14.1393 16.5842 14.2659 16.5395 14.3847C16.4948 14.5035 16.4268 14.6121 16.3394 14.7042C16.252 14.7962 16.147 14.8698 16.0307 14.9206C15.9144 14.9714 15.7891 14.9984 15.6622 15ZM1.89695 10.325H1.88715V4.625H8.33715C8.52423 4.62301 8.70666 4.56654 8.86215 4.4625L12.6872 1.875H14.7247V13.125H12.6872L8.86215 10.4875C8.70666 10.3835 8.52423 10.327 8.33715 10.325H2.20217C2.15205 10.3167 2.10102 10.3125 2.04956 10.3125C1.9981 10.3125 1.94708 10.3167 1.89695 10.325ZM2.98706 12.2V18.1625H5.66206V12.2H2.98706ZM16.5997 9.93612V5.01393C16.6536 5.02355 16.7072 5.03495 16.7605 5.04814C17.1202 5.13709 17.4556 5.30487 17.7425 5.53934C18.0293 5.77381 18.2605 6.06912 18.4192 6.40389C18.578 6.73866 18.6603 7.10452 18.6603 7.47502C18.6603 7.84552 18.578 8.21139 18.4192 8.54616C18.2605 8.88093 18.0293 9.17624 17.7425 9.41071C17.4556 9.64518 17.1202 9.81296 16.7605 9.90191C16.7072 9.91509 16.6536 9.9265 16.5997 9.93612Z" }); svg.appendChild(g2).appendChild(path); const speakerDefs = createElementNS("defs"); const speakerClipPathDef = setAttributesNS(createElementNS("clipPath"), { id: "clip0_57_80" }); const speakerRect = setAttributesNS(createElementNS("rect"), { width: `${SIZE$1}`, height: `${SIZE$1}`, fill: "white" }); speakerClipPathDef.appendChild(speakerRect); speakerDefs.appendChild(speakerClipPathDef); svg.appendChild(speakerDefs).appendChild(speakerClipPathDef).appendChild(speakerRect); return svg; } __name(FeedbackIcon, "FeedbackIcon"); function Actor({ triggerLabel, triggerAriaLabel, shadow, styleNonce }) { const el = DOCUMENT.createElement("button"); el.type = "button"; el.className = "widget__actor"; el.ariaHidden = "false"; el.ariaLabel = triggerAriaLabel || triggerLabel || TRIGGER_LABEL; el.appendChild(FeedbackIcon()); if (triggerLabel) { const label5 = DOCUMENT.createElement("span"); label5.appendChild(DOCUMENT.createTextNode(triggerLabel)); el.appendChild(label5); } const style2 = createActorStyles(styleNonce); return { el, appendToDom() { shadow.appendChild(style2); shadow.appendChild(el); }, removeFromDom() { shadow.removeChild(el); shadow.removeChild(style2); }, show() { el.ariaHidden = "false"; }, hide() { el.ariaHidden = "true"; } }; } __name(Actor, "Actor"); const PURPLE = "rgba(88, 74, 192, 1)"; const DEFAULT_LIGHT = { foreground: "#2b2233", background: "#ffffff", accentForeground: "white", accentBackground: PURPLE, successColor: "#268d75", errorColor: "#df3338", border: "1.5px solid rgba(41, 35, 47, 0.13)", boxShadow: "0px 4px 24px 0px rgba(43, 34, 51, 0.12)", outline: "1px auto var(--accent-background)", interactiveFilter: "brightness(95%)" }; const DEFAULT_DARK = { foreground: "#ebe6ef", background: "#29232f", accentForeground: "white", accentBackground: PURPLE, successColor: "#2da98c", errorColor: "#f55459", border: "1.5px solid rgba(235, 230, 239, 0.15)", boxShadow: "0px 4px 24px 0px rgba(43, 34, 51, 0.12)", outline: "1px auto var(--accent-background)", interactiveFilter: "brightness(150%)" }; function getThemedCssVariables(theme42) { return ` --foreground: ${theme42.foreground}; --background: ${theme42.background}; --accent-foreground: ${theme42.accentForeground}; --accent-background: ${theme42.accentBackground}; --success-color: ${theme42.successColor}; --error-color: ${theme42.errorColor}; --border: ${theme42.border}; --box-shadow: ${theme42.boxShadow}; --outline: ${theme42.outline}; --interactive-filter: ${theme42.interactiveFilter}; `; } __name(getThemedCssVariables, "getThemedCssVariables"); function createMainStyles({ colorScheme, themeDark, themeLight, styleNonce }) { const style2 = DOCUMENT.createElement("style"); style2.textContent = ` :host { --font-family: system-ui, 'Helvetica Neue', Arial, sans-serif; --font-size: 14px; --z-index: 100000; --page-margin: 16px; --inset: auto 0 0 auto; --actor-inset: var(--inset); font-family: var(--font-family); font-size: var(--font-size); ${colorScheme !== "system" ? "color-scheme: only light;" : ""} ${getThemedCssVariables( colorScheme === "dark" ? { ...DEFAULT_DARK, ...themeDark } : { ...DEFAULT_LIGHT, ...themeLight } )} } ${colorScheme === "system" ? ` @media (prefers-color-scheme: dark) { :host { ${getThemedCssVariables({ ...DEFAULT_DARK, ...themeDark })} } }` : ""} } `; if (styleNonce) { style2.setAttribute("nonce", styleNonce); } return style2; } __name(createMainStyles, "createMainStyles"); const buildFeedbackIntegration = /* @__PURE__ */ __name(({ lazyLoadIntegration: lazyLoadIntegration2, getModalIntegration, getScreenshotIntegration }) => { const feedbackIntegration = /* @__PURE__ */ __name(({ // FeedbackGeneralConfiguration id: id3 = "sentry-feedback", autoInject = true, showBranding = true, isEmailRequired = false, isNameRequired = false, showEmail = true, showName = true, enableScreenshot = true, useSentryUser = { email: "email", name: "username" }, tags, styleNonce, scriptNonce, // FeedbackThemeConfiguration colorScheme = "system", themeLight = {}, themeDark = {}, // FeedbackTextConfiguration addScreenshotButtonLabel = ADD_SCREENSHOT_LABEL, cancelButtonLabel = CANCEL_BUTTON_LABEL, confirmButtonLabel = CONFIRM_BUTTON_LABEL, emailLabel = EMAIL_LABEL, emailPlaceholder = EMAIL_PLACEHOLDER, formTitle = FORM_TITLE, isRequiredLabel = IS_REQUIRED_LABEL, messageLabel = MESSAGE_LABEL, messagePlaceholder = MESSAGE_PLACEHOLDER, nameLabel = NAME_LABEL, namePlaceholder = NAME_PLACEHOLDER, removeScreenshotButtonLabel = REMOVE_SCREENSHOT_LABEL, submitButtonLabel = SUBMIT_BUTTON_LABEL, successMessageText = SUCCESS_MESSAGE_TEXT, triggerLabel = TRIGGER_LABEL, triggerAriaLabel = "", // FeedbackCallbacks onFormOpen, onFormClose, onSubmitSuccess, onSubmitError, onFormSubmitted } = {}) => { const _options = { id: id3, autoInject, showBranding, isEmailRequired, isNameRequired, showEmail, showName, enableScreenshot, useSentryUser, tags, styleNonce, scriptNonce, colorScheme, themeDark, themeLight, triggerLabel, triggerAriaLabel, cancelButtonLabel, submitButtonLabel, confirmButtonLabel, formTitle, emailLabel, emailPlaceholder, messageLabel, messagePlaceholder, nameLabel, namePlaceholder, successMessageText, isRequiredLabel, addScreenshotButtonLabel, removeScreenshotButtonLabel, onFormClose, onFormOpen, onSubmitError, onSubmitSuccess, onFormSubmitted }; let _shadow = null; let _subscriptions = []; const _createShadow = /* @__PURE__ */ __name((options4) => { if (!_shadow) { const host = DOCUMENT.createElement("div"); host.id = String(options4.id); DOCUMENT.body.appendChild(host); _shadow = host.attachShadow({ mode: "open" }); _shadow.appendChild(createMainStyles(options4)); } return _shadow; }, "_createShadow"); const _loadAndRenderDialog = /* @__PURE__ */ __name(async (options4) => { const screenshotRequired = options4.enableScreenshot && isScreenshotSupported(); let modalIntegration; let screenshotIntegration; try { const modalIntegrationFn = getModalIntegration ? getModalIntegration() : await lazyLoadIntegration2("feedbackModalIntegration", scriptNonce); modalIntegration = modalIntegrationFn(); addIntegration(modalIntegration); } catch (e2) { DEBUG_BUILD$1 && logger$2.error( "[Feedback] Error when trying to load feedback integrations. Try using `feedbackSyncIntegration` in your `Sentry.init`." ); throw new Error("[Feedback] Missing feedback modal integration!"); } try { const screenshotIntegrationFn = screenshotRequired ? getScreenshotIntegration ? getScreenshotIntegration() : await lazyLoadIntegration2("feedbackScreenshotIntegration", scriptNonce) : void 0; if (screenshotIntegrationFn) { screenshotIntegration = screenshotIntegrationFn(); addIntegration(screenshotIntegration); } } catch (e2) { DEBUG_BUILD$1 && logger$2.error("[Feedback] Missing feedback screenshot integration. Proceeding without screenshots."); } const dialog = modalIntegration.createDialog({ options: { ...options4, onFormClose: /* @__PURE__ */ __name(() => { dialog && dialog.close(); options4.onFormClose && options4.onFormClose(); }, "onFormClose"), onFormSubmitted: /* @__PURE__ */ __name(() => { dialog && dialog.close(); options4.onFormSubmitted && options4.onFormSubmitted(); }, "onFormSubmitted") }, screenshotIntegration, sendFeedback, shadow: _createShadow(options4) }); return dialog; }, "_loadAndRenderDialog"); const _attachTo = /* @__PURE__ */ __name((el, optionOverrides = {}) => { const mergedOptions = mergeOptions$2(_options, optionOverrides); const targetEl = typeof el === "string" ? DOCUMENT.querySelector(el) : typeof el.addEventListener === "function" ? el : null; if (!targetEl) { DEBUG_BUILD$1 && logger$2.error("[Feedback] Unable to attach to target element"); throw new Error("Unable to attach to target element"); } let dialog = null; const handleClick2 = /* @__PURE__ */ __name(async () => { if (!dialog) { dialog = await _loadAndRenderDialog({ ...mergedOptions, onFormSubmitted: /* @__PURE__ */ __name(() => { dialog && dialog.removeFromDom(); mergedOptions.onFormSubmitted && mergedOptions.onFormSubmitted(); }, "onFormSubmitted") }); } dialog.appendToDom(); dialog.open(); }, "handleClick"); targetEl.addEventListener("click", handleClick2); const unsubscribe = /* @__PURE__ */ __name(() => { _subscriptions = _subscriptions.filter((sub) => sub !== unsubscribe); dialog && dialog.removeFromDom(); dialog = null; targetEl.removeEventListener("click", handleClick2); }, "unsubscribe"); _subscriptions.push(unsubscribe); return unsubscribe; }, "_attachTo"); const _createActor = /* @__PURE__ */ __name((optionOverrides = {}) => { const mergedOptions = mergeOptions$2(_options, optionOverrides); const shadow = _createShadow(mergedOptions); const actor = Actor({ triggerLabel: mergedOptions.triggerLabel, triggerAriaLabel: mergedOptions.triggerAriaLabel, shadow, styleNonce }); _attachTo(actor.el, { ...mergedOptions, onFormOpen() { actor.hide(); }, onFormClose() { actor.show(); }, onFormSubmitted() { actor.show(); } }); return actor; }, "_createActor"); return { name: "Feedback", setupOnce() { if (!isBrowser$1() || !_options.autoInject) { return; } if (DOCUMENT.readyState === "loading") { DOCUMENT.addEventListener("DOMContentLoaded", () => _createActor().appendToDom()); } else { _createActor().appendToDom(); } }, /** * Adds click listener to the element to open a feedback dialog * * The returned function can be used to remove the click listener */ attachTo: _attachTo, /** * Creates a new widget which is composed of a Button which triggers a Dialog. * Accepts partial options to override any options passed to constructor. */ createWidget(optionOverrides = {}) { const actor = _createActor(mergeOptions$2(_options, optionOverrides)); actor.appendToDom(); return actor; }, /** * Creates a new Form which you can * Accepts partial options to override any options passed to constructor. */ async createForm(optionOverrides = {}) { return _loadAndRenderDialog(mergeOptions$2(_options, optionOverrides)); }, /** * Removes the Feedback integration (including host, shadow DOM, and all widgets) */ remove() { if (_shadow) { _shadow.parentElement && _shadow.parentElement.remove(); _shadow = null; } _subscriptions.forEach((sub) => sub()); _subscriptions = []; } }; }, "feedbackIntegration"); return feedbackIntegration; }, "buildFeedbackIntegration"); function getFeedback() { const client = getClient(); return client && client.getIntegrationByName("Feedback"); } __name(getFeedback, "getFeedback"); var n, l$1, u$1, i$1, o$1, r$1, f$1, c$1 = {}, s$1 = [], a$1 = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, h$1 = Array.isArray; function v$1(n2, l2) { for (var u2 in l2) n2[u2] = l2[u2]; return n2; } __name(v$1, "v$1"); function p$1(n2) { var l2 = n2.parentNode; l2 && l2.removeChild(n2); } __name(p$1, "p$1"); function y$1(l2, u2, t2) { var i2, o2, r2, f2 = {}; for (r2 in u2) "key" == r2 ? i2 = u2[r2] : "ref" == r2 ? o2 = u2[r2] : f2[r2] = u2[r2]; if (arguments.length > 2 && (f2.children = arguments.length > 3 ? n.call(arguments, 2) : t2), "function" == typeof l2 && null != l2.defaultProps) for (r2 in l2.defaultProps) void 0 === f2[r2] && (f2[r2] = l2.defaultProps[r2]); return d$1(l2, f2, i2, o2, null); } __name(y$1, "y$1"); function d$1(n2, t2, i2, o2, r2) { var f2 = { type: n2, props: t2, key: i2, ref: o2, __k: null, __: null, __b: 0, __e: null, __d: void 0, __c: null, constructor: void 0, __v: null == r2 ? ++u$1 : r2, __i: -1, __u: 0 }; return null == r2 && null != l$1.vnode && l$1.vnode(f2), f2; } __name(d$1, "d$1"); function g$1$1(n2) { return n2.children; } __name(g$1$1, "g$1$1"); function b$1(n2, l2) { this.props = n2, this.context = l2; } __name(b$1, "b$1"); function m$1(n2, l2) { if (null == l2) return n2.__ ? m$1(n2.__, n2.__i + 1) : null; for (var u2; l2 < n2.__k.length; l2++) if (null != (u2 = n2.__k[l2]) && null != u2.__e) return u2.__e; return "function" == typeof n2.type ? m$1(n2) : null; } __name(m$1, "m$1"); function w$1(n2, u2, t2) { var i2, o2 = n2.__v, r2 = o2.__e, f2 = n2.__P; if (f2) return (i2 = v$1({}, o2)).__v = o2.__v + 1, l$1.vnode && l$1.vnode(i2), M(f2, i2, o2, n2.__n, void 0 !== f2.ownerSVGElement, 32 & o2.__u ? [r2] : null, u2, null == r2 ? m$1(o2) : r2, !!(32 & o2.__u), t2), i2.__.__k[i2.__i] = i2, i2.__d = void 0, i2.__e != r2 && k$1(i2), i2; } __name(w$1, "w$1"); function k$1(n2) { var l2, u2; if (null != (n2 = n2.__) && null != n2.__c) { for (n2.__e = n2.__c.base = null, l2 = 0; l2 < n2.__k.length; l2++) if (null != (u2 = n2.__k[l2]) && null != u2.__e) { n2.__e = n2.__c.base = u2.__e; break; } return k$1(n2); } } __name(k$1, "k$1"); function x$1(n2) { (!n2.__d && (n2.__d = true) && i$1.push(n2) && !C$1.__r++ || o$1 !== l$1.debounceRendering) && ((o$1 = l$1.debounceRendering) || r$1)(C$1); } __name(x$1, "x$1"); function C$1() { var n2, u2, t2, o2 = [], r2 = []; for (i$1.sort(f$1); n2 = i$1.shift(); ) n2.__d && (t2 = i$1.length, u2 = w$1(n2, o2, r2) || u2, 0 === t2 || i$1.length > t2 ? (j$1(o2, u2, r2), r2.length = o2.length = 0, u2 = void 0, i$1.sort(f$1)) : u2 && l$1.__c && l$1.__c(u2, s$1)); u2 && j$1(o2, u2, r2), C$1.__r = 0; } __name(C$1, "C$1"); function P$1(n2, l2, u2, t2, i2, o2, r2, f2, e2, a2, h2) { var v2, p2, y2, d2, _2, g2 = t2 && t2.__k || s$1, b2 = l2.length; for (u2.__d = e2, S(u2, l2, g2), e2 = u2.__d, v2 = 0; v2 < b2; v2++) null != (y2 = u2.__k[v2]) && "boolean" != typeof y2 && "function" != typeof y2 && (p2 = -1 === y2.__i ? c$1 : g2[y2.__i] || c$1, y2.__i = v2, M(n2, y2, p2, i2, o2, r2, f2, e2, a2, h2), d2 = y2.__e, y2.ref && p2.ref != y2.ref && (p2.ref && N(p2.ref, null, y2), h2.push(y2.ref, y2.__c || d2, y2)), null == _2 && null != d2 && (_2 = d2), 65536 & y2.__u || p2.__k === y2.__k ? e2 = $(y2, e2, n2) : "function" == typeof y2.type && void 0 !== y2.__d ? e2 = y2.__d : d2 && (e2 = d2.nextSibling), y2.__d = void 0, y2.__u &= -196609); u2.__d = e2, u2.__e = _2; } __name(P$1, "P$1"); function S(n2, l2, u2) { var t2, i2, o2, r2, f2, e2 = l2.length, c2 = u2.length, s2 = c2, a2 = 0; for (n2.__k = [], t2 = 0; t2 < e2; t2++) null != (i2 = n2.__k[t2] = null == (i2 = l2[t2]) || "boolean" == typeof i2 || "function" == typeof i2 ? null : "string" == typeof i2 || "number" == typeof i2 || "bigint" == typeof i2 || i2.constructor == String ? d$1(null, i2, null, null, i2) : h$1(i2) ? d$1(g$1$1, { children: i2 }, null, null, null) : void 0 === i2.constructor && i2.__b > 0 ? d$1(i2.type, i2.props, i2.key, i2.ref ? i2.ref : null, i2.__v) : i2) ? (i2.__ = n2, i2.__b = n2.__b + 1, f2 = I(i2, u2, r2 = t2 + a2, s2), i2.__i = f2, o2 = null, -1 !== f2 && (s2--, (o2 = u2[f2]) && (o2.__u |= 131072)), null == o2 || null === o2.__v ? (-1 == f2 && a2--, "function" != typeof i2.type && (i2.__u |= 65536)) : f2 !== r2 && (f2 === r2 + 1 ? a2++ : f2 > r2 ? s2 > e2 - r2 ? a2 += f2 - r2 : a2-- : a2 = f2 < r2 && f2 == r2 - 1 ? f2 - r2 : 0, f2 !== t2 + a2 && (i2.__u |= 65536))) : (o2 = u2[t2]) && null == o2.key && o2.__e && (o2.__e == n2.__d && (n2.__d = m$1(o2)), O(o2, o2, false), u2[t2] = null, s2--); if (s2) for (t2 = 0; t2 < c2; t2++) null != (o2 = u2[t2]) && 0 == (131072 & o2.__u) && (o2.__e == n2.__d && (n2.__d = m$1(o2)), O(o2, o2)); } __name(S, "S"); function $(n2, l2, u2) { var t2, i2; if ("function" == typeof n2.type) { for (t2 = n2.__k, i2 = 0; t2 && i2 < t2.length; i2++) t2[i2] && (t2[i2].__ = n2, l2 = $(t2[i2], l2, u2)); return l2; } n2.__e != l2 && (u2.insertBefore(n2.__e, l2 || null), l2 = n2.__e); do { l2 = l2 && l2.nextSibling; } while (null != l2 && 8 === l2.nodeType); return l2; } __name($, "$"); function I(n2, l2, u2, t2) { var i2 = n2.key, o2 = n2.type, r2 = u2 - 1, f2 = u2 + 1, e2 = l2[u2]; if (null === e2 || e2 && i2 == e2.key && o2 === e2.type) return u2; if (t2 > (null != e2 && 0 == (131072 & e2.__u) ? 1 : 0)) for (; r2 >= 0 || f2 < l2.length; ) { if (r2 >= 0) { if ((e2 = l2[r2]) && 0 == (131072 & e2.__u) && i2 == e2.key && o2 === e2.type) return r2; r2--; } if (f2 < l2.length) { if ((e2 = l2[f2]) && 0 == (131072 & e2.__u) && i2 == e2.key && o2 === e2.type) return f2; f2++; } } return -1; } __name(I, "I"); function T$1(n2, l2, u2) { "-" === l2[0] ? n2.setProperty(l2, null == u2 ? "" : u2) : n2[l2] = null == u2 ? "" : "number" != typeof u2 || a$1.test(l2) ? u2 : u2 + "px"; } __name(T$1, "T$1"); function A$1(n2, l2, u2, t2, i2) { var o2; n: if ("style" === l2) if ("string" == typeof u2) n2.style.cssText = u2; else { if ("string" == typeof t2 && (n2.style.cssText = t2 = ""), t2) for (l2 in t2) u2 && l2 in u2 || T$1(n2.style, l2, ""); if (u2) for (l2 in u2) t2 && u2[l2] === t2[l2] || T$1(n2.style, l2, u2[l2]); } else if ("o" === l2[0] && "n" === l2[1]) o2 = l2 !== (l2 = l2.replace(/(PointerCapture)$|Capture$/i, "$1")), l2 = l2.toLowerCase() in n2 ? l2.toLowerCase().slice(2) : l2.slice(2), n2.l || (n2.l = {}), n2.l[l2 + o2] = u2, u2 ? t2 ? u2.u = t2.u : (u2.u = Date.now(), n2.addEventListener(l2, o2 ? L : D$1, o2)) : n2.removeEventListener(l2, o2 ? L : D$1, o2); else { if (i2) l2 = l2.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" !== l2 && "height" !== l2 && "href" !== l2 && "list" !== l2 && "form" !== l2 && "tabIndex" !== l2 && "download" !== l2 && "rowSpan" !== l2 && "colSpan" !== l2 && "role" !== l2 && l2 in n2) try { n2[l2] = null == u2 ? "" : u2; break n; } catch (n3) { } "function" == typeof u2 || (null == u2 || false === u2 && "-" !== l2[4] ? n2.removeAttribute(l2) : n2.setAttribute(l2, u2)); } } __name(A$1, "A$1"); function D$1(n2) { if (this.l) { var u2 = this.l[n2.type + false]; if (n2.t) { if (n2.t <= u2.u) return; } else n2.t = Date.now(); return u2(l$1.event ? l$1.event(n2) : n2); } } __name(D$1, "D$1"); function L(n2) { if (this.l) return this.l[n2.type + true](l$1.event ? l$1.event(n2) : n2); } __name(L, "L"); function M(n2, u2, t2, i2, o2, r2, f2, e2, c2, s2) { var a2, p2, y2, d2, _2, m2, w2, k2, x2, C2, S2, $2, H, I2, T2, A2 = u2.type; if (void 0 !== u2.constructor) return null; 128 & t2.__u && (c2 = !!(32 & t2.__u), r2 = [e2 = u2.__e = t2.__e]), (a2 = l$1.__b) && a2(u2); n: if ("function" == typeof A2) try { if (k2 = u2.props, x2 = (a2 = A2.contextType) && i2[a2.__c], C2 = a2 ? x2 ? x2.props.value : a2.__ : i2, t2.__c ? w2 = (p2 = u2.__c = t2.__c).__ = p2.__E : ("prototype" in A2 && A2.prototype.render ? u2.__c = p2 = new A2(k2, C2) : (u2.__c = p2 = new b$1(k2, C2), p2.constructor = A2, p2.render = q$1), x2 && x2.sub(p2), p2.props = k2, p2.state || (p2.state = {}), p2.context = C2, p2.__n = i2, y2 = p2.__d = true, p2.__h = [], p2._sb = []), null == p2.__s && (p2.__s = p2.state), null != A2.getDerivedStateFromProps && (p2.__s == p2.state && (p2.__s = v$1({}, p2.__s)), v$1(p2.__s, A2.getDerivedStateFromProps(k2, p2.__s))), d2 = p2.props, _2 = p2.state, p2.__v = u2, y2) null == A2.getDerivedStateFromProps && null != p2.componentWillMount && p2.componentWillMount(), null != p2.componentDidMount && p2.__h.push(p2.componentDidMount); else { if (null == A2.getDerivedStateFromProps && k2 !== d2 && null != p2.componentWillReceiveProps && p2.componentWillReceiveProps(k2, C2), !p2.__e && (null != p2.shouldComponentUpdate && false === p2.shouldComponentUpdate(k2, p2.__s, C2) || u2.__v === t2.__v)) { for (u2.__v !== t2.__v && (p2.props = k2, p2.state = p2.__s, p2.__d = false), u2.__e = t2.__e, u2.__k = t2.__k, u2.__k.forEach(function(n3) { n3 && (n3.__ = u2); }), S2 = 0; S2 < p2._sb.length; S2++) p2.__h.push(p2._sb[S2]); p2._sb = [], p2.__h.length && f2.push(p2); break n; } null != p2.componentWillUpdate && p2.componentWillUpdate(k2, p2.__s, C2), null != p2.componentDidUpdate && p2.__h.push(function() { p2.componentDidUpdate(d2, _2, m2); }); } if (p2.context = C2, p2.props = k2, p2.__P = n2, p2.__e = false, $2 = l$1.__r, H = 0, "prototype" in A2 && A2.prototype.render) { for (p2.state = p2.__s, p2.__d = false, $2 && $2(u2), a2 = p2.render(p2.props, p2.state, p2.context), I2 = 0; I2 < p2._sb.length; I2++) p2.__h.push(p2._sb[I2]); p2._sb = []; } else do { p2.__d = false, $2 && $2(u2), a2 = p2.render(p2.props, p2.state, p2.context), p2.state = p2.__s; } while (p2.__d && ++H < 25); p2.state = p2.__s, null != p2.getChildContext && (i2 = v$1(v$1({}, i2), p2.getChildContext())), y2 || null == p2.getSnapshotBeforeUpdate || (m2 = p2.getSnapshotBeforeUpdate(d2, _2)), P$1(n2, h$1(T2 = null != a2 && a2.type === g$1$1 && null == a2.key ? a2.props.children : a2) ? T2 : [T2], u2, t2, i2, o2, r2, f2, e2, c2, s2), p2.base = u2.__e, u2.__u &= -161, p2.__h.length && f2.push(p2), w2 && (p2.__E = p2.__ = null); } catch (n3) { u2.__v = null, c2 || null != r2 ? (u2.__e = e2, u2.__u |= c2 ? 160 : 32, r2[r2.indexOf(e2)] = null) : (u2.__e = t2.__e, u2.__k = t2.__k), l$1.__e(n3, u2, t2); } else null == r2 && u2.__v === t2.__v ? (u2.__k = t2.__k, u2.__e = t2.__e) : u2.__e = z$1(t2.__e, u2, t2, i2, o2, r2, f2, c2, s2); (a2 = l$1.diffed) && a2(u2); } __name(M, "M"); function j$1(n2, u2, t2) { for (var i2 = 0; i2 < t2.length; i2++) N(t2[i2], t2[++i2], t2[++i2]); l$1.__c && l$1.__c(u2, n2), n2.some(function(u3) { try { n2 = u3.__h, u3.__h = [], n2.some(function(n3) { n3.call(u3); }); } catch (n3) { l$1.__e(n3, u3.__v); } }); } __name(j$1, "j$1"); function z$1(l2, u2, t2, i2, o2, r2, f2, e2, s2) { var a2, v2, y2, d2, _2, g2, b2, w2 = t2.props, k2 = u2.props, x2 = u2.type; if ("svg" === x2 && (o2 = true), null != r2) { for (a2 = 0; a2 < r2.length; a2++) if ((_2 = r2[a2]) && "setAttribute" in _2 == !!x2 && (x2 ? _2.localName === x2 : 3 === _2.nodeType)) { l2 = _2, r2[a2] = null; break; } } if (null == l2) { if (null === x2) return document.createTextNode(k2); l2 = o2 ? document.createElementNS("http://www.w3.org/2000/svg", x2) : document.createElement(x2, k2.is && k2), r2 = null, e2 = false; } if (null === x2) w2 === k2 || e2 && l2.data === k2 || (l2.data = k2); else { if (r2 = r2 && n.call(l2.childNodes), w2 = t2.props || c$1, !e2 && null != r2) for (w2 = {}, a2 = 0; a2 < l2.attributes.length; a2++) w2[(_2 = l2.attributes[a2]).name] = _2.value; for (a2 in w2) _2 = w2[a2], "children" == a2 || ("dangerouslySetInnerHTML" == a2 ? y2 = _2 : "key" === a2 || a2 in k2 || A$1(l2, a2, null, _2, o2)); for (a2 in k2) _2 = k2[a2], "children" == a2 ? d2 = _2 : "dangerouslySetInnerHTML" == a2 ? v2 = _2 : "value" == a2 ? g2 = _2 : "checked" == a2 ? b2 = _2 : "key" === a2 || e2 && "function" != typeof _2 || w2[a2] === _2 || A$1(l2, a2, _2, w2[a2], o2); if (v2) e2 || y2 && (v2.__html === y2.__html || v2.__html === l2.innerHTML) || (l2.innerHTML = v2.__html), u2.__k = []; else if (y2 && (l2.innerHTML = ""), P$1(l2, h$1(d2) ? d2 : [d2], u2, t2, i2, o2 && "foreignObject" !== x2, r2, f2, r2 ? r2[0] : t2.__k && m$1(t2, 0), e2, s2), null != r2) for (a2 = r2.length; a2--; ) null != r2[a2] && p$1(r2[a2]); e2 || (a2 = "value", void 0 !== g2 && (g2 !== l2[a2] || "progress" === x2 && !g2 || "option" === x2 && g2 !== w2[a2]) && A$1(l2, a2, g2, w2[a2], false), a2 = "checked", void 0 !== b2 && b2 !== l2[a2] && A$1(l2, a2, b2, w2[a2], false)); } return l2; } __name(z$1, "z$1"); function N(n2, u2, t2) { try { "function" == typeof n2 ? n2(u2) : n2.current = u2; } catch (n3) { l$1.__e(n3, t2); } } __name(N, "N"); function O(n2, u2, t2) { var i2, o2; if (l$1.unmount && l$1.unmount(n2), (i2 = n2.ref) && (i2.current && i2.current !== n2.__e || N(i2, null, u2)), null != (i2 = n2.__c)) { if (i2.componentWillUnmount) try { i2.componentWillUnmount(); } catch (n3) { l$1.__e(n3, u2); } i2.base = i2.__P = null, n2.__c = void 0; } if (i2 = n2.__k) for (o2 = 0; o2 < i2.length; o2++) i2[o2] && O(i2[o2], u2, t2 || "function" != typeof n2.type); t2 || null == n2.__e || p$1(n2.__e), n2.__ = n2.__e = n2.__d = void 0; } __name(O, "O"); function q$1(n2, l2, u2) { return this.constructor(n2, u2); } __name(q$1, "q$1"); function B$1(u2, t2, i2) { var o2, r2, f2, e2; l$1.__ && l$1.__(u2, t2), r2 = (o2 = "function" == typeof i2) ? null : t2.__k, f2 = [], e2 = [], M(t2, u2 = (!o2 && i2 || t2).__k = y$1(g$1$1, null, [u2]), r2 || c$1, c$1, void 0 !== t2.ownerSVGElement, !o2 && i2 ? [i2] : r2 ? null : t2.firstChild ? n.call(t2.childNodes) : null, f2, !o2 && i2 ? i2 : r2 ? r2.__e : t2.firstChild, o2, e2), u2.__d = void 0, j$1(f2, u2, e2); } __name(B$1, "B$1"); n = s$1.slice, l$1 = { __e: /* @__PURE__ */ __name(function(n2, l2, u2, t2) { for (var i2, o2, r2; l2 = l2.__; ) if ((i2 = l2.__c) && !i2.__) try { if ((o2 = i2.constructor) && null != o2.getDerivedStateFromError && (i2.setState(o2.getDerivedStateFromError(n2)), r2 = i2.__d), null != i2.componentDidCatch && (i2.componentDidCatch(n2, t2 || {}), r2 = i2.__d), r2) return i2.__E = i2; } catch (l3) { n2 = l3; } throw n2; }, "__e") }, u$1 = 0, b$1.prototype.setState = function(n2, l2) { var u2; u2 = null != this.__s && this.__s !== this.state ? this.__s : this.__s = v$1({}, this.state), "function" == typeof n2 && (n2 = n2(v$1({}, u2), this.props)), n2 && v$1(u2, n2), null != n2 && this.__v && (l2 && this._sb.push(l2), x$1(this)); }, b$1.prototype.forceUpdate = function(n2) { this.__v && (this.__e = true, n2 && this.__h.push(n2), x$1(this)); }, b$1.prototype.render = g$1$1, i$1 = [], r$1 = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f$1 = /* @__PURE__ */ __name(function(n2, l2) { return n2.__v.__b - l2.__v.__b; }, "f$1"), C$1.__r = 0; var t$1, r, u, i$2, o = 0, f = [], c = [], e = l$1, a = e.__b, v = e.__r, l = e.diffed, m = e.__c, s = e.unmount, d = e.__; function h$2(n2, t2) { e.__h && e.__h(r, n2, o || t2), o = 0; var u2 = r.__H || (r.__H = { __: [], __h: [] }); return n2 >= u2.__.length && u2.__.push({ __V: c }), u2.__[n2]; } __name(h$2, "h$2"); function p$2(n2) { return o = 1, y(D, n2); } __name(p$2, "p$2"); function y(n2, u2, i2) { var o2 = h$2(t$1++, 2); if (o2.t = n2, !o2.__c && (o2.__ = [i2 ? i2(u2) : D(void 0, u2), function(n3) { var t2 = o2.__N ? o2.__N[0] : o2.__[0], r2 = o2.t(t2, n3); t2 !== r2 && (o2.__N = [r2, o2.__[1]], o2.__c.setState({})); }], o2.__c = r, !r.u)) { var f2 = /* @__PURE__ */ __name(function(n3, t2, r2) { if (!o2.__c.__H) return true; var u3 = o2.__c.__H.__.filter(function(n4) { return !!n4.__c; }); if (u3.every(function(n4) { return !n4.__N; })) return !c2 || c2.call(this, n3, t2, r2); var i3 = false; return u3.forEach(function(n4) { if (n4.__N) { var t3 = n4.__[0]; n4.__ = n4.__N, n4.__N = void 0, t3 !== n4.__[0] && (i3 = true); } }), !(!i3 && o2.__c.props === n3) && (!c2 || c2.call(this, n3, t2, r2)); }, "f"); r.u = true; var c2 = r.shouldComponentUpdate, e2 = r.componentWillUpdate; r.componentWillUpdate = function(n3, t2, r2) { if (this.__e) { var u3 = c2; c2 = void 0, f2(n3, t2, r2), c2 = u3; } e2 && e2.call(this, n3, t2, r2); }, r.shouldComponentUpdate = f2; } return o2.__N || o2.__; } __name(y, "y"); function _$1(n2, u2) { var i2 = h$2(t$1++, 3); !e.__s && C(i2.__H, u2) && (i2.__ = n2, i2.i = u2, r.__H.__h.push(i2)); } __name(_$1, "_$1"); function A(n2, u2) { var i2 = h$2(t$1++, 4); !e.__s && C(i2.__H, u2) && (i2.__ = n2, i2.i = u2, r.__h.push(i2)); } __name(A, "A"); function F(n2) { return o = 5, q(function() { return { current: n2 }; }, []); } __name(F, "F"); function T(n2, t2, r2) { o = 6, A(function() { return "function" == typeof n2 ? (n2(t2()), function() { return n2(null); }) : n2 ? (n2.current = t2(), function() { return n2.current = null; }) : void 0; }, null == r2 ? r2 : r2.concat(n2)); } __name(T, "T"); function q(n2, r2) { var u2 = h$2(t$1++, 7); return C(u2.__H, r2) ? (u2.__V = n2(), u2.i = r2, u2.__h = n2, u2.__V) : u2.__; } __name(q, "q"); function x(n2, t2) { return o = 8, q(function() { return n2; }, t2); } __name(x, "x"); function P$2(n2) { var u2 = r.context[n2.__c], i2 = h$2(t$1++, 9); return i2.c = n2, u2 ? (null == i2.__ && (i2.__ = true, u2.sub(r)), u2.props.value) : n2.__; } __name(P$2, "P$2"); function V(n2, t2) { e.useDebugValue && e.useDebugValue(t2 ? t2(n2) : n2); } __name(V, "V"); function b(n2) { var u2 = h$2(t$1++, 10), i2 = p$2(); return u2.__ = n2, r.componentDidCatch || (r.componentDidCatch = function(n3, t2) { u2.__ && u2.__(n3, t2), i2[1](n3); }), [i2[0], function() { i2[1](void 0); }]; } __name(b, "b"); function g$6() { var n2 = h$2(t$1++, 11); if (!n2.__) { for (var u2 = r.__v; null !== u2 && !u2.__m && null !== u2.__; ) u2 = u2.__; var i2 = u2.__m || (u2.__m = [0, 0]); n2.__ = "P" + i2[0] + "-" + i2[1]++; } return n2.__; } __name(g$6, "g$6"); function j() { for (var n2; n2 = f.shift(); ) if (n2.__P && n2.__H) try { n2.__H.__h.forEach(z$2), n2.__H.__h.forEach(B), n2.__H.__h = []; } catch (t2) { n2.__H.__h = [], e.__e(t2, n2.__v); } } __name(j, "j"); e.__b = function(n2) { r = null, a && a(n2); }, e.__ = function(n2, t2) { t2.__k && t2.__k.__m && (n2.__m = t2.__k.__m), d && d(n2, t2); }, e.__r = function(n2) { v && v(n2), t$1 = 0; var i2 = (r = n2.__c).__H; i2 && (u === r ? (i2.__h = [], r.__h = [], i2.__.forEach(function(n3) { n3.__N && (n3.__ = n3.__N), n3.__V = c, n3.__N = n3.i = void 0; })) : (i2.__h.forEach(z$2), i2.__h.forEach(B), i2.__h = [], t$1 = 0)), u = r; }, e.diffed = function(n2) { l && l(n2); var t2 = n2.__c; t2 && t2.__H && (t2.__H.__h.length && (1 !== f.push(t2) && i$2 === e.requestAnimationFrame || ((i$2 = e.requestAnimationFrame) || w)(j)), t2.__H.__.forEach(function(n3) { n3.i && (n3.__H = n3.i), n3.__V !== c && (n3.__ = n3.__V), n3.i = void 0, n3.__V = c; })), u = r = null; }, e.__c = function(n2, t2) { t2.some(function(n3) { try { n3.__h.forEach(z$2), n3.__h = n3.__h.filter(function(n4) { return !n4.__ || B(n4); }); } catch (r2) { t2.some(function(n4) { n4.__h && (n4.__h = []); }), t2 = [], e.__e(r2, n3.__v); } }), m && m(n2, t2); }, e.unmount = function(n2) { s && s(n2); var t2, r2 = n2.__c; r2 && r2.__H && (r2.__H.__.forEach(function(n3) { try { z$2(n3); } catch (n4) { t2 = n4; } }), r2.__H = void 0, t2 && e.__e(t2, r2.__v)); }; var k = "function" == typeof requestAnimationFrame; function w(n2) { var t2, r2 = /* @__PURE__ */ __name(function() { clearTimeout(u2), k && cancelAnimationFrame(t2), setTimeout(n2); }, "r"), u2 = setTimeout(r2, 100); k && (t2 = requestAnimationFrame(r2)); } __name(w, "w"); function z$2(n2) { var t2 = r, u2 = n2.__c; "function" == typeof u2 && (n2.__c = void 0, u2()), r = t2; } __name(z$2, "z$2"); function B(n2) { var t2 = r; n2.__c = n2.__(), r = t2; } __name(B, "B"); function C(n2, t2) { return !n2 || n2.length !== t2.length || t2.some(function(t3, r2) { return t3 !== n2[r2]; }); } __name(C, "C"); function D(n2, t2) { return "function" == typeof t2 ? t2(n2) : t2; } __name(D, "D"); const hooks = { __proto__: null, useCallback: x, useContext: P$2, useDebugValue: V, useEffect: _$1, useErrorBoundary: b, useId: g$6, useImperativeHandle: T, useLayoutEffect: A, useMemo: q, useReducer: y, useRef: F, useState: p$2 }; const XMLNS$1 = "http://www.w3.org/2000/svg"; function SentryLogo() { const createElementNS = /* @__PURE__ */ __name((tagName) => DOCUMENT.createElementNS(XMLNS$1, tagName), "createElementNS"); const svg = setAttributesNS(createElementNS("svg"), { width: "32", height: "30", viewBox: "0 0 72 66", fill: "inherit" }); const path = setAttributesNS(createElementNS("path"), { transform: "translate(11, 11)", d: "M29,2.26a4.67,4.67,0,0,0-8,0L14.42,13.53A32.21,32.21,0,0,1,32.17,40.19H27.55A27.68,27.68,0,0,0,12.09,17.47L6,28a15.92,15.92,0,0,1,9.23,12.17H4.62A.76.76,0,0,1,4,39.06l2.94-5a10.74,10.74,0,0,0-3.36-1.9l-2.91,5a4.54,4.54,0,0,0,1.69,6.24A4.66,4.66,0,0,0,4.62,44H19.15a19.4,19.4,0,0,0-8-17.31l2.31-4A23.87,23.87,0,0,1,23.76,44H36.07a35.88,35.88,0,0,0-16.41-31.8l4.67-8a.77.77,0,0,1,1.05-.27c.53.29,20.29,34.77,20.66,35.17a.76.76,0,0,1-.68,1.13H40.6q.09,1.91,0,3.81h4.78A4.59,4.59,0,0,0,50,39.43a4.49,4.49,0,0,0-.62-2.28Z" }); svg.appendChild(path); return svg; } __name(SentryLogo, "SentryLogo"); function DialogHeader({ options: options4 }) { const logoHtml = q(() => ({ __html: SentryLogo().outerHTML }), []); return y$1( "h2", { class: "dialog__header" }, y$1("span", { class: "dialog__title" }, options4.formTitle), options4.showBranding ? y$1( "a", { class: "brand-link", target: "_blank", href: "https://sentry.io/welcome/", title: "Powered by Sentry", rel: "noopener noreferrer", dangerouslySetInnerHTML: logoHtml } ) : null ); } __name(DialogHeader, "DialogHeader"); function getMissingFields(feedback, props) { const emptyFields = []; if (props.isNameRequired && !feedback.name) { emptyFields.push(props.nameLabel); } if (props.isEmailRequired && !feedback.email) { emptyFields.push(props.emailLabel); } if (!feedback.message) { emptyFields.push(props.messageLabel); } return emptyFields; } __name(getMissingFields, "getMissingFields"); function retrieveStringValue(formData, key) { const value4 = formData.get(key); if (typeof value4 === "string") { return value4.trim(); } return ""; } __name(retrieveStringValue, "retrieveStringValue"); function Form({ options: options4, defaultEmail, defaultName, onFormClose, onSubmit, onSubmitSuccess, onSubmitError, showEmail, showName, screenshotInput }) { const { tags, addScreenshotButtonLabel, removeScreenshotButtonLabel, cancelButtonLabel, emailLabel, emailPlaceholder, isEmailRequired, isNameRequired, messageLabel, messagePlaceholder, nameLabel, namePlaceholder, submitButtonLabel, isRequiredLabel } = options4; const [error2, setError] = p$2(null); const [showScreenshotInput, setShowScreenshotInput] = p$2(false); const ScreenshotInputComponent = screenshotInput && screenshotInput.input; const [screenshotError, setScreenshotError] = p$2(null); const onScreenshotError = x((error3) => { setScreenshotError(error3); setShowScreenshotInput(false); }, []); const hasAllRequiredFields = x( (data25) => { const missingFields = getMissingFields(data25, { emailLabel, isEmailRequired, isNameRequired, messageLabel, nameLabel }); if (missingFields.length > 0) { setError(`Please enter in the following required fields: ${missingFields.join(", ")}`); } else { setError(null); } return missingFields.length === 0; }, [emailLabel, isEmailRequired, isNameRequired, messageLabel, nameLabel] ); const handleSubmit = x( async (e2) => { try { e2.preventDefault(); if (!(e2.target instanceof HTMLFormElement)) { return; } const formData = new FormData(e2.target); const attachment = await (screenshotInput && showScreenshotInput ? screenshotInput.value() : void 0); const data25 = { name: retrieveStringValue(formData, "name"), email: retrieveStringValue(formData, "email"), message: retrieveStringValue(formData, "message"), attachments: attachment ? [attachment] : void 0 }; if (!hasAllRequiredFields(data25)) { return; } try { await onSubmit( { name: data25.name, email: data25.email, message: data25.message, source: FEEDBACK_WIDGET_SOURCE, tags }, { attachments: data25.attachments } ); onSubmitSuccess(data25); } catch (error3) { DEBUG_BUILD$1 && logger$2.error(error3); setError(error3); onSubmitError(error3); } } catch (e22) { } }, [screenshotInput && showScreenshotInput, onSubmitSuccess, onSubmitError] ); return y$1( "form", { class: "form", onSubmit: handleSubmit }, ScreenshotInputComponent && showScreenshotInput ? y$1(ScreenshotInputComponent, { onError: onScreenshotError }) : null, y$1( "div", { class: "form__right", "data-sentry-feedback": true }, y$1( "div", { class: "form__top" }, error2 ? y$1("div", { class: "form__error-container" }, error2) : null, showName ? y$1( "label", { for: "name", class: "form__label" }, y$1(LabelText, { label: nameLabel, isRequiredLabel, isRequired: isNameRequired }), y$1( "input", { class: "form__input", defaultValue: defaultName, id: "name", name: "name", placeholder: namePlaceholder, required: isNameRequired, type: "text" } ) ) : y$1("input", { "aria-hidden": true, value: defaultName, name: "name", type: "hidden" }), showEmail ? y$1( "label", { for: "email", class: "form__label" }, y$1(LabelText, { label: emailLabel, isRequiredLabel, isRequired: isEmailRequired }), y$1( "input", { class: "form__input", defaultValue: defaultEmail, id: "email", name: "email", placeholder: emailPlaceholder, required: isEmailRequired, type: "email" } ) ) : y$1("input", { "aria-hidden": true, value: defaultEmail, name: "email", type: "hidden" }), y$1( "label", { for: "message", class: "form__label" }, y$1(LabelText, { label: messageLabel, isRequiredLabel, isRequired: true }), y$1( "textarea", { autoFocus: true, class: "form__input form__input--textarea", id: "message", name: "message", placeholder: messagePlaceholder, required: true, rows: 5 } ) ), ScreenshotInputComponent ? y$1( "label", { for: "screenshot", class: "form__label" }, y$1( "button", { class: "btn btn--default", type: "button", onClick: /* @__PURE__ */ __name(() => { setScreenshotError(null); setShowScreenshotInput((prev2) => !prev2); }, "onClick") }, showScreenshotInput ? removeScreenshotButtonLabel : addScreenshotButtonLabel ), screenshotError ? y$1("div", { class: "form__error-container" }, screenshotError.message) : null ) : null ), y$1( "div", { class: "btn-group" }, y$1( "button", { class: "btn btn--primary", type: "submit" }, submitButtonLabel ), y$1( "button", { class: "btn btn--default", type: "button", onClick: onFormClose }, cancelButtonLabel ) ) ) ); } __name(Form, "Form"); function LabelText({ label: label5, isRequired, isRequiredLabel }) { return y$1( "span", { class: "form__label__text" }, label5, isRequired && y$1("span", { class: "form__label__text--required" }, isRequiredLabel) ); } __name(LabelText, "LabelText"); const WIDTH = 16; const HEIGHT = 17; const XMLNS = "http://www.w3.org/2000/svg"; function SuccessIcon() { const createElementNS = /* @__PURE__ */ __name((tagName) => WINDOW.document.createElementNS(XMLNS, tagName), "createElementNS"); const svg = setAttributesNS(createElementNS("svg"), { width: `${WIDTH}`, height: `${HEIGHT}`, viewBox: `0 0 ${WIDTH} ${HEIGHT}`, fill: "inherit" }); const g2 = setAttributesNS(createElementNS("g"), { clipPath: "url(#clip0_57_156)" }); const path2 = setAttributesNS(createElementNS("path"), { ["fill-rule"]: "evenodd", ["clip-rule"]: "evenodd", d: "M3.55544 15.1518C4.87103 16.0308 6.41775 16.5 8 16.5C10.1217 16.5 12.1566 15.6571 13.6569 14.1569C15.1571 12.6566 16 10.6217 16 8.5C16 6.91775 15.5308 5.37103 14.6518 4.05544C13.7727 2.73985 12.5233 1.71447 11.0615 1.10897C9.59966 0.503466 7.99113 0.34504 6.43928 0.653721C4.88743 0.962403 3.46197 1.72433 2.34315 2.84315C1.22433 3.96197 0.462403 5.38743 0.153721 6.93928C-0.15496 8.49113 0.00346625 10.0997 0.608967 11.5615C1.21447 13.0233 2.23985 14.2727 3.55544 15.1518ZM4.40546 3.1204C5.46945 2.40946 6.72036 2.03 8 2.03C9.71595 2.03 11.3616 2.71166 12.575 3.92502C13.7883 5.13838 14.47 6.78405 14.47 8.5C14.47 9.77965 14.0905 11.0306 13.3796 12.0945C12.6687 13.1585 11.6582 13.9878 10.476 14.4775C9.29373 14.9672 7.99283 15.0953 6.73777 14.8457C5.48271 14.596 4.32987 13.9798 3.42502 13.075C2.52018 12.1701 1.90397 11.0173 1.65432 9.76224C1.40468 8.50718 1.5328 7.20628 2.0225 6.02404C2.5122 4.8418 3.34148 3.83133 4.40546 3.1204Z" }); const path = setAttributesNS(createElementNS("path"), { d: "M6.68775 12.4297C6.78586 12.4745 6.89218 12.4984 7 12.5C7.11275 12.4955 7.22315 12.4664 7.32337 12.4145C7.4236 12.3627 7.51121 12.2894 7.58 12.2L12 5.63999C12.0848 5.47724 12.1071 5.28902 12.0625 5.11098C12.0178 4.93294 11.9095 4.77744 11.7579 4.67392C11.6064 4.57041 11.4221 4.52608 11.24 4.54931C11.0579 4.57254 10.8907 4.66173 10.77 4.79999L6.88 10.57L5.13 8.56999C5.06508 8.49566 4.98613 8.43488 4.89768 8.39111C4.80922 8.34735 4.713 8.32148 4.61453 8.31498C4.51605 8.30847 4.41727 8.32147 4.32382 8.35322C4.23038 8.38497 4.14413 8.43484 4.07 8.49999C3.92511 8.63217 3.83692 8.81523 3.82387 9.01092C3.81083 9.2066 3.87393 9.39976 4 9.54999L6.43 12.24C6.50187 12.3204 6.58964 12.385 6.68775 12.4297Z" }); svg.appendChild(g2).append(path, path2); const speakerDefs = createElementNS("defs"); const speakerClipPathDef = setAttributesNS(createElementNS("clipPath"), { id: "clip0_57_156" }); const speakerRect = setAttributesNS(createElementNS("rect"), { width: `${WIDTH}`, height: `${WIDTH}`, fill: "white", transform: "translate(0 0.5)" }); speakerClipPathDef.appendChild(speakerRect); speakerDefs.appendChild(speakerClipPathDef); svg.appendChild(speakerDefs).appendChild(speakerClipPathDef).appendChild(speakerRect); return svg; } __name(SuccessIcon, "SuccessIcon"); function Dialog({ open: open2, onFormSubmitted, ...props }) { const options4 = props.options; const successIconHtml = q(() => ({ __html: SuccessIcon().outerHTML }), []); const [timeoutId, setTimeoutId] = p$2(null); const handleOnSuccessClick = x(() => { if (timeoutId) { clearTimeout(timeoutId); setTimeoutId(null); } onFormSubmitted(); }, [timeoutId]); const onSubmitSuccess = x( (data25) => { props.onSubmitSuccess(data25); setTimeoutId( setTimeout(() => { onFormSubmitted(); setTimeoutId(null); }, SUCCESS_MESSAGE_TIMEOUT) ); }, [onFormSubmitted] ); return y$1( g$1$1, null, timeoutId ? y$1( "div", { class: "success__position", onClick: handleOnSuccessClick }, y$1( "div", { class: "success__content" }, options4.successMessageText, y$1("span", { class: "success__icon", dangerouslySetInnerHTML: successIconHtml }) ) ) : y$1( "dialog", { class: "dialog", onClick: options4.onFormClose, open: open2 }, y$1( "div", { class: "dialog__position" }, y$1( "div", { class: "dialog__content", onClick: /* @__PURE__ */ __name((e2) => { e2.stopPropagation(); }, "onClick") }, y$1(DialogHeader, { options: options4 }), y$1(Form, { ...props, onSubmitSuccess }) ) ) ) ); } __name(Dialog, "Dialog"); const DIALOG = ` .dialog { position: fixed; z-index: var(--z-index); margin: 0; inset: 0; display: flex; align-items: center; justify-content: center; padding: 0; height: 100vh; width: 100vw; color: var(--dialog-color, var(--foreground)); fill: var(--dialog-color, var(--foreground)); line-height: 1.75em; background-color: rgba(0, 0, 0, 0.05); border: none; inset: 0; opacity: 1; transition: opacity 0.2s ease-in-out; } .dialog__position { position: fixed; z-index: var(--z-index); inset: var(--dialog-inset); padding: var(--page-margin); display: flex; max-height: calc(100vh - (2 * var(--page-margin))); } @media (max-width: 600px) { .dialog__position { inset: var(--page-margin); padding: 0; } } .dialog__position:has(.editor) { inset: var(--page-margin); padding: 0; } .dialog:not([open]) { opacity: 0; pointer-events: none; visibility: hidden; } .dialog:not([open]) .dialog__content { transform: translate(0, -16px) scale(0.98); } .dialog__content { display: flex; flex-direction: column; gap: 16px; padding: var(--dialog-padding, 24px); max-width: 100%; width: 100%; max-height: 100%; overflow: auto; background: var(--dialog-background, var(--background)); border-radius: var(--dialog-border-radius, 20px); border: var(--dialog-border, var(--border)); box-shadow: var(--dialog-box-shadow, var(--box-shadow)); transform: translate(0, 0) scale(1); transition: transform 0.2s ease-in-out; } `; const DIALOG_HEADER = ` .dialog__header { display: flex; gap: 4px; justify-content: space-between; font-weight: var(--dialog-header-weight, 600); margin: 0; } .dialog__title { align-self: center; width: var(--form-width, 272px); } @media (max-width: 600px) { .dialog__title { width: auto; } } .dialog__position:has(.editor) .dialog__title { width: auto; } .brand-link { display: inline-flex; } .brand-link:focus-visible { outline: var(--outline); } `; const FORM = ` .form { display: flex; overflow: auto; flex-direction: row; gap: 16px; flex: 1 0; } .form__right { flex: 0 0 auto; display: flex; overflow: auto; flex-direction: column; justify-content: space-between; gap: 20px; width: var(--form-width, 100%); } .dialog__position:has(.editor) .form__right { width: var(--form-width, 272px); } .form__top { display: flex; flex-direction: column; gap: 8px; } .form__error-container { color: var(--error-color); fill: var(--error-color); } .form__label { display: flex; flex-direction: column; gap: 4px; margin: 0px; } .form__label__text { display: flex; gap: 4px; align-items: center; } .form__label__text--required { font-size: 0.85em; } .form__input { font-family: inherit; line-height: inherit; background: transparent; box-sizing: border-box; border: var(--input-border, var(--border)); border-radius: var(--input-border-radius, 6px); color: var(--input-color, inherit); fill: var(--input-color, inherit); font-size: var(--input-font-size, inherit); font-weight: var(--input-font-weight, 500); padding: 6px 12px; } .form__input::placeholder { opacity: 0.65; color: var(--input-placeholder-color, inherit); filter: var(--interactive-filter); } .form__input:focus-visible { outline: var(--input-focus-outline, var(--outline)); } .form__input--textarea { font-family: inherit; resize: vertical; } .error { color: var(--error-color); fill: var(--error-color); } `; const BUTTON = ` .btn-group { display: grid; gap: 8px; } .btn { line-height: inherit; border: var(--button-border, var(--border)); border-radius: var(--button-border-radius, 6px); cursor: pointer; font-family: inherit; font-size: var(--button-font-size, inherit); font-weight: var(--button-font-weight, 600); padding: var(--button-padding, 6px 16px); } .btn[disabled] { opacity: 0.6; pointer-events: none; } .btn--primary { color: var(--button-primary-color, var(--accent-foreground)); fill: var(--button-primary-color, var(--accent-foreground)); background: var(--button-primary-background, var(--accent-background)); border: var(--button-primary-border, var(--border)); border-radius: var(--button-primary-border-radius, 6px); font-weight: var(--button-primary-font-weight, 500); } .btn--primary:hover { color: var(--button-primary-hover-color, var(--accent-foreground)); fill: var(--button-primary-hover-color, var(--accent-foreground)); background: var(--button-primary-hover-background, var(--accent-background)); filter: var(--interactive-filter); } .btn--primary:focus-visible { background: var(--button-primary-hover-background, var(--accent-background)); filter: var(--interactive-filter); outline: var(--button-primary-focus-outline, var(--outline)); } .btn--default { color: var(--button-color, var(--foreground)); fill: var(--button-color, var(--foreground)); background: var(--button-background, var(--background)); border: var(--button-border, var(--border)); border-radius: var(--button-border-radius, 6px); font-weight: var(--button-font-weight, 500); } .btn--default:hover { color: var(--button-color, var(--foreground)); fill: var(--button-color, var(--foreground)); background: var(--button-hover-background, var(--background)); filter: var(--interactive-filter); } .btn--default:focus-visible { background: var(--button-hover-background, var(--background)); filter: var(--interactive-filter); outline: var(--button-focus-outline, var(--outline)); } `; const SUCCESS = ` .success__position { position: fixed; inset: var(--dialog-inset); padding: var(--page-margin); z-index: var(--z-index); } .success__content { background: var(--success-background, var(--background)); border: var(--success-border, var(--border)); border-radius: var(--success-border-radius, 1.7em/50%); box-shadow: var(--success-box-shadow, var(--box-shadow)); font-weight: var(--success-font-weight, 600); color: var(--success-color); fill: var(--success-color); padding: 12px 24px; line-height: 1.75em; display: grid; align-items: center; grid-auto-flow: column; gap: 6px; cursor: default; } .success__icon { display: flex; } `; function createDialogStyles(styleNonce) { const style2 = DOCUMENT.createElement("style"); style2.textContent = ` :host { --dialog-inset: var(--inset); } ${DIALOG} ${DIALOG_HEADER} ${FORM} ${BUTTON} ${SUCCESS} `; if (styleNonce) { style2.setAttribute("nonce", styleNonce); } return style2; } __name(createDialogStyles, "createDialogStyles"); function getUser() { const currentUser = getCurrentScope$1().getUser(); const isolationUser = getIsolationScope().getUser(); const globalUser = getGlobalScope().getUser(); if (currentUser && Object.keys(currentUser).length) { return currentUser; } if (isolationUser && Object.keys(isolationUser).length) { return isolationUser; } return globalUser; } __name(getUser, "getUser"); const feedbackModalIntegration = /* @__PURE__ */ __name(() => { return { name: "FeedbackModal", // eslint-disable-next-line @typescript-eslint/no-empty-function setupOnce() { }, createDialog: /* @__PURE__ */ __name(({ options: options4, screenshotIntegration, sendFeedback: sendFeedback2, shadow }) => { const shadowRoot = shadow; const userKey = options4.useSentryUser; const user = getUser(); const el = DOCUMENT.createElement("div"); const style2 = createDialogStyles(options4.styleNonce); let originalOverflow = ""; const dialog = { get el() { return el; }, appendToDom() { if (!shadowRoot.contains(style2) && !shadowRoot.contains(el)) { shadowRoot.appendChild(style2); shadowRoot.appendChild(el); } }, removeFromDom() { shadowRoot.removeChild(el); shadowRoot.removeChild(style2); DOCUMENT.body.style.overflow = originalOverflow; }, open() { renderContent(true); options4.onFormOpen && options4.onFormOpen(); originalOverflow = DOCUMENT.body.style.overflow; DOCUMENT.body.style.overflow = "hidden"; }, close() { renderContent(false); DOCUMENT.body.style.overflow = originalOverflow; } }; const screenshotInput = screenshotIntegration && screenshotIntegration.createInput({ h: y$1, hooks, dialog, options: options4 }); const renderContent = /* @__PURE__ */ __name((open2) => { B$1( y$1( Dialog, { options: options4, screenshotInput, showName: options4.showName || options4.isNameRequired, showEmail: options4.showEmail || options4.isEmailRequired, defaultName: userKey && user && user[userKey.name] || "", defaultEmail: userKey && user && user[userKey.email] || "", onFormClose: /* @__PURE__ */ __name(() => { renderContent(false); options4.onFormClose && options4.onFormClose(); }, "onFormClose"), onSubmit: sendFeedback2, onSubmitSuccess: /* @__PURE__ */ __name((data25) => { renderContent(false); options4.onSubmitSuccess && options4.onSubmitSuccess(data25); }, "onSubmitSuccess"), onSubmitError: /* @__PURE__ */ __name((error2) => { options4.onSubmitError && options4.onSubmitError(error2); }, "onSubmitError"), onFormSubmitted: /* @__PURE__ */ __name(() => { options4.onFormSubmitted && options4.onFormSubmitted(); }, "onFormSubmitted"), open: open2 } ), el ); }, "renderContent"); return dialog; }, "createDialog") }; }, "feedbackModalIntegration"); function CropCornerFactory({ h: h2 // eslint-disable-line @typescript-eslint/no-unused-vars }) { return /* @__PURE__ */ __name(function CropCorner({ top, left, corner, onGrabButton }) { return h2( "button", { class: `editor__crop-corner editor__crop-corner--${corner} `, style: { top, left }, onMouseDown: /* @__PURE__ */ __name((e2) => { e2.preventDefault(); onGrabButton(e2, corner); }, "onMouseDown"), onClick: /* @__PURE__ */ __name((e2) => { e2.preventDefault(); }, "onClick") } ); }, "CropCorner"); } __name(CropCornerFactory, "CropCornerFactory"); function createScreenshotInputStyles(styleNonce) { const style2 = DOCUMENT.createElement("style"); const surface200 = "#1A141F"; const gray100 = "#302735"; style2.textContent = ` .editor { padding: 10px; padding-top: 65px; padding-bottom: 65px; flex-grow: 1; background-color: ${surface200}; background-image: repeating-linear-gradient( -145deg, transparent, transparent 8px, ${surface200} 8px, ${surface200} 11px ), repeating-linear-gradient( -45deg, transparent, transparent 15px, ${gray100} 15px, ${gray100} 16px ); } .editor__canvas-container { width: 100%; height: 100%; position: relative; display: flex; align-items: center; justify-content: center; } .editor__canvas-container canvas { object-fit: contain; position: relative; } .editor__crop-btn-group { padding: 8px; gap: 8px; border-radius: var(--menu-border-radius, 6px); background: var(--button-primary-background, var(--background)); width: 175px; position: absolute; } .editor__crop-corner { width: 30px; height: 30px; position: absolute; background: none; border: 3px solid #ffffff; } .editor__crop-corner--top-left { cursor: nwse-resize; border-right: none; border-bottom: none; } .editor__crop-corner--top-right { cursor: nesw-resize; border-left: none; border-bottom: none; } .editor__crop-corner--bottom-left { cursor: nesw-resize; border-right: none; border-top: none; } .editor__crop-corner--bottom-right { cursor: nwse-resize; border-left: none; border-top: none; } `; if (styleNonce) { style2.setAttribute("nonce", styleNonce); } return style2; } __name(createScreenshotInputStyles, "createScreenshotInputStyles"); function useTakeScreenshotFactory({ hooks: hooks2 }) { return /* @__PURE__ */ __name(function useTakeScreenshot({ onBeforeScreenshot, onScreenshot, onAfterScreenshot, onError }) { hooks2.useEffect(() => { const takeScreenshot = /* @__PURE__ */ __name(async () => { onBeforeScreenshot(); const stream = await NAVIGATOR.mediaDevices.getDisplayMedia({ video: { width: WINDOW.innerWidth * WINDOW.devicePixelRatio, height: WINDOW.innerHeight * WINDOW.devicePixelRatio }, audio: false, // @ts-expect-error experimental flags: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#prefercurrenttab monitorTypeSurfaces: "exclude", preferCurrentTab: true, selfBrowserSurface: "include", surfaceSwitching: "exclude" }); const video = DOCUMENT.createElement("video"); await new Promise((resolve2, reject3) => { video.srcObject = stream; video.onloadedmetadata = () => { onScreenshot(video); stream.getTracks().forEach((track2) => track2.stop()); resolve2(); }; video.play().catch(reject3); }); onAfterScreenshot(); }, "takeScreenshot"); takeScreenshot().catch(onError); }, []); }, "useTakeScreenshot"); } __name(useTakeScreenshotFactory, "useTakeScreenshotFactory"); const CROP_BUTTON_SIZE = 30; const CROP_BUTTON_BORDER = 3; const CROP_BUTTON_OFFSET = CROP_BUTTON_SIZE + CROP_BUTTON_BORDER; const DPI = WINDOW.devicePixelRatio; const constructRect = /* @__PURE__ */ __name((box) => { return { x: Math.min(box.startX, box.endX), y: Math.min(box.startY, box.endY), width: Math.abs(box.startX - box.endX), height: Math.abs(box.startY - box.endY) }; }, "constructRect"); const getContainedSize = /* @__PURE__ */ __name((img) => { const imgClientHeight = img.clientHeight; const imgClientWidth = img.clientWidth; const ratio = img.width / img.height; let width2 = imgClientHeight * ratio; let height = imgClientHeight; if (width2 > imgClientWidth) { width2 = imgClientWidth; height = imgClientWidth / ratio; } const x2 = (imgClientWidth - width2) / 2; const y2 = (imgClientHeight - height) / 2; return { startX: x2, startY: y2, endX: width2 + x2, endY: height + y2 }; }, "getContainedSize"); function ScreenshotEditorFactory({ h: h2, hooks: hooks2, imageBuffer, dialog, options: options4 }) { const useTakeScreenshot = useTakeScreenshotFactory({ hooks: hooks2 }); return /* @__PURE__ */ __name(function ScreenshotEditor({ onError }) { const styles = hooks2.useMemo(() => ({ __html: createScreenshotInputStyles(options4.styleNonce).innerText }), []); const CropCorner = CropCornerFactory({ h: h2 }); const canvasContainerRef = hooks2.useRef(null); const cropContainerRef = hooks2.useRef(null); const croppingRef = hooks2.useRef(null); const [croppingRect, setCroppingRect] = hooks2.useState({ startX: 0, startY: 0, endX: 0, endY: 0 }); const [confirmCrop, setConfirmCrop] = hooks2.useState(false); const [isResizing, setIsResizing] = hooks2.useState(false); hooks2.useEffect(() => { WINDOW.addEventListener("resize", resizeCropper, false); }, []); function resizeCropper() { const cropper = croppingRef.current; const imageDimensions = constructRect(getContainedSize(imageBuffer)); if (cropper) { cropper.width = imageDimensions.width * DPI; cropper.height = imageDimensions.height * DPI; cropper.style.width = `${imageDimensions.width}px`; cropper.style.height = `${imageDimensions.height}px`; const ctx = cropper.getContext("2d"); if (ctx) { ctx.scale(DPI, DPI); } } const cropButton = cropContainerRef.current; if (cropButton) { cropButton.style.width = `${imageDimensions.width}px`; cropButton.style.height = `${imageDimensions.height}px`; } setCroppingRect({ startX: 0, startY: 0, endX: imageDimensions.width, endY: imageDimensions.height }); } __name(resizeCropper, "resizeCropper"); hooks2.useEffect(() => { const cropper = croppingRef.current; if (!cropper) { return; } const ctx = cropper.getContext("2d"); if (!ctx) { return; } const imageDimensions = constructRect(getContainedSize(imageBuffer)); const croppingBox = constructRect(croppingRect); ctx.clearRect(0, 0, imageDimensions.width, imageDimensions.height); ctx.fillStyle = "rgba(0, 0, 0, 0.5)"; ctx.fillRect(0, 0, imageDimensions.width, imageDimensions.height); ctx.clearRect(croppingBox.x, croppingBox.y, croppingBox.width, croppingBox.height); ctx.strokeStyle = "#ffffff"; ctx.lineWidth = 3; ctx.strokeRect(croppingBox.x + 1, croppingBox.y + 1, croppingBox.width - 2, croppingBox.height - 2); ctx.strokeStyle = "#000000"; ctx.lineWidth = 1; ctx.strokeRect(croppingBox.x + 3, croppingBox.y + 3, croppingBox.width - 6, croppingBox.height - 6); }, [croppingRect]); function onGrabButton(e2, corner) { setConfirmCrop(false); setIsResizing(true); const handleMouseMove2 = makeHandleMouseMove(corner); const handleMouseUp = /* @__PURE__ */ __name(() => { DOCUMENT.removeEventListener("mousemove", handleMouseMove2); DOCUMENT.removeEventListener("mouseup", handleMouseUp); setConfirmCrop(true); setIsResizing(false); }, "handleMouseUp"); DOCUMENT.addEventListener("mouseup", handleMouseUp); DOCUMENT.addEventListener("mousemove", handleMouseMove2); } __name(onGrabButton, "onGrabButton"); const makeHandleMouseMove = hooks2.useCallback((corner) => { return function(e2) { if (!croppingRef.current) { return; } const cropCanvas = croppingRef.current; const cropBoundingRect = cropCanvas.getBoundingClientRect(); const mouseX = e2.clientX - cropBoundingRect.x; const mouseY = e2.clientY - cropBoundingRect.y; switch (corner) { case "top-left": setCroppingRect((prev2) => ({ ...prev2, startX: Math.min(Math.max(0, mouseX), prev2.endX - CROP_BUTTON_OFFSET), startY: Math.min(Math.max(0, mouseY), prev2.endY - CROP_BUTTON_OFFSET) })); break; case "top-right": setCroppingRect((prev2) => ({ ...prev2, endX: Math.max(Math.min(mouseX, cropCanvas.width / DPI), prev2.startX + CROP_BUTTON_OFFSET), startY: Math.min(Math.max(0, mouseY), prev2.endY - CROP_BUTTON_OFFSET) })); break; case "bottom-left": setCroppingRect((prev2) => ({ ...prev2, startX: Math.min(Math.max(0, mouseX), prev2.endX - CROP_BUTTON_OFFSET), endY: Math.max(Math.min(mouseY, cropCanvas.height / DPI), prev2.startY + CROP_BUTTON_OFFSET) })); break; case "bottom-right": setCroppingRect((prev2) => ({ ...prev2, endX: Math.max(Math.min(mouseX, cropCanvas.width / DPI), prev2.startX + CROP_BUTTON_OFFSET), endY: Math.max(Math.min(mouseY, cropCanvas.height / DPI), prev2.startY + CROP_BUTTON_OFFSET) })); break; } }; }, []); const initialPositionRef = hooks2.useRef({ initialX: 0, initialY: 0 }); function onDragStart2(e2) { if (isResizing) return; initialPositionRef.current = { initialX: e2.clientX, initialY: e2.clientY }; const handleMouseMove2 = /* @__PURE__ */ __name((moveEvent) => { const cropCanvas = croppingRef.current; if (!cropCanvas) return; const deltaX = moveEvent.clientX - initialPositionRef.current.initialX; const deltaY = moveEvent.clientY - initialPositionRef.current.initialY; setCroppingRect((prev2) => { const newStartX = Math.max( 0, Math.min(prev2.startX + deltaX, cropCanvas.width / DPI - (prev2.endX - prev2.startX)) ); const newStartY = Math.max( 0, Math.min(prev2.startY + deltaY, cropCanvas.height / DPI - (prev2.endY - prev2.startY)) ); const newEndX = newStartX + (prev2.endX - prev2.startX); const newEndY = newStartY + (prev2.endY - prev2.startY); initialPositionRef.current.initialX = moveEvent.clientX; initialPositionRef.current.initialY = moveEvent.clientY; return { startX: newStartX, startY: newStartY, endX: newEndX, endY: newEndY }; }); }, "handleMouseMove"); const handleMouseUp = /* @__PURE__ */ __name(() => { DOCUMENT.removeEventListener("mousemove", handleMouseMove2); DOCUMENT.removeEventListener("mouseup", handleMouseUp); }, "handleMouseUp"); DOCUMENT.addEventListener("mousemove", handleMouseMove2); DOCUMENT.addEventListener("mouseup", handleMouseUp); } __name(onDragStart2, "onDragStart"); function submit() { const cutoutCanvas = DOCUMENT.createElement("canvas"); const imageBox = constructRect(getContainedSize(imageBuffer)); const croppingBox = constructRect(croppingRect); cutoutCanvas.width = croppingBox.width * DPI; cutoutCanvas.height = croppingBox.height * DPI; const cutoutCtx = cutoutCanvas.getContext("2d"); if (cutoutCtx && imageBuffer) { cutoutCtx.drawImage( imageBuffer, croppingBox.x / imageBox.width * imageBuffer.width, croppingBox.y / imageBox.height * imageBuffer.height, croppingBox.width / imageBox.width * imageBuffer.width, croppingBox.height / imageBox.height * imageBuffer.height, 0, 0, cutoutCanvas.width, cutoutCanvas.height ); } const ctx = imageBuffer.getContext("2d"); if (ctx) { ctx.clearRect(0, 0, imageBuffer.width, imageBuffer.height); imageBuffer.width = cutoutCanvas.width; imageBuffer.height = cutoutCanvas.height; imageBuffer.style.width = `${croppingBox.width}px`; imageBuffer.style.height = `${croppingBox.height}px`; ctx.drawImage(cutoutCanvas, 0, 0); resizeCropper(); } } __name(submit, "submit"); useTakeScreenshot({ onBeforeScreenshot: hooks2.useCallback(() => { dialog.el.style.display = "none"; }, []), onScreenshot: hooks2.useCallback( (imageSource) => { const context = imageBuffer.getContext("2d"); if (!context) { throw new Error("Could not get canvas context"); } imageBuffer.width = imageSource.videoWidth; imageBuffer.height = imageSource.videoHeight; imageBuffer.style.width = "100%"; imageBuffer.style.height = "100%"; context.drawImage(imageSource, 0, 0); }, [imageBuffer] ), onAfterScreenshot: hooks2.useCallback(() => { dialog.el.style.display = "block"; const container = canvasContainerRef.current; container && container.appendChild(imageBuffer); resizeCropper(); }, []), onError: hooks2.useCallback((error2) => { dialog.el.style.display = "block"; onError(error2); }, []) }); return h2( "div", { class: "editor" }, h2("style", { nonce: options4.styleNonce, dangerouslySetInnerHTML: styles }), h2( "div", { class: "editor__canvas-container", ref: canvasContainerRef }, h2( "div", { class: "editor__crop-container", style: { position: "absolute", zIndex: 1 }, ref: cropContainerRef }, h2( "canvas", { onMouseDown: onDragStart2, style: { position: "absolute", cursor: confirmCrop ? "move" : "auto" }, ref: croppingRef } ), h2( CropCorner, { left: croppingRect.startX - CROP_BUTTON_BORDER, top: croppingRect.startY - CROP_BUTTON_BORDER, onGrabButton, corner: "top-left" } ), h2( CropCorner, { left: croppingRect.endX - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER, top: croppingRect.startY - CROP_BUTTON_BORDER, onGrabButton, corner: "top-right" } ), h2( CropCorner, { left: croppingRect.startX - CROP_BUTTON_BORDER, top: croppingRect.endY - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER, onGrabButton, corner: "bottom-left" } ), h2( CropCorner, { left: croppingRect.endX - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER, top: croppingRect.endY - CROP_BUTTON_SIZE + CROP_BUTTON_BORDER, onGrabButton, corner: "bottom-right" } ), h2( "div", { style: { left: Math.max(0, croppingRect.endX - 191), top: Math.max(0, croppingRect.endY + 8), display: confirmCrop ? "flex" : "none" }, class: "editor__crop-btn-group" }, h2( "button", { onClick: /* @__PURE__ */ __name((e2) => { e2.preventDefault(); if (croppingRef.current) { setCroppingRect({ startX: 0, startY: 0, endX: croppingRef.current.width / DPI, endY: croppingRef.current.height / DPI }); } setConfirmCrop(false); }, "onClick"), class: "btn btn--default" }, options4.cancelButtonLabel ), h2( "button", { onClick: /* @__PURE__ */ __name((e2) => { e2.preventDefault(); submit(); setConfirmCrop(false); }, "onClick"), class: "btn btn--primary" }, options4.confirmButtonLabel ) ) ) ) ); }, "ScreenshotEditor"); } __name(ScreenshotEditorFactory, "ScreenshotEditorFactory"); const feedbackScreenshotIntegration = /* @__PURE__ */ __name(() => { return { name: "FeedbackScreenshot", // eslint-disable-next-line @typescript-eslint/no-empty-function setupOnce() { }, createInput: /* @__PURE__ */ __name(({ h: h2, hooks: hooks2, dialog, options: options4 }) => { const imageBuffer = DOCUMENT.createElement("canvas"); return { input: ScreenshotEditorFactory({ h: h2, hooks: hooks2, imageBuffer, dialog, options: options4 }), // eslint-disable-line @typescript-eslint/no-explicit-any value: /* @__PURE__ */ __name(async () => { const blob = await new Promise((resolve2) => { imageBuffer.toBlob(resolve2, "image/png"); }); if (blob) { const data25 = new Uint8Array(await blob.arrayBuffer()); const attachment = { data: data25, filename: "screenshot.png", contentType: "application/png" // attachmentType?: string; }; return attachment; } return void 0; }, "value") }; }, "createInput") }; }, "feedbackScreenshotIntegration"); const feedbackAsyncIntegration = buildFeedbackIntegration({ lazyLoadIntegration }); const feedbackSyncIntegration = buildFeedbackIntegration({ getModalIntegration: /* @__PURE__ */ __name(() => feedbackModalIntegration, "getModalIntegration"), getScreenshotIntegration: /* @__PURE__ */ __name(() => feedbackScreenshotIntegration, "getScreenshotIntegration") }); function increment(name2, value4 = 1, data25) { metrics$1.increment(BrowserMetricsAggregator, name2, value4, data25); } __name(increment, "increment"); function distribution(name2, value4, data25) { metrics$1.distribution(BrowserMetricsAggregator, name2, value4, data25); } __name(distribution, "distribution"); function set$5(name2, value4, data25) { metrics$1.set(BrowserMetricsAggregator, name2, value4, data25); } __name(set$5, "set$5"); function gauge(name2, value4, data25) { metrics$1.gauge(BrowserMetricsAggregator, name2, value4, data25); } __name(gauge, "gauge"); function timing(name2, value4, unit = "second", data25) { return metrics$1.timing(BrowserMetricsAggregator, name2, value4, unit, data25); } __name(timing, "timing"); const metrics = { increment, distribution, set: set$5, gauge, timing }; const responseToSpanId = /* @__PURE__ */ new WeakMap(); const spanIdToEndTimestamp = /* @__PURE__ */ new Map(); const defaultRequestInstrumentationOptions = { traceFetch: true, traceXHR: true, enableHTTPTimings: true, trackFetchStreamPerformance: false }; function instrumentOutgoingRequests(client, _options) { const { traceFetch, traceXHR, trackFetchStreamPerformance, shouldCreateSpanForRequest, enableHTTPTimings, tracePropagationTargets } = { traceFetch: defaultRequestInstrumentationOptions.traceFetch, traceXHR: defaultRequestInstrumentationOptions.traceXHR, trackFetchStreamPerformance: defaultRequestInstrumentationOptions.trackFetchStreamPerformance, ..._options }; const shouldCreateSpan = typeof shouldCreateSpanForRequest === "function" ? shouldCreateSpanForRequest : (_2) => true; const shouldAttachHeadersWithTargets = /* @__PURE__ */ __name((url) => shouldAttachHeaders(url, tracePropagationTargets), "shouldAttachHeadersWithTargets"); const spans = {}; if (traceFetch) { client.addEventProcessor((event) => { if (event.type === "transaction" && event.spans) { event.spans.forEach((span) => { if (span.op === "http.client") { const updatedTimestamp = spanIdToEndTimestamp.get(span.span_id); if (updatedTimestamp) { span.timestamp = updatedTimestamp / 1e3; spanIdToEndTimestamp.delete(span.span_id); } } }); } return event; }); if (trackFetchStreamPerformance) { addFetchEndInstrumentationHandler((handlerData) => { if (handlerData.response) { const span = responseToSpanId.get(handlerData.response); if (span && handlerData.endTimestamp) { spanIdToEndTimestamp.set(span, handlerData.endTimestamp); } } }); } addFetchInstrumentationHandler((handlerData) => { const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans); if (handlerData.response && handlerData.fetchData.__span) { responseToSpanId.set(handlerData.response, handlerData.fetchData.__span); } if (createdSpan) { const fullUrl = getFullURL(handlerData.fetchData.url); const host = fullUrl ? parseUrl$1(fullUrl).host : void 0; createdSpan.setAttributes({ "http.url": fullUrl, "server.address": host }); } if (enableHTTPTimings && createdSpan) { addHTTPTimings(createdSpan); } }); } if (traceXHR) { addXhrInstrumentationHandler((handlerData) => { const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans); if (enableHTTPTimings && createdSpan) { addHTTPTimings(createdSpan); } }); } } __name(instrumentOutgoingRequests, "instrumentOutgoingRequests"); function isPerformanceResourceTiming(entry) { return entry.entryType === "resource" && "initiatorType" in entry && typeof entry.nextHopProtocol === "string" && (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest"); } __name(isPerformanceResourceTiming, "isPerformanceResourceTiming"); function addHTTPTimings(span) { const { url } = spanToJSON(span).data || {}; if (!url || typeof url !== "string") { return; } const cleanup = addPerformanceInstrumentationHandler("resource", ({ entries }) => { entries.forEach((entry) => { if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) { const spanData = resourceTimingEntryToSpanData(entry); spanData.forEach((data25) => span.setAttribute(...data25)); setTimeout(cleanup); } }); }); } __name(addHTTPTimings, "addHTTPTimings"); function extractNetworkProtocol(nextHopProtocol) { let name2 = "unknown"; let version2 = "unknown"; let _name = ""; for (const char of nextHopProtocol) { if (char === "/") { [name2, version2] = nextHopProtocol.split("/"); break; } if (!isNaN(Number(char))) { name2 = _name === "h" ? "http" : _name; version2 = nextHopProtocol.split(_name)[1]; break; } _name += char; } if (_name === nextHopProtocol) { name2 = _name; } return { name: name2, version: version2 }; } __name(extractNetworkProtocol, "extractNetworkProtocol"); function getAbsoluteTime(time = 0) { return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1e3; } __name(getAbsoluteTime, "getAbsoluteTime"); function resourceTimingEntryToSpanData(resourceTiming) { const { name: name2, version: version2 } = extractNetworkProtocol(resourceTiming.nextHopProtocol); const timingSpanData = []; timingSpanData.push(["network.protocol.version", version2], ["network.protocol.name", name2]); if (!browserPerformanceTimeOrigin) { return timingSpanData; } return [ ...timingSpanData, ["http.request.redirect_start", getAbsoluteTime(resourceTiming.redirectStart)], ["http.request.fetch_start", getAbsoluteTime(resourceTiming.fetchStart)], ["http.request.domain_lookup_start", getAbsoluteTime(resourceTiming.domainLookupStart)], ["http.request.domain_lookup_end", getAbsoluteTime(resourceTiming.domainLookupEnd)], ["http.request.connect_start", getAbsoluteTime(resourceTiming.connectStart)], ["http.request.secure_connection_start", getAbsoluteTime(resourceTiming.secureConnectionStart)], ["http.request.connection_end", getAbsoluteTime(resourceTiming.connectEnd)], ["http.request.request_start", getAbsoluteTime(resourceTiming.requestStart)], ["http.request.response_start", getAbsoluteTime(resourceTiming.responseStart)], ["http.request.response_end", getAbsoluteTime(resourceTiming.responseEnd)] ]; } __name(resourceTimingEntryToSpanData, "resourceTimingEntryToSpanData"); function shouldAttachHeaders(targetUrl, tracePropagationTargets) { const href = WINDOW$5.location && WINDOW$5.location.href; if (!href) { const isRelativeSameOriginRequest = !!targetUrl.match(/^\/(?!\/)/); if (!tracePropagationTargets) { return isRelativeSameOriginRequest; } else { return stringMatchesSomePattern(targetUrl, tracePropagationTargets); } } else { let resolvedUrl; let currentOrigin; try { resolvedUrl = new URL(targetUrl, href); currentOrigin = new URL(href).origin; } catch (e2) { return false; } const isSameOriginRequest = resolvedUrl.origin === currentOrigin; if (!tracePropagationTargets) { return isSameOriginRequest; } else { return stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) || isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets); } } } __name(shouldAttachHeaders, "shouldAttachHeaders"); function xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeaders2, spans) { const xhr = handlerData.xhr; const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY]; if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) { return void 0; } const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(sentryXhrData.url); if (handlerData.endTimestamp && shouldCreateSpanResult) { const spanId = xhr.__sentry_xhr_span_id__; if (!spanId) return; const span2 = spans[spanId]; if (span2 && sentryXhrData.status_code !== void 0) { setHttpStatus(span2, sentryXhrData.status_code); span2.end(); delete spans[spanId]; } return void 0; } const fullUrl = getFullURL(sentryXhrData.url); const host = fullUrl ? parseUrl$1(fullUrl).host : void 0; const hasParent = !!getActiveSpan(); const span = shouldCreateSpanResult && hasParent ? startInactiveSpan({ name: `${sentryXhrData.method} ${sentryXhrData.url}`, attributes: { type: "xhr", "http.method": sentryXhrData.method, "http.url": fullUrl, url: sentryXhrData.url, "server.address": host, [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser", [SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.client" } }) : new SentryNonRecordingSpan(); xhr.__sentry_xhr_span_id__ = span.spanContext().spanId; spans[xhr.__sentry_xhr_span_id__] = span; if (shouldAttachHeaders2(sentryXhrData.url)) { addTracingHeadersToXhrRequest( xhr, // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction), // we do not want to use the span as base for the trace headers, // which means that the headers will be generated from the scope and the sampling decision is deferred hasTracingEnabled() && hasParent ? span : void 0 ); } return span; } __name(xhrCallback, "xhrCallback"); function addTracingHeadersToXhrRequest(xhr, span) { const { "sentry-trace": sentryTrace, baggage } = getTraceData({ span }); if (sentryTrace) { setHeaderOnXhr(xhr, sentryTrace, baggage); } } __name(addTracingHeadersToXhrRequest, "addTracingHeadersToXhrRequest"); function setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader) { try { xhr.setRequestHeader("sentry-trace", sentryTraceHeader); if (sentryBaggageHeader) { xhr.setRequestHeader("baggage", sentryBaggageHeader); } } catch (_2) { } } __name(setHeaderOnXhr, "setHeaderOnXhr"); function getFullURL(url) { try { const parsed = new URL(url, WINDOW$5.location.origin); return parsed.href; } catch (e2) { return void 0; } } __name(getFullURL, "getFullURL"); function registerBackgroundTabDetection() { if (WINDOW$5 && WINDOW$5.document) { WINDOW$5.document.addEventListener("visibilitychange", () => { const activeSpan = getActiveSpan(); if (!activeSpan) { return; } const rootSpan = getRootSpan(activeSpan); if (WINDOW$5.document.hidden && rootSpan) { const cancelledStatus = "cancelled"; const { op, status } = spanToJSON(rootSpan); if (DEBUG_BUILD$4) { logger$2.log(`[Tracing] Transaction: ${cancelledStatus} -> since tab moved to the background, op: ${op}`); } if (!status) { rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message: cancelledStatus }); } rootSpan.setAttribute("sentry.cancellation_reason", "document.hidden"); rootSpan.end(); } }); } else { DEBUG_BUILD$4 && logger$2.warn("[Tracing] Could not set up background tab detection due to lack of global document"); } } __name(registerBackgroundTabDetection, "registerBackgroundTabDetection"); const BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing"; const DEFAULT_BROWSER_TRACING_OPTIONS = { ...TRACING_DEFAULTS, instrumentNavigation: true, instrumentPageLoad: true, markBackgroundSpan: true, enableLongTask: true, enableLongAnimationFrame: true, enableInp: true, _experiments: {}, ...defaultRequestInstrumentationOptions }; const browserTracingIntegration$1 = /* @__PURE__ */ __name((_options = {}) => { registerSpanErrorInstrumentation(); const { enableInp, enableLongTask, enableLongAnimationFrame, _experiments: { enableInteractions, enableStandaloneClsSpans }, beforeStartSpan, idleTimeout, finalTimeout, childSpanTimeout, markBackgroundSpan, traceFetch, traceXHR, trackFetchStreamPerformance, shouldCreateSpanForRequest, enableHTTPTimings, instrumentPageLoad, instrumentNavigation } = { ...DEFAULT_BROWSER_TRACING_OPTIONS, ..._options }; const _collectWebVitals = startTrackingWebVitals({ recordClsStandaloneSpans: enableStandaloneClsSpans || false }); if (enableInp) { startTrackingINP(); } if (enableLongAnimationFrame && GLOBAL_OBJ.PerformanceObserver && PerformanceObserver.supportedEntryTypes && PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")) { startTrackingLongAnimationFrames(); } else if (enableLongTask) { startTrackingLongTasks(); } if (enableInteractions) { startTrackingInteractions(); } const latestRoute = { name: void 0, source: void 0 }; function _createRouteSpan(client, startSpanOptions) { const isPageloadTransaction = startSpanOptions.op === "pageload"; const finalStartSpanOptions = beforeStartSpan ? beforeStartSpan(startSpanOptions) : startSpanOptions; const attributes = finalStartSpanOptions.attributes || {}; if (startSpanOptions.name !== finalStartSpanOptions.name) { attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = "custom"; finalStartSpanOptions.attributes = attributes; } latestRoute.name = finalStartSpanOptions.name; latestRoute.source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; const idleSpan = startIdleSpan(finalStartSpanOptions, { idleTimeout, finalTimeout, childSpanTimeout, // should wait for finish signal if it's a pageload transaction disableAutoFinish: isPageloadTransaction, beforeSpanEnd: /* @__PURE__ */ __name((span) => { _collectWebVitals(); addPerformanceEntries(span, { recordClsOnPageloadSpan: !enableStandaloneClsSpans }); }, "beforeSpanEnd") }); function emitFinish() { if (["interactive", "complete"].includes(WINDOW$5.document.readyState)) { client.emit("idleSpanEnableAutoFinish", idleSpan); } } __name(emitFinish, "emitFinish"); if (isPageloadTransaction && WINDOW$5.document) { WINDOW$5.document.addEventListener("readystatechange", () => { emitFinish(); }); emitFinish(); } return idleSpan; } __name(_createRouteSpan, "_createRouteSpan"); return { name: BROWSER_TRACING_INTEGRATION_ID, afterAllSetup(client) { let activeSpan; let startingUrl = WINDOW$5.location && WINDOW$5.location.href; function maybeEndActiveSpan() { if (activeSpan && !spanToJSON(activeSpan).timestamp) { DEBUG_BUILD$4 && logger$2.log(`[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).op}`); activeSpan.end(); } } __name(maybeEndActiveSpan, "maybeEndActiveSpan"); client.on("startNavigationSpan", (startSpanOptions) => { if (getClient() !== client) { return; } maybeEndActiveSpan(); activeSpan = _createRouteSpan(client, { op: "navigation", ...startSpanOptions }); }); client.on("startPageLoadSpan", (startSpanOptions, traceOptions = {}) => { if (getClient() !== client) { return; } maybeEndActiveSpan(); const sentryTrace = traceOptions.sentryTrace || getMetaContent("sentry-trace"); const baggage = traceOptions.baggage || getMetaContent("baggage"); const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); getCurrentScope$1().setPropagationContext(propagationContext); activeSpan = _createRouteSpan(client, { op: "pageload", ...startSpanOptions }); }); client.on("spanEnd", (span) => { const op = spanToJSON(span).op; if (span !== getRootSpan(span) || op !== "navigation" && op !== "pageload") { return; } const scope = getCurrentScope$1(); const oldPropagationContext = scope.getPropagationContext(); scope.setPropagationContext({ ...oldPropagationContext, sampled: oldPropagationContext.sampled !== void 0 ? oldPropagationContext.sampled : spanIsSampled(span), dsc: oldPropagationContext.dsc || getDynamicSamplingContextFromSpan(span) }); }); if (WINDOW$5.location) { if (instrumentPageLoad) { startBrowserTracingPageLoadSpan(client, { name: WINDOW$5.location.pathname, // pageload should always start at timeOrigin (and needs to be in s, not ms) startTime: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1e3 : void 0, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url", [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.browser" } }); } if (instrumentNavigation) { addHistoryInstrumentationHandler(({ to, from: from2 }) => { if (from2 === void 0 && startingUrl && startingUrl.indexOf(to) !== -1) { startingUrl = void 0; return; } if (from2 !== to) { startingUrl = void 0; startBrowserTracingNavigationSpan(client, { name: WINDOW$5.location.pathname, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url", [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.navigation.browser" } }); } }); } } if (markBackgroundSpan) { registerBackgroundTabDetection(); } if (enableInteractions) { registerInteractionListener(idleTimeout, finalTimeout, childSpanTimeout, latestRoute); } if (enableInp) { registerInpInteractionListener(); } instrumentOutgoingRequests(client, { traceFetch, traceXHR, trackFetchStreamPerformance, tracePropagationTargets: client.getOptions().tracePropagationTargets, shouldCreateSpanForRequest, enableHTTPTimings }); } }; }, "browserTracingIntegration$1"); function startBrowserTracingPageLoadSpan(client, spanOptions, traceOptions) { client.emit("startPageLoadSpan", spanOptions, traceOptions); getCurrentScope$1().setTransactionName(spanOptions.name); const span = getActiveSpan(); const op = span && spanToJSON(span).op; return op === "pageload" ? span : void 0; } __name(startBrowserTracingPageLoadSpan, "startBrowserTracingPageLoadSpan"); function startBrowserTracingNavigationSpan(client, spanOptions) { getIsolationScope().setPropagationContext({ traceId: generateTraceId() }); getCurrentScope$1().setPropagationContext({ traceId: generateTraceId() }); client.emit("startNavigationSpan", spanOptions); getCurrentScope$1().setTransactionName(spanOptions.name); const span = getActiveSpan(); const op = span && spanToJSON(span).op; return op === "navigation" ? span : void 0; } __name(startBrowserTracingNavigationSpan, "startBrowserTracingNavigationSpan"); function getMetaContent(metaName) { const metaTag = getDomElement(`meta[name=${metaName}]`); return metaTag ? metaTag.getAttribute("content") : void 0; } __name(getMetaContent, "getMetaContent"); function registerInteractionListener(idleTimeout, finalTimeout, childSpanTimeout, latestRoute) { let inflightInteractionSpan; const registerInteractionTransaction = /* @__PURE__ */ __name(() => { const op = "ui.action.click"; const activeSpan = getActiveSpan(); const rootSpan = activeSpan && getRootSpan(activeSpan); if (rootSpan) { const currentRootSpanOp = spanToJSON(rootSpan).op; if (["navigation", "pageload"].includes(currentRootSpanOp)) { DEBUG_BUILD$4 && logger$2.warn(`[Tracing] Did not create ${op} span because a pageload or navigation span is in progress.`); return void 0; } } if (inflightInteractionSpan) { inflightInteractionSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, "interactionInterrupted"); inflightInteractionSpan.end(); inflightInteractionSpan = void 0; } if (!latestRoute.name) { DEBUG_BUILD$4 && logger$2.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`); return void 0; } inflightInteractionSpan = startIdleSpan( { name: latestRoute.name, op, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.source || "url" } }, { idleTimeout, finalTimeout, childSpanTimeout } ); }, "registerInteractionTransaction"); if (WINDOW$5.document) { addEventListener("click", registerInteractionTransaction, { once: false, capture: true }); } } __name(registerInteractionListener, "registerInteractionListener"); function promisifyRequest(request) { return new Promise((resolve2, reject3) => { request.oncomplete = request.onsuccess = () => resolve2(request.result); request.onabort = request.onerror = () => reject3(request.error); }); } __name(promisifyRequest, "promisifyRequest"); function createStore(dbName, storeName) { const request = indexedDB.open(dbName); request.onupgradeneeded = () => request.result.createObjectStore(storeName); const dbp = promisifyRequest(request); return (callback) => dbp.then((db) => callback(db.transaction(storeName, "readwrite").objectStore(storeName))); } __name(createStore, "createStore"); function keys$7(store) { return promisifyRequest(store.getAllKeys()); } __name(keys$7, "keys$7"); function push(store, value4, maxQueueSize) { return store((store2) => { return keys$7(store2).then((keys2) => { if (keys2.length >= maxQueueSize) { return; } store2.put(value4, Math.max(...keys2, 0) + 1); return promisifyRequest(store2.transaction); }); }); } __name(push, "push"); function unshift(store, value4, maxQueueSize) { return store((store2) => { return keys$7(store2).then((keys2) => { if (keys2.length >= maxQueueSize) { return; } store2.put(value4, Math.min(...keys2, 0) - 1); return promisifyRequest(store2.transaction); }); }); } __name(unshift, "unshift"); function shift$1(store) { return store((store2) => { return keys$7(store2).then((keys2) => { const firstKey = keys2[0]; if (firstKey == null) { return void 0; } return promisifyRequest(store2.get(firstKey)).then((value4) => { store2.delete(firstKey); return promisifyRequest(store2.transaction).then(() => value4); }); }); }); } __name(shift$1, "shift$1"); function createIndexedDbStore(options4) { let store; function getStore() { if (store == void 0) { store = createStore(options4.dbName || "sentry-offline", options4.storeName || "queue"); } return store; } __name(getStore, "getStore"); return { push: /* @__PURE__ */ __name(async (env) => { try { const serialized = await serializeEnvelope(env); await push(getStore(), serialized, options4.maxQueueSize || 30); } catch (_2) { } }, "push"), unshift: /* @__PURE__ */ __name(async (env) => { try { const serialized = await serializeEnvelope(env); await unshift(getStore(), serialized, options4.maxQueueSize || 30); } catch (_2) { } }, "unshift"), shift: /* @__PURE__ */ __name(async () => { try { const deserialized = await shift$1(getStore()); if (deserialized) { return parseEnvelope(deserialized); } } catch (_2) { } return void 0; }, "shift") }; } __name(createIndexedDbStore, "createIndexedDbStore"); function makeIndexedDbOfflineTransport(createTransport2) { return (options4) => createTransport2({ ...options4, createStore: createIndexedDbStore }); } __name(makeIndexedDbOfflineTransport, "makeIndexedDbOfflineTransport"); function makeBrowserOfflineTransport(createTransport2 = makeFetchTransport) { return makeIndexedDbOfflineTransport(makeOfflineTransport(createTransport2)); } __name(makeBrowserOfflineTransport, "makeBrowserOfflineTransport"); const MS_TO_NS = 1e6; const THREAD_ID_STRING = String(0); const THREAD_NAME = "main"; let OS_PLATFORM = ""; let OS_PLATFORM_VERSION = ""; let OS_ARCH = ""; let OS_BROWSER = WINDOW$5.navigator && WINDOW$5.navigator.userAgent || ""; let OS_MODEL = ""; const OS_LOCALE = WINDOW$5.navigator && WINDOW$5.navigator.language || WINDOW$5.navigator && WINDOW$5.navigator.languages && WINDOW$5.navigator.languages[0] || ""; function isUserAgentData(data25) { return typeof data25 === "object" && data25 !== null && "getHighEntropyValues" in data25; } __name(isUserAgentData, "isUserAgentData"); const userAgentData = WINDOW$5.navigator && WINDOW$5.navigator.userAgentData; if (isUserAgentData(userAgentData)) { userAgentData.getHighEntropyValues(["architecture", "model", "platform", "platformVersion", "fullVersionList"]).then((ua) => { OS_PLATFORM = ua.platform || ""; OS_ARCH = ua.architecture || ""; OS_MODEL = ua.model || ""; OS_PLATFORM_VERSION = ua.platformVersion || ""; if (ua.fullVersionList && ua.fullVersionList.length > 0) { const firstUa = ua.fullVersionList[ua.fullVersionList.length - 1]; OS_BROWSER = `${firstUa.brand} ${firstUa.version}`; } }).catch((e2) => void 0); } function isProcessedJSSelfProfile(profile) { return !("thread_metadata" in profile); } __name(isProcessedJSSelfProfile, "isProcessedJSSelfProfile"); function enrichWithThreadInformation(profile) { if (!isProcessedJSSelfProfile(profile)) { return profile; } return convertJSSelfProfileToSampledFormat(profile); } __name(enrichWithThreadInformation, "enrichWithThreadInformation"); function getTraceId(event) { const traceId = event && event.contexts && event.contexts["trace"] && event.contexts["trace"]["trace_id"]; if (typeof traceId === "string" && traceId.length !== 32) { if (DEBUG_BUILD$4) { logger$2.log(`[Profiling] Invalid traceId: ${traceId} on profiled event`); } } if (typeof traceId !== "string") { return ""; } return traceId; } __name(getTraceId, "getTraceId"); function createProfilePayload(profile_id, start_timestamp, processed_profile, event) { if (event.type !== "transaction") { throw new TypeError("Profiling events may only be attached to transactions, this should never occur."); } if (processed_profile === void 0 || processed_profile === null) { throw new TypeError( `Cannot construct profiling event envelope without a valid profile. Got ${processed_profile} instead.` ); } const traceId = getTraceId(event); const enrichedThreadProfile = enrichWithThreadInformation(processed_profile); const transactionStartMs = start_timestamp ? start_timestamp : typeof event.start_timestamp === "number" ? event.start_timestamp * 1e3 : timestampInSeconds() * 1e3; const transactionEndMs = typeof event.timestamp === "number" ? event.timestamp * 1e3 : timestampInSeconds() * 1e3; const profile = { event_id: profile_id, timestamp: new Date(transactionStartMs).toISOString(), platform: "javascript", version: "1", release: event.release || "", environment: event.environment || DEFAULT_ENVIRONMENT, runtime: { name: "javascript", version: WINDOW$5.navigator.userAgent }, os: { name: OS_PLATFORM, version: OS_PLATFORM_VERSION, build_number: OS_BROWSER }, device: { locale: OS_LOCALE, model: OS_MODEL, manufacturer: OS_BROWSER, architecture: OS_ARCH, is_emulator: false }, debug_meta: { images: applyDebugMetadata(processed_profile.resources) }, profile: enrichedThreadProfile, transactions: [ { name: event.transaction || "", id: event.event_id || uuid4(), trace_id: traceId, active_thread_id: THREAD_ID_STRING, relative_start_ns: "0", relative_end_ns: ((transactionEndMs - transactionStartMs) * 1e6).toFixed(0) } ] }; return profile; } __name(createProfilePayload, "createProfilePayload"); function isAutomatedPageLoadSpan(span) { return spanToJSON(span).op === "pageload"; } __name(isAutomatedPageLoadSpan, "isAutomatedPageLoadSpan"); function convertJSSelfProfileToSampledFormat(input) { let EMPTY_STACK_ID = void 0; let STACK_ID = 0; const profile = { samples: [], stacks: [], frames: [], thread_metadata: { [THREAD_ID_STRING]: { name: THREAD_NAME } } }; const firstSample = input.samples[0]; if (!firstSample) { return profile; } const start2 = firstSample.timestamp; const origin2 = typeof performance.timeOrigin === "number" ? performance.timeOrigin : browserPerformanceTimeOrigin || 0; const adjustForOriginChange = origin2 - (browserPerformanceTimeOrigin || origin2); input.samples.forEach((jsSample, i2) => { if (jsSample.stackId === void 0) { if (EMPTY_STACK_ID === void 0) { EMPTY_STACK_ID = STACK_ID; profile.stacks[EMPTY_STACK_ID] = []; STACK_ID++; } profile["samples"][i2] = { // convert ms timestamp to ns elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start2) * MS_TO_NS).toFixed(0), stack_id: EMPTY_STACK_ID, thread_id: THREAD_ID_STRING }; return; } let stackTop = input.stacks[jsSample.stackId]; const stack2 = []; while (stackTop) { stack2.push(stackTop.frameId); const frame = input.frames[stackTop.frameId]; if (frame && profile.frames[stackTop.frameId] === void 0) { profile.frames[stackTop.frameId] = { function: frame.name, abs_path: typeof frame.resourceId === "number" ? input.resources[frame.resourceId] : void 0, lineno: frame.line, colno: frame.column }; } stackTop = stackTop.parentId === void 0 ? void 0 : input.stacks[stackTop.parentId]; } const sample = { // convert ms timestamp to ns elapsed_since_start_ns: ((jsSample.timestamp + adjustForOriginChange - start2) * MS_TO_NS).toFixed(0), stack_id: STACK_ID, thread_id: THREAD_ID_STRING }; profile["stacks"][STACK_ID] = stack2; profile["samples"][i2] = sample; STACK_ID++; }); return profile; } __name(convertJSSelfProfileToSampledFormat, "convertJSSelfProfileToSampledFormat"); function addProfilesToEnvelope(envelope, profiles) { if (!profiles.length) { return envelope; } for (const profile of profiles) { envelope[1].push([{ type: "profile" }, profile]); } return envelope; } __name(addProfilesToEnvelope, "addProfilesToEnvelope"); function findProfiledTransactionsFromEnvelope(envelope) { const events2 = []; forEachEnvelopeItem(envelope, (item3, type) => { if (type !== "transaction") { return; } for (let j2 = 1; j2 < item3.length; j2++) { const event = item3[j2]; if (event && event.contexts && event.contexts["profile"] && event.contexts["profile"]["profile_id"]) { events2.push(item3[j2]); } } }); return events2; } __name(findProfiledTransactionsFromEnvelope, "findProfiledTransactionsFromEnvelope"); function applyDebugMetadata(resource_paths) { const client = getClient(); const options4 = client && client.getOptions(); const stackParser = options4 && options4.stackParser; if (!stackParser) { return []; } return getDebugImagesForResources(stackParser, resource_paths); } __name(applyDebugMetadata, "applyDebugMetadata"); function isValidSampleRate(rate) { if (typeof rate !== "number" && typeof rate !== "boolean" || typeof rate === "number" && isNaN(rate)) { DEBUG_BUILD$4 && logger$2.warn( `[Profiling] Invalid sample rate. 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; } if (rate === true || rate === false) { return true; } if (rate < 0 || rate > 1) { DEBUG_BUILD$4 && logger$2.warn(`[Profiling] Invalid sample rate. Sample rate must be between 0 and 1. Got ${rate}.`); return false; } return true; } __name(isValidSampleRate, "isValidSampleRate"); function isValidProfile(profile) { if (profile.samples.length < 2) { if (DEBUG_BUILD$4) { logger$2.log("[Profiling] Discarding profile because it contains less than 2 samples"); } return false; } if (!profile.frames.length) { if (DEBUG_BUILD$4) { logger$2.log("[Profiling] Discarding profile because it contains no frames"); } return false; } return true; } __name(isValidProfile, "isValidProfile"); let PROFILING_CONSTRUCTOR_FAILED = false; const MAX_PROFILE_DURATION_MS = 3e4; function isJSProfilerSupported(maybeProfiler) { return typeof maybeProfiler === "function"; } __name(isJSProfilerSupported, "isJSProfilerSupported"); function startJSSelfProfile() { const JSProfilerConstructor = WINDOW$5.Profiler; if (!isJSProfilerSupported(JSProfilerConstructor)) { if (DEBUG_BUILD$4) { logger$2.log( "[Profiling] Profiling is not supported by this browser, Profiler interface missing on window object." ); } return; } const samplingIntervalMS = 10; const maxSamples = Math.floor(MAX_PROFILE_DURATION_MS / samplingIntervalMS); try { return new JSProfilerConstructor({ sampleInterval: samplingIntervalMS, maxBufferSize: maxSamples }); } catch (e2) { if (DEBUG_BUILD$4) { logger$2.log( "[Profiling] Failed to initialize the Profiling constructor, this is likely due to a missing 'Document-Policy': 'js-profiling' header." ); logger$2.log("[Profiling] Disabling profiling for current user session."); } PROFILING_CONSTRUCTOR_FAILED = true; } return; } __name(startJSSelfProfile, "startJSSelfProfile"); function shouldProfileSpan(span) { if (PROFILING_CONSTRUCTOR_FAILED) { if (DEBUG_BUILD$4) { logger$2.log("[Profiling] Profiling has been disabled for the duration of the current user session."); } return false; } if (!span.isRecording()) { if (DEBUG_BUILD$4) { logger$2.log("[Profiling] Discarding profile because transaction was not sampled."); } return false; } const client = getClient(); const options4 = client && client.getOptions(); if (!options4) { DEBUG_BUILD$4 && logger$2.log("[Profiling] Profiling disabled, no options found."); return false; } const profilesSampleRate = options4.profilesSampleRate; if (!isValidSampleRate(profilesSampleRate)) { DEBUG_BUILD$4 && logger$2.warn("[Profiling] Discarding profile because of invalid sample rate."); return false; } if (!profilesSampleRate) { DEBUG_BUILD$4 && logger$2.log( "[Profiling] Discarding profile because a negative sampling decision was inherited or profileSampleRate is set to 0" ); return false; } const sampled = profilesSampleRate === true ? true : Math.random() < profilesSampleRate; if (!sampled) { DEBUG_BUILD$4 && logger$2.log( `[Profiling] Discarding profile because it's not included in the random sample (sampling rate = ${Number( profilesSampleRate )})` ); return false; } return true; } __name(shouldProfileSpan, "shouldProfileSpan"); function createProfilingEvent(profile_id, start_timestamp, profile, event) { if (!isValidProfile(profile)) { return null; } return createProfilePayload(profile_id, start_timestamp, profile, event); } __name(createProfilingEvent, "createProfilingEvent"); const PROFILE_MAP = /* @__PURE__ */ new Map(); function getActiveProfilesCount() { return PROFILE_MAP.size; } __name(getActiveProfilesCount, "getActiveProfilesCount"); function takeProfileFromGlobalCache(profile_id) { const profile = PROFILE_MAP.get(profile_id); if (profile) { PROFILE_MAP.delete(profile_id); } return profile; } __name(takeProfileFromGlobalCache, "takeProfileFromGlobalCache"); function addProfileToGlobalCache(profile_id, profile) { PROFILE_MAP.set(profile_id, profile); if (PROFILE_MAP.size > 30) { const last = PROFILE_MAP.keys().next().value; PROFILE_MAP.delete(last); } } __name(addProfileToGlobalCache, "addProfileToGlobalCache"); function startProfileForSpan(span) { let startTimestamp; if (isAutomatedPageLoadSpan(span)) { startTimestamp = timestampInSeconds() * 1e3; } const profiler2 = startJSSelfProfile(); if (!profiler2) { return; } if (DEBUG_BUILD$4) { logger$2.log(`[Profiling] started profiling span: ${spanToJSON(span).description}`); } const profileId = uuid4(); getCurrentScope$1().setContext("profile", { profile_id: profileId, start_timestamp: startTimestamp }); async function onProfileHandler() { if (!span) { return; } if (!profiler2) { return; } return profiler2.stop().then((profile) => { if (maxDurationTimeoutID) { WINDOW$5.clearTimeout(maxDurationTimeoutID); maxDurationTimeoutID = void 0; } if (DEBUG_BUILD$4) { logger$2.log(`[Profiling] stopped profiling of span: ${spanToJSON(span).description}`); } if (!profile) { if (DEBUG_BUILD$4) { logger$2.log( `[Profiling] profiler returned null profile for: ${spanToJSON(span).description}`, "this may indicate an overlapping span or a call to stopProfiling with a profile title that was never started" ); } return; } addProfileToGlobalCache(profileId, profile); }).catch((error2) => { if (DEBUG_BUILD$4) { logger$2.log("[Profiling] error while stopping profiler:", error2); } }); } __name(onProfileHandler, "onProfileHandler"); let maxDurationTimeoutID = WINDOW$5.setTimeout(() => { if (DEBUG_BUILD$4) { logger$2.log("[Profiling] max profile duration elapsed, stopping profiling for:", spanToJSON(span).description); } onProfileHandler(); }, MAX_PROFILE_DURATION_MS); const originalEnd = span.end.bind(span); function profilingWrappedSpanEnd() { if (!span) { return originalEnd(); } void onProfileHandler().then( () => { originalEnd(); }, () => { originalEnd(); } ); return span; } __name(profilingWrappedSpanEnd, "profilingWrappedSpanEnd"); span.end = profilingWrappedSpanEnd; } __name(startProfileForSpan, "startProfileForSpan"); const INTEGRATION_NAME$2 = "BrowserProfiling"; const _browserProfilingIntegration = /* @__PURE__ */ __name(() => { return { name: INTEGRATION_NAME$2, setup(client) { const activeSpan = getActiveSpan(); const rootSpan = activeSpan && getRootSpan(activeSpan); if (rootSpan && isAutomatedPageLoadSpan(rootSpan)) { if (shouldProfileSpan(rootSpan)) { startProfileForSpan(rootSpan); } } client.on("spanStart", (span) => { if (span === getRootSpan(span) && shouldProfileSpan(span)) { startProfileForSpan(span); } }); client.on("beforeEnvelope", (envelope) => { if (!getActiveProfilesCount()) { return; } const profiledTransactionEvents = findProfiledTransactionsFromEnvelope(envelope); if (!profiledTransactionEvents.length) { return; } const profilesToAddToEnvelope = []; for (const profiledTransaction of profiledTransactionEvents) { const context = profiledTransaction && profiledTransaction.contexts; const profile_id = context && context["profile"] && context["profile"]["profile_id"]; const start_timestamp = context && context["profile"] && context["profile"]["start_timestamp"]; if (typeof profile_id !== "string") { DEBUG_BUILD$4 && logger$2.log("[Profiling] cannot find profile for a span without a profile context"); continue; } if (!profile_id) { DEBUG_BUILD$4 && logger$2.log("[Profiling] cannot find profile for a span without a profile context"); continue; } if (context && context["profile"]) { delete context.profile; } const profile = takeProfileFromGlobalCache(profile_id); if (!profile) { DEBUG_BUILD$4 && logger$2.log(`[Profiling] Could not retrieve profile for span: ${profile_id}`); continue; } const profileEvent = createProfilingEvent( profile_id, start_timestamp, profile, profiledTransaction ); if (profileEvent) { profilesToAddToEnvelope.push(profileEvent); } } addProfilesToEnvelope(envelope, profilesToAddToEnvelope); }); } }; }, "_browserProfilingIntegration"); const browserProfilingIntegration = defineIntegration(_browserProfilingIntegration); const INTEGRATION_NAME$1 = "SpotlightBrowser"; const _spotlightIntegration = /* @__PURE__ */ __name((options4 = {}) => { const sidecarUrl = options4.sidecarUrl || "http://localhost:8969/stream"; return { name: INTEGRATION_NAME$1, setup: /* @__PURE__ */ __name(() => { DEBUG_BUILD$4 && logger$2.log("Using Sidecar URL", sidecarUrl); }, "setup"), // We don't want to send interaction transactions/root spans created from // clicks within Spotlight to Sentry. Neither do we want them to be sent to // spotlight. processEvent: /* @__PURE__ */ __name((event) => isSpotlightInteraction(event) ? null : event, "processEvent"), afterAllSetup: /* @__PURE__ */ __name((client) => { setupSidecarForwarding(client, sidecarUrl); }, "afterAllSetup") }; }, "_spotlightIntegration"); function setupSidecarForwarding(client, sidecarUrl) { const makeFetch = getNativeImplementation("fetch"); let failCount = 0; client.on("beforeEnvelope", (envelope) => { if (failCount > 3) { logger$2.warn("[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests:", failCount); return; } makeFetch(sidecarUrl, { method: "POST", body: serializeEnvelope(envelope), headers: { "Content-Type": "application/x-sentry-envelope" }, mode: "cors" }).then( (res) => { if (res.status >= 200 && res.status < 400) { failCount = 0; } }, (err) => { failCount++; logger$2.error( "Sentry SDK can't connect to Sidecar is it running? See: https://spotlightjs.com/sidecar/npx/", err ); } ); }); } __name(setupSidecarForwarding, "setupSidecarForwarding"); const spotlightBrowserIntegration = defineIntegration(_spotlightIntegration); function isSpotlightInteraction(event) { return Boolean( event.type === "transaction" && event.spans && event.contexts && event.contexts.trace && event.contexts.trace.op === "ui.action.click" && event.spans.some(({ description }) => description && description.includes("#sentry-spotlight")) ); } __name(isSpotlightInteraction, "isSpotlightInteraction"); const FLAG_BUFFER_SIZE = 100; function copyFlagsFromScopeToEvent(event) { const scope = getCurrentScope$1(); const flagContext = scope.getScopeData().contexts.flags; const flagBuffer = flagContext ? flagContext.values : []; if (!flagBuffer.length) { return event; } if (event.contexts === void 0) { event.contexts = {}; } event.contexts.flags = { values: [...flagBuffer] }; return event; } __name(copyFlagsFromScopeToEvent, "copyFlagsFromScopeToEvent"); function insertFlagToScope(name2, value4, maxSize = FLAG_BUFFER_SIZE) { const scopeContexts = getCurrentScope$1().getScopeData().contexts; if (!scopeContexts.flags) { scopeContexts.flags = { values: [] }; } const flags = scopeContexts.flags.values; insertToFlagBuffer(flags, name2, value4, maxSize); } __name(insertFlagToScope, "insertFlagToScope"); function insertToFlagBuffer(flags, name2, value4, maxSize) { if (typeof value4 !== "boolean") { return; } if (flags.length > maxSize) { DEBUG_BUILD$4 && logger$2.error(`[Feature Flags] insertToFlagBuffer called on a buffer larger than maxSize=${maxSize}`); return; } const index2 = flags.findIndex((f2) => f2.flag === name2); if (index2 !== -1) { flags.splice(index2, 1); } if (flags.length === maxSize) { flags.shift(); } flags.push({ flag: name2, result: value4 }); } __name(insertToFlagBuffer, "insertToFlagBuffer"); const featureFlagsIntegration = defineIntegration(() => { return { name: "FeatureFlags", processEvent(event, _hint, _client) { return copyFlagsFromScopeToEvent(event); }, addFeatureFlag(name2, value4) { insertFlagToScope(name2, value4); } }; }); const launchDarklyIntegration = defineIntegration(() => { return { name: "LaunchDarkly", processEvent(event, _hint, _client) { return copyFlagsFromScopeToEvent(event); } }; }); function buildLaunchDarklyFlagUsedHandler() { return { name: "sentry-flag-auditor", type: "flag-used", synchronous: true, /** * Handle a flag evaluation by storing its name and value on the current scope. */ method: /* @__PURE__ */ __name((flagKey, flagDetail, _context) => { insertFlagToScope(flagKey, flagDetail.value); }, "method") }; } __name(buildLaunchDarklyFlagUsedHandler, "buildLaunchDarklyFlagUsedHandler"); const openFeatureIntegration = defineIntegration(() => { return { name: "OpenFeature", processEvent(event, _hint, _client) { return copyFlagsFromScopeToEvent(event); } }; }); class OpenFeatureIntegrationHook { static { __name(this, "OpenFeatureIntegrationHook"); } /** * Successful evaluation result. */ after(_hookContext, evaluationDetails) { insertFlagToScope(evaluationDetails.flagKey, evaluationDetails.value); } /** * On error evaluation result. */ error(hookContext, _error, _hookHints) { insertFlagToScope(hookContext.flagKey, hookContext.defaultValue); } } const DEFAULT_HOOKS = ["activate", "mount", "update"]; const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; const classifyRE$1 = /(?:^|[-_])(\w)/g; const classify$1 = /* @__PURE__ */ __name((str) => str.replace(classifyRE$1, (c2) => c2.toUpperCase()).replace(/[-_]/g, ""), "classify$1"); const ROOT_COMPONENT_NAME = ""; const ANONYMOUS_COMPONENT_NAME = ""; const repeat = /* @__PURE__ */ __name((str, n2) => { return str.repeat(n2); }, "repeat"); const formatComponentName$1 = /* @__PURE__ */ __name((vm, includeFile) => { if (!vm) { return ANONYMOUS_COMPONENT_NAME; } if (vm.$root === vm) { return ROOT_COMPONENT_NAME; } if (!vm.$options) { return ANONYMOUS_COMPONENT_NAME; } const options4 = vm.$options; let name2 = options4.name || options4._componentTag || options4.__name; const file = options4.__file; if (!name2 && file) { const match2 = file.match(/([^/\\]+)\.vue$/); if (match2) { name2 = match2[1]; } } return (name2 ? `<${classify$1(name2)}>` : ANONYMOUS_COMPONENT_NAME) + (file && includeFile !== false ? ` at ${file}` : ""); }, "formatComponentName$1"); const generateComponentTrace = /* @__PURE__ */ __name((vm) => { if (vm && (vm._isVue || vm.__isVue) && vm.$parent) { const tree = []; let currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { const last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue; } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } const formattedTree = tree.map( (vm2, i2) => `${(i2 === 0 ? "---> " : repeat(" ", 5 + i2 * 2)) + (Array.isArray(vm2) ? `${formatComponentName$1(vm2[0])}... (${vm2[1]} recursive calls)` : formatComponentName$1(vm2))}` ).join("\n"); return ` found in ${formattedTree}`; } return ` (found in ${formatComponentName$1(vm)})`; }, "generateComponentTrace"); const attachErrorHandler = /* @__PURE__ */ __name((app2, options4) => { const { errorHandler: originalErrorHandler, warnHandler, silent } = app2.config; app2.config.errorHandler = (error2, vm, lifecycleHook) => { const componentName = formatComponentName$1(vm, false); const trace = vm ? generateComponentTrace(vm) : ""; const metadata = { componentName, lifecycleHook, trace }; if (options4.attachProps && vm) { if (vm.$options && vm.$options.propsData) { metadata.propsData = vm.$options.propsData; } else if (vm.$props) { metadata.propsData = vm.$props; } } setTimeout(() => { captureException(error2, { captureContext: { contexts: { vue: metadata } }, mechanism: { handled: false } }); }); if (typeof originalErrorHandler === "function" && app2.config.errorHandler) { originalErrorHandler.call(app2, error2, vm, lifecycleHook); } if (options4.logErrors) { const hasConsole = typeof console !== "undefined"; const message3 = `Error in ${lifecycleHook}: "${error2 && error2.toString()}"`; if (warnHandler) { warnHandler.call(null, message3, vm, trace); } else if (hasConsole && !silent) { consoleSandbox(() => { console.error(`[Vue warn]: ${message3}${trace}`); }); } } }; }, "attachErrorHandler"); const VUE_OP = "ui.vue"; const HOOKS = { activate: ["activated", "deactivated"], create: ["beforeCreate", "created"], // Vue 3 unmount: ["beforeUnmount", "unmounted"], // Vue 2 destroy: ["beforeDestroy", "destroyed"], mount: ["beforeMount", "mounted"], update: ["beforeUpdate", "updated"] }; function finishRootSpan(vm, timestamp2, timeout) { if (vm.$_sentryRootSpanTimer) { clearTimeout(vm.$_sentryRootSpanTimer); } vm.$_sentryRootSpanTimer = setTimeout(() => { if (vm.$root && vm.$root.$_sentryRootSpan) { vm.$root.$_sentryRootSpan.end(timestamp2); vm.$root.$_sentryRootSpan = void 0; } }, timeout); } __name(finishRootSpan, "finishRootSpan"); function findTrackComponent(trackComponents, formattedName) { function extractComponentName(name2) { return name2.replace(/^<([^\s]*)>(?: at [^\s]*)?$/, "$1"); } __name(extractComponentName, "extractComponentName"); const isMatched = trackComponents.some((compo) => { return extractComponentName(formattedName) === extractComponentName(compo); }); return isMatched; } __name(findTrackComponent, "findTrackComponent"); const createTracingMixins = /* @__PURE__ */ __name((options4) => { const hooks2 = (options4.hooks || []).concat(DEFAULT_HOOKS).filter((value4, index2, self2) => self2.indexOf(value4) === index2); const mixins = {}; for (const operation of hooks2) { const internalHooks = HOOKS[operation]; if (!internalHooks) { DEBUG_BUILD && logger$2.warn(`Unknown hook: ${operation}`); continue; } for (const internalHook of internalHooks) { mixins[internalHook] = function() { const isRoot = this.$root === this; if (isRoot) { this.$_sentryRootSpan = this.$_sentryRootSpan || startInactiveSpan({ name: "Application Render", op: `${VUE_OP}.render`, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.vue" }, onlyIfParent: true }); } const name2 = formatComponentName$1(this, false); const shouldTrack2 = Array.isArray(options4.trackComponents) ? findTrackComponent(options4.trackComponents, name2) : options4.trackComponents; if (!isRoot && !shouldTrack2) { return; } this.$_sentrySpans = this.$_sentrySpans || {}; if (internalHook == internalHooks[0]) { const activeSpan = this.$root && this.$root.$_sentryRootSpan || getActiveSpan(); if (activeSpan) { const oldSpan = this.$_sentrySpans[operation]; if (oldSpan) { oldSpan.end(); } this.$_sentrySpans[operation] = startInactiveSpan({ name: `Vue ${name2}`, op: `${VUE_OP}.${operation}`, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.vue" }, // UI spans should only be created if there is an active root span (transaction) onlyIfParent: true }); } } else { const span = this.$_sentrySpans[operation]; if (!span) return; span.end(); finishRootSpan(this, timestampInSeconds(), options4.timeout); } }; } } return mixins; }, "createTracingMixins"); const globalWithVue = GLOBAL_OBJ; const DEFAULT_CONFIG = { Vue: globalWithVue.Vue, attachProps: true, logErrors: true, attachErrorHandler: true, hooks: DEFAULT_HOOKS, timeout: 2e3, trackComponents: false }; const INTEGRATION_NAME = "Vue"; const vueIntegration = defineIntegration((integrationOptions = {}) => { return { name: INTEGRATION_NAME, setup(client) { const options4 = { ...DEFAULT_CONFIG, ...client.getOptions(), ...integrationOptions }; if (!options4.Vue && !options4.app) { consoleSandbox(() => { console.warn( "[@sentry/vue]: Misconfigured SDK. Vue specific errors will not be captured. Update your `Sentry.init` call with an appropriate config option: `app` (Application Instance - Vue 3) or `Vue` (Vue Constructor - Vue 2)." ); }); return; } if (options4.app) { const apps = Array.isArray(options4.app) ? options4.app : [options4.app]; apps.forEach((app2) => vueInit(app2, options4)); } else if (options4.Vue) { vueInit(options4.Vue, options4); } } }; }); const vueInit = /* @__PURE__ */ __name((app2, options4) => { if (DEBUG_BUILD) { const appWithInstance = app2; const isMounted = appWithInstance._instance && appWithInstance._instance.isMounted; if (isMounted === true) { consoleSandbox(() => { console.warn( "[@sentry/vue]: Misconfigured SDK. Vue app is already mounted. Make sure to call `app.mount()` after `Sentry.init()`." ); }); } } if (options4.attachErrorHandler) { attachErrorHandler(app2, options4); } if (hasTracingEnabled(options4)) { app2.mixin( createTracingMixins({ ...options4, // eslint-disable-next-line deprecation/deprecation ...options4.tracingOptions }) ); } }, "vueInit"); function init$3(config2 = {}) { const options4 = { _metadata: { sdk: { name: "sentry.javascript.vue", packages: [ { name: "npm:@sentry/vue", version: SDK_VERSION } ], version: SDK_VERSION } }, defaultIntegrations: [...getDefaultIntegrations(config2), vueIntegration()], ...config2 }; return init$4(options4); } __name(init$3, "init$3"); function instrumentVueRouter(router2, options4, startNavigationSpanFn) { let isFirstPageLoad = true; router2.onError((error2) => captureException(error2, { mechanism: { handled: false } })); router2.beforeEach((to, from2, next2) => { const isPageLoadNavigation = from2.name == null && from2.matched.length === 0 || from2.name === void 0 && isFirstPageLoad; if (isFirstPageLoad) { isFirstPageLoad = false; } const attributes = { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.navigation.vue" }; for (const key of Object.keys(to.params)) { attributes[`params.${key}`] = to.params[key]; } for (const key of Object.keys(to.query)) { const value4 = to.query[key]; if (value4) { attributes[`query.${key}`] = value4; } } let spanName = to.path; let transactionSource = "url"; if (to.name && options4.routeLabel !== "path") { spanName = to.name.toString(); transactionSource = "custom"; } else if (to.matched.length > 0) { const lastIndex2 = to.matched.length - 1; spanName = to.matched[lastIndex2].path; transactionSource = "route"; } getCurrentScope$1().setTransactionName(spanName); if (options4.instrumentPageLoad && isPageLoadNavigation) { const activeRootSpan = getActiveRootSpan(); if (activeRootSpan) { const existingAttributes = spanToJSON(activeRootSpan).data || {}; if (existingAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== "custom") { activeRootSpan.updateName(spanName); activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, transactionSource); } activeRootSpan.setAttributes({ ...attributes, [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.vue" }); } } if (options4.instrumentNavigation && !isPageLoadNavigation) { attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = transactionSource; attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] = "auto.navigation.vue"; startNavigationSpanFn({ name: spanName, op: "navigation", attributes }); } if (next2) { next2(); } }); } __name(instrumentVueRouter, "instrumentVueRouter"); function getActiveRootSpan() { const span = getActiveSpan(); const rootSpan = span && getRootSpan(span); if (!rootSpan) { return void 0; } const op = spanToJSON(rootSpan).op; return op === "navigation" || op === "pageload" ? rootSpan : void 0; } __name(getActiveRootSpan, "getActiveRootSpan"); function browserTracingIntegration(options4 = {}) { if (!options4.router) { return browserTracingIntegration$1(options4); } const integration = browserTracingIntegration$1({ ...options4, instrumentNavigation: false }); const { router: router2, instrumentNavigation = true, instrumentPageLoad = true, routeLabel = "name" } = options4; return { ...integration, afterAllSetup(client) { integration.afterAllSetup(client); const startNavigationSpan = /* @__PURE__ */ __name((options5) => { startBrowserTracingNavigationSpan(client, options5); }, "startNavigationSpan"); instrumentVueRouter(router2, { routeLabel, instrumentNavigation, instrumentPageLoad }, startNavigationSpan); } }; } __name(browserTracingIntegration, "browserTracingIntegration"); const createSentryPiniaPlugin = /* @__PURE__ */ __name((options4 = { attachPiniaState: true, addBreadcrumbs: true, actionTransformer: /* @__PURE__ */ __name((action) => action, "actionTransformer"), stateTransformer: /* @__PURE__ */ __name((state) => state, "stateTransformer") }) => { const plugin = /* @__PURE__ */ __name(({ store }) => { options4.attachPiniaState !== false && getGlobalScope().addEventProcessor((event, hint) => { try { const timestamp2 = (/* @__PURE__ */ new Date()).toTimeString().split(" ")[0]; const filename = `pinia_state_${store.$id}_${timestamp2}.json`; hint.attachments = [ ...hint.attachments || [], { filename, data: JSON.stringify(store.$state) } ]; } catch (_2) { } return event; }); store.$onAction((context) => { context.after(() => { const transformedActionName = options4.actionTransformer ? options4.actionTransformer(context.name) : context.name; if (typeof transformedActionName !== "undefined" && transformedActionName !== null && options4.addBreadcrumbs !== false) { addBreadcrumb({ category: "action", message: transformedActionName, level: "info" }); } const transformedState = options4.stateTransformer ? options4.stateTransformer(store.$state) : store.$state; const scope = getCurrentScope$1(); const currentState = scope.getScopeData().contexts.state; if (typeof transformedState !== "undefined" && transformedState !== null) { const client = getClient(); const options5 = client && client.getOptions(); const normalizationDepth = options5 && options5.normalizeDepth || 3; const piniaStateContext = { type: "pinia", value: transformedState }; const newState = { ...currentState || {}, state: piniaStateContext }; addNonEnumerableProperty( newState, "__sentry_override_normalization_depth__", 3 + // 3 layers for `state.value.transformedState normalizationDepth // rest for the actual state ); scope.setContext("state", newState); } else { scope.setContext("state", { ...currentState || {}, state: { type: "pinia", value: "undefined" } }); } }); }); }, "plugin"); return plugin; }, "createSentryPiniaPlugin"); /** * @vue/shared v3.4.31 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT **/ /*! #__NO_SIDE_EFFECTS__ */ // @__NO_SIDE_EFFECTS__ function makeMap(str, expectsLowerCase) { const set3 = new Set(str.split(",")); return expectsLowerCase ? (val) => set3.has(val.toLowerCase()) : (val) => set3.has(val); } __name(makeMap, "makeMap"); const EMPTY_OBJ = false ? Object.freeze({}) : {}; const EMPTY_ARR = false ? Object.freeze([]) : []; const NOOP = /* @__PURE__ */ __name(() => { }, "NOOP"); const NO = /* @__PURE__ */ __name(() => false, "NO"); const isOn = /* @__PURE__ */ __name((key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97), "isOn"); const isModelListener = /* @__PURE__ */ __name((key) => key.startsWith("onUpdate:"), "isModelListener"); const extend$1 = Object.assign; const remove$1 = /* @__PURE__ */ __name((arr, el) => { const i2 = arr.indexOf(el); if (i2 > -1) { arr.splice(i2, 1); } }, "remove$1"); const hasOwnProperty$d = Object.prototype.hasOwnProperty; const hasOwn$3 = /* @__PURE__ */ __name((val, key) => hasOwnProperty$d.call(val, key), "hasOwn$3"); const isArray$9 = Array.isArray; const isMap$3 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Map]", "isMap$3"); const isSet$3 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Set]", "isSet$3"); const isDate$2 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Date]", "isDate$2"); const isRegExp$4 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object RegExp]", "isRegExp$4"); const isFunction$8 = /* @__PURE__ */ __name((val) => typeof val === "function", "isFunction$8"); const isString$7 = /* @__PURE__ */ __name((val) => typeof val === "string", "isString$7"); const isSymbol$1 = /* @__PURE__ */ __name((val) => typeof val === "symbol", "isSymbol$1"); const isObject$d = /* @__PURE__ */ __name((val) => val !== null && typeof val === "object", "isObject$d"); const isPromise$1 = /* @__PURE__ */ __name((val) => { return (isObject$d(val) || isFunction$8(val)) && isFunction$8(val.then) && isFunction$8(val.catch); }, "isPromise$1"); const objectToString$3 = Object.prototype.toString; const toTypeString$1 = /* @__PURE__ */ __name((value4) => objectToString$3.call(value4), "toTypeString$1"); const toRawType = /* @__PURE__ */ __name((value4) => { return toTypeString$1(value4).slice(8, -1); }, "toRawType"); const isPlainObject$4 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Object]", "isPlainObject$4"); const isIntegerKey = /* @__PURE__ */ __name((key) => isString$7(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key, "isIntegerKey"); const isReservedProp = /* @__PURE__ */ makeMap( // the leading comma is intentional so empty string "" is also included ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" ); const isBuiltInDirective = /* @__PURE__ */ makeMap( "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" ); const cacheStringFunction$1 = /* @__PURE__ */ __name((fn) => { const cache2 = /* @__PURE__ */ Object.create(null); return (str) => { const hit = cache2[str]; return hit || (cache2[str] = fn(str)); }; }, "cacheStringFunction$1"); const camelizeRE$1 = /-(\w)/g; const camelize$1 = cacheStringFunction$1((str) => { return str.replace(camelizeRE$1, (_2, c2) => c2 ? c2.toUpperCase() : ""); }); const hyphenateRE$1 = /\B([A-Z])/g; const hyphenate$1 = cacheStringFunction$1( (str) => str.replace(hyphenateRE$1, "-$1").toLowerCase() ); const capitalize$1 = cacheStringFunction$1((str) => { return str.charAt(0).toUpperCase() + str.slice(1); }); const toHandlerKey = cacheStringFunction$1((str) => { const s2 = str ? `on${capitalize$1(str)}` : ``; return s2; }); const hasChanged = /* @__PURE__ */ __name((value4, oldValue2) => !Object.is(value4, oldValue2), "hasChanged"); const invokeArrayFns = /* @__PURE__ */ __name((fns, ...arg) => { for (let i2 = 0; i2 < fns.length; i2++) { fns[i2](...arg); } }, "invokeArrayFns"); const def = /* @__PURE__ */ __name((obj, key, value4, writable = false) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, writable, value: value4 }); }, "def"); const looseToNumber = /* @__PURE__ */ __name((val) => { const n2 = parseFloat(val); return isNaN(n2) ? val : n2; }, "looseToNumber"); const toNumber = /* @__PURE__ */ __name((val) => { const n2 = isString$7(val) ? Number(val) : NaN; return isNaN(n2) ? val : n2; }, "toNumber"); let _globalThis$1; const getGlobalThis$1 = /* @__PURE__ */ __name(() => { return _globalThis$1 || (_globalThis$1 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); }, "getGlobalThis$1"); const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/; function genPropsAccessExp(name2) { return identRE.test(name2) ? `__props.${name2}` : `__props[${JSON.stringify(name2)}]`; } __name(genPropsAccessExp, "genPropsAccessExp"); const PatchFlags = { "TEXT": 1, "1": "TEXT", "CLASS": 2, "2": "CLASS", "STYLE": 4, "4": "STYLE", "PROPS": 8, "8": "PROPS", "FULL_PROPS": 16, "16": "FULL_PROPS", "NEED_HYDRATION": 32, "32": "NEED_HYDRATION", "STABLE_FRAGMENT": 64, "64": "STABLE_FRAGMENT", "KEYED_FRAGMENT": 128, "128": "KEYED_FRAGMENT", "UNKEYED_FRAGMENT": 256, "256": "UNKEYED_FRAGMENT", "NEED_PATCH": 512, "512": "NEED_PATCH", "DYNAMIC_SLOTS": 1024, "1024": "DYNAMIC_SLOTS", "DEV_ROOT_FRAGMENT": 2048, "2048": "DEV_ROOT_FRAGMENT", "HOISTED": -1, "-1": "HOISTED", "BAIL": -2, "-2": "BAIL" }; const PatchFlagNames = { [1]: `TEXT`, [2]: `CLASS`, [4]: `STYLE`, [8]: `PROPS`, [16]: `FULL_PROPS`, [32]: `NEED_HYDRATION`, [64]: `STABLE_FRAGMENT`, [128]: `KEYED_FRAGMENT`, [256]: `UNKEYED_FRAGMENT`, [512]: `NEED_PATCH`, [1024]: `DYNAMIC_SLOTS`, [2048]: `DEV_ROOT_FRAGMENT`, [-1]: `HOISTED`, [-2]: `BAIL` }; const ShapeFlags = { "ELEMENT": 1, "1": "ELEMENT", "FUNCTIONAL_COMPONENT": 2, "2": "FUNCTIONAL_COMPONENT", "STATEFUL_COMPONENT": 4, "4": "STATEFUL_COMPONENT", "TEXT_CHILDREN": 8, "8": "TEXT_CHILDREN", "ARRAY_CHILDREN": 16, "16": "ARRAY_CHILDREN", "SLOTS_CHILDREN": 32, "32": "SLOTS_CHILDREN", "TELEPORT": 64, "64": "TELEPORT", "SUSPENSE": 128, "128": "SUSPENSE", "COMPONENT_SHOULD_KEEP_ALIVE": 256, "256": "COMPONENT_SHOULD_KEEP_ALIVE", "COMPONENT_KEPT_ALIVE": 512, "512": "COMPONENT_KEPT_ALIVE", "COMPONENT": 6, "6": "COMPONENT" }; const SlotFlags = { "STABLE": 1, "1": "STABLE", "DYNAMIC": 2, "2": "DYNAMIC", "FORWARDED": 3, "3": "FORWARDED" }; const slotFlagsText = { [1]: "STABLE", [2]: "DYNAMIC", [3]: "FORWARDED" }; const GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error"; const isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED); const isGloballyWhitelisted = isGloballyAllowed; const range = 2; function generateCodeFrame$1(source, start2 = 0, end = source.length) { start2 = Math.max(0, Math.min(start2, source.length)); end = Math.max(0, Math.min(end, source.length)); if (start2 > end) return ""; let lines = source.split(/(\r?\n)/); const newlineSequences = lines.filter((_2, idx) => idx % 2 === 1); lines = lines.filter((_2, idx) => idx % 2 === 0); let count = 0; const res = []; for (let i2 = 0; i2 < lines.length; i2++) { count += lines[i2].length + (newlineSequences[i2] && newlineSequences[i2].length || 0); if (count >= start2) { for (let j2 = i2 - range; j2 <= i2 + range || end > count; j2++) { if (j2 < 0 || j2 >= lines.length) continue; const line = j2 + 1; res.push( `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j2]}` ); const lineLength = lines[j2].length; const newLineSeqLength = newlineSequences[j2] && newlineSequences[j2].length || 0; if (j2 === i2) { const pad = start2 - (count - (lineLength + newLineSeqLength)); const length = Math.max( 1, end > count ? lineLength - pad : end - start2 ); res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); } else if (j2 > i2) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + "^".repeat(length)); } count += lineLength + newLineSeqLength; } } break; } } return res.join("\n"); } __name(generateCodeFrame$1, "generateCodeFrame$1"); function normalizeStyle(value4) { if (isArray$9(value4)) { const res = {}; for (let i2 = 0; i2 < value4.length; i2++) { const item3 = value4[i2]; const normalized = isString$7(item3) ? parseStringStyle(item3) : normalizeStyle(item3); if (normalized) { for (const key in normalized) { res[key] = normalized[key]; } } } return res; } else if (isString$7(value4) || isObject$d(value4)) { return value4; } } __name(normalizeStyle, "normalizeStyle"); const listDelimiterRE = /;(?![^(]*\))/g; const propertyDelimiterRE = /:([^]+)/; const styleCommentRE = /\/\*[^]*?\*\//g; function parseStringStyle(cssText) { const ret = {}; cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item3) => { if (item3) { const tmp = item3.split(propertyDelimiterRE); tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); } }); return ret; } __name(parseStringStyle, "parseStringStyle"); function stringifyStyle(styles) { let ret = ""; if (!styles || isString$7(styles)) { return ret; } for (const key in styles) { const value4 = styles[key]; if (isString$7(value4) || typeof value4 === "number") { const normalizedKey = key.startsWith(`--`) ? key : hyphenate$1(key); ret += `${normalizedKey}:${value4};`; } } return ret; } __name(stringifyStyle, "stringifyStyle"); function normalizeClass(value4) { let res = ""; if (isString$7(value4)) { res = value4; } else if (isArray$9(value4)) { for (let i2 = 0; i2 < value4.length; i2++) { const normalized = normalizeClass(value4[i2]); if (normalized) { res += normalized + " "; } } } else if (isObject$d(value4)) { for (const name2 in value4) { if (value4[name2]) { res += name2 + " "; } } } return res.trim(); } __name(normalizeClass, "normalizeClass"); function normalizeProps(props) { if (!props) return null; let { class: klass, style: style2 } = props; if (klass && !isString$7(klass)) { props.class = normalizeClass(klass); } if (style2) { props.style = normalizeStyle(style2); } return props; } __name(normalizeProps, "normalizeProps"); const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; const MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"; const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); const isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS); const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; const isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); const isBooleanAttr = /* @__PURE__ */ makeMap( specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` ); function includeBooleanAttr(value4) { return !!value4 || value4 === ""; } __name(includeBooleanAttr, "includeBooleanAttr"); const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; const attrValidationCache = {}; function isSSRSafeAttrName(name2) { if (attrValidationCache.hasOwnProperty(name2)) { return attrValidationCache[name2]; } const isUnsafe = unsafeAttrCharRE.test(name2); if (isUnsafe) { console.error(`unsafe attribute name: ${name2}`); } return attrValidationCache[name2] = !isUnsafe; } __name(isSSRSafeAttrName, "isSSRSafeAttrName"); const propsToAttrMap = { acceptCharset: "accept-charset", className: "class", htmlFor: "for", httpEquiv: "http-equiv" }; const isKnownHtmlAttr = /* @__PURE__ */ makeMap( `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap` ); const isKnownSvgAttr = /* @__PURE__ */ makeMap( `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan` ); function isRenderableAttrValue(value4) { if (value4 == null) { return false; } const type = typeof value4; return type === "string" || type === "number" || type === "boolean"; } __name(isRenderableAttrValue, "isRenderableAttrValue"); const escapeRE$2 = /["'&<>]/; function escapeHtml$2(string) { const str = "" + string; const match2 = escapeRE$2.exec(str); if (!match2) { return str; } let html = ""; let escaped; let index2; let lastIndex2 = 0; for (index2 = match2.index; index2 < str.length; index2++) { switch (str.charCodeAt(index2)) { case 34: escaped = """; break; case 38: escaped = "&"; break; case 39: escaped = "'"; break; case 60: escaped = "<"; break; case 62: escaped = ">"; break; default: continue; } if (lastIndex2 !== index2) { html += str.slice(lastIndex2, index2); } lastIndex2 = index2 + 1; html += escaped; } return lastIndex2 !== index2 ? html + str.slice(lastIndex2, index2) : html; } __name(escapeHtml$2, "escapeHtml$2"); const commentStripRE = /^-?>||--!>| looseEqual(item3, val)); } __name(looseIndexOf, "looseIndexOf"); const isRef$1 = /* @__PURE__ */ __name((val) => { return !!(val && val.__v_isRef === true); }, "isRef$1"); const toDisplayString$1 = /* @__PURE__ */ __name((val) => { return isString$7(val) ? val : val == null ? "" : isArray$9(val) || isObject$d(val) && (val.toString === objectToString$3 || !isFunction$8(val.toString)) ? isRef$1(val) ? toDisplayString$1(val.value) : JSON.stringify(val, replacer, 2) : String(val); }, "toDisplayString$1"); const replacer = /* @__PURE__ */ __name((_key, val) => { if (isRef$1(val)) { return replacer(_key, val.value); } else if (isMap$3(val)) { return { [`Map(${val.size})`]: [...val.entries()].reduce( (entries, [key, val2], i2) => { entries[stringifySymbol(key, i2) + " =>"] = val2; return entries; }, {} ) }; } else if (isSet$3(val)) { return { [`Set(${val.size})`]: [...val.values()].map((v2) => stringifySymbol(v2)) }; } else if (isSymbol$1(val)) { return stringifySymbol(val); } else if (isObject$d(val) && !isArray$9(val) && !isPlainObject$4(val)) { return String(val); } return val; }, "replacer"); const stringifySymbol = /* @__PURE__ */ __name((v2, i2 = "") => { var _a2; return ( // Symbol.description in es2019+ so we need to cast here to pass // the lib: es2016 check isSymbol$1(v2) ? `Symbol(${(_a2 = v2.description) != null ? _a2 : i2})` : v2 ); }, "stringifySymbol"); /** * @vue/reactivity v3.4.31 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT **/ function warn$4(msg, ...args) { console.warn(`[Vue warn] ${msg}`, ...args); } __name(warn$4, "warn$4"); let activeEffectScope; class EffectScope { static { __name(this, "EffectScope"); } constructor(detached = false) { this.detached = detached; this._active = true; this.effects = []; this.cleanups = []; this.parent = activeEffectScope; if (!detached && activeEffectScope) { this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( this ) - 1; } } get active() { return this._active; } run(fn) { if (this._active) { const currentEffectScope = activeEffectScope; try { activeEffectScope = this; return fn(); } finally { activeEffectScope = currentEffectScope; } } else if (false) { warn$4(`cannot run an inactive effect scope.`); } } /** * This should only be called on non-detached scopes * @internal */ on() { activeEffectScope = this; } /** * This should only be called on non-detached scopes * @internal */ off() { activeEffectScope = this.parent; } stop(fromParent) { if (this._active) { let i2, l2; for (i2 = 0, l2 = this.effects.length; i2 < l2; i2++) { this.effects[i2].stop(); } for (i2 = 0, l2 = this.cleanups.length; i2 < l2; i2++) { this.cleanups[i2](); } if (this.scopes) { for (i2 = 0, l2 = this.scopes.length; i2 < l2; i2++) { this.scopes[i2].stop(true); } } if (!this.detached && this.parent && !fromParent) { const last = this.parent.scopes.pop(); if (last && last !== this) { this.parent.scopes[this.index] = last; last.index = this.index; } } this.parent = void 0; this._active = false; } } } function effectScope(detached) { return new EffectScope(detached); } __name(effectScope, "effectScope"); function recordEffectScope(effect2, scope = activeEffectScope) { if (scope && scope.active) { scope.effects.push(effect2); } } __name(recordEffectScope, "recordEffectScope"); function getCurrentScope() { return activeEffectScope; } __name(getCurrentScope, "getCurrentScope"); function onScopeDispose(fn) { if (activeEffectScope) { activeEffectScope.cleanups.push(fn); } else if (false) { warn$4( `onScopeDispose() is called when there is no active effect scope to be associated with.` ); } } __name(onScopeDispose, "onScopeDispose"); let activeEffect; class ReactiveEffect { static { __name(this, "ReactiveEffect"); } constructor(fn, trigger2, scheduler, scope) { this.fn = fn; this.trigger = trigger2; this.scheduler = scheduler; this.active = true; this.deps = []; this._dirtyLevel = 4; this._trackId = 0; this._runnings = 0; this._shouldSchedule = false; this._depsLength = 0; recordEffectScope(this, scope); } get dirty() { if (this._dirtyLevel === 2 || this._dirtyLevel === 3) { this._dirtyLevel = 1; pauseTracking(); for (let i2 = 0; i2 < this._depsLength; i2++) { const dep = this.deps[i2]; if (dep.computed) { triggerComputed(dep.computed); if (this._dirtyLevel >= 4) { break; } } } if (this._dirtyLevel === 1) { this._dirtyLevel = 0; } resetTracking(); } return this._dirtyLevel >= 4; } set dirty(v2) { this._dirtyLevel = v2 ? 4 : 0; } run() { this._dirtyLevel = 0; if (!this.active) { return this.fn(); } let lastShouldTrack = shouldTrack; let lastEffect = activeEffect; try { shouldTrack = true; activeEffect = this; this._runnings++; preCleanupEffect(this); return this.fn(); } finally { postCleanupEffect(this); this._runnings--; activeEffect = lastEffect; shouldTrack = lastShouldTrack; } } stop() { if (this.active) { preCleanupEffect(this); postCleanupEffect(this); this.onStop && this.onStop(); this.active = false; } } } function triggerComputed(computed2) { return computed2.value; } __name(triggerComputed, "triggerComputed"); function preCleanupEffect(effect2) { effect2._trackId++; effect2._depsLength = 0; } __name(preCleanupEffect, "preCleanupEffect"); function postCleanupEffect(effect2) { if (effect2.deps.length > effect2._depsLength) { for (let i2 = effect2._depsLength; i2 < effect2.deps.length; i2++) { cleanupDepEffect(effect2.deps[i2], effect2); } effect2.deps.length = effect2._depsLength; } } __name(postCleanupEffect, "postCleanupEffect"); function cleanupDepEffect(dep, effect2) { const trackId = dep.get(effect2); if (trackId !== void 0 && effect2._trackId !== trackId) { dep.delete(effect2); if (dep.size === 0) { dep.cleanup(); } } } __name(cleanupDepEffect, "cleanupDepEffect"); function effect(fn, options4) { if (fn.effect instanceof ReactiveEffect) { fn = fn.effect.fn; } const _effect = new ReactiveEffect(fn, NOOP, () => { if (_effect.dirty) { _effect.run(); } }); if (options4) { extend$1(_effect, options4); if (options4.scope) recordEffectScope(_effect, options4.scope); } if (!options4 || !options4.lazy) { _effect.run(); } const runner = _effect.run.bind(_effect); runner.effect = _effect; return runner; } __name(effect, "effect"); function stop(runner) { runner.effect.stop(); } __name(stop, "stop"); let shouldTrack = true; let pauseScheduleStack = 0; const trackStack = []; function pauseTracking() { trackStack.push(shouldTrack); shouldTrack = false; } __name(pauseTracking, "pauseTracking"); function enableTracking() { trackStack.push(shouldTrack); shouldTrack = true; } __name(enableTracking, "enableTracking"); function resetTracking() { const last = trackStack.pop(); shouldTrack = last === void 0 ? true : last; } __name(resetTracking, "resetTracking"); function pauseScheduling() { pauseScheduleStack++; } __name(pauseScheduling, "pauseScheduling"); function resetScheduling() { pauseScheduleStack--; while (!pauseScheduleStack && queueEffectSchedulers.length) { queueEffectSchedulers.shift()(); } } __name(resetScheduling, "resetScheduling"); function trackEffect(effect2, dep, debuggerEventExtraInfo) { var _a2; if (dep.get(effect2) !== effect2._trackId) { dep.set(effect2, effect2._trackId); const oldDep = effect2.deps[effect2._depsLength]; if (oldDep !== dep) { if (oldDep) { cleanupDepEffect(oldDep, effect2); } effect2.deps[effect2._depsLength++] = dep; } else { effect2._depsLength++; } if (false) { (_a2 = effect2.onTrack) == null ? void 0 : _a2.call(effect2, extend$1({ effect: effect2 }, debuggerEventExtraInfo)); } } } __name(trackEffect, "trackEffect"); const queueEffectSchedulers = []; function triggerEffects(dep, dirtyLevel, debuggerEventExtraInfo) { var _a2; pauseScheduling(); for (const effect2 of dep.keys()) { let tracking; if (effect2._dirtyLevel < dirtyLevel && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { effect2._shouldSchedule || (effect2._shouldSchedule = effect2._dirtyLevel === 0); effect2._dirtyLevel = dirtyLevel; } if (effect2._shouldSchedule && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { if (false) { (_a2 = effect2.onTrigger) == null ? void 0 : _a2.call(effect2, extend$1({ effect: effect2 }, debuggerEventExtraInfo)); } effect2.trigger(); if ((!effect2._runnings || effect2.allowRecurse) && effect2._dirtyLevel !== 2) { effect2._shouldSchedule = false; if (effect2.scheduler) { queueEffectSchedulers.push(effect2.scheduler); } } } } resetScheduling(); } __name(triggerEffects, "triggerEffects"); const createDep = /* @__PURE__ */ __name((cleanup, computed2) => { const dep = /* @__PURE__ */ new Map(); dep.cleanup = cleanup; dep.computed = computed2; return dep; }, "createDep"); const targetMap = /* @__PURE__ */ new WeakMap(); const ITERATE_KEY = Symbol(false ? "iterate" : ""); const MAP_KEY_ITERATE_KEY = Symbol(false ? "Map key iterate" : ""); function track(target, type, key) { if (shouldTrack && activeEffect) { let depsMap = targetMap.get(target); if (!depsMap) { targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); } let dep = depsMap.get(key); if (!dep) { depsMap.set(key, dep = createDep(() => depsMap.delete(key))); } trackEffect( activeEffect, dep, false ? { target, type, key } : void 0 ); } } __name(track, "track"); function trigger(target, type, key, newValue2, oldValue2, oldTarget) { const depsMap = targetMap.get(target); if (!depsMap) { return; } let deps = []; if (type === "clear") { deps = [...depsMap.values()]; } else if (key === "length" && isArray$9(target)) { const newLength = Number(newValue2); depsMap.forEach((dep, key2) => { if (key2 === "length" || !isSymbol$1(key2) && key2 >= newLength) { deps.push(dep); } }); } else { if (key !== void 0) { deps.push(depsMap.get(key)); } switch (type) { case "add": if (!isArray$9(target)) { deps.push(depsMap.get(ITERATE_KEY)); if (isMap$3(target)) { deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); } } else if (isIntegerKey(key)) { deps.push(depsMap.get("length")); } break; case "delete": if (!isArray$9(target)) { deps.push(depsMap.get(ITERATE_KEY)); if (isMap$3(target)) { deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); } } break; case "set": if (isMap$3(target)) { deps.push(depsMap.get(ITERATE_KEY)); } break; } } pauseScheduling(); for (const dep of deps) { if (dep) { triggerEffects( dep, 4, false ? { target, type, key, newValue: newValue2, oldValue: oldValue2, oldTarget } : void 0 ); } } resetScheduling(); } __name(trigger, "trigger"); function getDepFromReactive(object, key) { const depsMap = targetMap.get(object); return depsMap && depsMap.get(key); } __name(getDepFromReactive, "getDepFromReactive"); const isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`); const builtInSymbols = new Set( /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol$1) ); const arrayInstrumentations = /* @__PURE__ */ createArrayInstrumentations(); function createArrayInstrumentations() { const instrumentations = {}; ["includes", "indexOf", "lastIndexOf"].forEach((key) => { instrumentations[key] = function(...args) { const arr = toRaw(this); for (let i2 = 0, l2 = this.length; i2 < l2; i2++) { track(arr, "get", i2 + ""); } const res = arr[key](...args); if (res === -1 || res === false) { return arr[key](...args.map(toRaw)); } else { return res; } }; }); ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { instrumentations[key] = function(...args) { pauseTracking(); pauseScheduling(); const res = toRaw(this)[key].apply(this, args); resetScheduling(); resetTracking(); return res; }; }); return instrumentations; } __name(createArrayInstrumentations, "createArrayInstrumentations"); function hasOwnProperty$c(key) { if (!isSymbol$1(key)) key = String(key); const obj = toRaw(this); track(obj, "has", key); return obj.hasOwnProperty(key); } __name(hasOwnProperty$c, "hasOwnProperty$c"); class BaseReactiveHandler { static { __name(this, "BaseReactiveHandler"); } constructor(_isReadonly = false, _isShallow = false) { this._isReadonly = _isReadonly; this._isShallow = _isShallow; } get(target, key, receiver) { const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_isShallow") { return isShallow2; } else if (key === "__v_raw") { if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype // this means the reciever is a user proxy of the reactive proxy Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) { return target; } return; } const targetIsArray = isArray$9(target); if (!isReadonly2) { if (targetIsArray && hasOwn$3(arrayInstrumentations, key)) { return Reflect.get(arrayInstrumentations, key, receiver); } if (key === "hasOwnProperty") { return hasOwnProperty$c; } } const res = Reflect.get(target, key, receiver); if (isSymbol$1(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; } if (!isReadonly2) { track(target, "get", key); } if (isShallow2) { return res; } if (isRef(res)) { return targetIsArray && isIntegerKey(key) ? res : res.value; } if (isObject$d(res)) { return isReadonly2 ? readonly(res) : reactive(res); } return res; } } class MutableReactiveHandler extends BaseReactiveHandler { static { __name(this, "MutableReactiveHandler"); } constructor(isShallow2 = false) { super(false, isShallow2); } set(target, key, value4, receiver) { let oldValue2 = target[key]; if (!this._isShallow) { const isOldValueReadonly = isReadonly(oldValue2); if (!isShallow(value4) && !isReadonly(value4)) { oldValue2 = toRaw(oldValue2); value4 = toRaw(value4); } if (!isArray$9(target) && isRef(oldValue2) && !isRef(value4)) { if (isOldValueReadonly) { return false; } else { oldValue2.value = value4; return true; } } } const hadKey = isArray$9(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn$3(target, key); const result = Reflect.set(target, key, value4, receiver); if (target === toRaw(receiver)) { if (!hadKey) { trigger(target, "add", key, value4); } else if (hasChanged(value4, oldValue2)) { trigger(target, "set", key, value4, oldValue2); } } return result; } deleteProperty(target, key) { const hadKey = hasOwn$3(target, key); const oldValue2 = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { trigger(target, "delete", key, void 0, oldValue2); } return result; } has(target, key) { const result = Reflect.has(target, key); if (!isSymbol$1(key) || !builtInSymbols.has(key)) { track(target, "has", key); } return result; } ownKeys(target) { track( target, "iterate", isArray$9(target) ? "length" : ITERATE_KEY ); return Reflect.ownKeys(target); } } class ReadonlyReactiveHandler extends BaseReactiveHandler { static { __name(this, "ReadonlyReactiveHandler"); } constructor(isShallow2 = false) { super(true, isShallow2); } set(target, key) { if (false) { warn$4( `Set operation on key "${String(key)}" failed: target is readonly.`, target ); } return true; } deleteProperty(target, key) { if (false) { warn$4( `Delete operation on key "${String(key)}" failed: target is readonly.`, target ); } return true; } } const mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler(); const readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(); const shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler( true ); const shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true); const toShallow = /* @__PURE__ */ __name((value4) => value4, "toShallow"); const getProto = /* @__PURE__ */ __name((v2) => Reflect.getPrototypeOf(v2), "getProto"); function get$3(target, key, isReadonly2 = false, isShallow2 = false) { target = target["__v_raw"]; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (!isReadonly2) { if (hasChanged(key, rawKey)) { track(rawTarget, "get", key); } track(rawTarget, "get", rawKey); } const { has: has2 } = getProto(rawTarget); const wrap2 = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive$1; if (has2.call(rawTarget, key)) { return wrap2(target.get(key)); } else if (has2.call(rawTarget, rawKey)) { return wrap2(target.get(rawKey)); } else if (target !== rawTarget) { target.get(key); } } __name(get$3, "get$3"); function has$1(key, isReadonly2 = false) { const target = this["__v_raw"]; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (!isReadonly2) { if (hasChanged(key, rawKey)) { track(rawTarget, "has", key); } track(rawTarget, "has", rawKey); } return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); } __name(has$1, "has$1"); function size(target, isReadonly2 = false) { target = target["__v_raw"]; !isReadonly2 && track(toRaw(target), "iterate", ITERATE_KEY); return Reflect.get(target, "size", target); } __name(size, "size"); function add$1(value4) { value4 = toRaw(value4); const target = toRaw(this); const proto = getProto(target); const hadKey = proto.has.call(target, value4); if (!hadKey) { target.add(value4); trigger(target, "add", value4, value4); } return this; } __name(add$1, "add$1"); function set$4(key, value4) { value4 = toRaw(value4); const target = toRaw(this); const { has: has2, get: get22 } = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw(key); hadKey = has2.call(target, key); } else if (false) { checkIdentityKeys(target, has2, key); } const oldValue2 = get22.call(target, key); target.set(key, value4); if (!hadKey) { trigger(target, "add", key, value4); } else if (hasChanged(value4, oldValue2)) { trigger(target, "set", key, value4, oldValue2); } return this; } __name(set$4, "set$4"); function deleteEntry(key) { const target = toRaw(this); const { has: has2, get: get22 } = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw(key); hadKey = has2.call(target, key); } else if (false) { checkIdentityKeys(target, has2, key); } const oldValue2 = get22 ? get22.call(target, key) : void 0; const result = target.delete(key); if (hadKey) { trigger(target, "delete", key, void 0, oldValue2); } return result; } __name(deleteEntry, "deleteEntry"); function clear() { const target = toRaw(this); const hadItems = target.size !== 0; const oldTarget = false ? isMap$3(target) ? new Map(target) : new Set(target) : void 0; const result = target.clear(); if (hadItems) { trigger(target, "clear", void 0, void 0, oldTarget); } return result; } __name(clear, "clear"); function createForEach(isReadonly2, isShallow2) { return /* @__PURE__ */ __name(function forEach3(callback, thisArg) { const observed = this; const target = observed["__v_raw"]; const rawTarget = toRaw(target); const wrap2 = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive$1; !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY); return target.forEach((value4, key) => { return callback.call(thisArg, wrap2(value4), wrap2(key), observed); }); }, "forEach"); } __name(createForEach, "createForEach"); function createIterableMethod(method, isReadonly2, isShallow2) { return function(...args) { const target = this["__v_raw"]; const rawTarget = toRaw(target); const targetIsMap = isMap$3(rawTarget); const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; const isKeyOnly = method === "keys" && targetIsMap; const innerIterator = target[method](...args); const wrap2 = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive$1; !isReadonly2 && track( rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY ); return { // iterator protocol next() { const { value: value4, done } = innerIterator.next(); return done ? { value: value4, done } : { value: isPair ? [wrap2(value4[0]), wrap2(value4[1])] : wrap2(value4), done }; }, // iterable protocol [Symbol.iterator]() { return this; } }; }; } __name(createIterableMethod, "createIterableMethod"); function createReadonlyMethod(type) { return function(...args) { if (false) { const key = args[0] ? `on key "${args[0]}" ` : ``; warn$4( `${capitalize$1(type)} operation ${key}failed: target is readonly.`, toRaw(this) ); } return type === "delete" ? false : type === "clear" ? void 0 : this; }; } __name(createReadonlyMethod, "createReadonlyMethod"); function createInstrumentations() { const mutableInstrumentations2 = { get(key) { return get$3(this, key); }, get size() { return size(this); }, has: has$1, add: add$1, set: set$4, delete: deleteEntry, clear, forEach: createForEach(false, false) }; const shallowInstrumentations2 = { get(key) { return get$3(this, key, false, true); }, get size() { return size(this); }, has: has$1, add: add$1, set: set$4, delete: deleteEntry, clear, forEach: createForEach(false, true) }; const readonlyInstrumentations2 = { get(key) { return get$3(this, key, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, false) }; const shallowReadonlyInstrumentations2 = { get(key) { return get$3(this, key, true, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, true) }; const iteratorMethods = [ "keys", "values", "entries", Symbol.iterator ]; iteratorMethods.forEach((method) => { mutableInstrumentations2[method] = createIterableMethod(method, false, false); readonlyInstrumentations2[method] = createIterableMethod(method, true, false); shallowInstrumentations2[method] = createIterableMethod(method, false, true); shallowReadonlyInstrumentations2[method] = createIterableMethod( method, true, true ); }); return [ mutableInstrumentations2, readonlyInstrumentations2, shallowInstrumentations2, shallowReadonlyInstrumentations2 ]; } __name(createInstrumentations, "createInstrumentations"); const [ mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations ] = /* @__PURE__ */ createInstrumentations(); function createInstrumentationGetter(isReadonly2, shallow) { const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations; return (target, key, receiver) => { if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_raw") { return target; } return Reflect.get( hasOwn$3(instrumentations, key) && key in target ? instrumentations : target, key, receiver ); }; } __name(createInstrumentationGetter, "createInstrumentationGetter"); const mutableCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(false, false) }; const shallowCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(false, true) }; const readonlyCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(true, false) }; const shallowReadonlyCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(true, true) }; function checkIdentityKeys(target, has2, key) { const rawKey = toRaw(key); if (rawKey !== key && has2.call(target, rawKey)) { const type = toRawType(target); warn$4( `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.` ); } } __name(checkIdentityKeys, "checkIdentityKeys"); const reactiveMap = /* @__PURE__ */ new WeakMap(); const shallowReactiveMap = /* @__PURE__ */ new WeakMap(); const readonlyMap = /* @__PURE__ */ new WeakMap(); const shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { case "Object": case "Array": return 1; case "Map": case "Set": case "WeakMap": case "WeakSet": return 2; default: return 0; } } __name(targetTypeMap, "targetTypeMap"); function getTargetType(value4) { return value4["__v_skip"] || !Object.isExtensible(value4) ? 0 : targetTypeMap(toRawType(value4)); } __name(getTargetType, "getTargetType"); function reactive(target) { if (isReadonly(target)) { return target; } return createReactiveObject( target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap ); } __name(reactive, "reactive"); function shallowReactive(target) { return createReactiveObject( target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap ); } __name(shallowReactive, "shallowReactive"); function readonly(target) { return createReactiveObject( target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap ); } __name(readonly, "readonly"); function shallowReadonly(target) { return createReactiveObject( target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap ); } __name(shallowReadonly, "shallowReadonly"); function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { if (!isObject$d(target)) { if (false) { warn$4( `value cannot be made ${isReadonly2 ? "readonly" : "reactive"}: ${String( target )}` ); } return target; } if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { return target; } const existingProxy = proxyMap.get(target); if (existingProxy) { return existingProxy; } const targetType = getTargetType(target); if (targetType === 0) { return target; } const proxy = new Proxy( target, targetType === 2 ? collectionHandlers : baseHandlers ); proxyMap.set(target, proxy); return proxy; } __name(createReactiveObject, "createReactiveObject"); function isReactive(value4) { if (isReadonly(value4)) { return isReactive(value4["__v_raw"]); } return !!(value4 && value4["__v_isReactive"]); } __name(isReactive, "isReactive"); function isReadonly(value4) { return !!(value4 && value4["__v_isReadonly"]); } __name(isReadonly, "isReadonly"); function isShallow(value4) { return !!(value4 && value4["__v_isShallow"]); } __name(isShallow, "isShallow"); function isProxy(value4) { return value4 ? !!value4["__v_raw"] : false; } __name(isProxy, "isProxy"); function toRaw(observed) { const raw = observed && observed["__v_raw"]; return raw ? toRaw(raw) : observed; } __name(toRaw, "toRaw"); function markRaw(value4) { if (Object.isExtensible(value4)) { def(value4, "__v_skip", true); } return value4; } __name(markRaw, "markRaw"); const toReactive$1 = /* @__PURE__ */ __name((value4) => isObject$d(value4) ? reactive(value4) : value4, "toReactive$1"); const toReadonly = /* @__PURE__ */ __name((value4) => isObject$d(value4) ? readonly(value4) : value4, "toReadonly"); const COMPUTED_SIDE_EFFECT_WARN = `Computed is still dirty after getter evaluation, likely because a computed is mutating its own dependency in its getter. State mutations in computed getters should be avoided. Check the docs for more details: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free`; class ComputedRefImpl { static { __name(this, "ComputedRefImpl"); } constructor(getter, _setter, isReadonly2, isSSR) { this.getter = getter; this._setter = _setter; this.dep = void 0; this.__v_isRef = true; this["__v_isReadonly"] = false; this.effect = new ReactiveEffect( () => getter(this._value), () => triggerRefValue( this, this.effect._dirtyLevel === 2 ? 2 : 3 ) ); this.effect.computed = this; this.effect.active = this._cacheable = !isSSR; this["__v_isReadonly"] = isReadonly2; } get value() { const self2 = toRaw(this); if ((!self2._cacheable || self2.effect.dirty) && hasChanged(self2._value, self2._value = self2.effect.run())) { triggerRefValue(self2, 4); } trackRefValue(self2); if (self2.effect._dirtyLevel >= 2) { if (false) { warn$4(COMPUTED_SIDE_EFFECT_WARN, ` getter: `, this.getter); } triggerRefValue(self2, 2); } return self2._value; } set value(newValue2) { this._setter(newValue2); } // #region polyfill _dirty for backward compatibility third party code for Vue <= 3.3.x get _dirty() { return this.effect.dirty; } set _dirty(v2) { this.effect.dirty = v2; } // #endregion } function computed$1(getterOrOptions, debugOptions, isSSR = false) { let getter; let setter; const onlyGetter = isFunction$8(getterOrOptions); if (onlyGetter) { getter = getterOrOptions; setter = false ? () => { warn$4("Write operation failed: computed value is readonly"); } : NOOP; } else { getter = getterOrOptions.get; setter = getterOrOptions.set; } const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR); if (false) { cRef.effect.onTrack = debugOptions.onTrack; cRef.effect.onTrigger = debugOptions.onTrigger; } return cRef; } __name(computed$1, "computed$1"); function trackRefValue(ref2) { var _a2; if (shouldTrack && activeEffect) { ref2 = toRaw(ref2); trackEffect( activeEffect, (_a2 = ref2.dep) != null ? _a2 : ref2.dep = createDep( () => ref2.dep = void 0, ref2 instanceof ComputedRefImpl ? ref2 : void 0 ), false ? { target: ref2, type: "get", key: "value" } : void 0 ); } } __name(trackRefValue, "trackRefValue"); function triggerRefValue(ref2, dirtyLevel = 4, newVal, oldVal) { ref2 = toRaw(ref2); const dep = ref2.dep; if (dep) { triggerEffects( dep, dirtyLevel, false ? { target: ref2, type: "set", key: "value", newValue: newVal, oldValue: oldVal } : void 0 ); } } __name(triggerRefValue, "triggerRefValue"); function isRef(r2) { return !!(r2 && r2.__v_isRef === true); } __name(isRef, "isRef"); function ref(value4) { return createRef(value4, false); } __name(ref, "ref"); function shallowRef(value4) { return createRef(value4, true); } __name(shallowRef, "shallowRef"); function createRef(rawValue, shallow) { if (isRef(rawValue)) { return rawValue; } return new RefImpl(rawValue, shallow); } __name(createRef, "createRef"); class RefImpl { static { __name(this, "RefImpl"); } constructor(value4, __v_isShallow) { this.__v_isShallow = __v_isShallow; this.dep = void 0; this.__v_isRef = true; this._rawValue = __v_isShallow ? value4 : toRaw(value4); this._value = __v_isShallow ? value4 : toReactive$1(value4); } get value() { trackRefValue(this); return this._value; } set value(newVal) { const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal); newVal = useDirectValue ? newVal : toRaw(newVal); if (hasChanged(newVal, this._rawValue)) { const oldVal = this._rawValue; this._rawValue = newVal; this._value = useDirectValue ? newVal : toReactive$1(newVal); triggerRefValue(this, 4, newVal, oldVal); } } } function triggerRef(ref2) { triggerRefValue(ref2, 4, false ? ref2.value : void 0); } __name(triggerRef, "triggerRef"); function unref(ref2) { return isRef(ref2) ? ref2.value : ref2; } __name(unref, "unref"); function toValue$1(source) { return isFunction$8(source) ? source() : unref(source); } __name(toValue$1, "toValue$1"); const shallowUnwrapHandlers = { get: /* @__PURE__ */ __name((target, key, receiver) => unref(Reflect.get(target, key, receiver)), "get"), set: /* @__PURE__ */ __name((target, key, value4, receiver) => { const oldValue2 = target[key]; if (isRef(oldValue2) && !isRef(value4)) { oldValue2.value = value4; return true; } else { return Reflect.set(target, key, value4, receiver); } }, "set") }; function proxyRefs(objectWithRefs) { return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); } __name(proxyRefs, "proxyRefs"); class CustomRefImpl { static { __name(this, "CustomRefImpl"); } constructor(factory) { this.dep = void 0; this.__v_isRef = true; const { get: get22, set: set22 } = factory( () => trackRefValue(this), () => triggerRefValue(this) ); this._get = get22; this._set = set22; } get value() { return this._get(); } set value(newVal) { this._set(newVal); } } function customRef(factory) { return new CustomRefImpl(factory); } __name(customRef, "customRef"); function toRefs$1(object) { if (false) { warn$4(`toRefs() expects a reactive object but received a plain one.`); } const ret = isArray$9(object) ? new Array(object.length) : {}; for (const key in object) { ret[key] = propertyToRef(object, key); } return ret; } __name(toRefs$1, "toRefs$1"); class ObjectRefImpl { static { __name(this, "ObjectRefImpl"); } constructor(_object, _key, _defaultValue) { this._object = _object; this._key = _key; this._defaultValue = _defaultValue; this.__v_isRef = true; } get value() { const val = this._object[this._key]; return val === void 0 ? this._defaultValue : val; } set value(newVal) { this._object[this._key] = newVal; } get dep() { return getDepFromReactive(toRaw(this._object), this._key); } } class GetterRefImpl { static { __name(this, "GetterRefImpl"); } constructor(_getter) { this._getter = _getter; this.__v_isRef = true; this.__v_isReadonly = true; } get value() { return this._getter(); } } function toRef$1(source, key, defaultValue) { if (isRef(source)) { return source; } else if (isFunction$8(source)) { return new GetterRefImpl(source); } else if (isObject$d(source) && arguments.length > 1) { return propertyToRef(source, key, defaultValue); } else { return ref(source); } } __name(toRef$1, "toRef$1"); function propertyToRef(source, key, defaultValue) { const val = source[key]; return isRef(val) ? val : new ObjectRefImpl(source, key, defaultValue); } __name(propertyToRef, "propertyToRef"); const deferredComputed = computed$1; const TrackOpTypes = { "GET": "get", "HAS": "has", "ITERATE": "iterate" }; const TriggerOpTypes = { "SET": "set", "ADD": "add", "DELETE": "delete", "CLEAR": "clear" }; const ReactiveFlags = { "SKIP": "__v_skip", "IS_REACTIVE": "__v_isReactive", "IS_READONLY": "__v_isReadonly", "IS_SHALLOW": "__v_isShallow", "RAW": "__v_raw" }; /** * @vue/runtime-core v3.4.31 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT **/ const stack = []; function pushWarningContext(vnode) { stack.push(vnode); } __name(pushWarningContext, "pushWarningContext"); function popWarningContext() { stack.pop(); } __name(popWarningContext, "popWarningContext"); function warn$1$1(msg, ...args) { pauseTracking(); const instance = stack.length ? stack[stack.length - 1].component : null; const appWarnHandler = instance && instance.appContext.config.warnHandler; const trace = getComponentTrace(); if (appWarnHandler) { callWithErrorHandling( appWarnHandler, instance, 11, [ // eslint-disable-next-line no-restricted-syntax msg + args.map((a2) => { var _a2, _b; return (_b = (_a2 = a2.toString) == null ? void 0 : _a2.call(a2)) != null ? _b : JSON.stringify(a2); }).join(""), instance && instance.proxy, trace.map( ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>` ).join("\n"), trace ] ); } else { const warnArgs = [`[Vue warn]: ${msg}`, ...args]; if (trace.length && // avoid spamming console during tests true) { warnArgs.push(` `, ...formatTrace(trace)); } console.warn(...warnArgs); } resetTracking(); } __name(warn$1$1, "warn$1$1"); function getComponentTrace() { let currentVNode = stack[stack.length - 1]; if (!currentVNode) { return []; } const normalizedStack = []; while (currentVNode) { const last = normalizedStack[0]; if (last && last.vnode === currentVNode) { last.recurseCount++; } else { normalizedStack.push({ vnode: currentVNode, recurseCount: 0 }); } const parentInstance = currentVNode.component && currentVNode.component.parent; currentVNode = parentInstance && parentInstance.vnode; } return normalizedStack; } __name(getComponentTrace, "getComponentTrace"); function formatTrace(trace) { const logs = []; trace.forEach((entry, i2) => { logs.push(...i2 === 0 ? [] : [` `], ...formatTraceEntry(entry)); }); return logs; } __name(formatTrace, "formatTrace"); function formatTraceEntry({ vnode, recurseCount }) { const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; const isRoot = vnode.component ? vnode.component.parent == null : false; const open2 = ` at <${formatComponentName( vnode.component, vnode.type, isRoot )}`; const close5 = `>` + postfix; return vnode.props ? [open2, ...formatProps(vnode.props), close5] : [open2 + close5]; } __name(formatTraceEntry, "formatTraceEntry"); function formatProps(props) { const res = []; const keys2 = Object.keys(props); keys2.slice(0, 3).forEach((key) => { res.push(...formatProp(key, props[key])); }); if (keys2.length > 3) { res.push(` ...`); } return res; } __name(formatProps, "formatProps"); function formatProp(key, value4, raw) { if (isString$7(value4)) { value4 = JSON.stringify(value4); return raw ? value4 : [`${key}=${value4}`]; } else if (typeof value4 === "number" || typeof value4 === "boolean" || value4 == null) { return raw ? value4 : [`${key}=${value4}`]; } else if (isRef(value4)) { value4 = formatProp(key, toRaw(value4.value), true); return raw ? value4 : [`${key}=Ref<`, value4, `>`]; } else if (isFunction$8(value4)) { return [`${key}=fn${value4.name ? `<${value4.name}>` : ``}`]; } else { value4 = toRaw(value4); return raw ? value4 : [`${key}=`, value4]; } } __name(formatProp, "formatProp"); function assertNumber(val, type) { if (true) return; if (val === void 0) { return; } else if (typeof val !== "number") { warn$1$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`); } else if (isNaN(val)) { warn$1$1(`${type} is NaN - the duration expression might be incorrect.`); } } __name(assertNumber, "assertNumber"); const ErrorCodes = { "SETUP_FUNCTION": 0, "0": "SETUP_FUNCTION", "RENDER_FUNCTION": 1, "1": "RENDER_FUNCTION", "WATCH_GETTER": 2, "2": "WATCH_GETTER", "WATCH_CALLBACK": 3, "3": "WATCH_CALLBACK", "WATCH_CLEANUP": 4, "4": "WATCH_CLEANUP", "NATIVE_EVENT_HANDLER": 5, "5": "NATIVE_EVENT_HANDLER", "COMPONENT_EVENT_HANDLER": 6, "6": "COMPONENT_EVENT_HANDLER", "VNODE_HOOK": 7, "7": "VNODE_HOOK", "DIRECTIVE_HOOK": 8, "8": "DIRECTIVE_HOOK", "TRANSITION_HOOK": 9, "9": "TRANSITION_HOOK", "APP_ERROR_HANDLER": 10, "10": "APP_ERROR_HANDLER", "APP_WARN_HANDLER": 11, "11": "APP_WARN_HANDLER", "FUNCTION_REF": 12, "12": "FUNCTION_REF", "ASYNC_COMPONENT_LOADER": 13, "13": "ASYNC_COMPONENT_LOADER", "SCHEDULER": 14, "14": "SCHEDULER" }; const ErrorTypeStrings$1 = { ["sp"]: "serverPrefetch hook", ["bc"]: "beforeCreate hook", ["c"]: "created hook", ["bm"]: "beforeMount hook", ["m"]: "mounted hook", ["bu"]: "beforeUpdate hook", ["u"]: "updated", ["bum"]: "beforeUnmount hook", ["um"]: "unmounted hook", ["a"]: "activated hook", ["da"]: "deactivated hook", ["ec"]: "errorCaptured hook", ["rtc"]: "renderTracked hook", ["rtg"]: "renderTriggered hook", [0]: "setup function", [1]: "render function", [2]: "watcher getter", [3]: "watcher callback", [4]: "watcher cleanup function", [5]: "native event handler", [6]: "component event handler", [7]: "vnode hook", [8]: "directive hook", [9]: "transition hook", [10]: "app errorHandler", [11]: "app warnHandler", [12]: "ref function", [13]: "async component loader", [14]: "scheduler flush. This is likely a Vue internals bug. Please open an issue at https://github.com/vuejs/core ." }; function callWithErrorHandling(fn, instance, type, args) { try { return args ? fn(...args) : fn(); } catch (err) { handleError(err, instance, type); } } __name(callWithErrorHandling, "callWithErrorHandling"); function callWithAsyncErrorHandling(fn, instance, type, args) { if (isFunction$8(fn)) { const res = callWithErrorHandling(fn, instance, type, args); if (res && isPromise$1(res)) { res.catch((err) => { handleError(err, instance, type); }); } return res; } if (isArray$9(fn)) { const values = []; for (let i2 = 0; i2 < fn.length; i2++) { values.push(callWithAsyncErrorHandling(fn[i2], instance, type, args)); } return values; } else if (false) { warn$1$1( `Invalid value type passed to callWithAsyncErrorHandling(): ${typeof fn}` ); } } __name(callWithAsyncErrorHandling, "callWithAsyncErrorHandling"); function handleError(err, instance, type, throwInDev = true) { const contextVNode = instance ? instance.vnode : null; if (instance) { let cur = instance.parent; const exposedInstance = instance.proxy; const errorInfo = false ? ErrorTypeStrings$1[type] : `https://vuejs.org/error-reference/#runtime-${type}`; while (cur) { const errorCapturedHooks = cur.ec; if (errorCapturedHooks) { for (let i2 = 0; i2 < errorCapturedHooks.length; i2++) { if (errorCapturedHooks[i2](err, exposedInstance, errorInfo) === false) { return; } } } cur = cur.parent; } const appErrorHandler = instance.appContext.config.errorHandler; if (appErrorHandler) { pauseTracking(); callWithErrorHandling( appErrorHandler, null, 10, [err, exposedInstance, errorInfo] ); resetTracking(); return; } } logError(err, type, contextVNode, throwInDev); } __name(handleError, "handleError"); function logError(err, type, contextVNode, throwInDev = true) { if (false) { const info = ErrorTypeStrings$1[type]; if (contextVNode) { pushWarningContext(contextVNode); } warn$1$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`); if (contextVNode) { popWarningContext(); } if (throwInDev) { throw err; } else { console.error(err); } } else { console.error(err); } } __name(logError, "logError"); let isFlushing = false; let isFlushPending = false; const queue = []; let flushIndex = 0; const pendingPostFlushCbs = []; let activePostFlushCbs = null; let postFlushIndex = 0; const resolvedPromise = /* @__PURE__ */ Promise.resolve(); let currentFlushPromise = null; const RECURSION_LIMIT = 100; function nextTick(fn) { const p2 = currentFlushPromise || resolvedPromise; return fn ? p2.then(this ? fn.bind(this) : fn) : p2; } __name(nextTick, "nextTick"); function findInsertionIndex$1(id3) { let start2 = flushIndex + 1; let end = queue.length; while (start2 < end) { const middle = start2 + end >>> 1; const middleJob = queue[middle]; const middleJobId = getId(middleJob); if (middleJobId < id3 || middleJobId === id3 && middleJob.pre) { start2 = middle + 1; } else { end = middle; } } return start2; } __name(findInsertionIndex$1, "findInsertionIndex$1"); function queueJob(job) { if (!queue.length || !queue.includes( job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex )) { if (job.id == null) { queue.push(job); } else { queue.splice(findInsertionIndex$1(job.id), 0, job); } queueFlush(); } } __name(queueJob, "queueJob"); function queueFlush() { if (!isFlushing && !isFlushPending) { isFlushPending = true; currentFlushPromise = resolvedPromise.then(flushJobs); } } __name(queueFlush, "queueFlush"); function invalidateJob(job) { const i2 = queue.indexOf(job); if (i2 > flushIndex) { queue.splice(i2, 1); } } __name(invalidateJob, "invalidateJob"); function queuePostFlushCb(cb) { if (!isArray$9(cb)) { if (!activePostFlushCbs || !activePostFlushCbs.includes( cb, cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex )) { pendingPostFlushCbs.push(cb); } } else { pendingPostFlushCbs.push(...cb); } queueFlush(); } __name(queuePostFlushCb, "queuePostFlushCb"); function flushPreFlushCbs(instance, seen2, i2 = isFlushing ? flushIndex + 1 : 0) { if (false) { seen2 = seen2 || /* @__PURE__ */ new Map(); } for (; i2 < queue.length; i2++) { const cb = queue[i2]; if (cb && cb.pre) { if (instance && cb.id !== instance.uid) { continue; } if (false) { continue; } queue.splice(i2, 1); i2--; cb(); } } } __name(flushPreFlushCbs, "flushPreFlushCbs"); function flushPostFlushCbs(seen2) { if (pendingPostFlushCbs.length) { const deduped = [...new Set(pendingPostFlushCbs)].sort( (a2, b2) => getId(a2) - getId(b2) ); pendingPostFlushCbs.length = 0; if (activePostFlushCbs) { activePostFlushCbs.push(...deduped); return; } activePostFlushCbs = deduped; if (false) { seen2 = seen2 || /* @__PURE__ */ new Map(); } for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { const cb = activePostFlushCbs[postFlushIndex]; if (false) { continue; } if (cb.active !== false) cb(); } activePostFlushCbs = null; postFlushIndex = 0; } } __name(flushPostFlushCbs, "flushPostFlushCbs"); const getId = /* @__PURE__ */ __name((job) => job.id == null ? Infinity : job.id, "getId"); const comparator = /* @__PURE__ */ __name((a2, b2) => { const diff2 = getId(a2) - getId(b2); if (diff2 === 0) { if (a2.pre && !b2.pre) return -1; if (b2.pre && !a2.pre) return 1; } return diff2; }, "comparator"); function flushJobs(seen2) { isFlushPending = false; isFlushing = true; if (false) { seen2 = seen2 || /* @__PURE__ */ new Map(); } queue.sort(comparator); const check = false ? (job) => checkRecursiveUpdates(seen2, job) : NOOP; try { for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { const job = queue[flushIndex]; if (job && job.active !== false) { if (false) { continue; } callWithErrorHandling(job, null, 14); } } } finally { flushIndex = 0; queue.length = 0; flushPostFlushCbs(seen2); isFlushing = false; currentFlushPromise = null; if (queue.length || pendingPostFlushCbs.length) { flushJobs(seen2); } } } __name(flushJobs, "flushJobs"); function checkRecursiveUpdates(seen2, fn) { if (!seen2.has(fn)) { seen2.set(fn, 1); } else { const count = seen2.get(fn); if (count > RECURSION_LIMIT) { const instance = fn.ownerInstance; const componentName = instance && getComponentName(instance.type); handleError( `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`, null, 10 ); return true; } else { seen2.set(fn, count + 1); } } } __name(checkRecursiveUpdates, "checkRecursiveUpdates"); let isHmrUpdating = false; const hmrDirtyComponents = /* @__PURE__ */ new Set(); if (false) { getGlobalThis$1().__VUE_HMR_RUNTIME__ = { createRecord: tryWrap(createRecord), rerender: tryWrap(rerender), reload: tryWrap(reload) }; } const map$1 = /* @__PURE__ */ new Map(); function registerHMR(instance) { const id3 = instance.type.__hmrId; let record2 = map$1.get(id3); if (!record2) { createRecord(id3, instance.type); record2 = map$1.get(id3); } record2.instances.add(instance); } __name(registerHMR, "registerHMR"); function unregisterHMR(instance) { map$1.get(instance.type.__hmrId).instances.delete(instance); } __name(unregisterHMR, "unregisterHMR"); function createRecord(id3, initialDef) { if (map$1.has(id3)) { return false; } map$1.set(id3, { initialDef: normalizeClassComponent(initialDef), instances: /* @__PURE__ */ new Set() }); return true; } __name(createRecord, "createRecord"); function normalizeClassComponent(component) { return isClassComponent(component) ? component.__vccOpts : component; } __name(normalizeClassComponent, "normalizeClassComponent"); function rerender(id3, newRender) { const record2 = map$1.get(id3); if (!record2) { return; } record2.initialDef.render = newRender; [...record2.instances].forEach((instance) => { if (newRender) { instance.render = newRender; normalizeClassComponent(instance.type).render = newRender; } instance.renderCache = []; isHmrUpdating = true; instance.effect.dirty = true; instance.update(); isHmrUpdating = false; }); } __name(rerender, "rerender"); function reload(id3, newComp) { const record2 = map$1.get(id3); if (!record2) return; newComp = normalizeClassComponent(newComp); updateComponentDef(record2.initialDef, newComp); const instances = [...record2.instances]; for (const instance of instances) { const oldComp = normalizeClassComponent(instance.type); if (!hmrDirtyComponents.has(oldComp)) { if (oldComp !== record2.initialDef) { updateComponentDef(oldComp, newComp); } hmrDirtyComponents.add(oldComp); } instance.appContext.propsCache.delete(instance.type); instance.appContext.emitsCache.delete(instance.type); instance.appContext.optionsCache.delete(instance.type); if (instance.ceReload) { hmrDirtyComponents.add(oldComp); instance.ceReload(newComp.styles); hmrDirtyComponents.delete(oldComp); } else if (instance.parent) { instance.parent.effect.dirty = true; queueJob(() => { instance.parent.update(); hmrDirtyComponents.delete(oldComp); }); } else if (instance.appContext.reload) { instance.appContext.reload(); } else if (typeof window !== "undefined") { window.location.reload(); } else { console.warn( "[HMR] Root or manually mounted instance modified. Full reload required." ); } } queuePostFlushCb(() => { for (const instance of instances) { hmrDirtyComponents.delete( normalizeClassComponent(instance.type) ); } }); } __name(reload, "reload"); function updateComponentDef(oldComp, newComp) { extend$1(oldComp, newComp); for (const key in oldComp) { if (key !== "__file" && !(key in newComp)) { delete oldComp[key]; } } } __name(updateComponentDef, "updateComponentDef"); function tryWrap(fn) { return (id3, arg) => { try { return fn(id3, arg); } catch (e2) { console.error(e2); console.warn( `[HMR] Something went wrong during Vue component hot-reload. Full reload required.` ); } }; } __name(tryWrap, "tryWrap"); let devtools$1; let buffer = []; let devtoolsNotInstalled = false; function emit$1(event, ...args) { if (devtools$1) { devtools$1.emit(event, ...args); } else if (!devtoolsNotInstalled) { buffer.push({ event, args }); } } __name(emit$1, "emit$1"); function setDevtoolsHook$1(hook, target) { var _a2, _b; devtools$1 = hook; if (devtools$1) { devtools$1.enabled = true; buffer.forEach(({ event, args }) => devtools$1.emit(event, ...args)); buffer = []; } else if ( // handle late devtools injection - only do this if we are in an actual // browser environment to avoid the timer handle stalling test runner exit // (#4815) typeof window !== "undefined" && // some envs mock window but not fully window.HTMLElement && // also exclude jsdom // eslint-disable-next-line no-restricted-syntax !((_b = (_a2 = window.navigator) == null ? void 0 : _a2.userAgent) == null ? void 0 : _b.includes("jsdom")) ) { const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []; replay.push((newHook) => { setDevtoolsHook$1(newHook, target); }); setTimeout(() => { if (!devtools$1) { target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null; devtoolsNotInstalled = true; buffer = []; } }, 3e3); } else { devtoolsNotInstalled = true; buffer = []; } } __name(setDevtoolsHook$1, "setDevtoolsHook$1"); function devtoolsInitApp(app2, version2) { emit$1("app:init", app2, version2, { Fragment: Fragment$1, Text: Text$4, Comment, Static }); } __name(devtoolsInitApp, "devtoolsInitApp"); function devtoolsUnmountApp(app2) { emit$1("app:unmount", app2); } __name(devtoolsUnmountApp, "devtoolsUnmountApp"); const devtoolsComponentAdded = /* @__PURE__ */ createDevtoolsComponentHook( "component:added" /* COMPONENT_ADDED */ ); const devtoolsComponentUpdated = /* @__PURE__ */ createDevtoolsComponentHook( "component:updated" /* COMPONENT_UPDATED */ ); const _devtoolsComponentRemoved = /* @__PURE__ */ createDevtoolsComponentHook( "component:removed" /* COMPONENT_REMOVED */ ); const devtoolsComponentRemoved = /* @__PURE__ */ __name((component) => { if (devtools$1 && typeof devtools$1.cleanupBuffer === "function" && // remove the component if it wasn't buffered !devtools$1.cleanupBuffer(component)) { _devtoolsComponentRemoved(component); } }, "devtoolsComponentRemoved"); /*! #__NO_SIDE_EFFECTS__ */ // @__NO_SIDE_EFFECTS__ function createDevtoolsComponentHook(hook) { return (component) => { emit$1( hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : void 0, component ); }; } __name(createDevtoolsComponentHook, "createDevtoolsComponentHook"); const devtoolsPerfStart = /* @__PURE__ */ createDevtoolsPerformanceHook( "perf:start" /* PERFORMANCE_START */ ); const devtoolsPerfEnd = /* @__PURE__ */ createDevtoolsPerformanceHook( "perf:end" /* PERFORMANCE_END */ ); function createDevtoolsPerformanceHook(hook) { return (component, type, time) => { emit$1(hook, component.appContext.app, component.uid, component, type, time); }; } __name(createDevtoolsPerformanceHook, "createDevtoolsPerformanceHook"); function devtoolsComponentEmit(component, event, params) { emit$1( "component:emit", component.appContext.app, component, event, params ); } __name(devtoolsComponentEmit, "devtoolsComponentEmit"); function emit(instance, event, ...rawArgs) { if (instance.isUnmounted) return; const props = instance.vnode.props || EMPTY_OBJ; if (false) { const { emitsOptions, propsOptions: [propsOptions] } = instance; if (emitsOptions) { if (!(event in emitsOptions) && true) { if (!propsOptions || !(toHandlerKey(event) in propsOptions)) { warn$1$1( `Component emitted event "${event}" but it is neither declared in the emits option nor as an "${toHandlerKey(event)}" prop.` ); } } else { const validator3 = emitsOptions[event]; if (isFunction$8(validator3)) { const isValid2 = validator3(...rawArgs); if (!isValid2) { warn$1$1( `Invalid event arguments: event validation failed for event "${event}".` ); } } } } } let args = rawArgs; const isModelListener2 = event.startsWith("update:"); const modelArg = isModelListener2 && event.slice(7); if (modelArg && modelArg in props) { const modifiersKey = `${modelArg === "modelValue" ? "model" : modelArg}Modifiers`; const { number: number2, trim: trim2 } = props[modifiersKey] || EMPTY_OBJ; if (trim2) { args = rawArgs.map((a2) => isString$7(a2) ? a2.trim() : a2); } if (number2) { args = rawArgs.map(looseToNumber); } } if (false) { devtoolsComponentEmit(instance, event, args); } if (false) { const lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) { warn$1$1( `Event "${lowerCaseEvent}" is emitted in component ${formatComponentName( instance, instance.type )} but the handler is registered for "${event}". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "${hyphenate$1( event )}" instead of "${event}".` ); } } let handlerName; let handler6 = props[handlerName = toHandlerKey(event)] || // also try camelCase event handler (#2249) props[handlerName = toHandlerKey(camelize$1(event))]; if (!handler6 && isModelListener2) { handler6 = props[handlerName = toHandlerKey(hyphenate$1(event))]; } if (handler6) { callWithAsyncErrorHandling( handler6, instance, 6, args ); } const onceHandler = props[handlerName + `Once`]; if (onceHandler) { if (!instance.emitted) { instance.emitted = {}; } else if (instance.emitted[handlerName]) { return; } instance.emitted[handlerName] = true; callWithAsyncErrorHandling( onceHandler, instance, 6, args ); } } __name(emit, "emit"); function normalizeEmitsOptions(comp, appContext, asMixin = false) { const cache2 = appContext.emitsCache; const cached = cache2.get(comp); if (cached !== void 0) { return cached; } const raw = comp.emits; let normalized = {}; let hasExtends = false; if (!isFunction$8(comp)) { const extendEmits = /* @__PURE__ */ __name((raw2) => { const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); if (normalizedFromExtend) { hasExtends = true; extend$1(normalized, normalizedFromExtend); } }, "extendEmits"); if (!asMixin && appContext.mixins.length) { appContext.mixins.forEach(extendEmits); } if (comp.extends) { extendEmits(comp.extends); } if (comp.mixins) { comp.mixins.forEach(extendEmits); } } if (!raw && !hasExtends) { if (isObject$d(comp)) { cache2.set(comp, null); } return null; } if (isArray$9(raw)) { raw.forEach((key) => normalized[key] = null); } else { extend$1(normalized, raw); } if (isObject$d(comp)) { cache2.set(comp, normalized); } return normalized; } __name(normalizeEmitsOptions, "normalizeEmitsOptions"); function isEmitListener(options4, key) { if (!options4 || !isOn(key)) { return false; } key = key.slice(2).replace(/Once$/, ""); return hasOwn$3(options4, key[0].toLowerCase() + key.slice(1)) || hasOwn$3(options4, hyphenate$1(key)) || hasOwn$3(options4, key); } __name(isEmitListener, "isEmitListener"); let currentRenderingInstance = null; let currentScopeId = null; function setCurrentRenderingInstance(instance) { const prev2 = currentRenderingInstance; currentRenderingInstance = instance; currentScopeId = instance && instance.type.__scopeId || null; return prev2; } __name(setCurrentRenderingInstance, "setCurrentRenderingInstance"); function pushScopeId(id3) { currentScopeId = id3; } __name(pushScopeId, "pushScopeId"); function popScopeId() { currentScopeId = null; } __name(popScopeId, "popScopeId"); const withScopeId = /* @__PURE__ */ __name((_id2) => withCtx, "withScopeId"); function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { if (!ctx) return fn; if (fn._n) { return fn; } const renderFnWithContext = /* @__PURE__ */ __name((...args) => { if (renderFnWithContext._d) { setBlockTracking(-1); } const prevInstance = setCurrentRenderingInstance(ctx); let res; try { res = fn(...args); } finally { setCurrentRenderingInstance(prevInstance); if (renderFnWithContext._d) { setBlockTracking(1); } } if (false) { devtoolsComponentUpdated(ctx); } return res; }, "renderFnWithContext"); renderFnWithContext._n = true; renderFnWithContext._c = true; renderFnWithContext._d = true; return renderFnWithContext; } __name(withCtx, "withCtx"); let accessedAttrs = false; function markAttrsAccessed() { accessedAttrs = true; } __name(markAttrsAccessed, "markAttrsAccessed"); function renderComponentRoot(instance) { const { type: Component, vnode, proxy, withProxy, propsOptions: [propsOptions], slots, attrs: attrs4, emit: emit2, render: render2, renderCache, props, data: data25, setupState, ctx, inheritAttrs } = instance; const prev2 = setCurrentRenderingInstance(instance); let result; let fallthroughAttrs; if (false) { accessedAttrs = false; } try { if (vnode.shapeFlag & 4) { const proxyToUse = withProxy || proxy; const thisProxy = false ? new Proxy(proxyToUse, { get(target, key, receiver) { warn$1$1( `Property '${String( key )}' was accessed via 'this'. Avoid using 'this' in templates.` ); return Reflect.get(target, key, receiver); } }) : proxyToUse; result = normalizeVNode( render2.call( thisProxy, proxyToUse, renderCache, false ? shallowReadonly(props) : props, setupState, data25, ctx ) ); fallthroughAttrs = attrs4; } else { const render22 = Component; if (false) { markAttrsAccessed(); } result = normalizeVNode( render22.length > 1 ? render22( false ? shallowReadonly(props) : props, false ? { get attrs() { markAttrsAccessed(); return shallowReadonly(attrs4); }, slots, emit: emit2 } : { attrs: attrs4, slots, emit: emit2 } ) : render22( false ? shallowReadonly(props) : props, null ) ); fallthroughAttrs = Component.props ? attrs4 : getFunctionalFallthrough(attrs4); } } catch (err) { blockStack.length = 0; handleError(err, instance, 1); result = createVNode(Comment); } let root27 = result; let setRoot = void 0; if (false) { [root27, setRoot] = getChildRoot(result); } if (fallthroughAttrs && inheritAttrs !== false) { const keys2 = Object.keys(fallthroughAttrs); const { shapeFlag } = root27; if (keys2.length) { if (shapeFlag & (1 | 6)) { if (propsOptions && keys2.some(isModelListener)) { fallthroughAttrs = filterModelListeners( fallthroughAttrs, propsOptions ); } root27 = cloneVNode(root27, fallthroughAttrs, false, true); } else if (false) { const allAttrs = Object.keys(attrs4); const eventAttrs = []; const extraAttrs = []; for (let i2 = 0, l2 = allAttrs.length; i2 < l2; i2++) { const key = allAttrs[i2]; if (isOn(key)) { if (!isModelListener(key)) { eventAttrs.push(key[2].toLowerCase() + key.slice(3)); } } else { extraAttrs.push(key); } } if (extraAttrs.length) { warn$1$1( `Extraneous non-props attributes (${extraAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.` ); } if (eventAttrs.length) { warn$1$1( `Extraneous non-emits event listeners (${eventAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.` ); } } } } if (vnode.dirs) { if (false) { warn$1$1( `Runtime directive used on component with non-element root node. The directives will not function as intended.` ); } root27 = cloneVNode(root27, null, false, true); root27.dirs = root27.dirs ? root27.dirs.concat(vnode.dirs) : vnode.dirs; } if (vnode.transition) { if (false) { warn$1$1( `Component inside renders non-element root node that cannot be animated.` ); } root27.transition = vnode.transition; } if (false) { setRoot(root27); } else { result = root27; } setCurrentRenderingInstance(prev2); return result; } __name(renderComponentRoot, "renderComponentRoot"); const getChildRoot = /* @__PURE__ */ __name((vnode) => { const rawChildren = vnode.children; const dynamicChildren = vnode.dynamicChildren; const childRoot = filterSingleRoot(rawChildren, false); if (!childRoot) { return [vnode, void 0]; } else if (false) { return getChildRoot(childRoot); } const index2 = rawChildren.indexOf(childRoot); const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1; const setRoot = /* @__PURE__ */ __name((updatedRoot) => { rawChildren[index2] = updatedRoot; if (dynamicChildren) { if (dynamicIndex > -1) { dynamicChildren[dynamicIndex] = updatedRoot; } else if (updatedRoot.patchFlag > 0) { vnode.dynamicChildren = [...dynamicChildren, updatedRoot]; } } }, "setRoot"); return [normalizeVNode(childRoot), setRoot]; }, "getChildRoot"); function filterSingleRoot(children, recurse = true) { let singleRoot; for (let i2 = 0; i2 < children.length; i2++) { const child = children[i2]; if (isVNode$1(child)) { if (child.type !== Comment || child.children === "v-if") { if (singleRoot) { return; } else { singleRoot = child; if (false) { return filterSingleRoot(singleRoot.children); } } } } else { return; } } return singleRoot; } __name(filterSingleRoot, "filterSingleRoot"); const getFunctionalFallthrough = /* @__PURE__ */ __name((attrs4) => { let res; for (const key in attrs4) { if (key === "class" || key === "style" || isOn(key)) { (res || (res = {}))[key] = attrs4[key]; } } return res; }, "getFunctionalFallthrough"); const filterModelListeners = /* @__PURE__ */ __name((attrs4, props) => { const res = {}; for (const key in attrs4) { if (!isModelListener(key) || !(key.slice(9) in props)) { res[key] = attrs4[key]; } } return res; }, "filterModelListeners"); const isElementRoot = /* @__PURE__ */ __name((vnode) => { return vnode.shapeFlag & (6 | 1) || vnode.type === Comment; }, "isElementRoot"); function shouldUpdateComponent(prevVNode, nextVNode, optimized) { const { props: prevProps, children: prevChildren, component } = prevVNode; const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; const emits = component.emitsOptions; if (false) { return true; } if (nextVNode.dirs || nextVNode.transition) { return true; } if (optimized && patchFlag >= 0) { if (patchFlag & 1024) { return true; } if (patchFlag & 16) { if (!prevProps) { return !!nextProps; } return hasPropsChanged(prevProps, nextProps, emits); } else if (patchFlag & 8) { const dynamicProps = nextVNode.dynamicProps; for (let i2 = 0; i2 < dynamicProps.length; i2++) { const key = dynamicProps[i2]; if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) { return true; } } } } else { if (prevChildren || nextChildren) { if (!nextChildren || !nextChildren.$stable) { return true; } } if (prevProps === nextProps) { return false; } if (!prevProps) { return !!nextProps; } if (!nextProps) { return true; } return hasPropsChanged(prevProps, nextProps, emits); } return false; } __name(shouldUpdateComponent, "shouldUpdateComponent"); function hasPropsChanged(prevProps, nextProps, emitsOptions) { const nextKeys = Object.keys(nextProps); if (nextKeys.length !== Object.keys(prevProps).length) { return true; } for (let i2 = 0; i2 < nextKeys.length; i2++) { const key = nextKeys[i2]; if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) { return true; } } return false; } __name(hasPropsChanged, "hasPropsChanged"); function updateHOCHostEl({ vnode, parent }, el) { while (parent) { const root27 = parent.subTree; if (root27.suspense && root27.suspense.activeBranch === vnode) { root27.el = vnode.el; } if (root27 === vnode) { (vnode = parent.vnode).el = el; parent = parent.parent; } else { break; } } } __name(updateHOCHostEl, "updateHOCHostEl"); const COMPONENTS = "components"; const DIRECTIVES = "directives"; function resolveComponent(name2, maybeSelfReference) { return resolveAsset(COMPONENTS, name2, true, maybeSelfReference) || name2; } __name(resolveComponent, "resolveComponent"); const NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc"); function resolveDynamicComponent(component) { if (isString$7(component)) { return resolveAsset(COMPONENTS, component, false) || component; } else { return component || NULL_DYNAMIC_COMPONENT; } } __name(resolveDynamicComponent, "resolveDynamicComponent"); function resolveDirective(name2) { return resolveAsset(DIRECTIVES, name2); } __name(resolveDirective, "resolveDirective"); function resolveAsset(type, name2, warnMissing = true, maybeSelfReference = false) { const instance = currentRenderingInstance || currentInstance; if (instance) { const Component = instance.type; if (type === COMPONENTS) { const selfName = getComponentName( Component, false ); if (selfName && (selfName === name2 || selfName === camelize$1(name2) || selfName === capitalize$1(camelize$1(name2)))) { return Component; } } const res = ( // local registration // check instance[type] first which is resolved for options API resolve(instance[type] || Component[type], name2) || // global registration resolve(instance.appContext[type], name2) ); if (!res && maybeSelfReference) { return Component; } if (false) { const extra = type === COMPONENTS ? ` If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``; warn$1$1(`Failed to resolve ${type.slice(0, -1)}: ${name2}${extra}`); } return res; } else if (false) { warn$1$1( `resolve${capitalize$1(type.slice(0, -1))} can only be used in render() or setup().` ); } } __name(resolveAsset, "resolveAsset"); function resolve(registry, name2) { return registry && (registry[name2] || registry[camelize$1(name2)] || registry[capitalize$1(camelize$1(name2))]); } __name(resolve, "resolve"); const isSuspense = /* @__PURE__ */ __name((type) => type.__isSuspense, "isSuspense"); let suspenseId = 0; const SuspenseImpl = { name: "Suspense", // In order to make Suspense tree-shakable, we need to avoid importing it // directly in the renderer. The renderer checks for the __isSuspense flag // on a vnode's type and calls the `process` method, passing in renderer // internals. __isSuspense: true, process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { if (n1 == null) { mountSuspense( n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals ); } else { if (parentSuspense && parentSuspense.deps > 0 && !n1.suspense.isInFallback) { n2.suspense = n1.suspense; n2.suspense.vnode = n2; n2.el = n1.el; return; } patchSuspense( n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, rendererInternals ); } }, hydrate: hydrateSuspense, normalize: normalizeSuspenseChildren }; const Suspense = SuspenseImpl; function triggerEvent(vnode, name2) { const eventListener = vnode.props && vnode.props[name2]; if (isFunction$8(eventListener)) { eventListener(); } } __name(triggerEvent, "triggerEvent"); function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { const { p: patch2, o: { createElement: createElement2 } } = rendererInternals; const hiddenContainer = createElement2("div"); const suspense = vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals ); patch2( null, suspense.pendingBranch = vnode.ssContent, hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds ); if (suspense.deps > 0) { triggerEvent(vnode, "onPending"); triggerEvent(vnode, "onFallback"); patch2( null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context namespace, slotScopeIds ); setActiveBranch(suspense, vnode.ssFallback); } else { suspense.resolve(false, true); } } __name(mountSuspense, "mountSuspense"); function patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch2, um: unmount, o: { createElement: createElement2 } }) { const suspense = n2.suspense = n1.suspense; suspense.vnode = n2; n2.el = n1.el; const newBranch = n2.ssContent; const newFallback = n2.ssFallback; const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense; if (pendingBranch) { suspense.pendingBranch = newBranch; if (isSameVNodeType(newBranch, pendingBranch)) { patch2( pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized ); if (suspense.deps <= 0) { suspense.resolve(); } else if (isInFallback) { if (!isHydrating) { patch2( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context namespace, slotScopeIds, optimized ); setActiveBranch(suspense, newFallback); } } } else { suspense.pendingId = suspenseId++; if (isHydrating) { suspense.isHydrating = false; suspense.activeBranch = pendingBranch; } else { unmount(pendingBranch, parentComponent, suspense); } suspense.deps = 0; suspense.effects.length = 0; suspense.hiddenContainer = createElement2("div"); if (isInFallback) { patch2( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized ); if (suspense.deps <= 0) { suspense.resolve(); } else { patch2( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context namespace, slotScopeIds, optimized ); setActiveBranch(suspense, newFallback); } } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { patch2( activeBranch, newBranch, container, anchor, parentComponent, suspense, namespace, slotScopeIds, optimized ); suspense.resolve(true); } else { patch2( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized ); if (suspense.deps <= 0) { suspense.resolve(); } } } } else { if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { patch2( activeBranch, newBranch, container, anchor, parentComponent, suspense, namespace, slotScopeIds, optimized ); setActiveBranch(suspense, newBranch); } else { triggerEvent(n2, "onPending"); suspense.pendingBranch = newBranch; if (newBranch.shapeFlag & 512) { suspense.pendingId = newBranch.component.suspenseId; } else { suspense.pendingId = suspenseId++; } patch2( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized ); if (suspense.deps <= 0) { suspense.resolve(); } else { const { timeout, pendingId } = suspense; if (timeout > 0) { setTimeout(() => { if (suspense.pendingId === pendingId) { suspense.fallback(newFallback); } }, timeout); } else if (timeout === 0) { suspense.fallback(newFallback); } } } } } __name(patchSuspense, "patchSuspense"); let hasWarned$1 = false; function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) { if (false) { hasWarned$1 = true; console[console.info ? "info" : "log"]( ` is an experimental feature and its API will likely change.` ); } const { p: patch2, m: move, um: unmount, n: next2, o: { parentNode: parentNode2, remove: remove22 } } = rendererInternals; let parentSuspenseId; const isSuspensible = isVNodeSuspensible(vnode); if (isSuspensible) { if (parentSuspense && parentSuspense.pendingBranch) { parentSuspenseId = parentSuspense.pendingId; parentSuspense.deps++; } } const timeout = vnode.props ? toNumber(vnode.props.timeout) : void 0; if (false) { assertNumber(timeout, `Suspense timeout`); } const initialAnchor = anchor; const suspense = { vnode, parent: parentSuspense, parentComponent, namespace, container, hiddenContainer, deps: 0, pendingId: suspenseId++, timeout: typeof timeout === "number" ? timeout : -1, activeBranch: null, pendingBranch: null, isInFallback: !isHydrating, isHydrating, isUnmounted: false, effects: [], resolve(resume = false, sync = false) { if (false) { if (!resume && !suspense.pendingBranch) { throw new Error( `suspense.resolve() is called without a pending branch.` ); } if (suspense.isUnmounted) { throw new Error( `suspense.resolve() is called on an already unmounted suspense boundary.` ); } } const { vnode: vnode2, activeBranch, pendingBranch, pendingId, effects, parentComponent: parentComponent2, container: container2 } = suspense; let delayEnter = false; if (suspense.isHydrating) { suspense.isHydrating = false; } else if (!resume) { delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in"; if (delayEnter) { activeBranch.transition.afterLeave = () => { if (pendingId === suspense.pendingId) { move( pendingBranch, container2, anchor === initialAnchor ? next2(activeBranch) : anchor, 0 ); queuePostFlushCb(effects); } }; } if (activeBranch) { if (parentNode2(activeBranch.el) !== suspense.hiddenContainer) { anchor = next2(activeBranch); } unmount(activeBranch, parentComponent2, suspense, true); } if (!delayEnter) { move(pendingBranch, container2, anchor, 0); } } setActiveBranch(suspense, pendingBranch); suspense.pendingBranch = null; suspense.isInFallback = false; let parent = suspense.parent; let hasUnresolvedAncestor = false; while (parent) { if (parent.pendingBranch) { parent.effects.push(...effects); hasUnresolvedAncestor = true; break; } parent = parent.parent; } if (!hasUnresolvedAncestor && !delayEnter) { queuePostFlushCb(effects); } suspense.effects = []; if (isSuspensible) { if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) { parentSuspense.deps--; if (parentSuspense.deps === 0 && !sync) { parentSuspense.resolve(); } } } triggerEvent(vnode2, "onResolve"); }, fallback(fallbackVNode) { if (!suspense.pendingBranch) { return; } const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense; triggerEvent(vnode2, "onFallback"); const anchor2 = next2(activeBranch); const mountFallback = /* @__PURE__ */ __name(() => { if (!suspense.isInFallback) { return; } patch2( null, fallbackVNode, container2, anchor2, parentComponent2, null, // fallback tree will not have suspense context namespace2, slotScopeIds, optimized ); setActiveBranch(suspense, fallbackVNode); }, "mountFallback"); const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in"; if (delayEnter) { activeBranch.transition.afterLeave = mountFallback; } suspense.isInFallback = true; unmount( activeBranch, parentComponent2, null, // no suspense so unmount hooks fire now true // shouldRemove ); if (!delayEnter) { mountFallback(); } }, move(container2, anchor2, type) { suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type); suspense.container = container2; }, next() { return suspense.activeBranch && next2(suspense.activeBranch); }, registerDep(instance, setupRenderEffect, optimized2) { const isInPendingSuspense = !!suspense.pendingBranch; if (isInPendingSuspense) { suspense.deps++; } const hydratedEl = instance.vnode.el; instance.asyncDep.catch((err) => { handleError(err, instance, 0); }).then((asyncSetupResult) => { if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { return; } instance.asyncResolved = true; const { vnode: vnode2 } = instance; if (false) { pushWarningContext(vnode2); } handleSetupResult(instance, asyncSetupResult, false); if (hydratedEl) { vnode2.el = hydratedEl; } const placeholder = !hydratedEl && instance.subTree.el; setupRenderEffect( instance, vnode2, // component may have been moved before resolve. // if this is not a hydration, instance.subTree will be the comment // placeholder. parentNode2(hydratedEl || instance.subTree.el), // anchor will not be used if this is hydration, so only need to // consider the comment placeholder case. hydratedEl ? null : next2(instance.subTree), suspense, namespace, optimized2 ); if (placeholder) { remove22(placeholder); } updateHOCHostEl(instance, vnode2.el); if (false) { popWarningContext(); } if (isInPendingSuspense && --suspense.deps === 0) { suspense.resolve(); } }); }, unmount(parentSuspense2, doRemove) { suspense.isUnmounted = true; if (suspense.activeBranch) { unmount( suspense.activeBranch, parentComponent, parentSuspense2, doRemove ); } if (suspense.pendingBranch) { unmount( suspense.pendingBranch, parentComponent, parentSuspense2, doRemove ); } } }; return suspense; } __name(createSuspenseBoundary, "createSuspenseBoundary"); function hydrateSuspense(node3, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) { const suspense = vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, node3.parentNode, // eslint-disable-next-line no-restricted-globals document.createElement("div"), null, namespace, slotScopeIds, optimized, rendererInternals, true ); const result = hydrateNode( node3, suspense.pendingBranch = vnode.ssContent, parentComponent, suspense, slotScopeIds, optimized ); if (suspense.deps === 0) { suspense.resolve(false, true); } return result; } __name(hydrateSuspense, "hydrateSuspense"); function normalizeSuspenseChildren(vnode) { const { shapeFlag, children } = vnode; const isSlotChildren = shapeFlag & 32; vnode.ssContent = normalizeSuspenseSlot( isSlotChildren ? children.default : children ); vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment); } __name(normalizeSuspenseChildren, "normalizeSuspenseChildren"); function normalizeSuspenseSlot(s2) { let block3; if (isFunction$8(s2)) { const trackBlock = isBlockTreeEnabled && s2._c; if (trackBlock) { s2._d = false; openBlock(); } s2 = s2(); if (trackBlock) { s2._d = true; block3 = currentBlock; closeBlock(); } } if (isArray$9(s2)) { const singleChild = filterSingleRoot(s2); if (false) { warn$1$1(` slots expect a single root node.`); } s2 = singleChild; } s2 = normalizeVNode(s2); if (block3 && !s2.dynamicChildren) { s2.dynamicChildren = block3.filter((c2) => c2 !== s2); } return s2; } __name(normalizeSuspenseSlot, "normalizeSuspenseSlot"); function queueEffectWithSuspense(fn, suspense) { if (suspense && suspense.pendingBranch) { if (isArray$9(fn)) { suspense.effects.push(...fn); } else { suspense.effects.push(fn); } } else { queuePostFlushCb(fn); } } __name(queueEffectWithSuspense, "queueEffectWithSuspense"); function setActiveBranch(suspense, branch) { suspense.activeBranch = branch; const { vnode, parentComponent } = suspense; let el = branch.el; while (!el && branch.component) { branch = branch.component.subTree; el = branch.el; } vnode.el = el; if (parentComponent && parentComponent.subTree === vnode) { parentComponent.vnode.el = el; updateHOCHostEl(parentComponent, el); } } __name(setActiveBranch, "setActiveBranch"); function isVNodeSuspensible(vnode) { const suspensible = vnode.props && vnode.props.suspensible; return suspensible != null && suspensible !== false; } __name(isVNodeSuspensible, "isVNodeSuspensible"); function injectHook(type, hook, target = currentInstance, prepend2 = false) { if (target) { const hooks2 = target[type] || (target[type] = []); const wrappedHook = hook.__weh || (hook.__weh = (...args) => { pauseTracking(); const reset2 = setCurrentInstance(target); const res = callWithAsyncErrorHandling(hook, target, type, args); reset2(); resetTracking(); return res; }); if (prepend2) { hooks2.unshift(wrappedHook); } else { hooks2.push(wrappedHook); } return wrappedHook; } else if (false) { const apiName = toHandlerKey(ErrorTypeStrings$1[type].replace(/ hook$/, "")); warn$1$1( `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` ); } } __name(injectHook, "injectHook"); const createHook = /* @__PURE__ */ __name((lifecycle2) => (hook, target = currentInstance) => { if (!isInSSRComponentSetup || lifecycle2 === "sp") { injectHook(lifecycle2, (...args) => hook(...args), target); } }, "createHook"); const onBeforeMount = createHook("bm"); const onMounted = createHook("m"); const onBeforeUpdate = createHook("bu"); const onUpdated = createHook("u"); const onBeforeUnmount = createHook("bum"); const onUnmounted = createHook("um"); const onServerPrefetch = createHook("sp"); const onRenderTriggered = createHook( "rtg" ); const onRenderTracked = createHook( "rtc" ); function onErrorCaptured(hook, target = currentInstance) { injectHook("ec", hook, target); } __name(onErrorCaptured, "onErrorCaptured"); function validateDirectiveName(name2) { if (isBuiltInDirective(name2)) { warn$1$1("Do not use built-in directive ids as custom directive id: " + name2); } } __name(validateDirectiveName, "validateDirectiveName"); function withDirectives(vnode, directives) { if (currentRenderingInstance === null) { return vnode; } const instance = getComponentPublicInstance(currentRenderingInstance); const bindings = vnode.dirs || (vnode.dirs = []); for (let i2 = 0; i2 < directives.length; i2++) { let [dir, value4, arg, modifiers2 = EMPTY_OBJ] = directives[i2]; if (dir) { if (isFunction$8(dir)) { dir = { mounted: dir, updated: dir }; } if (dir.deep) { traverse(value4); } bindings.push({ dir, instance, value: value4, oldValue: void 0, arg, modifiers: modifiers2 }); } } return vnode; } __name(withDirectives, "withDirectives"); function invokeDirectiveHook(vnode, prevVNode, instance, name2) { const bindings = vnode.dirs; const oldBindings = prevVNode && prevVNode.dirs; for (let i2 = 0; i2 < bindings.length; i2++) { const binding = bindings[i2]; if (oldBindings) { binding.oldValue = oldBindings[i2].value; } let hook = binding.dir[name2]; if (hook) { pauseTracking(); callWithAsyncErrorHandling(hook, instance, 8, [ vnode.el, binding, vnode, prevVNode ]); resetTracking(); } } } __name(invokeDirectiveHook, "invokeDirectiveHook"); function renderList(source, renderItem, cache2, index2) { let ret; const cached = cache2 && cache2[index2]; if (isArray$9(source) || isString$7(source)) { ret = new Array(source.length); for (let i2 = 0, l2 = source.length; i2 < l2; i2++) { ret[i2] = renderItem(source[i2], i2, void 0, cached && cached[i2]); } } else if (typeof source === "number") { if (false) { warn$1$1(`The v-for range expect an integer value but got ${source}.`); } ret = new Array(source); for (let i2 = 0; i2 < source; i2++) { ret[i2] = renderItem(i2 + 1, i2, void 0, cached && cached[i2]); } } else if (isObject$d(source)) { if (source[Symbol.iterator]) { ret = Array.from( source, (item3, i2) => renderItem(item3, i2, void 0, cached && cached[i2]) ); } else { const keys2 = Object.keys(source); ret = new Array(keys2.length); for (let i2 = 0, l2 = keys2.length; i2 < l2; i2++) { const key = keys2[i2]; ret[i2] = renderItem(source[key], key, i2, cached && cached[i2]); } } } else { ret = []; } if (cache2) { cache2[index2] = ret; } return ret; } __name(renderList, "renderList"); function createSlots(slots, dynamicSlots) { for (let i2 = 0; i2 < dynamicSlots.length; i2++) { const slot = dynamicSlots[i2]; if (isArray$9(slot)) { for (let j2 = 0; j2 < slot.length; j2++) { slots[slot[j2].name] = slot[j2].fn; } } else if (slot) { slots[slot.name] = slot.key ? (...args) => { const res = slot.fn(...args); if (res) res.key = slot.key; return res; } : slot.fn; } } return slots; } __name(createSlots, "createSlots"); /*! #__NO_SIDE_EFFECTS__ */ // @__NO_SIDE_EFFECTS__ function defineComponent(options4, extraOptions) { return isFunction$8(options4) ? ( // #8326: extend call and options.name access are considered side-effects // by Rollup, so we have to wrap it in a pure-annotated IIFE. /* @__PURE__ */ (() => extend$1({ name: options4.name }, extraOptions, { setup: options4 }))() ) : options4; } __name(defineComponent, "defineComponent"); const isAsyncWrapper = /* @__PURE__ */ __name((i2) => !!i2.type.__asyncLoader, "isAsyncWrapper"); /*! #__NO_SIDE_EFFECTS__ */ // @__NO_SIDE_EFFECTS__ function defineAsyncComponent(source) { if (isFunction$8(source)) { source = { loader: source }; } const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out suspensible = true, onError: userOnError } = source; let pendingRequest = null; let resolvedComp; let retries = 0; const retry = /* @__PURE__ */ __name(() => { retries++; pendingRequest = null; return load2(); }, "retry"); const load2 = /* @__PURE__ */ __name(() => { let thisRequest; return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { err = err instanceof Error ? err : new Error(String(err)); if (userOnError) { return new Promise((resolve2, reject3) => { const userRetry = /* @__PURE__ */ __name(() => resolve2(retry()), "userRetry"); const userFail = /* @__PURE__ */ __name(() => reject3(err), "userFail"); userOnError(err, userRetry, userFail, retries + 1); }); } else { throw err; } }).then((comp) => { if (thisRequest !== pendingRequest && pendingRequest) { return pendingRequest; } if (false) { warn$1$1( `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` ); } if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { comp = comp.default; } if (false) { throw new Error(`Invalid async component load result: ${comp}`); } resolvedComp = comp; return comp; })); }, "load"); return /* @__PURE__ */ defineComponent({ name: "AsyncComponentWrapper", __asyncLoader: load2, get __asyncResolved() { return resolvedComp; }, setup() { const instance = currentInstance; if (resolvedComp) { return () => createInnerComp(resolvedComp, instance); } const onError = /* @__PURE__ */ __name((err) => { pendingRequest = null; handleError( err, instance, 13, !errorComponent ); }, "onError"); if (suspensible && instance.suspense || isInSSRComponentSetup) { return load2().then((comp) => { return () => createInnerComp(comp, instance); }).catch((err) => { onError(err); return () => errorComponent ? createVNode(errorComponent, { error: err }) : null; }); } const loaded = ref(false); const error2 = ref(); const delayed = ref(!!delay); if (delay) { setTimeout(() => { delayed.value = false; }, delay); } if (timeout != null) { setTimeout(() => { if (!loaded.value && !error2.value) { const err = new Error( `Async component timed out after ${timeout}ms.` ); onError(err); error2.value = err; } }, timeout); } load2().then(() => { loaded.value = true; if (instance.parent && isKeepAlive(instance.parent.vnode)) { instance.parent.effect.dirty = true; queueJob(instance.parent.update); } }).catch((err) => { onError(err); error2.value = err; }); return () => { if (loaded.value && resolvedComp) { return createInnerComp(resolvedComp, instance); } else if (error2.value && errorComponent) { return createVNode(errorComponent, { error: error2.value }); } else if (loadingComponent && !delayed.value) { return createVNode(loadingComponent); } }; } }); } __name(defineAsyncComponent, "defineAsyncComponent"); function createInnerComp(comp, parent) { const { ref: ref22, props, children, ce } = parent.vnode; const vnode = createVNode(comp, props, children); vnode.ref = ref22; vnode.ce = ce; delete parent.vnode.ce; return vnode; } __name(createInnerComp, "createInnerComp"); function renderSlot(slots, name2, props = {}, fallback, noSlotted) { if (currentRenderingInstance.isCE || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.isCE) { if (name2 !== "default") props.name = name2; return createVNode("slot", props, fallback && fallback()); } let slot = slots[name2]; if (false) { warn$1$1( `SSR-optimized slot function detected in a non-SSR-optimized render function. You need to mark this component with $dynamic-slots in the parent template.` ); slot = /* @__PURE__ */ __name(() => [], "slot"); } if (slot && slot._c) { slot._d = false; } openBlock(); const validSlotContent = slot && ensureValidVNode(slot(props)); const rendered = createBlock( Fragment$1, { key: props.key || // slot content array of a dynamic conditional slot may have a branch // key attached in the `createSlots` helper, respect that validSlotContent && validSlotContent.key || `_${name2}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 ? 64 : -2 ); if (!noSlotted && rendered.scopeId) { rendered.slotScopeIds = [rendered.scopeId + "-s"]; } if (slot && slot._c) { slot._d = true; } return rendered; } __name(renderSlot, "renderSlot"); function ensureValidVNode(vnodes) { return vnodes.some((child) => { if (!isVNode$1(child)) return true; if (child.type === Comment) return false; if (child.type === Fragment$1 && !ensureValidVNode(child.children)) return false; return true; }) ? vnodes : null; } __name(ensureValidVNode, "ensureValidVNode"); function toHandlers(obj, preserveCaseIfNecessary) { const ret = {}; if (false) { warn$1$1(`v-on with no argument expects an object value.`); return ret; } for (const key in obj) { ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key]; } return ret; } __name(toHandlers, "toHandlers"); const getPublicInstance = /* @__PURE__ */ __name((i2) => { if (!i2) return null; if (isStatefulComponent(i2)) return getComponentPublicInstance(i2); return getPublicInstance(i2.parent); }, "getPublicInstance"); const publicPropertiesMap = ( // Move PURE marker to new line to workaround compiler discarding it // due to type annotation /* @__PURE__ */ extend$1(/* @__PURE__ */ Object.create(null), { $: /* @__PURE__ */ __name((i2) => i2, "$"), $el: /* @__PURE__ */ __name((i2) => i2.vnode.el, "$el"), $data: /* @__PURE__ */ __name((i2) => i2.data, "$data"), $props: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.props) : i2.props, "$props"), $attrs: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.attrs) : i2.attrs, "$attrs"), $slots: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.slots) : i2.slots, "$slots"), $refs: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.refs) : i2.refs, "$refs"), $parent: /* @__PURE__ */ __name((i2) => getPublicInstance(i2.parent), "$parent"), $root: /* @__PURE__ */ __name((i2) => getPublicInstance(i2.root), "$root"), $emit: /* @__PURE__ */ __name((i2) => i2.emit, "$emit"), $options: /* @__PURE__ */ __name((i2) => true ? resolveMergedOptions(i2) : i2.type, "$options"), $forceUpdate: /* @__PURE__ */ __name((i2) => i2.f || (i2.f = () => { i2.effect.dirty = true; queueJob(i2.update); }), "$forceUpdate"), $nextTick: /* @__PURE__ */ __name((i2) => i2.n || (i2.n = nextTick.bind(i2.proxy)), "$nextTick"), $watch: /* @__PURE__ */ __name((i2) => true ? instanceWatch.bind(i2) : NOOP, "$watch") }) ); const isReservedPrefix = /* @__PURE__ */ __name((key) => key === "_" || key === "$", "isReservedPrefix"); const hasSetupBinding = /* @__PURE__ */ __name((state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn$3(state, key), "hasSetupBinding"); const PublicInstanceProxyHandlers = { get({ _: instance }, key) { if (key === "__v_skip") { return true; } const { ctx, setupState, data: data25, props, accessCache, type, appContext } = instance; if (false) { return true; } let normalizedProps; if (key[0] !== "$") { const n2 = accessCache[key]; if (n2 !== void 0) { switch (n2) { case 1: return setupState[key]; case 2: return data25[key]; case 4: return ctx[key]; case 3: return props[key]; } } else if (hasSetupBinding(setupState, key)) { accessCache[key] = 1; return setupState[key]; } else if (data25 !== EMPTY_OBJ && hasOwn$3(data25, key)) { accessCache[key] = 2; return data25[key]; } else if ( // only cache other properties when instance has declared (thus stable) // props (normalizedProps = instance.propsOptions[0]) && hasOwn$3(normalizedProps, key) ) { accessCache[key] = 3; return props[key]; } else if (ctx !== EMPTY_OBJ && hasOwn$3(ctx, key)) { accessCache[key] = 4; return ctx[key]; } else if (shouldCacheAccess) { accessCache[key] = 0; } } const publicGetter = publicPropertiesMap[key]; let cssModule, globalProperties; if (publicGetter) { if (key === "$attrs") { track(instance.attrs, "get", ""); } else if (false) { track(instance, "get", key); } return publicGetter(instance); } else if ( // css module (injected by vue-loader) (cssModule = type.__cssModules) && (cssModule = cssModule[key]) ) { return cssModule; } else if (ctx !== EMPTY_OBJ && hasOwn$3(ctx, key)) { accessCache[key] = 4; return ctx[key]; } else if ( // global properties globalProperties = appContext.config.globalProperties, hasOwn$3(globalProperties, key) ) { { return globalProperties[key]; } } else if (false) { if (data25 !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn$3(data25, key)) { warn$1$1( `Property ${JSON.stringify( key )} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.` ); } else if (instance === currentRenderingInstance) { warn$1$1( `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.` ); } } }, set({ _: instance }, key, value4) { const { data: data25, setupState, ctx } = instance; if (hasSetupBinding(setupState, key)) { setupState[key] = value4; return true; } else if (false) { warn$1$1(`Cannot mutate