//#region \0rolldown/runtime.js (function() { try { var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}; e.SENTRY_RELEASE = { id: "dc25092aee8a66b8f0868046d641f9fd9dcc8ff0" }; e._sentryModuleMetadata = e._sentryModuleMetadata || {}, e._sentryModuleMetadata[new e.Error().stack] = function(e) { for (var n = 1; n < arguments.length; n++) { var a = arguments[n]; if (null != a) for (var t in a) a.hasOwnProperty(t) && (e[t] = a[t]); } return e; }({}, e._sentryModuleMetadata[new e.Error().stack], { "version": "2.0.5", "appHost": "management" }); var n = new e.Error().stack; n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "15f77f42-944e-4497-910a-72b4e5452226", e._sentryDebugIdIdentifier = "sentry-dbid-15f77f42-944e-4497-910a-72b4e5452226"); } catch (e) {} })(); var __create$2 = Object.create; var __defProp$3 = Object.defineProperty; var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor; var __getOwnPropNames$2 = Object.getOwnPropertyNames; var __getProtoOf$2 = Object.getPrototypeOf; var __hasOwnProp$3 = Object.prototype.hasOwnProperty; var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports); var __exportAll = (all, no_symbols) => { let target = {}; for (var name in all) __defProp$3(target, name, { get: all[name], enumerable: true }); if (!no_symbols) __defProp$3(target, Symbol.toStringTag, { value: "Module" }); return target; }; var __copyProps$2 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames$2(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp$3.call(to, key) && key !== except) __defProp$3(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc$2(from, key)) || desc.enumerable }); } return to; }; var __toESM$2 = (mod, isNodeMode, target) => (target = mod != null ? __create$2(__getProtoOf$2(mod)) : {}, __copyProps$2(isNodeMode || !mod || !mod.__esModule ? __defProp$3(target, "default", { value: mod, enumerable: true }) : target, mod)); var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details."); }); //#endregion //#region \0vite/modulepreload-polyfill.js (function polyfill() { const relList = document.createElement("link").relList; if (relList && relList.supports && relList.supports("modulepreload")) return; for (const link of document.querySelectorAll("link[rel=\"modulepreload\"]")) processPreload(link); new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type !== "childList") continue; for (const node of mutation.addedNodes) if (node.tagName === "LINK" && node.rel === "modulepreload") processPreload(node); } }).observe(document, { childList: true, subtree: true }); function getFetchOpts(link) { const fetchOpts = {}; if (link.integrity) fetchOpts.integrity = link.integrity; if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy; if (link.crossOrigin === "use-credentials") fetchOpts.credentials = "include"; else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit"; else fetchOpts.credentials = "same-origin"; return fetchOpts; } function processPreload(link) { if (link.ep) return; link.ep = true; const fetchOpts = getFetchOpts(link); fetch(link.href, fetchOpts); } })(); //#endregion //#region ../../node_modules/.pnpm/@vue+shared@3.5.33/node_modules/@vue/shared/dist/shared.esm-bundler.js /** * @vue/shared v3.5.33 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT **/ // @__NO_SIDE_EFFECTS__ function makeMap(str) { const map = /* @__PURE__ */ Object.create(null); for (const key of str.split(",")) map[key] = 1; return (val) => val in map; } var EMPTY_OBJ = {}; var EMPTY_ARR = []; var NOOP = () => {}; var NO = () => false; var isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); var isModelListener = (key) => key.startsWith("onUpdate:"); var extend = Object.assign; var remove = (arr, el) => { const i = arr.indexOf(el); if (i > -1) arr.splice(i, 1); }; var hasOwnProperty$1 = Object.prototype.hasOwnProperty; var hasOwn$1 = (val, key) => hasOwnProperty$1.call(val, key); var isArray = Array.isArray; var isMap = (val) => toTypeString(val) === "[object Map]"; var isSet = (val) => toTypeString(val) === "[object Set]"; var isDate = (val) => toTypeString(val) === "[object Date]"; var isFunction$2 = (val) => typeof val === "function"; var isString$1 = (val) => typeof val === "string"; var isSymbol = (val) => typeof val === "symbol"; var isObject$2 = (val) => val !== null && typeof val === "object"; var isPromise = (val) => { return (isObject$2(val) || isFunction$2(val)) && isFunction$2(val.then) && isFunction$2(val.catch); }; var objectToString$1 = Object.prototype.toString; var toTypeString = (value) => objectToString$1.call(value); var toRawType = (value) => { return toTypeString(value).slice(8, -1); }; var isPlainObject$4 = (val) => toTypeString(val) === "[object Object]"; var isIntegerKey = (key) => isString$1(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; var isReservedProp = /* @__PURE__ */ makeMap(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"); var cacheStringFunction$2 = (fn) => { const cache = /* @__PURE__ */ Object.create(null); return ((str) => { return cache[str] || (cache[str] = fn(str)); }); }; var camelizeRE$2 = /-\w/g; var camelize$2 = cacheStringFunction$2((str) => { return str.replace(camelizeRE$2, (c) => c.slice(1).toUpperCase()); }); var hyphenateRE$2 = /\B([A-Z])/g; var hyphenate$2 = cacheStringFunction$2((str) => str.replace(hyphenateRE$2, "-$1").toLowerCase()); var capitalize = cacheStringFunction$2((str) => { return str.charAt(0).toUpperCase() + str.slice(1); }); var toHandlerKey = cacheStringFunction$2((str) => { return str ? `on${capitalize(str)}` : ``; }); var hasChanged = (value, oldValue) => !Object.is(value, oldValue); var invokeArrayFns = (fns, ...arg) => { for (let i = 0; i < fns.length; i++) fns[i](...arg); }; var def = (obj, key, value, writable = false) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, writable, value }); }; var looseToNumber = (val) => { const n = parseFloat(val); return isNaN(n) ? val : n; }; var _globalThis; var getGlobalThis = () => { return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); }; function normalizeStyle(value) { if (isArray(value)) { const res = {}; for (let i = 0; i < value.length; i++) { const item = value[i]; const normalized = isString$1(item) ? parseStringStyle(item) : normalizeStyle(item); if (normalized) for (const key in normalized) res[key] = normalized[key]; } return res; } else if (isString$1(value) || isObject$2(value)) return value; } var listDelimiterRE = /;(?![^(]*\))/g; var propertyDelimiterRE = /:([^]+)/; var styleCommentRE = /\/\*[^]*?\*\//g; function parseStringStyle(cssText) { const ret = {}; cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => { if (item) { const tmp = item.split(propertyDelimiterRE); tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); } }); return ret; } function normalizeClass(value) { let res = ""; if (isString$1(value)) res = value; else if (isArray(value)) for (let i = 0; i < value.length; i++) { const normalized = normalizeClass(value[i]); if (normalized) res += normalized + " "; } else if (isObject$2(value)) { for (const name in value) if (value[name]) res += name + " "; } return res.trim(); } function normalizeProps(props) { if (!props) return null; let { class: klass, style } = props; if (klass && !isString$1(klass)) props.class = normalizeClass(klass); if (style) props.style = normalizeStyle(style); return props; } var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); specialBooleanAttrs + ""; function includeBooleanAttr(value) { return !!value || value === ""; } function looseCompareArrays(a, b) { if (a.length !== b.length) return false; let equal = true; for (let i = 0; equal && i < a.length; i++) equal = looseEqual(a[i], b[i]); return equal; } function looseEqual(a, b) { if (a === b) return true; let aValidType = isDate(a); let bValidType = isDate(b); if (aValidType || bValidType) return aValidType && bValidType ? a.getTime() === b.getTime() : false; aValidType = isSymbol(a); bValidType = isSymbol(b); if (aValidType || bValidType) return a === b; aValidType = isArray(a); bValidType = isArray(b); if (aValidType || bValidType) return aValidType && bValidType ? looseCompareArrays(a, b) : false; aValidType = isObject$2(a); bValidType = isObject$2(b); if (aValidType || bValidType) { if (!aValidType || !bValidType) return false; if (Object.keys(a).length !== Object.keys(b).length) return false; for (const key in a) { const aHasKey = a.hasOwnProperty(key); const bHasKey = b.hasOwnProperty(key); if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) return false; } } return String(a) === String(b); } var isRef$1 = (val) => { return !!(val && val["__v_isRef"] === true); }; var toDisplayString = (val) => { return isString$1(val) ? val : val == null ? "" : isArray(val) || isObject$2(val) && (val.toString === objectToString$1 || !isFunction$2(val.toString)) ? isRef$1(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val); }; var replacer = (_key, val) => { if (isRef$1(val)) return replacer(_key, val.value); else if (isMap(val)) return { [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2], i) => { entries[stringifySymbol(key, i) + " =>"] = val2; return entries; }, {}) }; else if (isSet(val)) return { [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)) }; else if (isSymbol(val)) return stringifySymbol(val); else if (isObject$2(val) && !isArray(val) && !isPlainObject$4(val)) return String(val); return val; }; var stringifySymbol = (v, i = "") => { var _a; return isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v; }; //#endregion //#region ../../node_modules/.pnpm/@vue+reactivity@3.5.33/node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js /** * @vue/reactivity v3.5.33 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT **/ var activeEffectScope; var EffectScope = class { constructor(detached = false) { this.detached = detached; /** * @internal */ this._active = true; /** * @internal track `on` calls, allow `on` call multiple times */ this._on = 0; /** * @internal */ this.effects = []; /** * @internal */ this.cleanups = []; this._isPaused = false; this.__v_skip = true; this.parent = activeEffectScope; if (!detached && activeEffectScope) this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1; } get active() { return this._active; } pause() { if (this._active) { this._isPaused = true; let i, l; if (this.scopes) for (i = 0, l = this.scopes.length; i < l; i++) this.scopes[i].pause(); for (i = 0, l = this.effects.length; i < l; i++) this.effects[i].pause(); } } /** * Resumes the effect scope, including all child scopes and effects. */ resume() { if (this._active) { if (this._isPaused) { this._isPaused = false; let i, l; if (this.scopes) for (i = 0, l = this.scopes.length; i < l; i++) this.scopes[i].resume(); for (i = 0, l = this.effects.length; i < l; i++) this.effects[i].resume(); } } } run(fn) { if (this._active) { const currentEffectScope = activeEffectScope; try { activeEffectScope = this; return fn(); } finally { activeEffectScope = currentEffectScope; } } } /** * This should only be called on non-detached scopes * @internal */ on() { if (++this._on === 1) { this.prevScope = activeEffectScope; activeEffectScope = this; } } /** * This should only be called on non-detached scopes * @internal */ off() { if (this._on > 0 && --this._on === 0) { if (activeEffectScope === this) activeEffectScope = this.prevScope; else { let current = activeEffectScope; while (current) { if (current.prevScope === this) { current.prevScope = this.prevScope; break; } current = current.prevScope; } } this.prevScope = void 0; } } stop(fromParent) { if (this._active) { this._active = false; let i, l; for (i = 0, l = this.effects.length; i < l; i++) this.effects[i].stop(); this.effects.length = 0; for (i = 0, l = this.cleanups.length; i < l; i++) this.cleanups[i](); this.cleanups.length = 0; if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) this.scopes[i].stop(true); this.scopes.length = 0; } 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; } } }; function effectScope(detached) { return new EffectScope(detached); } function getCurrentScope$1() { return activeEffectScope; } function onScopeDispose(fn, failSilently = false) { if (activeEffectScope) activeEffectScope.cleanups.push(fn); } var activeSub; var pausedQueueEffects = /* @__PURE__ */ new WeakSet(); var ReactiveEffect = class { constructor(fn) { this.fn = fn; /** * @internal */ this.deps = void 0; /** * @internal */ this.depsTail = void 0; /** * @internal */ this.flags = 5; /** * @internal */ this.next = void 0; /** * @internal */ this.cleanup = void 0; this.scheduler = void 0; if (activeEffectScope && activeEffectScope.active) activeEffectScope.effects.push(this); } pause() { this.flags |= 64; } resume() { if (this.flags & 64) { this.flags &= -65; if (pausedQueueEffects.has(this)) { pausedQueueEffects.delete(this); this.trigger(); } } } /** * @internal */ notify() { if (this.flags & 2 && !(this.flags & 32)) return; if (!(this.flags & 8)) batch(this); } run() { if (!(this.flags & 1)) return this.fn(); this.flags |= 2; cleanupEffect(this); prepareDeps(this); const prevEffect = activeSub; const prevShouldTrack = shouldTrack; activeSub = this; shouldTrack = true; try { return this.fn(); } finally { cleanupDeps(this); activeSub = prevEffect; shouldTrack = prevShouldTrack; this.flags &= -3; } } stop() { if (this.flags & 1) { for (let link = this.deps; link; link = link.nextDep) removeSub(link); this.deps = this.depsTail = void 0; cleanupEffect(this); this.onStop && this.onStop(); this.flags &= -2; } } trigger() { if (this.flags & 64) pausedQueueEffects.add(this); else if (this.scheduler) this.scheduler(); else this.runIfDirty(); } /** * @internal */ runIfDirty() { if (isDirty(this)) this.run(); } get dirty() { return isDirty(this); } }; var batchDepth = 0; var batchedSub; var batchedComputed; function batch(sub, isComputed = false) { sub.flags |= 8; if (isComputed) { sub.next = batchedComputed; batchedComputed = sub; return; } sub.next = batchedSub; batchedSub = sub; } function startBatch() { batchDepth++; } function endBatch() { if (--batchDepth > 0) return; if (batchedComputed) { let e = batchedComputed; batchedComputed = void 0; while (e) { const next = e.next; e.next = void 0; e.flags &= -9; e = next; } } let error; while (batchedSub) { let e = batchedSub; batchedSub = void 0; while (e) { const next = e.next; e.next = void 0; e.flags &= -9; if (e.flags & 1) try { e.trigger(); } catch (err) { if (!error) error = err; } e = next; } } if (error) throw error; } function prepareDeps(sub) { for (let link = sub.deps; link; link = link.nextDep) { link.version = -1; link.prevActiveLink = link.dep.activeLink; link.dep.activeLink = link; } } function cleanupDeps(sub) { let head; let tail = sub.depsTail; let link = tail; while (link) { const prev = link.prevDep; if (link.version === -1) { if (link === tail) tail = prev; removeSub(link); removeDep(link); } else head = link; link.dep.activeLink = link.prevActiveLink; link.prevActiveLink = void 0; link = prev; } sub.deps = head; sub.depsTail = tail; } function isDirty(sub) { for (let link = sub.deps; link; link = link.nextDep) if (link.dep.version !== link.version || link.dep.computed && (refreshComputed(link.dep.computed) || link.dep.version !== link.version)) return true; if (sub._dirty) return true; return false; } function refreshComputed(computed) { if (computed.flags & 4 && !(computed.flags & 16)) return; computed.flags &= -17; if (computed.globalVersion === globalVersion) return; computed.globalVersion = globalVersion; if (!computed.isSSR && computed.flags & 128 && (!computed.deps && !computed._dirty || !isDirty(computed))) return; computed.flags |= 2; const dep = computed.dep; const prevSub = activeSub; const prevShouldTrack = shouldTrack; activeSub = computed; shouldTrack = true; try { prepareDeps(computed); const value = computed.fn(computed._value); if (dep.version === 0 || hasChanged(value, computed._value)) { computed.flags |= 128; computed._value = value; dep.version++; } } catch (err) { dep.version++; throw err; } finally { activeSub = prevSub; shouldTrack = prevShouldTrack; cleanupDeps(computed); computed.flags &= -3; } } function removeSub(link, soft = false) { const { dep, prevSub, nextSub } = link; if (prevSub) { prevSub.nextSub = nextSub; link.prevSub = void 0; } if (nextSub) { nextSub.prevSub = prevSub; link.nextSub = void 0; } if (dep.subs === link) { dep.subs = prevSub; if (!prevSub && dep.computed) { dep.computed.flags &= -5; for (let l = dep.computed.deps; l; l = l.nextDep) removeSub(l, true); } } if (!soft && !--dep.sc && dep.map) dep.map.delete(dep.key); } function removeDep(link) { const { prevDep, nextDep } = link; if (prevDep) { prevDep.nextDep = nextDep; link.prevDep = void 0; } if (nextDep) { nextDep.prevDep = prevDep; link.nextDep = void 0; } } var shouldTrack = true; var trackStack = []; function pauseTracking() { trackStack.push(shouldTrack); shouldTrack = false; } function resetTracking() { const last = trackStack.pop(); shouldTrack = last === void 0 ? true : last; } function cleanupEffect(e) { const { cleanup } = e; e.cleanup = void 0; if (cleanup) { const prevSub = activeSub; activeSub = void 0; try { cleanup(); } finally { activeSub = prevSub; } } } var globalVersion = 0; var Link = class { constructor(sub, dep) { this.sub = sub; this.dep = dep; this.version = dep.version; this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0; } }; var Dep = class { constructor(computed) { this.computed = computed; this.version = 0; /** * Link between this dep and the current active effect */ this.activeLink = void 0; /** * Doubly linked list representing the subscribing effects (tail) */ this.subs = void 0; /** * For object property deps cleanup */ this.map = void 0; this.key = void 0; /** * Subscriber counter */ this.sc = 0; /** * @internal */ this.__v_skip = true; } track(debugInfo) { if (!activeSub || !shouldTrack || activeSub === this.computed) return; let link = this.activeLink; if (link === void 0 || link.sub !== activeSub) { link = this.activeLink = new Link(activeSub, this); if (!activeSub.deps) activeSub.deps = activeSub.depsTail = link; else { link.prevDep = activeSub.depsTail; activeSub.depsTail.nextDep = link; activeSub.depsTail = link; } addSub(link); } else if (link.version === -1) { link.version = this.version; if (link.nextDep) { const next = link.nextDep; next.prevDep = link.prevDep; if (link.prevDep) link.prevDep.nextDep = next; link.prevDep = activeSub.depsTail; link.nextDep = void 0; activeSub.depsTail.nextDep = link; activeSub.depsTail = link; if (activeSub.deps === link) activeSub.deps = next; } } return link; } trigger(debugInfo) { this.version++; globalVersion++; this.notify(debugInfo); } notify(debugInfo) { startBatch(); try { for (let link = this.subs; link; link = link.prevSub) if (link.sub.notify()) link.sub.dep.notify(); } finally { endBatch(); } } }; function addSub(link) { link.dep.sc++; if (link.sub.flags & 4) { const computed = link.dep.computed; if (computed && !link.dep.subs) { computed.flags |= 20; for (let l = computed.deps; l; l = l.nextDep) addSub(l); } const currentTail = link.dep.subs; if (currentTail !== link) { link.prevSub = currentTail; if (currentTail) currentTail.nextSub = link; } link.dep.subs = link; } } var targetMap = /* @__PURE__ */ new WeakMap(); var ITERATE_KEY = /* @__PURE__ */ Symbol(""); var MAP_KEY_ITERATE_KEY = /* @__PURE__ */ Symbol(""); var ARRAY_ITERATE_KEY = /* @__PURE__ */ Symbol(""); function track(target, type, key) { if (shouldTrack && activeSub) { 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 = new Dep()); dep.map = depsMap; dep.key = key; } dep.track(); } } function trigger(target, type, key, newValue, oldValue, oldTarget) { const depsMap = targetMap.get(target); if (!depsMap) { globalVersion++; return; } const run = (dep) => { if (dep) dep.trigger(); }; startBatch(); if (type === "clear") depsMap.forEach(run); else { const targetIsArray = isArray(target); const isArrayIndex = targetIsArray && isIntegerKey(key); if (targetIsArray && key === "length") { const newLength = Number(newValue); depsMap.forEach((dep, key2) => { if (key2 === "length" || key2 === ARRAY_ITERATE_KEY || !isSymbol(key2) && key2 >= newLength) run(dep); }); } else { if (key !== void 0 || depsMap.has(void 0)) run(depsMap.get(key)); if (isArrayIndex) run(depsMap.get(ARRAY_ITERATE_KEY)); switch (type) { case "add": if (!targetIsArray) { run(depsMap.get(ITERATE_KEY)); if (isMap(target)) run(depsMap.get(MAP_KEY_ITERATE_KEY)); } else if (isArrayIndex) run(depsMap.get("length")); break; case "delete": if (!targetIsArray) { run(depsMap.get(ITERATE_KEY)); if (isMap(target)) run(depsMap.get(MAP_KEY_ITERATE_KEY)); } break; case "set": if (isMap(target)) run(depsMap.get(ITERATE_KEY)); break; } } } endBatch(); } function getDepFromReactive(object, key) { const depMap = targetMap.get(object); return depMap && depMap.get(key); } function reactiveReadArray(array) { const raw = /* @__PURE__ */ toRaw(array); if (raw === array) return raw; track(raw, "iterate", ARRAY_ITERATE_KEY); return /* @__PURE__ */ isShallow(array) ? raw : raw.map(toReactive); } function shallowReadArray(arr) { track(arr = /* @__PURE__ */ toRaw(arr), "iterate", ARRAY_ITERATE_KEY); return arr; } function toWrapped(target, item) { if (/* @__PURE__ */ isReadonly(target)) return /* @__PURE__ */ isReactive(target) ? toReadonly(toReactive(item)) : toReadonly(item); return toReactive(item); } var arrayInstrumentations = { __proto__: null, [Symbol.iterator]() { return iterator(this, Symbol.iterator, (item) => toWrapped(this, item)); }, concat(...args) { return reactiveReadArray(this).concat(...args.map((x) => isArray(x) ? reactiveReadArray(x) : x)); }, entries() { return iterator(this, "entries", (value) => { value[1] = toWrapped(this, value[1]); return value; }); }, every(fn, thisArg) { return apply(this, "every", fn, thisArg, void 0, arguments); }, filter(fn, thisArg) { return apply(this, "filter", fn, thisArg, (v) => v.map((item) => toWrapped(this, item)), arguments); }, find(fn, thisArg) { return apply(this, "find", fn, thisArg, (item) => toWrapped(this, item), arguments); }, findIndex(fn, thisArg) { return apply(this, "findIndex", fn, thisArg, void 0, arguments); }, findLast(fn, thisArg) { return apply(this, "findLast", fn, thisArg, (item) => toWrapped(this, item), arguments); }, findLastIndex(fn, thisArg) { return apply(this, "findLastIndex", fn, thisArg, void 0, arguments); }, forEach(fn, thisArg) { return apply(this, "forEach", fn, thisArg, void 0, arguments); }, includes(...args) { return searchProxy(this, "includes", args); }, indexOf(...args) { return searchProxy(this, "indexOf", args); }, join(separator) { return reactiveReadArray(this).join(separator); }, lastIndexOf(...args) { return searchProxy(this, "lastIndexOf", args); }, map(fn, thisArg) { return apply(this, "map", fn, thisArg, void 0, arguments); }, pop() { return noTracking(this, "pop"); }, push(...args) { return noTracking(this, "push", args); }, reduce(fn, ...args) { return reduce(this, "reduce", fn, args); }, reduceRight(fn, ...args) { return reduce(this, "reduceRight", fn, args); }, shift() { return noTracking(this, "shift"); }, some(fn, thisArg) { return apply(this, "some", fn, thisArg, void 0, arguments); }, splice(...args) { return noTracking(this, "splice", args); }, toReversed() { return reactiveReadArray(this).toReversed(); }, toSorted(comparer) { return reactiveReadArray(this).toSorted(comparer); }, toSpliced(...args) { return reactiveReadArray(this).toSpliced(...args); }, unshift(...args) { return noTracking(this, "unshift", args); }, values() { return iterator(this, "values", (item) => toWrapped(this, item)); } }; function iterator(self, method, wrapValue) { const arr = shallowReadArray(self); const iter = arr[method](); if (arr !== self && !/* @__PURE__ */ isShallow(self)) { iter._next = iter.next; iter.next = () => { const result = iter._next(); if (!result.done) result.value = wrapValue(result.value); return result; }; } return iter; } var arrayProto = Array.prototype; function apply(self, method, fn, thisArg, wrappedRetFn, args) { const arr = shallowReadArray(self); const needsWrap = arr !== self && !/* @__PURE__ */ isShallow(self); const methodFn = arr[method]; if (methodFn !== arrayProto[method]) { const result2 = methodFn.apply(self, args); return needsWrap ? toReactive(result2) : result2; } let wrappedFn = fn; if (arr !== self) { if (needsWrap) wrappedFn = function(item, index) { return fn.call(this, toWrapped(self, item), index, self); }; else if (fn.length > 2) wrappedFn = function(item, index) { return fn.call(this, item, index, self); }; } const result = methodFn.call(arr, wrappedFn, thisArg); return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result; } function reduce(self, method, fn, args) { const arr = shallowReadArray(self); const needsWrap = arr !== self && !/* @__PURE__ */ isShallow(self); let wrappedFn = fn; let wrapInitialAccumulator = false; if (arr !== self) { if (needsWrap) { wrapInitialAccumulator = args.length === 0; wrappedFn = function(acc, item, index) { if (wrapInitialAccumulator) { wrapInitialAccumulator = false; acc = toWrapped(self, acc); } return fn.call(this, acc, toWrapped(self, item), index, self); }; } else if (fn.length > 3) wrappedFn = function(acc, item, index) { return fn.call(this, acc, item, index, self); }; } const result = arr[method](wrappedFn, ...args); return wrapInitialAccumulator ? toWrapped(self, result) : result; } function searchProxy(self, method, args) { const arr = /* @__PURE__ */ toRaw(self); track(arr, "iterate", ARRAY_ITERATE_KEY); const res = arr[method](...args); if ((res === -1 || res === false) && /* @__PURE__ */ isProxy(args[0])) { args[0] = /* @__PURE__ */ toRaw(args[0]); return arr[method](...args); } return res; } function noTracking(self, method, args = []) { pauseTracking(); startBatch(); const res = (/* @__PURE__ */ toRaw(self))[method].apply(self, args); endBatch(); resetTracking(); return res; } var isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`); var builtInSymbols = new Set(/* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol)); function hasOwnProperty(key) { if (!isSymbol(key)) key = String(key); const obj = /* @__PURE__ */ toRaw(this); track(obj, "has", key); return obj.hasOwnProperty(key); } var BaseReactiveHandler = class { constructor(_isReadonly = false, _isShallow = false) { this._isReadonly = _isReadonly; this._isShallow = _isShallow; } get(target, key, receiver) { if (key === "__v_skip") return target["__v_skip"]; 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) || Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) return target; return; } const targetIsArray = isArray(target); if (!isReadonly2) { let fn; if (targetIsArray && (fn = arrayInstrumentations[key])) return fn; if (key === "hasOwnProperty") return hasOwnProperty; } const res = Reflect.get(target, key, /* @__PURE__ */ isRef(target) ? target : receiver); if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) return res; if (!isReadonly2) track(target, "get", key); if (isShallow2) return res; if (/* @__PURE__ */ isRef(res)) { const value = targetIsArray && isIntegerKey(key) ? res : res.value; return isReadonly2 && isObject$2(value) ? /* @__PURE__ */ readonly(value) : value; } if (isObject$2(res)) return isReadonly2 ? /* @__PURE__ */ readonly(res) : /* @__PURE__ */ reactive(res); return res; } }; var MutableReactiveHandler = class extends BaseReactiveHandler { constructor(isShallow2 = false) { super(false, isShallow2); } set(target, key, value, receiver) { let oldValue = target[key]; const isArrayWithIntegerKey = isArray(target) && isIntegerKey(key); if (!this._isShallow) { const isOldValueReadonly = /* @__PURE__ */ isReadonly(oldValue); if (!/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) { oldValue = /* @__PURE__ */ toRaw(oldValue); value = /* @__PURE__ */ toRaw(value); } if (!isArrayWithIntegerKey && /* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) if (isOldValueReadonly) return true; else { oldValue.value = value; return true; } } const hadKey = isArrayWithIntegerKey ? Number(key) < target.length : hasOwn$1(target, key); const result = Reflect.set(target, key, value, /* @__PURE__ */ isRef(target) ? target : receiver); if (target === /* @__PURE__ */ toRaw(receiver)) { if (!hadKey) trigger(target, "add", key, value); else if (hasChanged(value, oldValue)) trigger(target, "set", key, value, oldValue); } return result; } deleteProperty(target, key) { const hadKey = hasOwn$1(target, key); const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) trigger(target, "delete", key, void 0, oldValue); return result; } has(target, key) { const result = Reflect.has(target, key); if (!isSymbol(key) || !builtInSymbols.has(key)) track(target, "has", key); return result; } ownKeys(target) { track(target, "iterate", isArray(target) ? "length" : ITERATE_KEY); return Reflect.ownKeys(target); } }; var ReadonlyReactiveHandler = class extends BaseReactiveHandler { constructor(isShallow2 = false) { super(true, isShallow2); } set(target, key) { return true; } deleteProperty(target, key) { return true; } }; var mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler(); var readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(); var shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(true); var shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true); var toShallow = (value) => value; var getProto = (v) => Reflect.getPrototypeOf(v); function createIterableMethod(method, isReadonly2, isShallow2) { return function(...args) { const target = this["__v_raw"]; const rawTarget = /* @__PURE__ */ toRaw(target); const targetIsMap = isMap(rawTarget); const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; const isKeyOnly = method === "keys" && targetIsMap; const innerIterator = target[method](...args); const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; !isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY); return extend(Object.create(innerIterator), { next() { const { value, done } = innerIterator.next(); return done ? { value, done } : { value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), done }; } }); }; } function createReadonlyMethod(type) { return function(...args) { return type === "delete" ? false : type === "clear" ? void 0 : this; }; } function createInstrumentations(readonly, shallow) { const instrumentations = { get(key) { const target = this["__v_raw"]; const rawTarget = /* @__PURE__ */ toRaw(target); const rawKey = /* @__PURE__ */ toRaw(key); if (!readonly) { if (hasChanged(key, rawKey)) track(rawTarget, "get", key); track(rawTarget, "get", rawKey); } const { has } = getProto(rawTarget); const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive; if (has.call(rawTarget, key)) return wrap(target.get(key)); else if (has.call(rawTarget, rawKey)) return wrap(target.get(rawKey)); else if (target !== rawTarget) target.get(key); }, get size() { const target = this["__v_raw"]; !readonly && track(/* @__PURE__ */ toRaw(target), "iterate", ITERATE_KEY); return target.size; }, has(key) { const target = this["__v_raw"]; const rawTarget = /* @__PURE__ */ toRaw(target); const rawKey = /* @__PURE__ */ toRaw(key); if (!readonly) { if (hasChanged(key, rawKey)) track(rawTarget, "has", key); track(rawTarget, "has", rawKey); } return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); }, forEach(callback, thisArg) { const observed = this; const target = observed["__v_raw"]; const rawTarget = /* @__PURE__ */ toRaw(target); const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive; !readonly && track(rawTarget, "iterate", ITERATE_KEY); return target.forEach((value, key) => { return callback.call(thisArg, wrap(value), wrap(key), observed); }); } }; extend(instrumentations, readonly ? { add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear") } : { add(value) { const target = /* @__PURE__ */ toRaw(this); const proto = getProto(target); const rawValue = /* @__PURE__ */ toRaw(value); const valueToAdd = !shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value) ? rawValue : value; if (!(proto.has.call(target, valueToAdd) || hasChanged(value, valueToAdd) && proto.has.call(target, value) || hasChanged(rawValue, valueToAdd) && proto.has.call(target, rawValue))) { target.add(valueToAdd); trigger(target, "add", valueToAdd, valueToAdd); } return this; }, set(key, value) { if (!shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) value = /* @__PURE__ */ toRaw(value); const target = /* @__PURE__ */ toRaw(this); const { has, get } = getProto(target); let hadKey = has.call(target, key); if (!hadKey) { key = /* @__PURE__ */ toRaw(key); hadKey = has.call(target, key); } const oldValue = get.call(target, key); target.set(key, value); if (!hadKey) trigger(target, "add", key, value); else if (hasChanged(value, oldValue)) trigger(target, "set", key, value, oldValue); return this; }, delete(key) { const target = /* @__PURE__ */ toRaw(this); const { has, get } = getProto(target); let hadKey = has.call(target, key); if (!hadKey) { key = /* @__PURE__ */ toRaw(key); hadKey = has.call(target, key); } const oldValue = get ? get.call(target, key) : void 0; const result = target.delete(key); if (hadKey) trigger(target, "delete", key, void 0, oldValue); return result; }, clear() { const target = /* @__PURE__ */ toRaw(this); const hadItems = target.size !== 0; const oldTarget = void 0; const result = target.clear(); if (hadItems) trigger(target, "clear", void 0, void 0, oldTarget); return result; } }); [ "keys", "values", "entries", Symbol.iterator ].forEach((method) => { instrumentations[method] = createIterableMethod(method, readonly, shallow); }); return instrumentations; } function createInstrumentationGetter(isReadonly2, shallow) { const instrumentations = createInstrumentations(isReadonly2, shallow); 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$1(instrumentations, key) && key in target ? instrumentations : target, key, receiver); }; } var mutableCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(false, false) }; var shallowCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(false, true) }; var readonlyCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(true, false) }; var shallowReadonlyCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(true, true) }; var reactiveMap = /* @__PURE__ */ new WeakMap(); var shallowReactiveMap = /* @__PURE__ */ new WeakMap(); var readonlyMap = /* @__PURE__ */ new WeakMap(); var 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; } } function getTargetType(value) { return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(toRawType(value)); } // @__NO_SIDE_EFFECTS__ function reactive(target) { if (/* @__PURE__ */ isReadonly(target)) return target; return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); } // @__NO_SIDE_EFFECTS__ function shallowReactive(target) { return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap); } // @__NO_SIDE_EFFECTS__ function readonly(target) { return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); } // @__NO_SIDE_EFFECTS__ function shallowReadonly(target) { return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); } function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { if (!isObject$2(target)) return target; if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) return target; const targetType = getTargetType(target); if (targetType === 0) return target; const existingProxy = proxyMap.get(target); if (existingProxy) return existingProxy; const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers); proxyMap.set(target, proxy); return proxy; } // @__NO_SIDE_EFFECTS__ function isReactive(value) { if (/* @__PURE__ */ isReadonly(value)) return /* @__PURE__ */ isReactive(value["__v_raw"]); return !!(value && value["__v_isReactive"]); } // @__NO_SIDE_EFFECTS__ function isReadonly(value) { return !!(value && value["__v_isReadonly"]); } // @__NO_SIDE_EFFECTS__ function isShallow(value) { return !!(value && value["__v_isShallow"]); } // @__NO_SIDE_EFFECTS__ function isProxy(value) { return value ? !!value["__v_raw"] : false; } // @__NO_SIDE_EFFECTS__ function toRaw(observed) { const raw = observed && observed["__v_raw"]; return raw ? /* @__PURE__ */ toRaw(raw) : observed; } function markRaw(value) { if (!hasOwn$1(value, "__v_skip") && Object.isExtensible(value)) def(value, "__v_skip", true); return value; } var toReactive = (value) => isObject$2(value) ? /* @__PURE__ */ reactive(value) : value; var toReadonly = (value) => isObject$2(value) ? /* @__PURE__ */ readonly(value) : value; // @__NO_SIDE_EFFECTS__ function isRef(r) { return r ? r["__v_isRef"] === true : false; } // @__NO_SIDE_EFFECTS__ function ref(value) { return createRef(value, false); } function createRef(rawValue, shallow) { if (/* @__PURE__ */ isRef(rawValue)) return rawValue; return new RefImpl(rawValue, shallow); } var RefImpl = class { constructor(value, isShallow2) { this.dep = new Dep(); this["__v_isRef"] = true; this["__v_isShallow"] = false; this._rawValue = isShallow2 ? value : /* @__PURE__ */ toRaw(value); this._value = isShallow2 ? value : toReactive(value); this["__v_isShallow"] = isShallow2; } get value() { this.dep.track(); return this._value; } set value(newValue) { const oldValue = this._rawValue; const useDirectValue = this["__v_isShallow"] || /* @__PURE__ */ isShallow(newValue) || /* @__PURE__ */ isReadonly(newValue); newValue = useDirectValue ? newValue : /* @__PURE__ */ toRaw(newValue); if (hasChanged(newValue, oldValue)) { this._rawValue = newValue; this._value = useDirectValue ? newValue : toReactive(newValue); this.dep.trigger(); } } }; function unref(ref2) { return /* @__PURE__ */ isRef(ref2) ? ref2.value : ref2; } var shallowUnwrapHandlers = { get: (target, key, receiver) => key === "__v_raw" ? target : unref(Reflect.get(target, key, receiver)), set: (target, key, value, receiver) => { const oldValue = target[key]; if (/* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) { oldValue.value = value; return true; } else return Reflect.set(target, key, value, receiver); } }; function proxyRefs(objectWithRefs) { return /* @__PURE__ */ isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); } // @__NO_SIDE_EFFECTS__ function toRefs(object) { const ret = isArray(object) ? new Array(object.length) : {}; for (const key in object) ret[key] = propertyToRef(object, key); return ret; } var ObjectRefImpl = class { constructor(_object, key, _defaultValue) { this._object = _object; this._defaultValue = _defaultValue; this["__v_isRef"] = true; this._value = void 0; this._key = isSymbol(key) ? key : String(key); this._raw = /* @__PURE__ */ toRaw(_object); let shallow = true; let obj = _object; if (!isArray(_object) || isSymbol(this._key) || !isIntegerKey(this._key)) do shallow = !/* @__PURE__ */ isProxy(obj) || /* @__PURE__ */ isShallow(obj); while (shallow && (obj = obj["__v_raw"])); this._shallow = shallow; } get value() { let val = this._object[this._key]; if (this._shallow) val = unref(val); return this._value = val === void 0 ? this._defaultValue : val; } set value(newVal) { if (this._shallow && /* @__PURE__ */ isRef(this._raw[this._key])) { const nestedRef = this._object[this._key]; if (/* @__PURE__ */ isRef(nestedRef)) { nestedRef.value = newVal; return; } } this._object[this._key] = newVal; } get dep() { return getDepFromReactive(this._raw, this._key); } }; var GetterRefImpl = class { constructor(_getter) { this._getter = _getter; this["__v_isRef"] = true; this["__v_isReadonly"] = true; this._value = void 0; } get value() { return this._value = this._getter(); } }; // @__NO_SIDE_EFFECTS__ function toRef(source, key, defaultValue) { if (/* @__PURE__ */ isRef(source)) return source; else if (isFunction$2(source)) return new GetterRefImpl(source); else if (isObject$2(source) && arguments.length > 1) return propertyToRef(source, key, defaultValue); else return /* @__PURE__ */ ref(source); } function propertyToRef(source, key, defaultValue) { return new ObjectRefImpl(source, key, defaultValue); } var ComputedRefImpl = class { constructor(fn, setter, isSSR) { this.fn = fn; this.setter = setter; /** * @internal */ this._value = void 0; /** * @internal */ this.dep = new Dep(this); /** * @internal */ this.__v_isRef = true; /** * @internal */ this.deps = void 0; /** * @internal */ this.depsTail = void 0; /** * @internal */ this.flags = 16; /** * @internal */ this.globalVersion = globalVersion - 1; /** * @internal */ this.next = void 0; this.effect = this; this["__v_isReadonly"] = !setter; this.isSSR = isSSR; } /** * @internal */ notify() { this.flags |= 16; if (!(this.flags & 8) && activeSub !== this) { batch(this, true); return true; } } get value() { const link = this.dep.track(); refreshComputed(this); if (link) link.version = this.dep.version; return this._value; } set value(newValue) { if (this.setter) this.setter(newValue); } }; // @__NO_SIDE_EFFECTS__ function computed$1(getterOrOptions, debugOptions, isSSR = false) { let getter; let setter; if (isFunction$2(getterOrOptions)) getter = getterOrOptions; else { getter = getterOrOptions.get; setter = getterOrOptions.set; } return new ComputedRefImpl(getter, setter, isSSR); } var INITIAL_WATCHER_VALUE = {}; var cleanupMap = /* @__PURE__ */ new WeakMap(); var activeWatcher = void 0; function onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) { if (owner) { let cleanups = cleanupMap.get(owner); if (!cleanups) cleanupMap.set(owner, cleanups = []); cleanups.push(cleanupFn); } } function watch$1(source, cb, options = EMPTY_OBJ) { const { immediate, deep, once, scheduler, augmentJob, call } = options; const reactiveGetter = (source2) => { if (deep) return source2; if (/* @__PURE__ */ isShallow(source2) || deep === false || deep === 0) return traverse(source2, 1); return traverse(source2); }; let effect; let getter; let cleanup; let boundCleanup; let forceTrigger = false; let isMultiSource = false; if (/* @__PURE__ */ isRef(source)) { getter = () => source.value; forceTrigger = /* @__PURE__ */ isShallow(source); } else if (/* @__PURE__ */ isReactive(source)) { getter = () => reactiveGetter(source); forceTrigger = true; } else if (isArray(source)) { isMultiSource = true; forceTrigger = source.some((s) => /* @__PURE__ */ isReactive(s) || /* @__PURE__ */ isShallow(s)); getter = () => source.map((s) => { if (/* @__PURE__ */ isRef(s)) return s.value; else if (/* @__PURE__ */ isReactive(s)) return reactiveGetter(s); else if (isFunction$2(s)) return call ? call(s, 2) : s(); }); } else if (isFunction$2(source)) if (cb) getter = call ? () => call(source, 2) : source; else getter = () => { if (cleanup) { pauseTracking(); try { cleanup(); } finally { resetTracking(); } } const currentEffect = activeWatcher; activeWatcher = effect; try { return call ? call(source, 3, [boundCleanup]) : source(boundCleanup); } finally { activeWatcher = currentEffect; } }; else getter = NOOP; if (cb && deep) { const baseGetter = getter; const depth = deep === true ? Infinity : deep; getter = () => traverse(baseGetter(), depth); } const scope = getCurrentScope$1(); const watchHandle = () => { effect.stop(); if (scope && scope.active) remove(scope.effects, effect); }; if (once && cb) { const _cb = cb; cb = (...args) => { _cb(...args); watchHandle(); }; } let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE; const job = (immediateFirstRun) => { if (!(effect.flags & 1) || !effect.dirty && !immediateFirstRun) return; if (cb) { const newValue = effect.run(); if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue))) { if (cleanup) cleanup(); const currentWatcher = activeWatcher; activeWatcher = effect; try { const args = [ newValue, oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue, boundCleanup ]; oldValue = newValue; call ? call(cb, 3, args) : cb(...args); } finally { activeWatcher = currentWatcher; } } } else effect.run(); }; if (augmentJob) augmentJob(job); effect = new ReactiveEffect(getter); effect.scheduler = scheduler ? () => scheduler(job, false) : job; boundCleanup = (fn) => onWatcherCleanup(fn, false, effect); cleanup = effect.onStop = () => { const cleanups = cleanupMap.get(effect); if (cleanups) { if (call) call(cleanups, 4); else for (const cleanup2 of cleanups) cleanup2(); cleanupMap.delete(effect); } }; if (cb) if (immediate) job(true); else oldValue = effect.run(); else if (scheduler) scheduler(job.bind(null, true), true); else effect.run(); watchHandle.pause = effect.pause.bind(effect); watchHandle.resume = effect.resume.bind(effect); watchHandle.stop = watchHandle; return watchHandle; } function traverse(value, depth = Infinity, seen) { if (depth <= 0 || !isObject$2(value) || value["__v_skip"]) return value; seen = seen || /* @__PURE__ */ new Map(); if ((seen.get(value) || 0) >= depth) return value; seen.set(value, depth); depth--; if (/* @__PURE__ */ isRef(value)) traverse(value.value, depth, seen); else if (isArray(value)) for (let i = 0; i < value.length; i++) traverse(value[i], depth, seen); else if (isSet(value) || isMap(value)) value.forEach((v) => { traverse(v, depth, seen); }); else if (isPlainObject$4(value)) { for (const key in value) traverse(value[key], depth, seen); for (const key of Object.getOwnPropertySymbols(value)) if (Object.prototype.propertyIsEnumerable.call(value, key)) traverse(value[key], depth, seen); } return value; } //#endregion //#region ../../node_modules/.pnpm/@vue+runtime-core@3.5.33/node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js /** * @vue/runtime-core v3.5.33 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT **/ function callWithErrorHandling(fn, instance, type, args) { try { return args ? fn(...args) : fn(); } catch (err) { handleError(err, instance, type); } } function callWithAsyncErrorHandling(fn, instance, type, args) { if (isFunction$2(fn)) { const res = callWithErrorHandling(fn, instance, type, args); if (res && isPromise(res)) res.catch((err) => { handleError(err, instance, type); }); return res; } if (isArray(fn)) { const values = []; for (let i = 0; i < fn.length; i++) values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)); return values; } } function handleError(err, instance, type, throwInDev = true) { const contextVNode = instance ? instance.vnode : null; const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || EMPTY_OBJ; if (instance) { let cur = instance.parent; const exposedInstance = instance.proxy; const errorInfo = `https://vuejs.org/error-reference/#runtime-${type}`; while (cur) { const errorCapturedHooks = cur.ec; if (errorCapturedHooks) { for (let i = 0; i < errorCapturedHooks.length; i++) if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) return; } cur = cur.parent; } if (errorHandler) { pauseTracking(); callWithErrorHandling(errorHandler, null, 10, [ err, exposedInstance, errorInfo ]); resetTracking(); return; } } logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction); } function logError(err, type, contextVNode, throwInDev = true, throwInProd = false) { if (throwInProd) throw err; else console.error(err); } var queue = []; var flushIndex = -1; var pendingPostFlushCbs = []; var activePostFlushCbs = null; var postFlushIndex = 0; var resolvedPromise = /* @__PURE__ */ Promise.resolve(); var currentFlushPromise = null; function nextTick(fn) { const p = currentFlushPromise || resolvedPromise; return fn ? p.then(this ? fn.bind(this) : fn) : p; } function findInsertionIndex(id) { let start = flushIndex + 1; let end = queue.length; while (start < end) { const middle = start + end >>> 1; const middleJob = queue[middle]; const middleJobId = getId(middleJob); if (middleJobId < id || middleJobId === id && middleJob.flags & 2) start = middle + 1; else end = middle; } return start; } function queueJob(job) { if (!(job.flags & 1)) { const jobId = getId(job); const lastJob = queue[queue.length - 1]; if (!lastJob || !(job.flags & 2) && jobId >= getId(lastJob)) queue.push(job); else queue.splice(findInsertionIndex(jobId), 0, job); job.flags |= 1; queueFlush(); } } function queueFlush() { if (!currentFlushPromise) currentFlushPromise = resolvedPromise.then(flushJobs); } function queuePostFlushCb(cb) { if (!isArray(cb)) { if (activePostFlushCbs && cb.id === -1) activePostFlushCbs.splice(postFlushIndex + 1, 0, cb); else if (!(cb.flags & 1)) { pendingPostFlushCbs.push(cb); cb.flags |= 1; } } else pendingPostFlushCbs.push(...cb); queueFlush(); } function flushPreFlushCbs(instance, seen, i = flushIndex + 1) { for (; i < queue.length; i++) { const cb = queue[i]; if (cb && cb.flags & 2) { if (instance && cb.id !== instance.uid) continue; queue.splice(i, 1); i--; if (cb.flags & 4) cb.flags &= -2; cb(); if (!(cb.flags & 4)) cb.flags &= -2; } } } function flushPostFlushCbs(seen) { if (pendingPostFlushCbs.length) { const deduped = [...new Set(pendingPostFlushCbs)].sort((a, b) => getId(a) - getId(b)); pendingPostFlushCbs.length = 0; if (activePostFlushCbs) { activePostFlushCbs.push(...deduped); return; } activePostFlushCbs = deduped; for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { const cb = activePostFlushCbs[postFlushIndex]; if (cb.flags & 4) cb.flags &= -2; if (!(cb.flags & 8)) cb(); cb.flags &= -2; } activePostFlushCbs = null; postFlushIndex = 0; } } var getId = (job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id; function flushJobs(seen) { try { for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { const job = queue[flushIndex]; if (job && !(job.flags & 8)) { if (job.flags & 4) job.flags &= -2; callWithErrorHandling(job, job.i, job.i ? 15 : 14); if (!(job.flags & 4)) job.flags &= -2; } } } finally { for (; flushIndex < queue.length; flushIndex++) { const job = queue[flushIndex]; if (job) job.flags &= -2; } flushIndex = -1; queue.length = 0; flushPostFlushCbs(seen); currentFlushPromise = null; if (queue.length || pendingPostFlushCbs.length) flushJobs(seen); } } var currentRenderingInstance = null; var currentScopeId = null; function setCurrentRenderingInstance(instance) { const prev = currentRenderingInstance; currentRenderingInstance = instance; currentScopeId = instance && instance.type.__scopeId || null; return prev; } function pushScopeId(id) { currentScopeId = id; } function popScopeId() { currentScopeId = null; } var withScopeId = (_id) => withCtx; function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { if (!ctx) return fn; if (fn._n) return fn; const renderFnWithContext = (...args) => { if (renderFnWithContext._d) setBlockTracking(-1); const prevInstance = setCurrentRenderingInstance(ctx); let res; try { res = fn(...args); } finally { setCurrentRenderingInstance(prevInstance); if (renderFnWithContext._d) setBlockTracking(1); } return res; }; renderFnWithContext._n = true; renderFnWithContext._c = true; renderFnWithContext._d = true; return renderFnWithContext; } function invokeDirectiveHook(vnode, prevVNode, instance, name) { const bindings = vnode.dirs; const oldBindings = prevVNode && prevVNode.dirs; for (let i = 0; i < bindings.length; i++) { const binding = bindings[i]; if (oldBindings) binding.oldValue = oldBindings[i].value; let hook = binding.dir[name]; if (hook) { pauseTracking(); callWithAsyncErrorHandling(hook, instance, 8, [ vnode.el, binding, vnode, prevVNode ]); resetTracking(); } } } function provide(key, value) { if (currentInstance) { let provides = currentInstance.provides; const parentProvides = currentInstance.parent && currentInstance.parent.provides; if (parentProvides === provides) provides = currentInstance.provides = Object.create(parentProvides); provides[key] = value; } } function inject(key, defaultValue, treatDefaultAsFactory = false) { const instance = getCurrentInstance(); if (instance || currentApp) { let provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null || instance.ce ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0; if (provides && key in provides) return provides[key]; else if (arguments.length > 1) return treatDefaultAsFactory && isFunction$2(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue; } } function hasInjectionContext() { return !!(getCurrentInstance() || currentApp); } var ssrContextKey = /* @__PURE__ */ Symbol.for("v-scx"); var useSSRContext = () => { { const ctx = inject(ssrContextKey); if (!ctx) {} return ctx; } }; function watch(source, cb, options) { return doWatch(source, cb, options); } function doWatch(source, cb, options = EMPTY_OBJ) { const { immediate, deep, flush, once } = options; const baseWatchOptions = extend({}, options); const runsImmediately = cb && immediate || !cb && flush !== "post"; let ssrCleanup; if (isInSSRComponentSetup) { if (flush === "sync") { const ctx = useSSRContext(); ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []); } else if (!runsImmediately) { const watchStopHandle = () => {}; watchStopHandle.stop = NOOP; watchStopHandle.resume = NOOP; watchStopHandle.pause = NOOP; return watchStopHandle; } } const instance = currentInstance; baseWatchOptions.call = (fn, type, args) => callWithAsyncErrorHandling(fn, instance, type, args); let isPre = false; if (flush === "post") baseWatchOptions.scheduler = (job) => { queuePostRenderEffect(job, instance && instance.suspense); }; else if (flush !== "sync") { isPre = true; baseWatchOptions.scheduler = (job, isFirstRun) => { if (isFirstRun) job(); else queueJob(job); }; } baseWatchOptions.augmentJob = (job) => { if (cb) job.flags |= 4; if (isPre) { job.flags |= 2; if (instance) { job.id = instance.uid; job.i = instance; } } }; const watchHandle = watch$1(source, cb, baseWatchOptions); if (isInSSRComponentSetup) { if (ssrCleanup) ssrCleanup.push(watchHandle); else if (runsImmediately) watchHandle(); } return watchHandle; } function instanceWatch(source, value, options) { const publicThis = this.proxy; const getter = isString$1(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); let cb; if (isFunction$2(value)) cb = value; else { cb = value.handler; options = value; } const reset = setCurrentInstance(this); const res = doWatch(getter, cb.bind(publicThis), options); reset(); return res; } function createPathGetter(ctx, path) { const segments = path.split("."); return () => { let cur = ctx; for (let i = 0; i < segments.length && cur; i++) cur = cur[segments[i]]; return cur; }; } var TeleportEndKey = /* @__PURE__ */ Symbol("_vte"); var isTeleport = (type) => type.__isTeleport; var leaveCbKey = /* @__PURE__ */ Symbol("_leaveCb"); var enterCbKey = /* @__PURE__ */ Symbol("_enterCb"); var recursiveGetSubtree = (instance) => { const subTree = instance.subTree; return subTree.component ? recursiveGetSubtree(subTree.component) : subTree; }; function getLeavingNodesForType(state, vnode) { const { leavingVNodes } = state; let leavingVNodesCache = leavingVNodes.get(vnode.type); if (!leavingVNodesCache) { leavingVNodesCache = /* @__PURE__ */ Object.create(null); leavingVNodes.set(vnode.type, leavingVNodesCache); } return leavingVNodesCache; } function resolveTransitionHooks(vnode, props, state, instance, postClone) { const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props; const key = String(vnode.key); const leavingVNodesCache = getLeavingNodesForType(state, vnode); const callHook = (hook, args) => { hook && callWithAsyncErrorHandling(hook, instance, 9, args); }; const callAsyncHook = (hook, args) => { const done = args[1]; callHook(hook, args); if (isArray(hook)) { if (hook.every((hook2) => hook2.length <= 1)) done(); } else if (hook.length <= 1) done(); }; const hooks = { mode, persisted, beforeEnter(el) { let hook = onBeforeEnter; if (!state.isMounted) if (appear) hook = onBeforeAppear || onBeforeEnter; else return; if (el[leaveCbKey]) el[leaveCbKey](true); const leavingVNode = leavingVNodesCache[key]; if (leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el[leaveCbKey]) leavingVNode.el[leaveCbKey](); callHook(hook, [el]); }, enter(el) { if (leavingVNodesCache[key] === vnode) return; let hook = onEnter; let afterHook = onAfterEnter; let cancelHook = onEnterCancelled; if (!state.isMounted) if (appear) { hook = onAppear || onEnter; afterHook = onAfterAppear || onAfterEnter; cancelHook = onAppearCancelled || onEnterCancelled; } else return; let called = false; el[enterCbKey] = (cancelled) => { if (called) return; called = true; if (cancelled) callHook(cancelHook, [el]); else callHook(afterHook, [el]); if (hooks.delayedLeave) hooks.delayedLeave(); el[enterCbKey] = void 0; }; const done = el[enterCbKey].bind(null, false); if (hook) callAsyncHook(hook, [el, done]); else done(); }, leave(el, remove) { const key2 = String(vnode.key); if (el[enterCbKey]) el[enterCbKey](true); if (state.isUnmounting) return remove(); callHook(onBeforeLeave, [el]); let called = false; el[leaveCbKey] = (cancelled) => { if (called) return; called = true; remove(); if (cancelled) callHook(onLeaveCancelled, [el]); else callHook(onAfterLeave, [el]); el[leaveCbKey] = void 0; if (leavingVNodesCache[key2] === vnode) delete leavingVNodesCache[key2]; }; const done = el[leaveCbKey].bind(null, false); leavingVNodesCache[key2] = vnode; if (onLeave) callAsyncHook(onLeave, [el, done]); else done(); }, clone(vnode2) { const hooks2 = resolveTransitionHooks(vnode2, props, state, instance, postClone); if (postClone) postClone(hooks2); return hooks2; } }; return hooks; } function setTransitionHooks(vnode, hooks) { if (vnode.shapeFlag & 6 && vnode.component) { vnode.transition = hooks; setTransitionHooks(vnode.component.subTree, hooks); } else if (vnode.shapeFlag & 128) { vnode.ssContent.transition = hooks.clone(vnode.ssContent); vnode.ssFallback.transition = hooks.clone(vnode.ssFallback); } else vnode.transition = hooks; } function getTransitionRawChildren(children, keepComment = false, parentKey) { let ret = []; let keyedFragmentCount = 0; for (let i = 0; i < children.length; i++) { let child = children[i]; const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i); if (child.type === Fragment) { if (child.patchFlag & 128) keyedFragmentCount++; ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key)); } else if (keepComment || child.type !== Comment) ret.push(key != null ? cloneVNode(child, { key }) : child); } if (keyedFragmentCount > 1) for (let i = 0; i < ret.length; i++) ret[i].patchFlag = -2; return ret; } // @__NO_SIDE_EFFECTS__ function defineComponent(options, extraOptions) { return isFunction$2(options) ? /* @__PURE__ */ (() => extend({ name: options.name }, extraOptions, { setup: options }))() : options; } function markAsyncBoundary(instance) { instance.ids = [ instance.ids[0] + instance.ids[2]++ + "-", 0, 0 ]; } function isTemplateRefKey(refs, key) { let desc; return !!((desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable); } var pendingSetRefMap = /* @__PURE__ */ new WeakMap(); function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { if (isArray(rawRef)) { rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount)); return; } if (isAsyncWrapper(vnode) && !isUnmount) { if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree); return; } const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el; const value = isUnmount ? null : refValue; const { i: owner, r: ref } = rawRef; const oldRef = oldRawRef && oldRawRef.r; const refs = owner.refs === EMPTY_OBJ ? owner.refs = {} : owner.refs; const setupState = owner.setupState; const rawSetupState = /* @__PURE__ */ toRaw(setupState); const canSetSetupRef = setupState === EMPTY_OBJ ? NO : (key) => { if (isTemplateRefKey(refs, key)) return false; return hasOwn$1(rawSetupState, key); }; const canSetRef = (ref2, key) => { if (key && isTemplateRefKey(refs, key)) return false; return true; }; if (oldRef != null && oldRef !== ref) { invalidatePendingSetRef(oldRawRef); if (isString$1(oldRef)) { refs[oldRef] = null; if (canSetSetupRef(oldRef)) setupState[oldRef] = null; } else if (/* @__PURE__ */ isRef(oldRef)) { const oldRawRefAtom = oldRawRef; if (canSetRef(oldRef, oldRawRefAtom.k)) oldRef.value = null; if (oldRawRefAtom.k) refs[oldRawRefAtom.k] = null; } } if (isFunction$2(ref)) callWithErrorHandling(ref, owner, 12, [value, refs]); else { const _isString = isString$1(ref); const _isRef = /* @__PURE__ */ isRef(ref); if (_isString || _isRef) { const doSet = () => { if (rawRef.f) { const existing = _isString ? canSetSetupRef(ref) ? setupState[ref] : refs[ref] : canSetRef(ref) || !rawRef.k ? ref.value : refs[rawRef.k]; if (isUnmount) isArray(existing) && remove(existing, refValue); else if (!isArray(existing)) if (_isString) { refs[ref] = [refValue]; if (canSetSetupRef(ref)) setupState[ref] = refs[ref]; } else { const newVal = [refValue]; if (canSetRef(ref, rawRef.k)) ref.value = newVal; if (rawRef.k) refs[rawRef.k] = newVal; } else if (!existing.includes(refValue)) existing.push(refValue); } else if (_isString) { refs[ref] = value; if (canSetSetupRef(ref)) setupState[ref] = value; } else if (_isRef) { if (canSetRef(ref, rawRef.k)) ref.value = value; if (rawRef.k) refs[rawRef.k] = value; } }; if (value) { const job = () => { doSet(); pendingSetRefMap.delete(rawRef); }; job.id = -1; pendingSetRefMap.set(rawRef, job); queuePostRenderEffect(job, parentSuspense); } else { invalidatePendingSetRef(rawRef); doSet(); } } } } function invalidatePendingSetRef(rawRef) { const pendingSetRef = pendingSetRefMap.get(rawRef); if (pendingSetRef) { pendingSetRef.flags |= 8; pendingSetRefMap.delete(rawRef); } } getGlobalThis().requestIdleCallback; getGlobalThis().cancelIdleCallback; var isAsyncWrapper = (i) => !!i.type.__asyncLoader; var isKeepAlive = (vnode) => vnode.type.__isKeepAlive; function onActivated(hook, target) { registerKeepAliveHook(hook, "a", target); } function onDeactivated(hook, target) { registerKeepAliveHook(hook, "da", target); } function registerKeepAliveHook(hook, type, target = currentInstance) { const wrappedHook = hook.__wdc || (hook.__wdc = () => { let current = target; while (current) { if (current.isDeactivated) return; current = current.parent; } return hook(); }); injectHook(type, wrappedHook, target); if (target) { let current = target.parent; while (current && current.parent) { if (isKeepAlive(current.parent.vnode)) injectToKeepAliveRoot(wrappedHook, type, target, current); current = current.parent; } } } function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { const injected = injectHook(type, hook, keepAliveRoot, true); onUnmounted(() => { remove(keepAliveRoot[type], injected); }, target); } function injectHook(type, hook, target = currentInstance, prepend = false) { if (target) { const hooks = target[type] || (target[type] = []); const wrappedHook = hook.__weh || (hook.__weh = (...args) => { pauseTracking(); const reset = setCurrentInstance(target); const res = callWithAsyncErrorHandling(hook, target, type, args); reset(); resetTracking(); return res; }); if (prepend) hooks.unshift(wrappedHook); else hooks.push(wrappedHook); return wrappedHook; } } var createHook = (lifecycle) => (hook, target = currentInstance) => { if (!isInSSRComponentSetup || lifecycle === "sp") injectHook(lifecycle, (...args) => hook(...args), target); }; var onBeforeMount = createHook("bm"); var onMounted = createHook("m"); var onBeforeUpdate = createHook("bu"); var onUpdated = createHook("u"); var onBeforeUnmount = createHook("bum"); var onUnmounted = createHook("um"); var onServerPrefetch = createHook("sp"); var onRenderTriggered = createHook("rtg"); var onRenderTracked = createHook("rtc"); function onErrorCaptured(hook, target = currentInstance) { injectHook("ec", hook, target); } var COMPONENTS = "components"; function resolveComponent(name, maybeSelfReference) { return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; } var NULL_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol.for("v-ndc"); function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { const instance = currentRenderingInstance || currentInstance; if (instance) { const Component = instance.type; if (type === COMPONENTS) { const selfName = getComponentName$1(Component, false); if (selfName && (selfName === name || selfName === camelize$2(name) || selfName === capitalize(camelize$2(name)))) return Component; } const res = resolve(instance[type] || Component[type], name) || resolve(instance.appContext[type], name); if (!res && maybeSelfReference) return Component; return res; } } function resolve(registry, name) { return registry && (registry[name] || registry[camelize$2(name)] || registry[capitalize(camelize$2(name))]); } function renderList(source, renderItem, cache, index) { let ret; const cached = cache && cache[index]; const sourceIsArray = isArray(source); if (sourceIsArray || isString$1(source)) { const sourceIsReactiveArray = sourceIsArray && /* @__PURE__ */ isReactive(source); let needsWrap = false; let isReadonlySource = false; if (sourceIsReactiveArray) { needsWrap = !/* @__PURE__ */ isShallow(source); isReadonlySource = /* @__PURE__ */ isReadonly(source); source = shallowReadArray(source); } ret = new Array(source.length); for (let i = 0, l = source.length; i < l; i++) ret[i] = renderItem(needsWrap ? isReadonlySource ? toReadonly(toReactive(source[i])) : toReactive(source[i]) : source[i], i, void 0, cached && cached[i]); } else if (typeof source === "number") { ret = new Array(source); for (let i = 0; i < source; i++) ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]); } else if (isObject$2(source)) if (source[Symbol.iterator]) ret = Array.from(source, (item, i) => renderItem(item, i, void 0, cached && cached[i])); else { const keys = Object.keys(source); ret = new Array(keys.length); for (let i = 0, l = keys.length; i < l; i++) { const key = keys[i]; ret[i] = renderItem(source[key], key, i, cached && cached[i]); } } else ret = []; if (cache) cache[index] = ret; return ret; } function renderSlot(slots, name, props = {}, fallback, noSlotted) { if (currentRenderingInstance.ce || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.ce) { const hasProps = Object.keys(props).length > 0; if (name !== "default") props.name = name; return openBlock(), createBlock(Fragment, null, [createVNode("slot", props, fallback && fallback())], hasProps ? -2 : 64); } let slot = slots[name]; if (slot && slot._c) slot._d = false; openBlock(); const validSlotContent = slot && ensureValidVNode(slot(props)); const slotKey = props.key || validSlotContent && validSlotContent.key; const rendered = createBlock(Fragment, { key: (slotKey && !isSymbol(slotKey) ? slotKey : `_${name}`) + (!validSlotContent && fallback ? "_fb" : "") }, 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; } function ensureValidVNode(vnodes) { return vnodes.some((child) => { if (!isVNode(child)) return true; if (child.type === Comment) return false; if (child.type === Fragment && !ensureValidVNode(child.children)) return false; return true; }) ? vnodes : null; } var getPublicInstance = (i) => { if (!i) return null; if (isStatefulComponent(i)) return getComponentPublicInstance(i); return getPublicInstance(i.parent); }; var publicPropertiesMap = /* @__PURE__ */ extend(/* @__PURE__ */ Object.create(null), { $: (i) => i, $el: (i) => i.vnode.el, $data: (i) => i.data, $props: (i) => i.props, $attrs: (i) => i.attrs, $slots: (i) => i.slots, $refs: (i) => i.refs, $parent: (i) => getPublicInstance(i.parent), $root: (i) => getPublicInstance(i.root), $host: (i) => i.ce, $emit: (i) => i.emit, $options: (i) => resolveMergedOptions(i), $forceUpdate: (i) => i.f || (i.f = () => { queueJob(i.update); }), $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)), $watch: (i) => instanceWatch.bind(i) }); var hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn$1(state, key); var PublicInstanceProxyHandlers = { get({ _: instance }, key) { if (key === "__v_skip") return true; const { ctx, setupState, data, props, accessCache, type, appContext } = instance; if (key[0] !== "$") { const n = accessCache[key]; if (n !== void 0) switch (n) { case 1: return setupState[key]; case 2: return data[key]; case 4: return ctx[key]; case 3: return props[key]; } else if (hasSetupBinding(setupState, key)) { accessCache[key] = 1; return setupState[key]; } else if (data !== EMPTY_OBJ && hasOwn$1(data, key)) { accessCache[key] = 2; return data[key]; } else if (hasOwn$1(props, key)) { accessCache[key] = 3; return props[key]; } else if (ctx !== EMPTY_OBJ && hasOwn$1(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", ""); return publicGetter(instance); } else if ((cssModule = type.__cssModules) && (cssModule = cssModule[key])) return cssModule; else if (ctx !== EMPTY_OBJ && hasOwn$1(ctx, key)) { accessCache[key] = 4; return ctx[key]; } else if (globalProperties = appContext.config.globalProperties, hasOwn$1(globalProperties, key)) return globalProperties[key]; }, set({ _: instance }, key, value) { const { data, setupState, ctx } = instance; if (hasSetupBinding(setupState, key)) { setupState[key] = value; return true; } else if (data !== EMPTY_OBJ && hasOwn$1(data, key)) { data[key] = value; return true; } else if (hasOwn$1(instance.props, key)) return false; if (key[0] === "$" && key.slice(1) in instance) return false; else ctx[key] = value; return true; }, has({ _: { data, setupState, accessCache, ctx, appContext, props, type } }, key) { let cssModules; return !!(accessCache[key] || data !== EMPTY_OBJ && key[0] !== "$" && hasOwn$1(data, key) || hasSetupBinding(setupState, key) || hasOwn$1(props, key) || hasOwn$1(ctx, key) || hasOwn$1(publicPropertiesMap, key) || hasOwn$1(appContext.config.globalProperties, key) || (cssModules = type.__cssModules) && cssModules[key]); }, defineProperty(target, key, descriptor) { if (descriptor.get != null) target._.accessCache[key] = 0; else if (hasOwn$1(descriptor, "value")) this.set(target, key, descriptor.value, null); return Reflect.defineProperty(target, key, descriptor); } }; function normalizePropsOrEmits(props) { return isArray(props) ? props.reduce((normalized, p) => (normalized[p] = null, normalized), {}) : props; } var shouldCacheAccess = true; function applyOptions(instance) { const options = resolveMergedOptions(instance); const publicThis = instance.proxy; const ctx = instance.ctx; shouldCacheAccess = false; if (options.beforeCreate) callHook$1(options.beforeCreate, instance, "bc"); const { data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions, created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch, expose, inheritAttrs, components, directives, filters } = options; const checkDuplicateProperties = null; if (injectOptions) resolveInjections(injectOptions, ctx, checkDuplicateProperties); if (methods) for (const key in methods) { const methodHandler = methods[key]; if (isFunction$2(methodHandler)) ctx[key] = methodHandler.bind(publicThis); } if (dataOptions) { const data = dataOptions.call(publicThis, publicThis); if (!isObject$2(data)) {} else instance.data = /* @__PURE__ */ reactive(data); } shouldCacheAccess = true; if (computedOptions) for (const key in computedOptions) { const opt = computedOptions[key]; const c = computed({ get: isFunction$2(opt) ? opt.bind(publicThis, publicThis) : isFunction$2(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP, set: !isFunction$2(opt) && isFunction$2(opt.set) ? opt.set.bind(publicThis) : NOOP }); Object.defineProperty(ctx, key, { enumerable: true, configurable: true, get: () => c.value, set: (v) => c.value = v }); } if (watchOptions) for (const key in watchOptions) createWatcher(watchOptions[key], ctx, publicThis, key); if (provideOptions) { const provides = isFunction$2(provideOptions) ? provideOptions.call(publicThis) : provideOptions; Reflect.ownKeys(provides).forEach((key) => { provide(key, provides[key]); }); } if (created) callHook$1(created, instance, "c"); function registerLifecycleHook(register, hook) { if (isArray(hook)) hook.forEach((_hook) => register(_hook.bind(publicThis))); else if (hook) register(hook.bind(publicThis)); } registerLifecycleHook(onBeforeMount, beforeMount); registerLifecycleHook(onMounted, mounted); registerLifecycleHook(onBeforeUpdate, beforeUpdate); registerLifecycleHook(onUpdated, updated); registerLifecycleHook(onActivated, activated); registerLifecycleHook(onDeactivated, deactivated); registerLifecycleHook(onErrorCaptured, errorCaptured); registerLifecycleHook(onRenderTracked, renderTracked); registerLifecycleHook(onRenderTriggered, renderTriggered); registerLifecycleHook(onBeforeUnmount, beforeUnmount); registerLifecycleHook(onUnmounted, unmounted); registerLifecycleHook(onServerPrefetch, serverPrefetch); if (isArray(expose)) { if (expose.length) { const exposed = instance.exposed || (instance.exposed = {}); expose.forEach((key) => { Object.defineProperty(exposed, key, { get: () => publicThis[key], set: (val) => publicThis[key] = val, enumerable: true }); }); } else if (!instance.exposed) instance.exposed = {}; } if (render && instance.render === NOOP) instance.render = render; if (inheritAttrs != null) instance.inheritAttrs = inheritAttrs; if (components) instance.components = components; if (directives) instance.directives = directives; if (serverPrefetch) markAsyncBoundary(instance); } function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP) { if (isArray(injectOptions)) injectOptions = normalizeInject(injectOptions); for (const key in injectOptions) { const opt = injectOptions[key]; let injected; if (isObject$2(opt)) if ("default" in opt) injected = inject(opt.from || key, opt.default, true); else injected = inject(opt.from || key); else injected = inject(opt); if (/* @__PURE__ */ isRef(injected)) Object.defineProperty(ctx, key, { enumerable: true, configurable: true, get: () => injected.value, set: (v) => injected.value = v }); else ctx[key] = injected; } } function callHook$1(hook, instance, type) { callWithAsyncErrorHandling(isArray(hook) ? hook.map((h) => h.bind(instance.proxy)) : hook.bind(instance.proxy), instance, type); } function createWatcher(raw, ctx, publicThis, key) { let getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key]; if (isString$1(raw)) { const handler = ctx[raw]; if (isFunction$2(handler)) watch(getter, handler); } else if (isFunction$2(raw)) watch(getter, raw.bind(publicThis)); else if (isObject$2(raw)) if (isArray(raw)) raw.forEach((r) => createWatcher(r, ctx, publicThis, key)); else { const handler = isFunction$2(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler]; if (isFunction$2(handler)) watch(getter, handler, raw); } } function resolveMergedOptions(instance) { const base = instance.type; const { mixins, extends: extendsOptions } = base; const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext; const cached = cache.get(base); let resolved; if (cached) resolved = cached; else if (!globalMixins.length && !mixins && !extendsOptions) resolved = base; else { resolved = {}; if (globalMixins.length) globalMixins.forEach((m) => mergeOptions(resolved, m, optionMergeStrategies, true)); mergeOptions(resolved, base, optionMergeStrategies); } if (isObject$2(base)) cache.set(base, resolved); return resolved; } function mergeOptions(to, from, strats, asMixin = false) { const { mixins, extends: extendsOptions } = from; if (extendsOptions) mergeOptions(to, extendsOptions, strats, true); if (mixins) mixins.forEach((m) => mergeOptions(to, m, strats, true)); for (const key in from) if (asMixin && key === "expose") {} else { const strat = internalOptionMergeStrats[key] || strats && strats[key]; to[key] = strat ? strat(to[key], from[key]) : from[key]; } return to; } var internalOptionMergeStrats = { data: mergeDataFn, props: mergeEmitsOrPropsOptions, emits: mergeEmitsOrPropsOptions, methods: mergeObjectOptions, computed: mergeObjectOptions, beforeCreate: mergeAsArray, created: mergeAsArray, beforeMount: mergeAsArray, mounted: mergeAsArray, beforeUpdate: mergeAsArray, updated: mergeAsArray, beforeDestroy: mergeAsArray, beforeUnmount: mergeAsArray, destroyed: mergeAsArray, unmounted: mergeAsArray, activated: mergeAsArray, deactivated: mergeAsArray, errorCaptured: mergeAsArray, serverPrefetch: mergeAsArray, components: mergeObjectOptions, directives: mergeObjectOptions, watch: mergeWatchOptions, provide: mergeDataFn, inject: mergeInject }; function mergeDataFn(to, from) { if (!from) return to; if (!to) return from; return function mergedDataFn() { return extend(isFunction$2(to) ? to.call(this, this) : to, isFunction$2(from) ? from.call(this, this) : from); }; } function mergeInject(to, from) { return mergeObjectOptions(normalizeInject(to), normalizeInject(from)); } function normalizeInject(raw) { if (isArray(raw)) { const res = {}; for (let i = 0; i < raw.length; i++) res[raw[i]] = raw[i]; return res; } return raw; } function mergeAsArray(to, from) { return to ? [...new Set([].concat(to, from))] : from; } function mergeObjectOptions(to, from) { return to ? extend(/* @__PURE__ */ Object.create(null), to, from) : from; } function mergeEmitsOrPropsOptions(to, from) { if (to) { if (isArray(to) && isArray(from)) return [.../* @__PURE__ */ new Set([...to, ...from])]; return extend(/* @__PURE__ */ Object.create(null), normalizePropsOrEmits(to), normalizePropsOrEmits(from != null ? from : {})); } else return from; } function mergeWatchOptions(to, from) { if (!to) return from; if (!from) return to; const merged = extend(/* @__PURE__ */ Object.create(null), to); for (const key in from) merged[key] = mergeAsArray(to[key], from[key]); return merged; } function createAppContext() { return { app: null, config: { isNativeTag: NO, performance: false, globalProperties: {}, optionMergeStrategies: {}, errorHandler: void 0, warnHandler: void 0, compilerOptions: {} }, mixins: [], components: {}, directives: {}, provides: /* @__PURE__ */ Object.create(null), optionsCache: /* @__PURE__ */ new WeakMap(), propsCache: /* @__PURE__ */ new WeakMap(), emitsCache: /* @__PURE__ */ new WeakMap() }; } var uid$1 = 0; function createAppAPI(render, hydrate) { return function createApp(rootComponent, rootProps = null) { if (!isFunction$2(rootComponent)) rootComponent = extend({}, rootComponent); if (rootProps != null && !isObject$2(rootProps)) rootProps = null; const context = createAppContext(); const installedPlugins = /* @__PURE__ */ new WeakSet(); const pluginCleanupFns = []; let isMounted = false; const app = context.app = { _uid: uid$1++, _component: rootComponent, _props: rootProps, _container: null, _context: context, _instance: null, version: version$1, get config() { return context.config; }, set config(v) {}, use(plugin, ...options) { if (installedPlugins.has(plugin)) {} else if (plugin && isFunction$2(plugin.install)) { installedPlugins.add(plugin); plugin.install(app, ...options); } else if (isFunction$2(plugin)) { installedPlugins.add(plugin); plugin(app, ...options); } return app; }, mixin(mixin) { if (!context.mixins.includes(mixin)) context.mixins.push(mixin); return app; }, component(name, component) { if (!component) return context.components[name]; context.components[name] = component; return app; }, directive(name, directive) { if (!directive) return context.directives[name]; context.directives[name] = directive; return app; }, mount(rootContainer, isHydrate, namespace) { if (!isMounted) { const vnode = app._ceVNode || createVNode(rootComponent, rootProps); vnode.appContext = context; if (namespace === true) namespace = "svg"; else if (namespace === false) namespace = void 0; if (isHydrate && hydrate) hydrate(vnode, rootContainer); else render(vnode, rootContainer, namespace); isMounted = true; app._container = rootContainer; rootContainer.__vue_app__ = app; return getComponentPublicInstance(vnode.component); } }, onUnmount(cleanupFn) { pluginCleanupFns.push(cleanupFn); }, unmount() { if (isMounted) { callWithAsyncErrorHandling(pluginCleanupFns, app._instance, 16); render(null, app._container); delete app._container.__vue_app__; } }, provide(key, value) { context.provides[key] = value; return app; }, runWithContext(fn) { const lastApp = currentApp; currentApp = app; try { return fn(); } finally { currentApp = lastApp; } } }; return app; }; } var currentApp = null; var getModelModifiers = (props, modelName) => { return modelName === "modelValue" || modelName === "model-value" ? props.modelModifiers : props[`${modelName}Modifiers`] || props[`${camelize$2(modelName)}Modifiers`] || props[`${hyphenate$2(modelName)}Modifiers`]; }; function emit(instance, event, ...rawArgs) { if (instance.isUnmounted) return; const props = instance.vnode.props || EMPTY_OBJ; let args = rawArgs; const isModelListener = event.startsWith("update:"); const modifiers = isModelListener && getModelModifiers(props, event.slice(7)); if (modifiers) { if (modifiers.trim) args = rawArgs.map((a) => isString$1(a) ? a.trim() : a); if (modifiers.number) args = rawArgs.map(looseToNumber); } let handlerName; let handler = props[handlerName = toHandlerKey(event)] || props[handlerName = toHandlerKey(camelize$2(event))]; if (!handler && isModelListener) handler = props[handlerName = toHandlerKey(hyphenate$2(event))]; if (handler) callWithAsyncErrorHandling(handler, 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); } } var mixinEmitsCache = /* @__PURE__ */ new WeakMap(); function normalizeEmitsOptions(comp, appContext, asMixin = false) { const cache = asMixin ? mixinEmitsCache : appContext.emitsCache; const cached = cache.get(comp); if (cached !== void 0) return cached; const raw = comp.emits; let normalized = {}; let hasExtends = false; if (!isFunction$2(comp)) { const extendEmits = (raw2) => { const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); if (normalizedFromExtend) { hasExtends = true; extend(normalized, normalizedFromExtend); } }; 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$2(comp)) cache.set(comp, null); return null; } if (isArray(raw)) raw.forEach((key) => normalized[key] = null); else extend(normalized, raw); if (isObject$2(comp)) cache.set(comp, normalized); return normalized; } function isEmitListener(options, key) { if (!options || !isOn(key)) return false; key = key.slice(2).replace(/Once$/, ""); return hasOwn$1(options, key[0].toLowerCase() + key.slice(1)) || hasOwn$1(options, hyphenate$2(key)) || hasOwn$1(options, key); } function renderComponentRoot(instance) { const { type: Component, vnode, proxy, withProxy, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, props, data, setupState, ctx, inheritAttrs } = instance; const prev = setCurrentRenderingInstance(instance); let result; let fallthroughAttrs; try { if (vnode.shapeFlag & 4) { const proxyToUse = withProxy || proxy; const thisProxy = proxyToUse; result = normalizeVNode(render.call(thisProxy, proxyToUse, renderCache, props, setupState, data, ctx)); fallthroughAttrs = attrs; } else { const render2 = Component; result = normalizeVNode(render2.length > 1 ? render2(props, { attrs, slots, emit }) : render2(props, null)); fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs); } } catch (err) { blockStack.length = 0; handleError(err, instance, 1); result = createVNode(Comment); } let root = result; if (fallthroughAttrs && inheritAttrs !== false) { const keys = Object.keys(fallthroughAttrs); const { shapeFlag } = root; if (keys.length) { if (shapeFlag & 7) { if (propsOptions && keys.some(isModelListener)) fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions); root = cloneVNode(root, fallthroughAttrs, false, true); } } } if (vnode.dirs) { root = cloneVNode(root, null, false, true); root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs; } if (vnode.transition) setTransitionHooks(root, vnode.transition); result = root; setCurrentRenderingInstance(prev); return result; } var getFunctionalFallthrough = (attrs) => { let res; for (const key in attrs) if (key === "class" || key === "style" || isOn(key)) (res || (res = {}))[key] = attrs[key]; return res; }; var filterModelListeners = (attrs, props) => { const res = {}; for (const key in attrs) if (!isModelListener(key) || !(key.slice(9) in props)) res[key] = attrs[key]; return res; }; function shouldUpdateComponent(prevVNode, nextVNode, optimized) { const { props: prevProps, children: prevChildren, component } = prevVNode; const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; const emits = component.emitsOptions; 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 i = 0; i < dynamicProps.length; i++) { const key = dynamicProps[i]; if (hasPropValueChanged(nextProps, 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; } function hasPropsChanged(prevProps, nextProps, emitsOptions) { const nextKeys = Object.keys(nextProps); if (nextKeys.length !== Object.keys(prevProps).length) return true; for (let i = 0; i < nextKeys.length; i++) { const key = nextKeys[i]; if (hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emitsOptions, key)) return true; } return false; } function hasPropValueChanged(nextProps, prevProps, key) { const nextProp = nextProps[key]; const prevProp = prevProps[key]; if (key === "style" && isObject$2(nextProp) && isObject$2(prevProp)) return !looseEqual(nextProp, prevProp); return nextProp !== prevProp; } function updateHOCHostEl({ vnode, parent, suspense }, el) { while (parent) { const root = parent.subTree; if (root.suspense && root.suspense.activeBranch === vnode) { root.suspense.vnode.el = root.el = el; vnode = root; } if (root === vnode) { (vnode = parent.vnode).el = el; parent = parent.parent; } else break; } if (suspense && suspense.activeBranch === vnode) suspense.vnode.el = el; } var internalObjectProto = {}; var createInternalObject = () => Object.create(internalObjectProto); var isInternalObject = (obj) => Object.getPrototypeOf(obj) === internalObjectProto; function initProps(instance, rawProps, isStateful, isSSR = false) { const props = {}; const attrs = createInternalObject(); instance.propsDefaults = /* @__PURE__ */ Object.create(null); setFullProps(instance, rawProps, props, attrs); for (const key in instance.propsOptions[0]) if (!(key in props)) props[key] = void 0; if (isStateful) instance.props = isSSR ? props : /* @__PURE__ */ shallowReactive(props); else if (!instance.type.props) instance.props = attrs; else instance.props = props; instance.attrs = attrs; } function updateProps(instance, rawProps, rawPrevProps, optimized) { const { props, attrs, vnode: { patchFlag } } = instance; const rawCurrentProps = /* @__PURE__ */ toRaw(props); const [options] = instance.propsOptions; let hasAttrsChanged = false; if ((optimized || patchFlag > 0) && !(patchFlag & 16)) { if (patchFlag & 8) { const propsToUpdate = instance.vnode.dynamicProps; for (let i = 0; i < propsToUpdate.length; i++) { let key = propsToUpdate[i]; if (isEmitListener(instance.emitsOptions, key)) continue; const value = rawProps[key]; if (options) if (hasOwn$1(attrs, key)) { if (value !== attrs[key]) { attrs[key] = value; hasAttrsChanged = true; } } else { const camelizedKey = camelize$2(key); props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false); } else if (value !== attrs[key]) { attrs[key] = value; hasAttrsChanged = true; } } } } else { if (setFullProps(instance, rawProps, props, attrs)) hasAttrsChanged = true; let kebabKey; for (const key in rawCurrentProps) if (!rawProps || !hasOwn$1(rawProps, key) && ((kebabKey = hyphenate$2(key)) === key || !hasOwn$1(rawProps, kebabKey))) if (options) { if (rawPrevProps && (rawPrevProps[key] !== void 0 || rawPrevProps[kebabKey] !== void 0)) props[key] = resolvePropValue(options, rawCurrentProps, key, void 0, instance, true); } else delete props[key]; if (attrs !== rawCurrentProps) { for (const key in attrs) if (!rawProps || !hasOwn$1(rawProps, key) && true) { delete attrs[key]; hasAttrsChanged = true; } } } if (hasAttrsChanged) trigger(instance.attrs, "set", ""); } function setFullProps(instance, rawProps, props, attrs) { const [options, needCastKeys] = instance.propsOptions; let hasAttrsChanged = false; let rawCastValues; if (rawProps) for (let key in rawProps) { if (isReservedProp(key)) continue; const value = rawProps[key]; let camelKey; if (options && hasOwn$1(options, camelKey = camelize$2(key))) if (!needCastKeys || !needCastKeys.includes(camelKey)) props[camelKey] = value; else (rawCastValues || (rawCastValues = {}))[camelKey] = value; else if (!isEmitListener(instance.emitsOptions, key)) { if (!(key in attrs) || value !== attrs[key]) { attrs[key] = value; hasAttrsChanged = true; } } } if (needCastKeys) { const rawCurrentProps = /* @__PURE__ */ toRaw(props); const castValues = rawCastValues || EMPTY_OBJ; for (let i = 0; i < needCastKeys.length; i++) { const key = needCastKeys[i]; props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn$1(castValues, key)); } } return hasAttrsChanged; } function resolvePropValue(options, props, key, value, instance, isAbsent) { const opt = options[key]; if (opt != null) { const hasDefault = hasOwn$1(opt, "default"); if (hasDefault && value === void 0) { const defaultValue = opt.default; if (opt.type !== Function && !opt.skipFactory && isFunction$2(defaultValue)) { const { propsDefaults } = instance; if (key in propsDefaults) value = propsDefaults[key]; else { const reset = setCurrentInstance(instance); value = propsDefaults[key] = defaultValue.call(null, props); reset(); } } else value = defaultValue; if (instance.ce) instance.ce._setProp(key, value); } if (opt[0]) { if (isAbsent && !hasDefault) value = false; else if (opt[1] && (value === "" || value === hyphenate$2(key))) value = true; } } return value; } var mixinPropsCache = /* @__PURE__ */ new WeakMap(); function normalizePropsOptions(comp, appContext, asMixin = false) { const cache = asMixin ? mixinPropsCache : appContext.propsCache; const cached = cache.get(comp); if (cached) return cached; const raw = comp.props; const normalized = {}; const needCastKeys = []; let hasExtends = false; if (!isFunction$2(comp)) { const extendProps = (raw2) => { hasExtends = true; const [props, keys] = normalizePropsOptions(raw2, appContext, true); extend(normalized, props); if (keys) needCastKeys.push(...keys); }; if (!asMixin && appContext.mixins.length) appContext.mixins.forEach(extendProps); if (comp.extends) extendProps(comp.extends); if (comp.mixins) comp.mixins.forEach(extendProps); } if (!raw && !hasExtends) { if (isObject$2(comp)) cache.set(comp, EMPTY_ARR); return EMPTY_ARR; } if (isArray(raw)) for (let i = 0; i < raw.length; i++) { const normalizedKey = camelize$2(raw[i]); if (validatePropName(normalizedKey)) normalized[normalizedKey] = EMPTY_OBJ; } else if (raw) for (const key in raw) { const normalizedKey = camelize$2(key); if (validatePropName(normalizedKey)) { const opt = raw[key]; const prop = normalized[normalizedKey] = isArray(opt) || isFunction$2(opt) ? { type: opt } : extend({}, opt); const propType = prop.type; let shouldCast = false; let shouldCastTrue = true; if (isArray(propType)) for (let index = 0; index < propType.length; ++index) { const type = propType[index]; const typeName = isFunction$2(type) && type.name; if (typeName === "Boolean") { shouldCast = true; break; } else if (typeName === "String") shouldCastTrue = false; } else shouldCast = isFunction$2(propType) && propType.name === "Boolean"; prop[0] = shouldCast; prop[1] = shouldCastTrue; if (shouldCast || hasOwn$1(prop, "default")) needCastKeys.push(normalizedKey); } } const res = [normalized, needCastKeys]; if (isObject$2(comp)) cache.set(comp, res); return res; } function validatePropName(key) { if (key[0] !== "$" && !isReservedProp(key)) return true; return false; } var isInternalKey = (key) => key === "_" || key === "_ctx" || key === "$stable"; var normalizeSlotValue = (value) => isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)]; var normalizeSlot = (key, rawSlot, ctx) => { if (rawSlot._n) return rawSlot; const normalized = withCtx((...args) => { return normalizeSlotValue(rawSlot(...args)); }, ctx); normalized._c = false; return normalized; }; var normalizeObjectSlots = (rawSlots, slots, instance) => { const ctx = rawSlots._ctx; for (const key in rawSlots) { if (isInternalKey(key)) continue; const value = rawSlots[key]; if (isFunction$2(value)) slots[key] = normalizeSlot(key, value, ctx); else if (value != null) { const normalized = normalizeSlotValue(value); slots[key] = () => normalized; } } }; var normalizeVNodeSlots = (instance, children) => { const normalized = normalizeSlotValue(children); instance.slots.default = () => normalized; }; var assignSlots = (slots, children, optimized) => { for (const key in children) if (optimized || !isInternalKey(key)) slots[key] = children[key]; }; var initSlots = (instance, children, optimized) => { const slots = instance.slots = createInternalObject(); if (instance.vnode.shapeFlag & 32) { const type = children._; if (type) { assignSlots(slots, children, optimized); if (optimized) def(slots, "_", type, true); } else normalizeObjectSlots(children, slots); } else if (children) normalizeVNodeSlots(instance, children); }; var updateSlots = (instance, children, optimized) => { const { vnode, slots } = instance; let needDeletionCheck = true; let deletionComparisonTarget = EMPTY_OBJ; if (vnode.shapeFlag & 32) { const type = children._; if (type) if (optimized && type === 1) needDeletionCheck = false; else assignSlots(slots, children, optimized); else { needDeletionCheck = !children.$stable; normalizeObjectSlots(children, slots); } deletionComparisonTarget = children; } else if (children) { normalizeVNodeSlots(instance, children); deletionComparisonTarget = { default: 1 }; } if (needDeletionCheck) { for (const key in slots) if (!isInternalKey(key) && deletionComparisonTarget[key] == null) delete slots[key]; } }; var queuePostRenderEffect = queueEffectWithSuspense; function createRenderer(options) { return baseCreateRenderer(options); } function baseCreateRenderer(options, createHydrationFns) { const target = getGlobalThis(); target.__VUE__ = true; const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, insertStaticContent: hostInsertStaticContent } = options; const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = void 0, slotScopeIds = null, optimized = !!n2.dynamicChildren) => { if (n1 === n2) return; if (n1 && !isSameVNodeType(n1, n2)) { anchor = getNextHostNode(n1); unmount(n1, parentComponent, parentSuspense, true); n1 = null; } if (n2.patchFlag === -2) { optimized = false; n2.dynamicChildren = null; } const { type, ref, shapeFlag } = n2; switch (type) { case Text: processText(n1, n2, container, anchor); break; case Comment: processCommentNode(n1, n2, container, anchor); break; case Static: if (n1 == null) mountStaticNode(n2, container, anchor, namespace); break; case Fragment: processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); break; default: if (shapeFlag & 1) processElement(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); else if (shapeFlag & 6) processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); else if (shapeFlag & 64) type.process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals); else if (shapeFlag & 128) type.process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals); } if (ref != null && parentComponent) setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2); else if (ref == null && n1 && n1.ref != null) setRef(n1.ref, null, parentSuspense, n1, true); }; const processText = (n1, n2, container, anchor) => { if (n1 == null) hostInsert(n2.el = hostCreateText(n2.children), container, anchor); else { const el = n2.el = n1.el; if (n2.children !== n1.children) hostSetText(el, n2.children); } }; const processCommentNode = (n1, n2, container, anchor) => { if (n1 == null) hostInsert(n2.el = hostCreateComment(n2.children || ""), container, anchor); else n2.el = n1.el; }; const mountStaticNode = (n2, container, anchor, namespace) => { [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, namespace, n2.el, n2.anchor); }; const moveStaticNode = ({ el, anchor }, container, nextSibling) => { let next; while (el && el !== anchor) { next = hostNextSibling(el); hostInsert(el, container, nextSibling); el = next; } hostInsert(anchor, container, nextSibling); }; const removeStaticNode = ({ el, anchor }) => { let next; while (el && el !== anchor) { next = hostNextSibling(el); hostRemove(el); el = next; } hostRemove(anchor); }; const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { if (n2.type === "svg") namespace = "svg"; else if (n2.type === "math") namespace = "mathml"; if (n1 == null) mountElement(n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); else { const customElement = n1.el && n1.el._isVueCE ? n1.el : null; try { if (customElement) customElement._beginPatch(); patchElement(n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); } finally { if (customElement) customElement._endPatch(); } } }; const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { let el; let vnodeHook; const { props, shapeFlag, transition, dirs } = vnode; el = vnode.el = hostCreateElement(vnode.type, namespace, props && props.is, props); if (shapeFlag & 8) hostSetElementText(el, vnode.children); else if (shapeFlag & 16) mountChildren(vnode.children, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(vnode, namespace), slotScopeIds, optimized); if (dirs) invokeDirectiveHook(vnode, null, parentComponent, "created"); setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent); if (props) { for (const key in props) if (key !== "value" && !isReservedProp(key)) hostPatchProp(el, key, null, props[key], namespace, parentComponent); if ("value" in props) hostPatchProp(el, "value", null, props.value, namespace); if (vnodeHook = props.onVnodeBeforeMount) invokeVNodeHook(vnodeHook, parentComponent, vnode); } if (dirs) invokeDirectiveHook(vnode, null, parentComponent, "beforeMount"); const needCallTransitionHooks = needTransition(parentSuspense, transition); if (needCallTransitionHooks) transition.beforeEnter(el); hostInsert(el, container, anchor); if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) queuePostRenderEffect(() => { try { vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); needCallTransitionHooks && transition.enter(el); dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted"); } finally {} }, parentSuspense); }; const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => { if (scopeId) hostSetScopeId(el, scopeId); if (slotScopeIds) for (let i = 0; i < slotScopeIds.length; i++) hostSetScopeId(el, slotScopeIds[i]); if (parentComponent) { let subTree = parentComponent.subTree; if (vnode === subTree || isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) { const parentVNode = parentComponent.vnode; setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent); } } }; const mountChildren = (children, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, start = 0) => { for (let i = start; i < children.length; i++) patch(null, children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]), container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); }; const patchElement = (n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { const el = n2.el = n1.el; let { patchFlag, dynamicChildren, dirs } = n2; patchFlag |= n1.patchFlag & 16; const oldProps = n1.props || EMPTY_OBJ; const newProps = n2.props || EMPTY_OBJ; let vnodeHook; parentComponent && toggleRecurse(parentComponent, false); if (vnodeHook = newProps.onVnodeBeforeUpdate) invokeVNodeHook(vnodeHook, parentComponent, n2, n1); if (dirs) invokeDirectiveHook(n2, n1, parentComponent, "beforeUpdate"); parentComponent && toggleRecurse(parentComponent, true); if (oldProps.innerHTML && newProps.innerHTML == null || oldProps.textContent && newProps.textContent == null) hostSetElementText(el, ""); if (dynamicChildren) patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds); else if (!optimized) patchChildren(n1, n2, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds, false); if (patchFlag > 0) { if (patchFlag & 16) patchProps(el, oldProps, newProps, parentComponent, namespace); else { if (patchFlag & 2) { if (oldProps.class !== newProps.class) hostPatchProp(el, "class", null, newProps.class, namespace); } if (patchFlag & 4) hostPatchProp(el, "style", oldProps.style, newProps.style, namespace); if (patchFlag & 8) { const propsToUpdate = n2.dynamicProps; for (let i = 0; i < propsToUpdate.length; i++) { const key = propsToUpdate[i]; const prev = oldProps[key]; const next = newProps[key]; if (next !== prev || key === "value") hostPatchProp(el, key, prev, next, namespace, parentComponent); } } } if (patchFlag & 1) { if (n1.children !== n2.children) hostSetElementText(el, n2.children); } } else if (!optimized && dynamicChildren == null) patchProps(el, oldProps, newProps, parentComponent, namespace); if ((vnodeHook = newProps.onVnodeUpdated) || dirs) queuePostRenderEffect(() => { vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1); dirs && invokeDirectiveHook(n2, n1, parentComponent, "updated"); }, parentSuspense); }; const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace, slotScopeIds) => { for (let i = 0; i < newChildren.length; i++) { const oldVNode = oldChildren[i]; const newVNode = newChildren[i]; patch(oldVNode, newVNode, oldVNode.el && (oldVNode.type === Fragment || !isSameVNodeType(oldVNode, newVNode) || oldVNode.shapeFlag & 198) ? hostParentNode(oldVNode.el) : fallbackContainer, null, parentComponent, parentSuspense, namespace, slotScopeIds, true); } }; const patchProps = (el, oldProps, newProps, parentComponent, namespace) => { if (oldProps !== newProps) { if (oldProps !== EMPTY_OBJ) { for (const key in oldProps) if (!isReservedProp(key) && !(key in newProps)) hostPatchProp(el, key, oldProps[key], null, namespace, parentComponent); } for (const key in newProps) { if (isReservedProp(key)) continue; const next = newProps[key]; const prev = oldProps[key]; if (next !== prev && key !== "value") hostPatchProp(el, key, prev, next, namespace, parentComponent); } if ("value" in newProps) hostPatchProp(el, "value", oldProps.value, newProps.value, namespace); } }; const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText(""); const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText(""); let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2; if (fragmentSlotScopeIds) slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds; if (n1 == null) { hostInsert(fragmentStartAnchor, container, anchor); hostInsert(fragmentEndAnchor, container, anchor); mountChildren(n2.children || [], container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); } else if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && n1.dynamicChildren && n1.dynamicChildren.length === dynamicChildren.length) { patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, namespace, slotScopeIds); if (n2.key != null || parentComponent && n2 === parentComponent.subTree) traverseStaticChildren(n1, n2, true); } else patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); }; const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { n2.slotScopeIds = slotScopeIds; if (n1 == null) if (n2.shapeFlag & 512) parentComponent.ctx.activate(n2, container, anchor, namespace, optimized); else mountComponent(n2, container, anchor, parentComponent, parentSuspense, namespace, optimized); else updateComponent(n1, n2, optimized); }; const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, namespace, optimized) => { const instance = initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense); if (isKeepAlive(initialVNode)) instance.ctx.renderer = internals; setupComponent(instance, false, optimized); if (instance.asyncDep) { parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect, optimized); if (!initialVNode.el) { const placeholder = instance.subTree = createVNode(Comment); processCommentNode(null, placeholder, container, anchor); initialVNode.placeholder = placeholder.el; } } else setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, namespace, optimized); }; const updateComponent = (n1, n2, optimized) => { const instance = n2.component = n1.component; if (shouldUpdateComponent(n1, n2, optimized)) if (instance.asyncDep && !instance.asyncResolved) { updateComponentPreRender(instance, n2, optimized); return; } else { instance.next = n2; instance.update(); } else { n2.el = n1.el; instance.vnode = n2; } }; const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, namespace, optimized) => { const componentUpdateFn = () => { if (!instance.isMounted) { let vnodeHook; const { el, props } = initialVNode; const { bm, m, parent, root, type } = instance; const isAsyncWrapperVNode = isAsyncWrapper(initialVNode); toggleRecurse(instance, false); if (bm) invokeArrayFns(bm); if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) invokeVNodeHook(vnodeHook, parent, initialVNode); toggleRecurse(instance, true); if (el && hydrateNode) { const hydrateSubTree = () => { instance.subTree = renderComponentRoot(instance); hydrateNode(el, instance.subTree, instance, parentSuspense, null); }; if (isAsyncWrapperVNode && type.__asyncHydrate) type.__asyncHydrate(el, instance, hydrateSubTree); else hydrateSubTree(); } else { if (root.ce && root.ce._hasShadowRoot()) root.ce._injectChildStyle(type, instance.parent ? instance.parent.type : void 0); const subTree = instance.subTree = renderComponentRoot(instance); patch(null, subTree, container, anchor, instance, parentSuspense, namespace); initialVNode.el = subTree.el; } if (m) queuePostRenderEffect(m, parentSuspense); if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) { const scopedInitialVNode = initialVNode; queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense); } if (initialVNode.shapeFlag & 256 || parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & 256) instance.a && queuePostRenderEffect(instance.a, parentSuspense); instance.isMounted = true; initialVNode = container = anchor = null; } else { let { next, bu, u, parent, vnode } = instance; { const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance); if (nonHydratedAsyncRoot) { if (next) { next.el = vnode.el; updateComponentPreRender(instance, next, optimized); } nonHydratedAsyncRoot.asyncDep.then(() => { queuePostRenderEffect(() => { if (!instance.isUnmounted) update(); }, parentSuspense); }); return; } } let originNext = next; let vnodeHook; toggleRecurse(instance, false); if (next) { next.el = vnode.el; updateComponentPreRender(instance, next, optimized); } else next = vnode; if (bu) invokeArrayFns(bu); if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) invokeVNodeHook(vnodeHook, parent, next, vnode); toggleRecurse(instance, true); const nextTree = renderComponentRoot(instance); const prevTree = instance.subTree; instance.subTree = nextTree; patch(prevTree, nextTree, hostParentNode(prevTree.el), getNextHostNode(prevTree), instance, parentSuspense, namespace); next.el = nextTree.el; if (originNext === null) updateHOCHostEl(instance, nextTree.el); if (u) queuePostRenderEffect(u, parentSuspense); if (vnodeHook = next.props && next.props.onVnodeUpdated) queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense); } }; instance.scope.on(); const effect = instance.effect = new ReactiveEffect(componentUpdateFn); instance.scope.off(); const update = instance.update = effect.run.bind(effect); const job = instance.job = effect.runIfDirty.bind(effect); job.i = instance; job.id = instance.uid; effect.scheduler = () => queueJob(job); toggleRecurse(instance, true); update(); }; const updateComponentPreRender = (instance, nextVNode, optimized) => { nextVNode.component = instance; const prevProps = instance.vnode.props; instance.vnode = nextVNode; instance.next = null; updateProps(instance, nextVNode.props, prevProps, optimized); updateSlots(instance, nextVNode.children, optimized); pauseTracking(); flushPreFlushCbs(instance); resetTracking(); }; const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized = false) => { const c1 = n1 && n1.children; const prevShapeFlag = n1 ? n1.shapeFlag : 0; const c2 = n2.children; const { patchFlag, shapeFlag } = n2; if (patchFlag > 0) { if (patchFlag & 128) { patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); return; } else if (patchFlag & 256) { patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); return; } } if (shapeFlag & 8) { if (prevShapeFlag & 16) unmountChildren(c1, parentComponent, parentSuspense); if (c2 !== c1) hostSetElementText(container, c2); } else if (prevShapeFlag & 16) if (shapeFlag & 16) patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); else unmountChildren(c1, parentComponent, parentSuspense, true); else { if (prevShapeFlag & 8) hostSetElementText(container, ""); if (shapeFlag & 16) mountChildren(c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); } }; const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { c1 = c1 || EMPTY_ARR; c2 = c2 || EMPTY_ARR; const oldLength = c1.length; const newLength = c2.length; const commonLength = Math.min(oldLength, newLength); let i; for (i = 0; i < commonLength; i++) { const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); } if (oldLength > newLength) unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength); else mountChildren(c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, commonLength); }; const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { let i = 0; const l2 = c2.length; let e1 = c1.length - 1; let e2 = l2 - 1; while (i <= e1 && i <= e2) { const n1 = c1[i]; const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); if (isSameVNodeType(n1, n2)) patch(n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); else break; i++; } while (i <= e1 && i <= e2) { const n1 = c1[e1]; const n2 = c2[e2] = optimized ? cloneIfMounted(c2[e2]) : normalizeVNode(c2[e2]); if (isSameVNodeType(n1, n2)) patch(n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); else break; e1--; e2--; } if (i > e1) { if (i <= e2) { const nextPos = e2 + 1; const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor; while (i <= e2) { patch(null, c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]), container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); i++; } } } else if (i > e2) while (i <= e1) { unmount(c1[i], parentComponent, parentSuspense, true); i++; } else { const s1 = i; const s2 = i; const keyToNewIndexMap = /* @__PURE__ */ new Map(); for (i = s2; i <= e2; i++) { const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); if (nextChild.key != null) keyToNewIndexMap.set(nextChild.key, i); } let j; let patched = 0; const toBePatched = e2 - s2 + 1; let moved = false; let maxNewIndexSoFar = 0; const newIndexToOldIndexMap = new Array(toBePatched); for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0; for (i = s1; i <= e1; i++) { const prevChild = c1[i]; if (patched >= toBePatched) { unmount(prevChild, parentComponent, parentSuspense, true); continue; } let newIndex; if (prevChild.key != null) newIndex = keyToNewIndexMap.get(prevChild.key); else for (j = s2; j <= e2; j++) if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j])) { newIndex = j; break; } if (newIndex === void 0) unmount(prevChild, parentComponent, parentSuspense, true); else { newIndexToOldIndexMap[newIndex - s2] = i + 1; if (newIndex >= maxNewIndexSoFar) maxNewIndexSoFar = newIndex; else moved = true; patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); patched++; } } const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : EMPTY_ARR; j = increasingNewIndexSequence.length - 1; for (i = toBePatched - 1; i >= 0; i--) { const nextIndex = s2 + i; const nextChild = c2[nextIndex]; const anchorVNode = c2[nextIndex + 1]; const anchor = nextIndex + 1 < l2 ? anchorVNode.el || resolveAsyncComponentPlaceholder(anchorVNode) : parentAnchor; if (newIndexToOldIndexMap[i] === 0) patch(null, nextChild, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); else if (moved) if (j < 0 || i !== increasingNewIndexSequence[j]) move(nextChild, container, anchor, 2); else j--; } } }; const move = (vnode, container, anchor, moveType, parentSuspense = null) => { const { el, type, transition, children, shapeFlag } = vnode; if (shapeFlag & 6) { move(vnode.component.subTree, container, anchor, moveType); return; } if (shapeFlag & 128) { vnode.suspense.move(container, anchor, moveType); return; } if (shapeFlag & 64) { type.move(vnode, container, anchor, internals); return; } if (type === Fragment) { hostInsert(el, container, anchor); for (let i = 0; i < children.length; i++) move(children[i], container, anchor, moveType); hostInsert(vnode.anchor, container, anchor); return; } if (type === Static) { moveStaticNode(vnode, container, anchor); return; } if (moveType !== 2 && shapeFlag & 1 && transition) if (moveType === 0) { transition.beforeEnter(el); hostInsert(el, container, anchor); queuePostRenderEffect(() => transition.enter(el), parentSuspense); } else { const { leave, delayLeave, afterLeave } = transition; const remove2 = () => { if (vnode.ctx.isUnmounted) hostRemove(el); else hostInsert(el, container, anchor); }; const performLeave = () => { if (el._isLeaving) el[leaveCbKey](true); leave(el, () => { remove2(); afterLeave && afterLeave(); }); }; if (delayLeave) delayLeave(el, remove2, performLeave); else performLeave(); } else hostInsert(el, container, anchor); }; const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => { const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs, cacheIndex, memo } = vnode; if (patchFlag === -2) optimized = false; if (ref != null) { pauseTracking(); setRef(ref, null, parentSuspense, vnode, true); resetTracking(); } if (cacheIndex != null) parentComponent.renderCache[cacheIndex] = void 0; if (shapeFlag & 256) { parentComponent.ctx.deactivate(vnode); return; } const shouldInvokeDirs = shapeFlag & 1 && dirs; const shouldInvokeVnodeHook = !isAsyncWrapper(vnode); let vnodeHook; if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) invokeVNodeHook(vnodeHook, parentComponent, vnode); if (shapeFlag & 6) unmountComponent(vnode.component, parentSuspense, doRemove); else { if (shapeFlag & 128) { vnode.suspense.unmount(parentSuspense, doRemove); return; } if (shouldInvokeDirs) invokeDirectiveHook(vnode, null, parentComponent, "beforeUnmount"); if (shapeFlag & 64) vnode.type.remove(vnode, parentComponent, parentSuspense, internals, doRemove); else if (dynamicChildren && !dynamicChildren.hasOnce && (type !== Fragment || patchFlag > 0 && patchFlag & 64)) unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true); else if (type === Fragment && patchFlag & 384 || !optimized && shapeFlag & 16) unmountChildren(children, parentComponent, parentSuspense); if (doRemove) remove(vnode); } const shouldInvalidateMemo = memo != null && cacheIndex == null; if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs || shouldInvalidateMemo) queuePostRenderEffect(() => { vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, "unmounted"); if (shouldInvalidateMemo) vnode.el = null; }, parentSuspense); }; const remove = (vnode) => { const { type, el, anchor, transition } = vnode; if (type === Fragment) { removeFragment(el, anchor); return; } if (type === Static) { removeStaticNode(vnode); return; } const performRemove = () => { hostRemove(el); if (transition && !transition.persisted && transition.afterLeave) transition.afterLeave(); }; if (vnode.shapeFlag & 1 && transition && !transition.persisted) { const { leave, delayLeave } = transition; const performLeave = () => leave(el, performRemove); if (delayLeave) delayLeave(vnode.el, performRemove, performLeave); else performLeave(); } else performRemove(); }; const removeFragment = (cur, end) => { let next; while (cur !== end) { next = hostNextSibling(cur); hostRemove(cur); cur = next; } hostRemove(end); }; const unmountComponent = (instance, parentSuspense, doRemove) => { const { bum, scope, job, subTree, um, m, a } = instance; invalidateMount(m); invalidateMount(a); if (bum) invokeArrayFns(bum); scope.stop(); if (job) { job.flags |= 8; unmount(subTree, instance, parentSuspense, doRemove); } if (um) queuePostRenderEffect(um, parentSuspense); queuePostRenderEffect(() => { instance.isUnmounted = true; }, parentSuspense); }; const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => { for (let i = start; i < children.length; i++) unmount(children[i], parentComponent, parentSuspense, doRemove, optimized); }; const getNextHostNode = (vnode) => { if (vnode.shapeFlag & 6) return getNextHostNode(vnode.component.subTree); if (vnode.shapeFlag & 128) return vnode.suspense.next(); const el = hostNextSibling(vnode.anchor || vnode.el); const teleportEnd = el && el[TeleportEndKey]; return teleportEnd ? hostNextSibling(teleportEnd) : el; }; let isFlushing = false; const render = (vnode, container, namespace) => { let instance; if (vnode == null) { if (container._vnode) { unmount(container._vnode, null, null, true); instance = container._vnode.component; } } else patch(container._vnode || null, vnode, container, null, null, null, namespace); container._vnode = vnode; if (!isFlushing) { isFlushing = true; flushPreFlushCbs(instance); flushPostFlushCbs(); isFlushing = false; } }; const internals = { p: patch, um: unmount, m: move, r: remove, mt: mountComponent, mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, n: getNextHostNode, o: options }; let hydrate; let hydrateNode; if (createHydrationFns) [hydrate, hydrateNode] = createHydrationFns(internals); return { render, hydrate, createApp: createAppAPI(render, hydrate) }; } function resolveChildrenNamespace({ type, props }, currentNamespace) { return currentNamespace === "svg" && type === "foreignObject" || currentNamespace === "mathml" && type === "annotation-xml" && props && props.encoding && props.encoding.includes("html") ? void 0 : currentNamespace; } function toggleRecurse({ effect, job }, allowed) { if (allowed) { effect.flags |= 32; job.flags |= 4; } else { effect.flags &= -33; job.flags &= -5; } } function needTransition(parentSuspense, transition) { return (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted; } function traverseStaticChildren(n1, n2, shallow = false) { const ch1 = n1.children; const ch2 = n2.children; if (isArray(ch1) && isArray(ch2)) for (let i = 0; i < ch1.length; i++) { const c1 = ch1[i]; let c2 = ch2[i]; if (c2.shapeFlag & 1 && !c2.dynamicChildren) { if (c2.patchFlag <= 0 || c2.patchFlag === 32) { c2 = ch2[i] = cloneIfMounted(ch2[i]); c2.el = c1.el; } if (!shallow && c2.patchFlag !== -2) traverseStaticChildren(c1, c2); } if (c2.type === Text) { if (c2.patchFlag === -1) c2 = ch2[i] = cloneIfMounted(c2); c2.el = c1.el; } if (c2.type === Comment && !c2.el) c2.el = c1.el; } } function getSequence(arr) { const p = arr.slice(); const result = [0]; let i, j, u, v, c; const len = arr.length; for (i = 0; i < len; i++) { const arrI = arr[i]; if (arrI !== 0) { j = result[result.length - 1]; if (arr[j] < arrI) { p[i] = j; result.push(i); continue; } u = 0; v = result.length - 1; while (u < v) { c = u + v >> 1; if (arr[result[c]] < arrI) u = c + 1; else v = c; } if (arrI < arr[result[u]]) { if (u > 0) p[i] = result[u - 1]; result[u] = i; } } } u = result.length; v = result[u - 1]; while (u-- > 0) { result[u] = v; v = p[v]; } return result; } function locateNonHydratedAsyncRoot(instance) { const subComponent = instance.subTree.component; if (subComponent) if (subComponent.asyncDep && !subComponent.asyncResolved) return subComponent; else return locateNonHydratedAsyncRoot(subComponent); } function invalidateMount(hooks) { if (hooks) for (let i = 0; i < hooks.length; i++) hooks[i].flags |= 8; } function resolveAsyncComponentPlaceholder(anchorVnode) { if (anchorVnode.placeholder) return anchorVnode.placeholder; const instance = anchorVnode.component; if (instance) return resolveAsyncComponentPlaceholder(instance.subTree); return null; } var isSuspense = (type) => type.__isSuspense; function queueEffectWithSuspense(fn, suspense) { if (suspense && suspense.pendingBranch) if (isArray(fn)) suspense.effects.push(...fn); else suspense.effects.push(fn); else queuePostFlushCb(fn); } var Fragment = /* @__PURE__ */ Symbol.for("v-fgt"); var Text = /* @__PURE__ */ Symbol.for("v-txt"); var Comment = /* @__PURE__ */ Symbol.for("v-cmt"); var Static = /* @__PURE__ */ Symbol.for("v-stc"); var blockStack = []; var currentBlock = null; function openBlock(disableTracking = false) { blockStack.push(currentBlock = disableTracking ? null : []); } function closeBlock() { blockStack.pop(); currentBlock = blockStack[blockStack.length - 1] || null; } var isBlockTreeEnabled = 1; function setBlockTracking(value, inVOnce = false) { isBlockTreeEnabled += value; if (value < 0 && currentBlock && inVOnce) currentBlock.hasOnce = true; } function setupBlock(vnode) { vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null; closeBlock(); if (isBlockTreeEnabled > 0 && currentBlock) currentBlock.push(vnode); return vnode; } function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) { return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true)); } function createBlock(type, props, children, patchFlag, dynamicProps) { return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true)); } function isVNode(value) { return value ? value.__v_isVNode === true : false; } function isSameVNodeType(n1, n2) { return n1.type === n2.type && n1.key === n2.key; } var normalizeKey = ({ key }) => key != null ? key : null; var normalizeRef = ({ ref, ref_key, ref_for }) => { if (typeof ref === "number") ref = "" + ref; return ref != null ? isString$1(ref) || /* @__PURE__ */ isRef(ref) || isFunction$2(ref) ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for } : ref : null; }; function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1, isBlockNode = false, needFullChildrenNormalization = false) { const vnode = { __v_isVNode: true, __v_skip: true, type, props, key: props && normalizeKey(props), ref: props && normalizeRef(props), scopeId: currentScopeId, slotScopeIds: null, children, component: null, suspense: null, ssContent: null, ssFallback: null, dirs: null, transition: null, el: null, anchor: null, target: null, targetStart: null, targetAnchor: null, staticCount: 0, shapeFlag, patchFlag, dynamicProps, dynamicChildren: null, appContext: null, ctx: currentRenderingInstance }; if (needFullChildrenNormalization) { normalizeChildren(vnode, children); if (shapeFlag & 128) type.normalize(vnode); } else if (children) vnode.shapeFlag |= isString$1(children) ? 8 : 16; if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock && (vnode.patchFlag > 0 || shapeFlag & 6) && vnode.patchFlag !== 32) currentBlock.push(vnode); return vnode; } var createVNode = _createVNode; function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) { if (!type || type === NULL_DYNAMIC_COMPONENT) type = Comment; if (isVNode(type)) { const cloned = cloneVNode(type, props, true); if (children) normalizeChildren(cloned, children); if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) if (cloned.shapeFlag & 6) currentBlock[currentBlock.indexOf(type)] = cloned; else currentBlock.push(cloned); cloned.patchFlag = -2; return cloned; } if (isClassComponent(type)) type = type.__vccOpts; if (props) { props = guardReactiveProps(props); let { class: klass, style } = props; if (klass && !isString$1(klass)) props.class = normalizeClass(klass); if (isObject$2(style)) { if (/* @__PURE__ */ isProxy(style) && !isArray(style)) style = extend({}, style); props.style = normalizeStyle(style); } } const shapeFlag = isString$1(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : isObject$2(type) ? 4 : isFunction$2(type) ? 2 : 0; return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true); } function guardReactiveProps(props) { if (!props) return null; return /* @__PURE__ */ isProxy(props) || isInternalObject(props) ? extend({}, props) : props; } function cloneVNode(vnode, extraProps, mergeRef = false, cloneTransition = false) { const { props, ref, patchFlag, children, transition } = vnode; const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props; const cloned = { __v_isVNode: true, __v_skip: true, type: vnode.type, props: mergedProps, key: mergedProps && normalizeKey(mergedProps), ref: extraProps && extraProps.ref ? mergeRef && ref ? isArray(ref) ? ref.concat(normalizeRef(extraProps)) : [ref, normalizeRef(extraProps)] : normalizeRef(extraProps) : ref, scopeId: vnode.scopeId, slotScopeIds: vnode.slotScopeIds, children, target: vnode.target, targetStart: vnode.targetStart, targetAnchor: vnode.targetAnchor, staticCount: vnode.staticCount, shapeFlag: vnode.shapeFlag, patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag, dynamicProps: vnode.dynamicProps, dynamicChildren: vnode.dynamicChildren, appContext: vnode.appContext, dirs: vnode.dirs, transition, component: vnode.component, suspense: vnode.suspense, ssContent: vnode.ssContent && cloneVNode(vnode.ssContent), ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback), placeholder: vnode.placeholder, el: vnode.el, anchor: vnode.anchor, ctx: vnode.ctx, ce: vnode.ce }; if (transition && cloneTransition) setTransitionHooks(cloned, transition.clone(cloned)); return cloned; } function createTextVNode(text = " ", flag = 0) { return createVNode(Text, null, text, flag); } function createCommentVNode(text = "", asBlock = false) { return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text); } function normalizeVNode(child) { if (child == null || typeof child === "boolean") return createVNode(Comment); else if (isArray(child)) return createVNode(Fragment, null, child.slice()); else if (isVNode(child)) return cloneIfMounted(child); else return createVNode(Text, null, String(child)); } function cloneIfMounted(child) { return child.el === null && child.patchFlag !== -1 || child.memo ? child : cloneVNode(child); } function normalizeChildren(vnode, children) { let type = 0; const { shapeFlag } = vnode; if (children == null) children = null; else if (isArray(children)) type = 16; else if (typeof children === "object") if (shapeFlag & 65) { const slot = children.default; if (slot) { slot._c && (slot._d = false); normalizeChildren(vnode, slot()); slot._c && (slot._d = true); } return; } else { type = 32; const slotFlag = children._; if (!slotFlag && !isInternalObject(children)) children._ctx = currentRenderingInstance; else if (slotFlag === 3 && currentRenderingInstance) if (currentRenderingInstance.slots._ === 1) children._ = 1; else { children._ = 2; vnode.patchFlag |= 1024; } } else if (isFunction$2(children)) { children = { default: children, _ctx: currentRenderingInstance }; type = 32; } else { children = String(children); if (shapeFlag & 64) { type = 16; children = [createTextVNode(children)]; } else type = 8; } vnode.children = children; vnode.shapeFlag |= type; } function mergeProps(...args) { const ret = {}; for (let i = 0; i < args.length; i++) { const toMerge = args[i]; for (const key in toMerge) if (key === "class") { if (ret.class !== toMerge.class) ret.class = normalizeClass([ret.class, toMerge.class]); } else if (key === "style") ret.style = normalizeStyle([ret.style, toMerge.style]); else if (isOn(key)) { const existing = ret[key]; const incoming = toMerge[key]; if (incoming && existing !== incoming && !(isArray(existing) && existing.includes(incoming))) ret[key] = existing ? [].concat(existing, incoming) : incoming; else if (incoming == null && existing == null && !isModelListener(key)) ret[key] = incoming; } else if (key !== "") ret[key] = toMerge[key]; } return ret; } function invokeVNodeHook(hook, instance, vnode, prevVNode = null) { callWithAsyncErrorHandling(hook, instance, 7, [vnode, prevVNode]); } var emptyAppContext = createAppContext(); var uid = 0; function createComponentInstance(vnode, parent, suspense) { const type = vnode.type; const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext; const instance = { uid: uid++, vnode, type, parent, appContext, root: null, next: null, subTree: null, effect: null, update: null, job: null, scope: new EffectScope(true), render: null, proxy: null, exposed: null, exposeProxy: null, withProxy: null, provides: parent ? parent.provides : Object.create(appContext.provides), ids: parent ? parent.ids : [ "", 0, 0 ], accessCache: null, renderCache: [], components: null, directives: null, propsOptions: normalizePropsOptions(type, appContext), emitsOptions: normalizeEmitsOptions(type, appContext), emit: null, emitted: null, propsDefaults: EMPTY_OBJ, inheritAttrs: type.inheritAttrs, ctx: EMPTY_OBJ, data: EMPTY_OBJ, props: EMPTY_OBJ, attrs: EMPTY_OBJ, slots: EMPTY_OBJ, refs: EMPTY_OBJ, setupState: EMPTY_OBJ, setupContext: null, suspense, suspenseId: suspense ? suspense.pendingId : 0, asyncDep: null, asyncResolved: false, isMounted: false, isUnmounted: false, isDeactivated: false, bc: null, c: null, bm: null, m: null, bu: null, u: null, um: null, bum: null, da: null, a: null, rtg: null, rtc: null, ec: null, sp: null }; instance.ctx = { _: instance }; instance.root = parent ? parent.root : instance; instance.emit = emit.bind(null, instance); if (vnode.ce) vnode.ce(instance); return instance; } var currentInstance = null; var getCurrentInstance = () => currentInstance || currentRenderingInstance; var internalSetCurrentInstance; var setInSSRSetupState; { const g = getGlobalThis(); const registerGlobalSetter = (key, setter) => { let setters; if (!(setters = g[key])) setters = g[key] = []; setters.push(setter); return (v) => { if (setters.length > 1) setters.forEach((set) => set(v)); else setters[0](v); }; }; internalSetCurrentInstance = registerGlobalSetter(`__VUE_INSTANCE_SETTERS__`, (v) => currentInstance = v); setInSSRSetupState = registerGlobalSetter(`__VUE_SSR_SETTERS__`, (v) => isInSSRComponentSetup = v); } var setCurrentInstance = (instance) => { const prev = currentInstance; internalSetCurrentInstance(instance); instance.scope.on(); return () => { instance.scope.off(); internalSetCurrentInstance(prev); }; }; var unsetCurrentInstance = () => { currentInstance && currentInstance.scope.off(); internalSetCurrentInstance(null); }; function isStatefulComponent(instance) { return instance.vnode.shapeFlag & 4; } var isInSSRComponentSetup = false; function setupComponent(instance, isSSR = false, optimized = false) { isSSR && setInSSRSetupState(isSSR); const { props, children } = instance.vnode; const isStateful = isStatefulComponent(instance); initProps(instance, props, isStateful, isSSR); initSlots(instance, children, optimized || isSSR); const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0; isSSR && setInSSRSetupState(false); return setupResult; } function setupStatefulComponent(instance, isSSR) { const Component = instance.type; instance.accessCache = /* @__PURE__ */ Object.create(null); instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers); const { setup } = Component; if (setup) { pauseTracking(); const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null; const reset = setCurrentInstance(instance); const setupResult = callWithErrorHandling(setup, instance, 0, [instance.props, setupContext]); const isAsyncSetup = isPromise(setupResult); resetTracking(); reset(); if ((isAsyncSetup || instance.sp) && !isAsyncWrapper(instance)) markAsyncBoundary(instance); if (isAsyncSetup) { setupResult.then(unsetCurrentInstance, unsetCurrentInstance); if (isSSR) return setupResult.then((resolvedResult) => { handleSetupResult(instance, resolvedResult, isSSR); }).catch((e) => { handleError(e, instance, 0); }); else instance.asyncDep = setupResult; } else handleSetupResult(instance, setupResult, isSSR); } else finishComponentSetup(instance, isSSR); } function handleSetupResult(instance, setupResult, isSSR) { if (isFunction$2(setupResult)) if (instance.type.__ssrInlineRender) instance.ssrRender = setupResult; else instance.render = setupResult; else if (isObject$2(setupResult)) instance.setupState = proxyRefs(setupResult); finishComponentSetup(instance, isSSR); } var compile; var installWithProxy; function finishComponentSetup(instance, isSSR, skipOptions) { const Component = instance.type; if (!instance.render) { if (!isSSR && compile && !Component.render) { const template = Component.template || resolveMergedOptions(instance).template; if (template) { const { isCustomElement, compilerOptions } = instance.appContext.config; const { delimiters, compilerOptions: componentCompilerOptions } = Component; Component.render = compile(template, extend(extend({ isCustomElement, delimiters }, compilerOptions), componentCompilerOptions)); } } instance.render = Component.render || NOOP; if (installWithProxy) installWithProxy(instance); } { const reset = setCurrentInstance(instance); pauseTracking(); try { applyOptions(instance); } finally { resetTracking(); reset(); } } } var attrsProxyHandlers = { get(target, key) { track(target, "get", ""); return target[key]; } }; function createSetupContext(instance) { const expose = (exposed) => { instance.exposed = exposed || {}; }; return { attrs: new Proxy(instance.attrs, attrsProxyHandlers), slots: instance.slots, emit: instance.emit, expose }; } function getComponentPublicInstance(instance) { if (instance.exposed) return instance.exposeProxy || (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), { get(target, key) { if (key in target) return target[key]; else if (key in publicPropertiesMap) return publicPropertiesMap[key](instance); }, has(target, key) { return key in target || key in publicPropertiesMap; } })); else return instance.proxy; } function getComponentName$1(Component, includeInferred = true) { return isFunction$2(Component) ? Component.displayName || Component.name : Component.name || includeInferred && Component.__name; } function isClassComponent(value) { return isFunction$2(value) && "__vccOpts" in value; } var computed = (getterOrOptions, debugOptions) => { return /* @__PURE__ */ computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup); }; function h$3(type, propsOrChildren, children) { try { setBlockTracking(-1); const l = arguments.length; if (l === 2) if (isObject$2(propsOrChildren) && !isArray(propsOrChildren)) { if (isVNode(propsOrChildren)) return createVNode(type, null, [propsOrChildren]); return createVNode(type, propsOrChildren); } else return createVNode(type, null, propsOrChildren); else { if (l > 3) children = Array.prototype.slice.call(arguments, 2); else if (l === 3 && isVNode(children)) children = [children]; return createVNode(type, propsOrChildren, children); } } finally { setBlockTracking(1); } } var version$1 = "3.5.33"; //#endregion //#region ../../node_modules/.pnpm/@vue+runtime-dom@3.5.33/node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js /** * @vue/runtime-dom v3.5.33 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT **/ var policy = void 0; var tt$2 = typeof window !== "undefined" && window.trustedTypes; if (tt$2) try { policy = /* @__PURE__ */ tt$2.createPolicy("vue", { createHTML: (val) => val }); } catch (e) {} var unsafeToTrustedHTML = policy ? (val) => policy.createHTML(val) : (val) => val; var svgNS = "http://www.w3.org/2000/svg"; var mathmlNS = "http://www.w3.org/1998/Math/MathML"; var doc = typeof document !== "undefined" ? document : null; var templateContainer = doc && /* @__PURE__ */ doc.createElement("template"); var nodeOps = { insert: (child, parent, anchor) => { parent.insertBefore(child, anchor || null); }, remove: (child) => { const parent = child.parentNode; if (parent) parent.removeChild(child); }, createElement: (tag, namespace, is, props) => { const el = namespace === "svg" ? doc.createElementNS(svgNS, tag) : namespace === "mathml" ? doc.createElementNS(mathmlNS, tag) : is ? doc.createElement(tag, { is }) : doc.createElement(tag); if (tag === "select" && props && props.multiple != null) el.setAttribute("multiple", props.multiple); return el; }, createText: (text) => doc.createTextNode(text), createComment: (text) => doc.createComment(text), setText: (node, text) => { node.nodeValue = text; }, setElementText: (el, text) => { el.textContent = text; }, parentNode: (node) => node.parentNode, nextSibling: (node) => node.nextSibling, querySelector: (selector) => doc.querySelector(selector), setScopeId(el, id) { el.setAttribute(id, ""); }, insertStaticContent(content, parent, anchor, namespace, start, end) { const before = anchor ? anchor.previousSibling : parent.lastChild; if (start && (start === end || start.nextSibling)) while (true) { parent.insertBefore(start.cloneNode(true), anchor); if (start === end || !(start = start.nextSibling)) break; } else { templateContainer.innerHTML = unsafeToTrustedHTML(namespace === "svg" ? `${content}` : namespace === "mathml" ? `${content}` : content); const template = templateContainer.content; if (namespace === "svg" || namespace === "mathml") { const wrapper = template.firstChild; while (wrapper.firstChild) template.appendChild(wrapper.firstChild); template.removeChild(wrapper); } parent.insertBefore(template, anchor); } return [before ? before.nextSibling : parent.firstChild, anchor ? anchor.previousSibling : parent.lastChild]; } }; var vtcKey = /* @__PURE__ */ Symbol("_vtc"); function patchClass(el, value, isSVG) { const transitionClasses = el[vtcKey]; if (transitionClasses) value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(" "); if (value == null) el.removeAttribute("class"); else if (isSVG) el.setAttribute("class", value); else el.className = value; } var vShowOriginalDisplay = /* @__PURE__ */ Symbol("_vod"); var vShowHidden = /* @__PURE__ */ Symbol("_vsh"); var CSS_VAR_TEXT = /* @__PURE__ */ Symbol(""); var displayRE = /(?:^|;)\s*display\s*:/; function patchStyle(el, prev, next) { const style = el.style; const isCssString = isString$1(next); let hasControlledDisplay = false; if (next && !isCssString) { if (prev) if (!isString$1(prev)) { for (const key in prev) if (next[key] == null) setStyle(style, key, ""); } else for (const prevStyle of prev.split(";")) { const key = prevStyle.slice(0, prevStyle.indexOf(":")).trim(); if (next[key] == null) setStyle(style, key, ""); } for (const key in next) { if (key === "display") hasControlledDisplay = true; const value = next[key]; if (value != null) { if (!shouldPreserveTextareaResizeStyle(el, key, !isString$1(prev) && prev ? prev[key] : void 0, value)) setStyle(style, key, value); } else setStyle(style, key, ""); } } else if (isCssString) { if (prev !== next) { const cssVarText = style[CSS_VAR_TEXT]; if (cssVarText) next += ";" + cssVarText; style.cssText = next; hasControlledDisplay = displayRE.test(next); } } else if (prev) el.removeAttribute("style"); if (vShowOriginalDisplay in el) { el[vShowOriginalDisplay] = hasControlledDisplay ? style.display : ""; if (el[vShowHidden]) style.display = "none"; } } var importantRE = /\s*!important$/; function setStyle(style, name, val) { if (isArray(val)) val.forEach((v) => setStyle(style, name, v)); else { if (val == null) val = ""; if (name.startsWith("--")) style.setProperty(name, val); else { const prefixed = autoPrefix(style, name); if (importantRE.test(val)) style.setProperty(hyphenate$2(prefixed), val.replace(importantRE, ""), "important"); else style[prefixed] = val; } } } var prefixes = [ "Webkit", "Moz", "ms" ]; var prefixCache = {}; function autoPrefix(style, rawName) { const cached = prefixCache[rawName]; if (cached) return cached; let name = camelize$2(rawName); if (name !== "filter" && name in style) return prefixCache[rawName] = name; name = capitalize(name); for (let i = 0; i < prefixes.length; i++) { const prefixed = prefixes[i] + name; if (prefixed in style) return prefixCache[rawName] = prefixed; } return rawName; } function shouldPreserveTextareaResizeStyle(el, key, prev, next) { return el.tagName === "TEXTAREA" && (key === "width" || key === "height") && isString$1(next) && prev === next; } var xlinkNS = "http://www.w3.org/1999/xlink"; function patchAttr(el, key, value, isSVG, instance, isBoolean = isSpecialBooleanAttr(key)) { if (isSVG && key.startsWith("xlink:")) if (value == null) el.removeAttributeNS(xlinkNS, key.slice(6, key.length)); else el.setAttributeNS(xlinkNS, key, value); else if (value == null || isBoolean && !includeBooleanAttr(value)) el.removeAttribute(key); else el.setAttribute(key, isBoolean ? "" : isSymbol(value) ? String(value) : value); } function patchDOMProp(el, key, value, parentComponent, attrName) { if (key === "innerHTML" || key === "textContent") { if (value != null) el[key] = key === "innerHTML" ? unsafeToTrustedHTML(value) : value; return; } const tag = el.tagName; if (key === "value" && tag !== "PROGRESS" && !tag.includes("-")) { const oldValue = tag === "OPTION" ? el.getAttribute("value") || "" : el.value; const newValue = value == null ? el.type === "checkbox" ? "on" : "" : String(value); if (oldValue !== newValue || !("_value" in el)) el.value = newValue; if (value == null) el.removeAttribute(key); el._value = value; return; } let needRemove = false; if (value === "" || value == null) { const type = typeof el[key]; if (type === "boolean") value = includeBooleanAttr(value); else if (value == null && type === "string") { value = ""; needRemove = true; } else if (type === "number") { value = 0; needRemove = true; } } try { el[key] = value; } catch (e) {} needRemove && el.removeAttribute(attrName || key); } function addEventListener$1(el, event, handler, options) { el.addEventListener(event, handler, options); } function removeEventListener$1(el, event, handler, options) { el.removeEventListener(event, handler, options); } var veiKey = /* @__PURE__ */ Symbol("_vei"); function patchEvent(el, rawName, prevValue, nextValue, instance = null) { const invokers = el[veiKey] || (el[veiKey] = {}); const existingInvoker = invokers[rawName]; if (nextValue && existingInvoker) existingInvoker.value = nextValue; else { const [name, options] = parseName(rawName); if (nextValue) addEventListener$1(el, name, invokers[rawName] = createInvoker(nextValue, instance), options); else if (existingInvoker) { removeEventListener$1(el, name, existingInvoker, options); invokers[rawName] = void 0; } } } var optionsModifierRE = /(?:Once|Passive|Capture)$/; function parseName(name) { let options; if (optionsModifierRE.test(name)) { options = {}; let m; while (m = name.match(optionsModifierRE)) { name = name.slice(0, name.length - m[0].length); options[m[0].toLowerCase()] = true; } } return [name[2] === ":" ? name.slice(3) : hyphenate$2(name.slice(2)), options]; } var cachedNow = 0; var p$2 = /* @__PURE__ */ Promise.resolve(); var getNow = () => cachedNow || (p$2.then(() => cachedNow = 0), cachedNow = Date.now()); function createInvoker(initialValue, instance) { const invoker = (e) => { if (!e._vts) e._vts = Date.now(); else if (e._vts <= invoker.attached) return; callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5, [e]); }; invoker.value = initialValue; invoker.attached = getNow(); return invoker; } function patchStopImmediatePropagation(e, value) { if (isArray(value)) { const originalStop = e.stopImmediatePropagation; e.stopImmediatePropagation = () => { originalStop.call(e); e._stopped = true; }; return value.map((fn) => (e2) => !e2._stopped && fn && fn(e2)); } else return value; } var isNativeOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 96 && key.charCodeAt(2) < 123; var patchProp = (el, key, prevValue, nextValue, namespace, parentComponent) => { const isSVG = namespace === "svg"; if (key === "class") patchClass(el, nextValue, isSVG); else if (key === "style") patchStyle(el, prevValue, nextValue); else if (isOn(key)) { if (!isModelListener(key)) patchEvent(el, key, prevValue, nextValue, parentComponent); } else if (key[0] === "." ? (key = key.slice(1), true) : key[0] === "^" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) { patchDOMProp(el, key, nextValue); if (!el.tagName.includes("-") && (key === "value" || key === "checked" || key === "selected")) patchAttr(el, key, nextValue, isSVG, parentComponent, key !== "value"); } else if (el._isVueCE && (shouldSetAsPropForVueCE(el, key) || el._def.__asyncLoader && (/[A-Z]/.test(key) || !isString$1(nextValue)))) patchDOMProp(el, camelize$2(key), nextValue, parentComponent, key); else { if (key === "true-value") el._trueValue = nextValue; else if (key === "false-value") el._falseValue = nextValue; patchAttr(el, key, nextValue, isSVG); } }; function shouldSetAsProp(el, key, value, isSVG) { if (isSVG) { if (key === "innerHTML" || key === "textContent") return true; if (key in el && isNativeOn(key) && isFunction$2(value)) return true; return false; } if (key === "spellcheck" || key === "draggable" || key === "translate" || key === "autocorrect") return false; if (key === "sandbox" && el.tagName === "IFRAME") return false; if (key === "form") return false; if (key === "list" && el.tagName === "INPUT") return false; if (key === "type" && el.tagName === "TEXTAREA") return false; if (key === "width" || key === "height") { const tag = el.tagName; if (tag === "IMG" || tag === "VIDEO" || tag === "CANVAS" || tag === "SOURCE") return false; } if (isNativeOn(key) && isString$1(value)) return false; return key in el; } function shouldSetAsPropForVueCE(el, key) { const props = el._def.props; if (!props) return false; const camelKey = camelize$2(key); return Array.isArray(props) ? props.some((prop) => camelize$2(prop) === camelKey) : Object.keys(props).some((prop) => camelize$2(prop) === camelKey); } var keyNames = { esc: "escape", space: " ", up: "arrow-up", left: "arrow-left", right: "arrow-right", down: "arrow-down", delete: "backspace" }; var withKeys = (fn, modifiers) => { const cache = fn._withKeys || (fn._withKeys = {}); const cacheKey = modifiers.join("."); return cache[cacheKey] || (cache[cacheKey] = ((event) => { if (!("key" in event)) return; const eventKey = hyphenate$2(event.key); if (modifiers.some((k) => k === eventKey || keyNames[k] === eventKey)) return fn(event); })); }; var rendererOptions = /* @__PURE__ */ extend({ patchProp }, nodeOps); var renderer; function ensureRenderer() { return renderer || (renderer = createRenderer(rendererOptions)); } var createApp = ((...args) => { const app = ensureRenderer().createApp(...args); const { mount } = app; app.mount = (containerOrSelector) => { const container = normalizeContainer(containerOrSelector); if (!container) return; const component = app._component; if (!isFunction$2(component) && !component.render && !component.template) component.template = container.innerHTML; if (container.nodeType === 1) container.textContent = ""; const proxy = mount(container, false, resolveRootNamespace(container)); if (container instanceof Element) { container.removeAttribute("v-cloak"); container.setAttribute("data-v-app", ""); } return proxy; }; return app; }); function resolveRootNamespace(container) { if (container instanceof SVGElement) return "svg"; if (typeof MathMLElement === "function" && container instanceof MathMLElement) return "mathml"; } function normalizeContainer(container) { if (isString$1(container)) return document.querySelector(container); return container; } //#endregion //#region ../../node_modules/.pnpm/pretty-bytes@6.1.1/node_modules/pretty-bytes/index.js var BYTE_UNITS = [ "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" ]; var BIBYTE_UNITS = [ "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" ]; var BIT_UNITS = [ "b", "kbit", "Mbit", "Gbit", "Tbit", "Pbit", "Ebit", "Zbit", "Ybit" ]; var BIBIT_UNITS = [ "b", "kibit", "Mibit", "Gibit", "Tibit", "Pibit", "Eibit", "Zibit", "Yibit" ]; var toLocaleString = (number, locale, options) => { let result = number; if (typeof locale === "string" || Array.isArray(locale)) result = number.toLocaleString(locale, options); else if (locale === true || options !== void 0) result = number.toLocaleString(void 0, options); return result; }; function prettyBytes(number, options) { if (!Number.isFinite(number)) throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`); options = { bits: false, binary: false, space: true, ...options }; const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS; const separator = options.space ? " " : ""; if (options.signed && number === 0) return ` 0${separator}${UNITS[0]}`; const isNegative = number < 0; const prefix = isNegative ? "-" : options.signed ? "+" : ""; if (isNegative) number = -number; let localeOptions; if (options.minimumFractionDigits !== void 0) localeOptions = { minimumFractionDigits: options.minimumFractionDigits }; if (options.maximumFractionDigits !== void 0) localeOptions = { maximumFractionDigits: options.maximumFractionDigits, ...localeOptions }; if (number < 1) return prefix + toLocaleString(number, options.locale, localeOptions) + separator + UNITS[0]; const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1); number /= (options.binary ? 1024 : 1e3) ** exponent; if (!localeOptions) number = number.toPrecision(3); const numberString = toLocaleString(Number(number), options.locale, localeOptions); const unit = UNITS[exponent]; return prefix + numberString + separator + unit; } //#endregion //#region ../send/frontend/src/lib/const.ts var CONTAINER_TYPE = { CONVERSATION: "CONVERSATION", FOLDER: "FOLDER" }; var POPUP_READY = "POPUP_READY"; var ALL_UPLOADS_COMPLETE = "ALL_UPLOADS_COMPLETE"; var ALL_UPLOADS_ABORTED = "ALL_UPLOADS_ABORTED"; var ONE_MB_IN_BYTES = 1e3 * 1e3; var MAX_FILE_SIZE = ONE_MB_IN_BYTES * 1e3 * 20; var MAX_FILE_SIZE_HUMAN_READABLE = prettyBytes(MAX_FILE_SIZE); var SPLIT_SIZE = 100 * ONE_MB_IN_BYTES; var BRIDGE_PING = "APP/PING"; var OIDC_USER = "TB/OIDC_USER"; var OIDC_TOKEN = "TB/OIDC_TOKEN"; var SIGN_IN = "SIGN_IN"; var SIGN_OUT = "SIGN_OUT"; var SEND_MESSAGE_TO_BRIDGE = "SEND_MESSAGE_TO_BRIDGE"; var STORAGE_KEY_AUTH = "STORAGE_KEY_AUTH"; var GET_PENDING_ADDON_TOKEN = "TB/GET_PENDING_ADDON_TOKEN"; //#endregion //#region ../send/frontend/src/lib/streams.ts var DEFAULT_CHUNK_SIZE = 1024 * 64; function readableToTransformController(controller, overrides) { return { enqueue: controller.enqueue.bind(controller), error: controller.error.bind(controller), terminate: () => {}, desiredSize: controller.desiredSize, ...overrides }; } function transformStream(readable, transformer, oncancel) { try { return readable.pipeThrough(new TransformStream(transformer)); } catch (e) { const reader = readable.getReader(); return new ReadableStream({ start(controller) { if (transformer.start) return transformer.start(readableToTransformController(controller)); }, async pull(controller) { let enqueued = false; while (!enqueued) { const data = await reader.read(); if (data.done) { if (transformer.flush) await transformer.flush(readableToTransformController(controller)); return controller.close(); } await transformer.transform(data.value, readableToTransformController(controller, { enqueue(d) { enqueued = true; controller.enqueue(d); } })); } }, cancel(reason) { readable.cancel(reason); if (oncancel) oncancel(reason); } }); } } var BlobStreamController = class { constructor(blob, size) { this.blob = blob; this.index = 0; this.chunkSize = size || DEFAULT_CHUNK_SIZE; } pull(controller) { return new Promise((resolve, reject) => { const bytesLeft = this.blob.size - this.index; if (bytesLeft <= 0) { controller.close(); return resolve(); } const size = Math.min(this.chunkSize, bytesLeft); const slice = this.blob.slice(this.index, this.index + size); const reader = new FileReader(); reader.onload = () => { if (reader.result instanceof ArrayBuffer) { controller.enqueue(new Uint8Array(reader.result)); resolve(); } }; reader.onerror = reject; reader.readAsArrayBuffer(slice); this.index += size; }); } }; function blobStream(blob, size) { return new ReadableStream(new BlobStreamController(blob, size)); } //#endregion //#region ../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js var require_base64_js = /* @__PURE__ */ __commonJSMin(((exports) => { exports.byteLength = byteLength; exports.toByteArray = toByteArray; exports.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } revLookup["-".charCodeAt(0)] = 62; revLookup["_".charCodeAt(0)] = 63; function getLens(b64) { var len = b64.length; if (len % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4"); var validLen = b64.indexOf("="); if (validLen === -1) validLen = len; var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; } function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function toByteArray(b64) { var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0; var len = placeHoldersLen > 0 ? validLen - 4 : validLen; var i; for (i = 0; i < len; i += 4) { tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; arr[curByte++] = tmp >> 16 & 255; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 2) { tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 1) { tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255); output.push(tripletToBase64(tmp)); } return output.join(""); } function fromByteArray(uint8) { var tmp; var len = uint8.length; var extraBytes = len % 3; var parts = []; var maxChunkLength = 16383; for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); if (extraBytes === 1) { tmp = uint8[len - 1]; parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); } return parts.join(""); } })); //#endregion //#region ../../node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js var require_ieee754 = /* @__PURE__ */ __commonJSMin(((exports) => { /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & (1 << -nBits) - 1; s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) e = 1 - eBias; else if (e === eMax) return m ? NaN : (s ? -1 : 1) * Infinity; else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) value += rt / c; else value += rt * Math.pow(2, 1 - eBias); if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8); e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; })); //#endregion //#region ../../node_modules/.pnpm/buffer@6.0.3/node_modules/buffer/index.js /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ var require_buffer = /* @__PURE__ */ __commonJSMin(((exports) => { var base64 = require_base64_js(); var ieee754 = require_ieee754(); var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; exports.Buffer = Buffer; exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; var K_MAX_LENGTH = 2147483647; exports.kMaxLength = K_MAX_LENGTH; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."); function typedArraySupport() { try { const arr = new Uint8Array(1); const proto = { foo: function() { return 42; } }; Object.setPrototypeOf(proto, Uint8Array.prototype); Object.setPrototypeOf(arr, proto); return arr.foo() === 42; } catch (e) { return false; } } Object.defineProperty(Buffer.prototype, "parent", { enumerable: true, get: function() { if (!Buffer.isBuffer(this)) return void 0; return this.buffer; } }); Object.defineProperty(Buffer.prototype, "offset", { enumerable: true, get: function() { if (!Buffer.isBuffer(this)) return void 0; return this.byteOffset; } }); function createBuffer(length) { if (length > K_MAX_LENGTH) throw new RangeError("The value \"" + length + "\" is invalid for option \"size\""); const buf = new Uint8Array(length); Object.setPrototypeOf(buf, Buffer.prototype); return buf; } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { if (typeof arg === "number") { if (typeof encodingOrOffset === "string") throw new TypeError("The \"string\" argument must be of type string. Received type number"); return allocUnsafe(arg); } return from(arg, encodingOrOffset, length); } Buffer.poolSize = 8192; function from(value, encodingOrOffset, length) { if (typeof value === "string") return fromString(value, encodingOrOffset); if (ArrayBuffer.isView(value)) return fromArrayView(value); if (value == null) throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value); if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) return fromArrayBuffer(value, encodingOrOffset, length); if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) return fromArrayBuffer(value, encodingOrOffset, length); if (typeof value === "number") throw new TypeError("The \"value\" argument must not be of type number. Received type number"); const valueOf = value.valueOf && value.valueOf(); if (valueOf != null && valueOf !== value) return Buffer.from(valueOf, encodingOrOffset, length); const b = fromObject(value); if (b) return b; if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") return Buffer.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value); } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function(value, encodingOrOffset, length) { return from(value, encodingOrOffset, length); }; Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); Object.setPrototypeOf(Buffer, Uint8Array); function assertSize(size) { if (typeof size !== "number") throw new TypeError("\"size\" argument must be of type number"); else if (size < 0) throw new RangeError("The value \"" + size + "\" is invalid for option \"size\""); } function alloc(size, fill, encoding) { assertSize(size); if (size <= 0) return createBuffer(size); if (fill !== void 0) return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); return createBuffer(size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function(size, fill, encoding) { return alloc(size, fill, encoding); }; function allocUnsafe(size) { assertSize(size); return createBuffer(size < 0 ? 0 : checked(size) | 0); } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function(size) { return allocUnsafe(size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function(size) { return allocUnsafe(size); }; function fromString(string, encoding) { if (typeof encoding !== "string" || encoding === "") encoding = "utf8"; if (!Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding); const length = byteLength(string, encoding) | 0; let buf = createBuffer(length); const actual = buf.write(string, encoding); if (actual !== length) buf = buf.slice(0, actual); return buf; } function fromArrayLike(array) { const length = array.length < 0 ? 0 : checked(array.length) | 0; const buf = createBuffer(length); for (let i = 0; i < length; i += 1) buf[i] = array[i] & 255; return buf; } function fromArrayView(arrayView) { if (isInstance(arrayView, Uint8Array)) { const copy = new Uint8Array(arrayView); return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); } return fromArrayLike(arrayView); } function fromArrayBuffer(array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) throw new RangeError("\"offset\" is outside of buffer bounds"); if (array.byteLength < byteOffset + (length || 0)) throw new RangeError("\"length\" is outside of buffer bounds"); let buf; if (byteOffset === void 0 && length === void 0) buf = new Uint8Array(array); else if (length === void 0) buf = new Uint8Array(array, byteOffset); else buf = new Uint8Array(array, byteOffset, length); Object.setPrototypeOf(buf, Buffer.prototype); return buf; } function fromObject(obj) { if (Buffer.isBuffer(obj)) { const len = checked(obj.length) | 0; const buf = createBuffer(len); if (buf.length === 0) return buf; obj.copy(buf, 0, 0, len); return buf; } if (obj.length !== void 0) { if (typeof obj.length !== "number" || numberIsNaN(obj.length)) return createBuffer(0); return fromArrayLike(obj); } if (obj.type === "Buffer" && Array.isArray(obj.data)) return fromArrayLike(obj.data); } function checked(length) { if (length >= K_MAX_LENGTH) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); return length | 0; } function SlowBuffer(length) { if (+length != length) length = 0; return Buffer.alloc(+length); } Buffer.isBuffer = function isBuffer(b) { return b != null && b._isBuffer === true && b !== Buffer.prototype; }; Buffer.compare = function compare(a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) throw new TypeError("The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array"); if (a === b) return 0; let x = a.length; let y = b.length; for (let i = 0, len = Math.min(x, y); i < len; ++i) if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case "hex": case "utf8": case "utf-8": case "ascii": case "latin1": case "binary": case "base64": case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!Array.isArray(list)) throw new TypeError("\"list\" argument must be an Array of Buffers"); if (list.length === 0) return Buffer.alloc(0); let i; if (length === void 0) { length = 0; for (i = 0; i < list.length; ++i) length += list[i].length; } const buffer = Buffer.allocUnsafe(length); let pos = 0; for (i = 0; i < list.length; ++i) { let buf = list[i]; if (isInstance(buf, Uint8Array)) if (pos + buf.length > buffer.length) { if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf); buf.copy(buffer, pos); } else Uint8Array.prototype.set.call(buffer, buf, pos); else if (!Buffer.isBuffer(buf)) throw new TypeError("\"list\" argument must be an Array of Buffers"); else buf.copy(buffer, pos); pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (Buffer.isBuffer(string)) return string.length; if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) return string.byteLength; if (typeof string !== "string") throw new TypeError("The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type " + typeof string); const len = string.length; const mustMatch = arguments.length > 2 && arguments[2] === true; if (!mustMatch && len === 0) return 0; let loweredCase = false; for (;;) switch (encoding) { case "ascii": case "latin1": case "binary": return len; case "utf8": case "utf-8": return utf8ToBytes(string).length; case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return len * 2; case "hex": return len >>> 1; case "base64": return base64ToBytes(string).length; default: if (loweredCase) return mustMatch ? -1 : utf8ToBytes(string).length; encoding = ("" + encoding).toLowerCase(); loweredCase = true; } } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { let loweredCase = false; if (start === void 0 || start < 0) start = 0; if (start > this.length) return ""; if (end === void 0 || end > this.length) end = this.length; if (end <= 0) return ""; end >>>= 0; start >>>= 0; if (end <= start) return ""; if (!encoding) encoding = "utf8"; while (true) switch (encoding) { case "hex": return hexSlice(this, start, end); case "utf8": case "utf-8": return utf8Slice(this, start, end); case "ascii": return asciiSlice(this, start, end); case "latin1": case "binary": return latin1Slice(this, start, end); case "base64": return base64Slice(this, start, end); case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); encoding = (encoding + "").toLowerCase(); loweredCase = true; } } Buffer.prototype._isBuffer = true; function swap(b, n, m) { const i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { const len = this.length; if (len % 2 !== 0) throw new RangeError("Buffer size must be a multiple of 16-bits"); for (let i = 0; i < len; i += 2) swap(this, i, i + 1); return this; }; Buffer.prototype.swap32 = function swap32() { const len = this.length; if (len % 4 !== 0) throw new RangeError("Buffer size must be a multiple of 32-bits"); for (let i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { const len = this.length; if (len % 8 !== 0) throw new RangeError("Buffer size must be a multiple of 64-bits"); for (let i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { const length = this.length; if (length === 0) return ""; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.toLocaleString = Buffer.prototype.toString; Buffer.prototype.equals = function equals(b) { if (!Buffer.isBuffer(b)) throw new TypeError("Argument must be a Buffer"); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { let str = ""; const max = exports.INSPECT_MAX_BYTES; str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); if (this.length > max) str += " ... "; return ""; }; if (customInspectSymbol) Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) target = Buffer.from(target, target.offset, target.byteLength); if (!Buffer.isBuffer(target)) throw new TypeError("The \"target\" argument must be one of type Buffer or Uint8Array. Received type " + typeof target); if (start === void 0) start = 0; if (end === void 0) end = target ? target.length : 0; if (thisStart === void 0) thisStart = 0; if (thisEnd === void 0) thisEnd = this.length; if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) throw new RangeError("out of range index"); if (thisStart >= thisEnd && start >= end) return 0; if (thisStart >= thisEnd) return -1; if (start >= end) return 1; start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; let x = thisEnd - thisStart; let y = end - start; const len = Math.min(x, y); const thisCopy = this.slice(thisStart, thisEnd); const targetCopy = target.slice(start, end); for (let i = 0; i < len; ++i) if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } if (x < y) return -1; if (y < x) return 1; return 0; }; function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { if (buffer.length === 0) return -1; if (typeof byteOffset === "string") { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 2147483647) byteOffset = 2147483647; else if (byteOffset < -2147483648) byteOffset = -2147483648; byteOffset = +byteOffset; if (numberIsNaN(byteOffset)) byteOffset = dir ? 0 : buffer.length - 1; if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) if (dir) return -1; else byteOffset = buffer.length - 1; else if (byteOffset < 0) if (dir) byteOffset = 0; else return -1; if (typeof val === "string") val = Buffer.from(val, encoding); if (Buffer.isBuffer(val)) { if (val.length === 0) return -1; return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === "number") { val = val & 255; if (typeof Uint8Array.prototype.indexOf === "function") if (dir) return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); else return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError("val must be string, number or Buffer"); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { let indexSize = 1; let arrLength = arr.length; let valLength = val.length; if (encoding !== void 0) { encoding = String(encoding).toLowerCase(); if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { if (arr.length < 2 || val.length < 2) return -1; indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) return buf[i]; else return buf.readUInt16BE(i * indexSize); } let i; if (dir) { let foundIndex = -1; for (i = byteOffset; i < arrLength; i++) if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { let found = true; for (let j = 0; j < valLength; j++) if (read(arr, i + j) !== read(val, j)) { found = false; break; } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; const remaining = buf.length - offset; if (!length) length = remaining; else { length = Number(length); if (length > remaining) length = remaining; } const strLen = string.length; if (length > strLen / 2) length = strLen / 2; let i; for (i = 0; i < length; ++i) { const parsed = parseInt(string.substr(i * 2, 2), 16); if (numberIsNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer.prototype.write = function write(string, offset, length, encoding) { if (offset === void 0) { encoding = "utf8"; length = this.length; offset = 0; } else if (length === void 0 && typeof offset === "string") { encoding = offset; length = this.length; offset = 0; } else if (isFinite(offset)) { offset = offset >>> 0; if (isFinite(length)) { length = length >>> 0; if (encoding === void 0) encoding = "utf8"; } else { encoding = length; length = void 0; } } else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); const remaining = this.length - offset; if (length === void 0 || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) throw new RangeError("Attempt to write outside buffer bounds"); if (!encoding) encoding = "utf8"; let loweredCase = false; for (;;) switch (encoding) { case "hex": return hexWrite(this, string, offset, length); case "utf8": case "utf-8": return utf8Write(this, string, offset, length); case "ascii": case "latin1": case "binary": return asciiWrite(this, string, offset, length); case "base64": return base64Write(this, string, offset, length); case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); encoding = ("" + encoding).toLowerCase(); loweredCase = true; } }; Buffer.prototype.toJSON = function toJSON() { return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) return base64.fromByteArray(buf); else return base64.fromByteArray(buf.slice(start, end)); } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); const res = []; let i = start; while (i < end) { const firstByte = buf[i]; let codePoint = null; let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; if (i + bytesPerSequence <= end) { let secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 128) codePoint = firstByte; break; case 2: secondByte = buf[i + 1]; if ((secondByte & 192) === 128) { tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; if (tempCodePoint > 127) codePoint = tempCodePoint; } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) codePoint = tempCodePoint; } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; if (tempCodePoint > 65535 && tempCodePoint < 1114112) codePoint = tempCodePoint; } } } if (codePoint === null) { codePoint = 65533; bytesPerSequence = 1; } else if (codePoint > 65535) { codePoint -= 65536; res.push(codePoint >>> 10 & 1023 | 55296); codePoint = 56320 | codePoint & 1023; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } var MAX_ARGUMENTS_LENGTH = 4096; function decodeCodePointsArray(codePoints) { const len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) return String.fromCharCode.apply(String, codePoints); let res = ""; let i = 0; while (i < len) res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); return res; } function asciiSlice(buf, start, end) { let ret = ""; end = Math.min(buf.length, end); for (let i = start; i < end; ++i) ret += String.fromCharCode(buf[i] & 127); return ret; } function latin1Slice(buf, start, end) { let ret = ""; end = Math.min(buf.length, end); for (let i = start; i < end; ++i) ret += String.fromCharCode(buf[i]); return ret; } function hexSlice(buf, start, end) { const len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; let out = ""; for (let i = start; i < end; ++i) out += hexSliceLookupTable[buf[i]]; return out; } function utf16leSlice(buf, start, end) { const bytes = buf.slice(start, end); let res = ""; for (let i = 0; i < bytes.length - 1; i += 2) res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); return res; } Buffer.prototype.slice = function slice(start, end) { const len = this.length; start = ~~start; end = end === void 0 ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) start = len; if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) end = len; if (end < start) end = start; const newBuf = this.subarray(start, end); Object.setPrototypeOf(newBuf, Buffer.prototype); return newBuf; }; function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length"); } Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); let val = this[offset]; let mul = 1; let i = 0; while (++i < byteLength && (mul *= 256)) val += this[offset + i] * mul; return val; }; Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); let val = this[offset + --byteLength]; let mul = 1; while (byteLength > 0 && (mul *= 256)) val += this[offset + --byteLength] * mul; return val; }; Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; }; Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) boundsError(offset, this.length - 8); const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; return BigInt(lo) + (BigInt(hi) << BigInt(32)); }); Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) boundsError(offset, this.length - 8); const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; return (BigInt(hi) << BigInt(32)) + BigInt(lo); }); Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); let val = this[offset]; let mul = 1; let i = 0; while (++i < byteLength && (mul *= 256)) val += this[offset + i] * mul; mul *= 128; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) checkOffset(offset, byteLength, this.length); let i = byteLength; let mul = 1; let val = this[offset + --i]; while (i > 0 && (mul *= 256)) val += this[offset + --i] * mul; mul *= 128; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 128)) return this[offset]; return (255 - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); const val = this[offset] | this[offset + 1] << 8; return val & 32768 ? val | 4294901760 : val; }; Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); const val = this[offset + 1] | this[offset] << 8; return val & 32768 ? val | 4294901760 : val; }; Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) boundsError(offset, this.length - 8); const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); }); Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) boundsError(offset, this.length - 8); const val = (first << 24) + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); }); Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError("\"buffer\" argument must be a Buffer instance"); if (value > max || value < min) throw new RangeError("\"value\" argument is out of bounds"); if (offset + ext > buf.length) throw new RangeError("Index out of range"); } Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { const maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } let mul = 1; let i = 0; this[offset] = value & 255; while (++i < byteLength && (mul *= 256)) this[offset + i] = value / mul & 255; return offset + byteLength; }; Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; byteLength = byteLength >>> 0; if (!noAssert) { const maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } let i = byteLength - 1; let mul = 1; this[offset + i] = value & 255; while (--i >= 0 && (mul *= 256)) this[offset + i] = value / mul & 255; return offset + byteLength; }; Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 255, 0); this[offset] = value & 255; return offset + 1; }; Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); this[offset] = value & 255; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); this[offset] = value >>> 8; this[offset + 1] = value & 255; return offset + 2; }; Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 255; return offset + 4; }; Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 255; return offset + 4; }; function wrtBigUInt64LE(buf, value, offset, min, max) { checkIntBI(value, min, max, buf, offset, 7); let lo = Number(value & BigInt(4294967295)); buf[offset++] = lo; lo = lo >> 8; buf[offset++] = lo; lo = lo >> 8; buf[offset++] = lo; lo = lo >> 8; buf[offset++] = lo; let hi = Number(value >> BigInt(32) & BigInt(4294967295)); buf[offset++] = hi; hi = hi >> 8; buf[offset++] = hi; hi = hi >> 8; buf[offset++] = hi; hi = hi >> 8; buf[offset++] = hi; return offset; } function wrtBigUInt64BE(buf, value, offset, min, max) { checkIntBI(value, min, max, buf, offset, 7); let lo = Number(value & BigInt(4294967295)); buf[offset + 7] = lo; lo = lo >> 8; buf[offset + 6] = lo; lo = lo >> 8; buf[offset + 5] = lo; lo = lo >> 8; buf[offset + 4] = lo; let hi = Number(value >> BigInt(32) & BigInt(4294967295)); buf[offset + 3] = hi; hi = hi >> 8; buf[offset + 2] = hi; hi = hi >> 8; buf[offset + 1] = hi; hi = hi >> 8; buf[offset] = hi; return offset + 8; } Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); }); Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); }); Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { const limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } let i = 0; let mul = 1; let sub = 0; this[offset] = value & 255; while (++i < byteLength && (mul *= 256)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) sub = 1; this[offset + i] = (value / mul >> 0) - sub & 255; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { const limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } let i = byteLength - 1; let mul = 1; let sub = 0; this[offset + i] = value & 255; while (--i >= 0 && (mul *= 256)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) sub = 1; this[offset + i] = (value / mul >> 0) - sub & 255; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 127, -128); if (value < 0) value = 255 + value + 1; this[offset] = value & 255; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); this[offset] = value & 255; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); this[offset] = value >>> 8; this[offset + 1] = value & 255; return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); this[offset] = value & 255; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); if (value < 0) value = 4294967295 + value + 1; this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 255; return offset + 4; }; Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); }); Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); }); function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError("Index out of range"); if (offset < 0) throw new RangeError("Index out of range"); } function writeFloat(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); ieee754.write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); ieee754.write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); }; Buffer.prototype.copy = function copy(target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError("argument should be a Buffer"); if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; if (targetStart < 0) throw new RangeError("targetStart out of bounds"); if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); if (end < 0) throw new RangeError("sourceEnd out of bounds"); if (end > this.length) end = this.length; if (target.length - targetStart < end - start) end = target.length - targetStart + start; const len = end - start; if (this === target && typeof Uint8Array.prototype.copyWithin === "function") this.copyWithin(targetStart, start, end); else Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); return len; }; Buffer.prototype.fill = function fill(val, start, end, encoding) { if (typeof val === "string") { if (typeof start === "string") { encoding = start; start = 0; end = this.length; } else if (typeof end === "string") { encoding = end; end = this.length; } if (encoding !== void 0 && typeof encoding !== "string") throw new TypeError("encoding must be a string"); if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) throw new TypeError("Unknown encoding: " + encoding); if (val.length === 1) { const code = val.charCodeAt(0); if (encoding === "utf8" && code < 128 || encoding === "latin1") val = code; } } else if (typeof val === "number") val = val & 255; else if (typeof val === "boolean") val = Number(val); if (start < 0 || this.length < start || this.length < end) throw new RangeError("Out of range index"); if (end <= start) return this; start = start >>> 0; end = end === void 0 ? this.length : end >>> 0; if (!val) val = 0; let i; if (typeof val === "number") for (i = start; i < end; ++i) this[i] = val; else { const bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); const len = bytes.length; if (len === 0) throw new TypeError("The value \"" + val + "\" is invalid for argument \"value\""); for (i = 0; i < end - start; ++i) this[i + start] = bytes[i % len]; } return this; }; var errors = {}; function E(sym, getMessage, Base) { errors[sym] = class NodeError extends Base { constructor() { super(); Object.defineProperty(this, "message", { value: getMessage.apply(this, arguments), writable: true, configurable: true }); this.name = `${this.name} [${sym}]`; this.stack; delete this.name; } get code() { return sym; } set code(value) { Object.defineProperty(this, "code", { configurable: true, enumerable: true, value, writable: true }); } toString() { return `${this.name} [${sym}]: ${this.message}`; } }; } E("ERR_BUFFER_OUT_OF_BOUNDS", function(name) { if (name) return `${name} is outside of buffer bounds`; return "Attempt to access memory outside buffer bounds"; }, RangeError); E("ERR_INVALID_ARG_TYPE", function(name, actual) { return `The "${name}" argument must be of type number. Received type ${typeof actual}`; }, TypeError); E("ERR_OUT_OF_RANGE", function(str, range, input) { let msg = `The value of "${str}" is out of range.`; let received = input; if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) received = addNumericalSeparator(String(input)); else if (typeof input === "bigint") { received = String(input); if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) received = addNumericalSeparator(received); received += "n"; } msg += ` It must be ${range}. Received ${received}`; return msg; }, RangeError); function addNumericalSeparator(val) { let res = ""; let i = val.length; const start = val[0] === "-" ? 1 : 0; for (; i >= start + 4; i -= 3) res = `_${val.slice(i - 3, i)}${res}`; return `${val.slice(0, i)}${res}`; } function checkBounds(buf, offset, byteLength) { validateNumber(offset, "offset"); if (buf[offset] === void 0 || buf[offset + byteLength] === void 0) boundsError(offset, buf.length - (byteLength + 1)); } function checkIntBI(value, min, max, buf, offset, byteLength) { if (value > max || value < min) { const n = typeof min === "bigint" ? "n" : ""; let range; if (byteLength > 3) if (min === 0 || min === BigInt(0)) range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`; else range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength + 1) * 8 - 1}${n}`; else range = `>= ${min}${n} and <= ${max}${n}`; throw new errors.ERR_OUT_OF_RANGE("value", range, value); } checkBounds(buf, offset, byteLength); } function validateNumber(value, name) { if (typeof value !== "number") throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value); } function boundsError(value, length, type) { if (Math.floor(value) !== value) { validateNumber(value, type); throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); } if (length < 0) throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); throw new errors.ERR_OUT_OF_RANGE(type || "offset", `>= ${type ? 1 : 0} and <= ${length}`, value); } var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; function base64clean(str) { str = str.split("=")[0]; str = str.trim().replace(INVALID_BASE64_RE, ""); if (str.length < 2) return ""; while (str.length % 4 !== 0) str = str + "="; return str; } function utf8ToBytes(string, units) { units = units || Infinity; let codePoint; const length = string.length; let leadSurrogate = null; const bytes = []; for (let i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); if (codePoint > 55295 && codePoint < 57344) { if (!leadSurrogate) { if (codePoint > 56319) { if ((units -= 3) > -1) bytes.push(239, 191, 189); continue; } else if (i + 1 === length) { if ((units -= 3) > -1) bytes.push(239, 191, 189); continue; } leadSurrogate = codePoint; continue; } if (codePoint < 56320) { if ((units -= 3) > -1) bytes.push(239, 191, 189); leadSurrogate = codePoint; continue; } codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; } else if (leadSurrogate) { if ((units -= 3) > -1) bytes.push(239, 191, 189); } leadSurrogate = null; if (codePoint < 128) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 2048) { if ((units -= 2) < 0) break; bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128); } else if (codePoint < 65536) { if ((units -= 3) < 0) break; bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); } else if (codePoint < 1114112) { if ((units -= 4) < 0) break; bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); } else throw new Error("Invalid code point"); } return bytes; } function asciiToBytes(str) { const byteArray = []; for (let i = 0; i < str.length; ++i) byteArray.push(str.charCodeAt(i) & 255); return byteArray; } function utf16leToBytes(str, units) { let c, hi, lo; const byteArray = []; for (let i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return base64.toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { let i; for (i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } function isInstance(obj, type) { return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; } function numberIsNaN(obj) { return obj !== obj; } var hexSliceLookupTable = (function() { const alphabet = "0123456789abcdef"; const table = new Array(256); for (let i = 0; i < 16; ++i) { const i16 = i * 16; for (let j = 0; j < 16; ++j) table[i16 + j] = alphabet[i] + alphabet[j]; } return table; })(); function defineBigIntMethod(fn) { return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; } function BufferBigIntNotDefined() { throw new Error("BigInt not supported"); } })); //#endregion //#region ../../node_modules/.pnpm/global@4.4.0/node_modules/global/window.js var require_window = /* @__PURE__ */ __commonJSMin(((exports, module) => { var win; if (typeof window !== "undefined") win = window; else if (typeof global !== "undefined") win = global; else if (typeof self !== "undefined") win = self; else win = {}; module.exports = win; })); //#endregion //#region __vite-browser-external var require___vite_browser_external = /* @__PURE__ */ __commonJSMin(((exports, module) => { module.exports = {}; })); //#endregion //#region ../../node_modules/.pnpm/get-random-values@3.0.0/node_modules/get-random-values/index.js var require_get_random_values = /* @__PURE__ */ __commonJSMin(((exports, module) => { var window = require_window(); var nodeCrypto = require___vite_browser_external(); /** * @template {ArrayBufferView | null} T * @param {T} buf * @returns {T} */ function getRandomValues(buf) { if (window.crypto && window.crypto.getRandomValues) return window.crypto.getRandomValues(buf); if (typeof window.msCrypto === "object" && typeof window.msCrypto.getRandomValues === "function") return window.msCrypto.getRandomValues(buf); if (nodeCrypto.randomBytes) { if (!(buf instanceof Uint8Array)) throw new TypeError("expected Uint8Array"); if (buf.length > 65536) { var e = /* @__PURE__ */ new Error(); e.code = 22; e.message = "Failed to execute 'getRandomValues' on 'Crypto': The ArrayBufferView's byte length (" + buf.length + ") exceeds the number of bytes of entropy available via this API (65536)."; e.name = "QuotaExceededError"; throw e; } var bytes = nodeCrypto.randomBytes(buf.length); buf.set(bytes); return buf; } else throw new Error("No secure random number generator available."); } module.exports = getRandomValues; })); //#endregion //#region ../send/frontend/src/lib/ece.ts var import_buffer = require_buffer(); var import_get_random_values = /* @__PURE__ */ __toESM$2(require_get_random_values(), 1); var NONCE_LENGTH = 12; var TAG_LENGTH = 16; var KEY_LENGTH = 16; var MODE_ENCRYPT = "encrypt"; var MODE_DECRYPT = "decrypt"; var ECE_RECORD_SIZE = 1024 * 64; function generateSalt(len) { const randSalt = new Uint8Array(len); (0, import_get_random_values.default)(randSalt); return randSalt.buffer; } var ECETransformer = class { constructor(mode, ikm, rs, salt) { this.mode = mode; this.prevChunk; this.seq = 0; this.firstchunk = true; this.rs = rs; this.key = ikm; this.salt = salt; } async generateNonceBase() { const base = await window.crypto.subtle.exportKey("raw", this.key); const exported = new Uint8Array(base); return import_buffer.Buffer.from(exported.slice(0, NONCE_LENGTH)); } generateNonce(seq) { if (seq > 4294967295) throw new Error("record sequence number exceeds limit"); const nonce = import_buffer.Buffer.from(this.nonceBase); const xor = (nonce.readUIntBE(nonce.length - 4, 4) ^ seq) >>> 0; nonce.writeUIntBE(xor, nonce.length - 4, 4); return nonce; } pad(data, isLast) { const len = data.length; if (len + TAG_LENGTH >= this.rs) throw new Error("data too large for record size"); if (isLast) { const padding = import_buffer.Buffer.alloc(1); padding.writeUInt8(2, 0); return import_buffer.Buffer.concat([data, padding]); } else { const padding = import_buffer.Buffer.alloc(this.rs - len - TAG_LENGTH); padding.fill(0); padding.writeUInt8(1, 0); return import_buffer.Buffer.concat([data, padding]); } } unpad(data, isLast) { for (let i = data.length - 1; i >= 0; i--) if (data[i]) { if (isLast) { if (data[i] !== 2) throw new Error("delimiter of final record is not 2"); } else if (data[i] !== 1) throw new Error("delimiter of not final record is not 1"); return data.slice(0, i); } throw new Error("no delimiter found"); } createHeader() { const nums = import_buffer.Buffer.alloc(5); nums.writeUIntBE(this.rs, 0, 4); nums.writeUIntBE(0, 4, 1); return import_buffer.Buffer.concat([import_buffer.Buffer.from(this.salt), nums]); } readHeader(buffer) { if (buffer.length < 21) throw new Error("chunk too small for reading header"); const header = {}; header.salt = buffer.buffer.slice(0, KEY_LENGTH); header.rs = buffer.readUIntBE(KEY_LENGTH, 4); header.length = buffer.readUInt8(20) + KEY_LENGTH + 5; return header; } async encryptRecord(buffer, seq, isLast) { const nonce = this.generateNonce(seq); const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, this.key, this.pad(buffer, isLast)); return import_buffer.Buffer.from(encrypted); } async decryptRecord(buffer, seq, isLast) { const nonce = this.generateNonce(seq); const data = await crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, tagLength: 128 }, this.key, buffer); return this.unpad(import_buffer.Buffer.from(data), isLast); } async start(controller) { if (this.mode === MODE_ENCRYPT) { this.nonceBase = await this.generateNonceBase(); controller.enqueue(this.createHeader()); } else if (this.mode !== MODE_DECRYPT) throw new Error("mode must be either encrypt or decrypt"); } async transformPrevChunk(isLast, controller) { if (this.mode === MODE_ENCRYPT) { controller.enqueue(await this.encryptRecord(this.prevChunk, this.seq, isLast)); this.seq++; } else { if (this.seq === 0) { const header = this.readHeader(this.prevChunk); this.salt = header.salt; this.rs = header.rs; this.nonceBase = await this.generateNonceBase(); } else controller.enqueue(await this.decryptRecord(this.prevChunk, this.seq - 1, isLast)); this.seq++; } } async transform(chunk, controller) { if (!this.firstchunk) await this.transformPrevChunk(false, controller); this.firstchunk = false; this.prevChunk = import_buffer.Buffer.from(chunk.buffer); } async flush(controller) { if (this.prevChunk) await this.transformPrevChunk(true, controller); } }; var StreamSlicer = class { constructor(rs, mode) { this.mode = mode; this.rs = rs; this.chunkSize = mode === MODE_ENCRYPT ? rs - 17 : 21; this.partialChunk = new Uint8Array(this.chunkSize); this.offset = 0; } send(buf, controller) { controller.enqueue(buf); if (this.chunkSize === 21 && this.mode === MODE_DECRYPT) this.chunkSize = this.rs; this.partialChunk = new Uint8Array(this.chunkSize); this.offset = 0; } transform(chunk, controller) { let i = 0; if (this.offset > 0) { const len = Math.min(chunk.byteLength, this.chunkSize - this.offset); this.partialChunk.set(chunk.slice(0, len), this.offset); this.offset += len; i += len; if (this.offset === this.chunkSize) this.send(this.partialChunk, controller); } while (i < chunk.byteLength) { const remainingBytes = chunk.byteLength - i; if (remainingBytes >= this.chunkSize) { const record = chunk.slice(i, i + this.chunkSize); i += this.chunkSize; this.send(record, controller); } else { const end = chunk.slice(i, i + remainingBytes); i += end.byteLength; this.partialChunk.set(end); this.offset = end.byteLength; } } } flush(controller) { if (this.offset > 0) controller.enqueue(this.partialChunk.slice(0, this.offset)); } }; function encryptStream(input, key, rs = ECE_RECORD_SIZE, salt = generateSalt(KEY_LENGTH)) { const mode = "encrypt"; return transformStream(transformStream(input, new StreamSlicer(rs, mode)), new ECETransformer(mode, key, rs, salt)); } function decryptStream(input, key, rs = ECE_RECORD_SIZE) { const mode = "decrypt"; return transformStream(transformStream(input, new StreamSlicer(rs, mode)), new ECETransformer(mode, key, rs)); } //#endregion //#region ../send/frontend/src/apps/send/const.js /** * Enum for Initialization codes. Non-zero values indicate an error. * @readonly * @enum {number} */ var INIT_ERRORS = { NONE: 0, NO_USER: 1, NO_KEYCHAIN: 2, COULD_NOT_CREATE_DEFAULT_FOLDER: 3 }; //#endregion //#region ../send/frontend/src/lib/storage/LocalStorage.ts var LocalStorageAdapter = class { constructor() {} keys() { const keys = []; for (let i = 0; i < localStorage.length; i++) keys.push(localStorage.key(i)); return keys; } get(key) { const val = localStorage.getItem(key); if (!val) return null; return JSON.parse(val); } set(key, val) { const value = JSON.stringify(val); localStorage.setItem(key, value); } remove(id) { localStorage.removeItem(id); } clear() { console.log(`clearing localStorage`); localStorage.clear(); } }; //#endregion //#region ../send/frontend/src/lib/storage/index.ts var Storage$1 = class { constructor(Adapter = LocalStorageAdapter) { this.USER_KEY = "lb/user"; this.OTHER_KEYS_KEY = "lb/keys"; this.RSA_KEYS_KEY = "lb/rsa"; this.PASS_PHRASE = "lb/passphrase"; this.adapter = new Adapter(); } async storeUser(userObj) { this.adapter.set(this.USER_KEY, { ...userObj }); } async getUserFromLocalStorage() { return this.adapter.get(this.USER_KEY); } async storeKeys(keysObj) { this.adapter.set(this.OTHER_KEYS_KEY, { ...keysObj }); } async storePassPhrase(passPhrase) { this.adapter.set(this.PASS_PHRASE, { passPhrase }); } getPassPhrase() { return this.adapter.get(this.PASS_PHRASE)?.passPhrase || ""; } async loadKeys() { return this.adapter.get(this.OTHER_KEYS_KEY); } async storeKeypair(keypair) { this.adapter.set(this.RSA_KEYS_KEY, { ...keypair }); } async loadKeypair() { return this.adapter.get(this.RSA_KEYS_KEY); } async clear() { return this.adapter.clear(); } async export() { return { user: await this.getUserFromLocalStorage(), keypair: await this.loadKeypair(), keys: await this.loadKeys() }; } }; //#endregion //#region ../send/frontend/src/lib/bridgePassphrase.ts /** * Pull a passphrase shared from the web app via the token bridge into the * keychain. * * The web app (running in a browser tab) posts SEND_MESSAGE_TO_BRIDGE; the * add-on background stores its value in browser.storage.local under that key * (see background.ts). This moves that staged value into the keychain — i.e. * localStorage['lb/passphrase'], which every moz-extension page (background, * popup, management) shares — and clears the staged copy so it is consumed once. * * Runs only in an extension context where browser.storage.local exists; it is a * no-op in a plain web page (where `browser` is undefined). Safe to call from * any context that is about to restore keys, so the popup and background don't * depend on the management page having run the transfer first. * * @returns true if a bridged passphrase was found and stored, false otherwise. */ async function pullBridgedPassphrase(keychain) { if (typeof browser === "undefined" || !browser?.storage?.local) return false; try { const passphrase = (await browser.storage.local.get(SEND_MESSAGE_TO_BRIDGE))?.[SEND_MESSAGE_TO_BRIDGE]; if (!passphrase) return false; await keychain.storePassPhrase(passphrase); await browser.storage.local.remove(SEND_MESSAGE_TO_BRIDGE); console.log("✅ Pulled bridged passphrase into the keychain"); return true; } catch (error) { console.error("Error pulling bridged passphrase:", error); return false; } } //#endregion //#region ../send/frontend/src/lib/keychain.ts var import___vite_browser_external = /* @__PURE__ */ __toESM$2(require___vite_browser_external(), 1); var SALT_LENGTH = 128; var crypto$1 = import___vite_browser_external.default; try { crypto$1 = window.crypto; } catch (e) {} async function generateAesGcmKey() { try { return await crypto$1.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); } catch (err) { console.error(err); } } var Content = class { async generateKey() { return await generateAesGcmKey(); } }; var Container = class { async generateContainerKey() { try { return await crypto$1.subtle.generateKey({ name: "AES-KW", length: 256 }, true, ["wrapKey", "unwrapKey"]); } catch (err) { console.error(err); } } async wrapContentKey(key, wrappingKey) { const wrappedKey = await crypto$1.subtle.wrapKey("raw", key, wrappingKey, "AES-KW"); return Util.arrayBufferToBase64(wrappedKey); } async unwrapContentKey(wrappedKeyStr, wrappingKey) { const buf = Util.base64ToArrayBuffer(wrappedKeyStr); return await crypto$1.subtle.unwrapKey("raw", buf, wrappingKey, "AES-KW", "AES-GCM", true, ["encrypt", "decrypt"]); } }; var Password = class { async _wrap(keyToWrap, password, salt) { const wrappingKey = await getKey(await getKeyMaterial(password), salt); const wrappedKey = await crypto$1.subtle.wrapKey("raw", keyToWrap, wrappingKey, "AES-KW"); return Util.arrayBufferToBase64(wrappedKey); } async _unwrap(wrappedKeyStr, password, salt, algorithm, permissions) { const unwrappingKey = await getUnwrappingKey(password, salt); return crypto$1.subtle.unwrapKey("raw", Util.base64ToArrayBuffer(wrappedKeyStr), unwrappingKey, "AES-KW", algorithm, true, permissions); } async wrapContainerKey(keyToWrap, password, salt) { return await this._wrap(keyToWrap, password, salt); } async unwrapContainerKey(wrappedKeyStr, password, salt) { return await this._unwrap(wrappedKeyStr, password, salt, "AES-KW", ["wrapKey", "unwrapKey"]); } async wrapContentKey(keyToWrap, password, salt) { return await this._wrap(keyToWrap, password, salt); } async unwrapContentKey(wrappedKeyStr, password, salt) { return await this._unwrap(wrappedKeyStr, password, salt, "AES-GCM", ["encrypt", "decrypt"]); } }; var Rsa = class { async generateKeyPair() { const { publicKey, privateKey } = await crypto$1.subtle.generateKey({ name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([ 1, 0, 1 ]), hash: "SHA-256" }, true, ["wrapKey", "unwrapKey"]); this.publicKey = publicKey; this.privateKey = privateKey; return { publicKey, privateKey }; } async getPublicKeyJwk() { if (!this.publicKey) return null; const jwk = await rsaToJsonWebKey(this.publicKey); return JSON.stringify(jwk); } async getPrivateKeyJwk() { if (!this.privateKey) return null; const jwk = await rsaToJsonWebKey(this.privateKey); return JSON.stringify(jwk); } async setPrivateKeyFromJwk(jwk) { this.privateKey = await jwkToRsa(jwk); } async setPublicKeyFromJwk(jwk) { this.publicKey = await jwkToRsa(jwk); } async wrapContainerKey(aesKey, publicKey) { const wrappedKey = await crypto$1.subtle.wrapKey("jwk", aesKey, publicKey, { name: "RSA-OAEP" }); return Util.arrayBufferToBase64(wrappedKey); } async unwrapContainerKey(wrappedKeyStr, privateKey) { return await crypto$1.subtle.unwrapKey("jwk", Util.base64ToArrayBuffer(wrappedKeyStr), privateKey, { name: "RSA-OAEP" }, { name: "AES-KW", length: 256 }, true, ["wrapKey", "unwrapKey"]); } }; var Challenge = class { createChallenge() { return Util.arrayBufferToBase64(Util.generateSalt(SALT_LENGTH)); } async generateKey() { return await generateAesGcmKey(); } async encryptChallenge(challengePlaintext, key, salt) { const arrayBuffer = new TextEncoder().encode(challengePlaintext); const ciphertextBuffer = await crypto$1.subtle.encrypt({ name: "AES-GCM", iv: salt }, key, arrayBuffer); return Util.arrayBufferToBase64(ciphertextBuffer); } async decryptChallenge(challengeCiphertext, key, salt) { const arrayBuffer = await crypto$1.subtle.decrypt({ name: "AES-GCM", iv: salt }, key, Util.base64ToArrayBuffer(challengeCiphertext)); return new TextDecoder().decode(arrayBuffer); } }; var Backup = class { async generateKey() { return await generateAesGcmKey(); } async encryptBackup(plaintext, key, salt) { const arrayBuffer = new TextEncoder().encode(plaintext); const ciphertextBuffer = await crypto$1.subtle.encrypt({ name: "AES-GCM", iv: salt }, key, arrayBuffer); return Util.arrayBufferToBase64(ciphertextBuffer); } async decryptBackup(ciphertext, key, salt) { const arrayBuffer = await crypto$1.subtle.decrypt({ name: "AES-GCM", iv: salt }, key, Util.base64ToArrayBuffer(ciphertext)); return new TextDecoder().decode(arrayBuffer); } }; var Keychain = class { constructor(storage) { this._init(storage); this.locked = false; } _init(storage) { this.content = new Content(); this.container = new Container(); this.password = new Password(); this.rsa = new Rsa(); this.challenge = new Challenge(); this.backup = new Backup(); this._keys = {}; this._storage = storage ?? new Storage$1(); } get keys() { return { ...this._keys }; } set keys(keyObj) { this._keys = keyObj; } getPassphraseValue() { return this._storage.getPassPhrase(); } count() { return Object.keys(this._keys).length; } async add(id, key) { if (!this.rsa.publicKey) throw Error("Missing public key, required for wrapping AES key"); const wrappedKeyStr = await this.rsa.wrapContainerKey(key, this.rsa.publicKey); this._keys[id] = wrappedKeyStr; } async get(id) { const wrappedKeyStr = this._keys[id]; if (!wrappedKeyStr) throw Error(`You don't have the key to decrypt this container`); return await this.rsa.unwrapContainerKey(wrappedKeyStr, this.rsa.privateKey); } remove(id) { delete this._keys[id]; } async newKeyForContainer(id) { const key = await this.container.generateContainerKey(); console.log(`adding key for container id ${id}`); await this.add(id, key); } async exportKeypair() { return { publicKey: await this.rsa.getPublicKeyJwk(), privateKey: await this.rsa.getPrivateKeyJwk() }; } async exportKeys() { return { ...this.keys }; } async storePassPhrase(passphrase) { await this._storage.storePassPhrase(passphrase); } async store() { await this._storage.storeKeypair(await this.exportKeypair()); await this._storage.storeKeys(await this.exportKeys()); } async fallbackToStoredKeypair(keypair) { if (!keypair) keypair = await this._storage.loadKeypair(); return keypair; } async fallbackToStoredKeys(keys) { if (!keys) keys = await this._storage.loadKeys(); return keys; } async load(keypairStr, keys) { try { const { publicKey, privateKey } = await this.fallbackToStoredKeypair(keypairStr); await this.rsa.setPrivateKeyFromJwk(privateKey); await this.rsa.setPublicKeyFromJwk(publicKey); this.keys = await this.fallbackToStoredKeys(keys); return true; } catch (e) { console.log(`No keychain in storage`); return false; } } async generateBackupKey() { return await generateAesGcmKey(); } }; var Util = class { static generateSalt(size = 16) { return (0, import_get_random_values.default)(new Uint8Array(size)); } static generateRandomPassword(size = 16) { return this.arrayBufferToBase64(this.generateSalt(size)); } static async compareKeys(k1, k2) { return await exportKeyToBase64(k1) === await exportKeyToBase64(k2); } static arrayBufferToBase64(arrayBuffer) { const byteArray = new Uint8Array(arrayBuffer); const byteString = String.fromCharCode(...byteArray); return btoa(encodeURIComponent(byteString)); } static base64ToArrayBuffer(base64) { const byteString = decodeURIComponent(atob(base64)); const byteArray = new Uint8Array(byteString.length); for (let i = 0; i < byteString.length; i++) byteArray[i] = byteString.charCodeAt(i); return byteArray.buffer; } }; function getKeyMaterial(password) { const enc = new TextEncoder(); return crypto$1.subtle.importKey("raw", enc.encode(password), { name: "PBKDF2" }, false, ["deriveBits", "deriveKey"]); } function getKey(keyMaterial, salt) { return crypto$1.subtle.deriveKey({ name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" }, keyMaterial, { name: "AES-KW", length: 256 }, true, ["wrapKey", "unwrapKey"]); } async function getUnwrappingKey(password, salt) { const keyMaterial = await getKeyMaterial(password); return crypto$1.subtle.deriveKey({ name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" }, keyMaterial, { name: "AES-KW", length: 256 }, true, ["wrapKey", "unwrapKey"]); } async function rsaToJsonWebKey(key) { return await crypto$1.subtle.exportKey("jwk", key); } function toJsonWebKey(jwk) { if (typeof jwk === "string") return JSON.parse(jwk); return jwk; } async function jwkToRsa(jwk) { jwk = toJsonWebKey(jwk); return await crypto$1.subtle.importKey("jwk", jwk, { name: "RSA-OAEP", hash: "SHA-256" }, true, jwk.key_ops || []); } async function exportKeyToBase64(key) { const keyBuffer = await crypto$1.subtle.exportKey("raw", key); return Util.arrayBufferToBase64(keyBuffer); } async function decryptKeys(protectedContainerKeysObj, keychain, key, salt) { const obj = {}; await Promise.all(Object.keys(protectedContainerKeysObj).map(async (k) => { obj[k] = await keychain.backup.decryptBackup(protectedContainerKeysObj[k], key, salt); return true; })); return obj; } async function decryptAll(keychainFromParams, { protectedContainerKeysStr, protectedKeypairStr, passwordWrappedKeyStr, saltStr, password }) { const salt = Util.base64ToArrayBuffer(saltStr); const key = await keychainFromParams.password.unwrapContentKey(passwordWrappedKeyStr, password, salt); const protectedKeypair = JSON.parse(protectedKeypairStr); const publicKeyCiphertext = protectedKeypair.publicKey; const privateKeyCiphertext = protectedKeypair.privateKey; return { publicKeyJwk: await keychainFromParams.backup.decryptBackup(publicKeyCiphertext, key, salt), privateKeyJwk: await keychainFromParams.backup.decryptBackup(privateKeyCiphertext, key, salt), containerKeys: await decryptKeys(JSON.parse(protectedContainerKeysStr), keychainFromParams, key, salt) }; } var MSG_INCORRECT_PASSPHRASE = "Passphrase is incorrect"; var MSG_COULD_NOT_RETRIEVE = "Could not retrieve backup from the server."; async function restoreKeysUsingLocalStorage(keychain, api) { await pullBridgedPassphrase(keychain); console.log("🔑 auto restoring keys"); if (!keychain.getPassphraseValue()) { console.log("Keychain passphrase is not initialized"); return; } return restoreKeys(keychain, api); } async function restoreKeys(keychain, api, msg, passPhrase) { if (!msg) msg = { value: "" }; const password = keychain.getPassphraseValue() || passPhrase; if (!password) console.error("Keychain is not initialized"); let getBackupAPIResponse; try { getBackupAPIResponse = await api.call(`users/backup`); } catch (error) { console.error("Could not retrieve backup from the server.", error); return; } if (!getBackupAPIResponse) { msg.value = MSG_COULD_NOT_RETRIEVE; return; } const { backupContainerKeys, backupKeypair, backupKeystring, backupSalt } = getBackupAPIResponse; const decryptParams = { protectedContainerKeysStr: backupContainerKeys, protectedKeypairStr: backupKeypair, passwordWrappedKeyStr: backupKeystring, saltStr: backupSalt, password }; try { const { publicKeyJwk, privateKeyJwk, containerKeys } = await decryptAll(keychain, decryptParams); const keypair = { publicKey: publicKeyJwk, privateKey: privateKeyJwk }; await keychain.load(keypair, containerKeys); await keychain.store(); msg.value = "✅ Restore complete"; } catch (e) { keychain.locked = true; const KEY_RESTORE_ERROR = `⛔️ Could not restore keys. Please make sure your backup phrase is correct.`; console.error(KEY_RESTORE_ERROR, e); msg.value = MSG_INCORRECT_PASSPHRASE; throw new Error(KEY_RESTORE_ERROR); } } async function encryptKeys(containerKeysObj, key, salt, keychain) { const obj = {}; await Promise.all(Object.keys(containerKeysObj).map(async (k) => { obj[k] = await keychain.backup.encryptBackup(containerKeysObj[k], key, salt); return true; })); return obj; } async function encryptAll(publicKeyJwk, privateKeyJwk, containerKeys, password, keychain) { const key = await keychain.generateBackupKey(); const salt = Util.generateSalt(); const protectedContainerKeys = await encryptKeys(containerKeys, key, salt, keychain); const protectedContainerKeysStr = JSON.stringify(protectedContainerKeys); const protectedKeypair = { publicKey: await keychain.backup.encryptBackup(publicKeyJwk, key, salt), privateKey: await keychain.backup.encryptBackup(privateKeyJwk, key, salt) }; return { protectedContainerKeysStr, protectedKeypairStr: JSON.stringify(protectedKeypair), passwordWrappedKeyStr: await keychain.password.wrapContentKey(key, password, salt), saltStr: Util.arrayBufferToBase64(salt) }; } async function createBackup(keys, keypair, keystring, salt, api) { return await api.call(`users/backup`, { keys, keypair, keystring, salt }, "POST"); } async function backupKeys(keychain, api, msg) { const password = keychain.getPassphraseValue(); msg.value = ""; console.log("🔐 auto-backing up keys"); if (!password) { console.warn("Keychain is not initialized, cannot backup keys"); return; } const keypair = await keychain.exportKeypair(); const containerKeys = await keychain.exportKeys(); const { protectedContainerKeysStr, protectedKeypairStr, passwordWrappedKeyStr, saltStr } = await encryptAll(keypair.publicKey, keypair.privateKey, containerKeys, password, keychain); await createBackup(protectedContainerKeysStr, protectedKeypairStr, passwordWrappedKeyStr, saltStr, api); msg.value = "✅ Backup complete"; console.log("🔒 Backup complete"); } //#endregion //#region ../send/frontend/src/lib/clientConfig.ts function isClientExecution() { try { return true; } catch (error) { throw new Error("This code is running on server, it should be executed only on client"); } } isClientExecution(); isClientExecution(); var getEnvName = () => { isClientExecution(); const base_url = "https://send.tb.pro"; if (base_url.includes("send.tb.pro")) return "production"; if (base_url.includes("send-stage.tb.pro")) return "staging"; if (base_url.includes("localhost")) return "development"; }; //#endregion //#region ../../node_modules/.pnpm/pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3_/node_modules/pinia/dist/pinia.mjs /*! * pinia v2.3.1 * (c) 2025 Eduardo San Martin Morote * @license MIT */ /** * setActivePinia must be called to handle SSR at the top of functions like * `fetch`, `setup`, `serverPrefetch` and others */ var activePinia; /** * Sets or unsets the active pinia. Used in SSR and internally when calling * actions and getters * * @param pinia - Pinia instance */ var setActivePinia = (pinia) => activePinia = pinia; var piniaSymbol = Symbol(); function isPlainObject$3(o) { return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function"; } /** * Possible types for SubscriptionCallback */ var MutationType; (function(MutationType) { /** * Direct mutation of the state: * * - `store.name = 'new name'` * - `store.$state.name = 'new name'` * - `store.list.push('new item')` */ MutationType["direct"] = "direct"; /** * Mutated the state with `$patch` and an object * * - `store.$patch({ name: 'newName' })` */ MutationType["patchObject"] = "patch object"; /** * Mutated the state with `$patch` and a function * * - `store.$patch(state => state.name = 'newName')` */ MutationType["patchFunction"] = "patch function"; })(MutationType || (MutationType = {})); var IS_CLIENT = typeof window !== "undefined"; var _global = /*#__PURE__*/ (() => typeof window === "object" && window.window === window ? window : typeof self === "object" && self.self === self ? self : typeof global === "object" && global.global === global ? global : typeof globalThis === "object" ? globalThis : { HTMLElement: null })(); function bom(blob, { autoBom = false } = {}) { if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) return new Blob([String.fromCharCode(65279), blob], { type: blob.type }); return blob; } function download(url, name, opts) { const xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = "blob"; xhr.onload = function() { saveAs(xhr.response, name, opts); }; xhr.onerror = function() { console.error("could not download file"); }; xhr.send(); } function corsEnabled(url) { const xhr = new XMLHttpRequest(); xhr.open("HEAD", url, false); try { xhr.send(); } catch (e) {} return xhr.status >= 200 && xhr.status <= 299; } function click(node) { try { node.dispatchEvent(new MouseEvent("click")); } catch (e) { const evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); node.dispatchEvent(evt); } } var _navigator = typeof navigator === "object" ? navigator : { userAgent: "" }; var isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) && /AppleWebKit/.test(_navigator.userAgent) && !/Safari/.test(_navigator.userAgent))(); var saveAs = !IS_CLIENT ? () => {} : typeof HTMLAnchorElement !== "undefined" && "download" in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : "msSaveOrOpenBlob" in _navigator ? msSaveAs : fileSaverSaveAs; function downloadSaveAs(blob, name = "download", opts) { const a = document.createElement("a"); a.download = name; a.rel = "noopener"; if (typeof blob === "string") { a.href = blob; if (a.origin !== location.origin) if (corsEnabled(a.href)) download(blob, name, opts); else { a.target = "_blank"; click(a); } else click(a); } else { a.href = URL.createObjectURL(blob); setTimeout(function() { URL.revokeObjectURL(a.href); }, 4e4); setTimeout(function() { click(a); }, 0); } } function msSaveAs(blob, name = "download", opts) { if (typeof blob === "string") if (corsEnabled(blob)) download(blob, name, opts); else { const a = document.createElement("a"); a.href = blob; a.target = "_blank"; setTimeout(function() { click(a); }); } else navigator.msSaveOrOpenBlob(bom(blob, opts), name); } function fileSaverSaveAs(blob, name, opts, popup) { popup = popup || open("", "_blank"); if (popup) popup.document.title = popup.document.body.innerText = "downloading..."; if (typeof blob === "string") return download(blob, name, opts); const force = blob.type === "application/octet-stream"; const isSafari = /constructor/i.test(String(_global.HTMLElement)) || "safari" in _global; const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent); if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== "undefined") { const reader = new FileReader(); reader.onloadend = function() { let url = reader.result; if (typeof url !== "string") { popup = null; throw new Error("Wrong reader.result type"); } url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, "data:attachment/file;"); if (popup) popup.location.href = url; else location.assign(url); popup = null; }; reader.readAsDataURL(blob); } else { const url = URL.createObjectURL(blob); if (popup) popup.location.assign(url); else location.href = url; popup = null; setTimeout(function() { URL.revokeObjectURL(url); }, 4e4); } } var { assign: assign$1 } = Object; /** * Creates a Pinia instance to be used by the application */ function createPinia() { const scope = effectScope(true); const state = scope.run(() => /* @__PURE__ */ ref({})); let _p = []; let toBeInstalled = []; const pinia = markRaw({ install(app) { setActivePinia(pinia); pinia._a = app; app.provide(piniaSymbol, pinia); app.config.globalProperties.$pinia = pinia; toBeInstalled.forEach((plugin) => _p.push(plugin)); toBeInstalled = []; }, use(plugin) { if (!this._a && true) toBeInstalled.push(plugin); else _p.push(plugin); return this; }, _p, _a: null, _e: scope, _s: /* @__PURE__ */ new Map(), state }); return pinia; } var noop$3 = () => {}; function addSubscription(subscriptions, callback, detached, onCleanup = noop$3) { subscriptions.push(callback); const removeSubscription = () => { const idx = subscriptions.indexOf(callback); if (idx > -1) { subscriptions.splice(idx, 1); onCleanup(); } }; if (!detached && getCurrentScope$1()) onScopeDispose(removeSubscription); return removeSubscription; } function triggerSubscriptions(subscriptions, ...args) { subscriptions.slice().forEach((callback) => { callback(...args); }); } var fallbackRunWithContext = (fn) => fn(); /** * Marks a function as an action for `$onAction` * @internal */ var ACTION_MARKER = Symbol(); /** * Action name symbol. Allows to add a name to an action after defining it * @internal */ var ACTION_NAME = Symbol(); function mergeReactiveObjects(target, patchToApply) { if (target instanceof Map && patchToApply instanceof Map) patchToApply.forEach((value, key) => target.set(key, value)); else if (target instanceof Set && patchToApply instanceof Set) patchToApply.forEach(target.add, target); for (const key in patchToApply) { if (!patchToApply.hasOwnProperty(key)) continue; const subPatch = patchToApply[key]; const targetValue = target[key]; if (isPlainObject$3(targetValue) && isPlainObject$3(subPatch) && target.hasOwnProperty(key) && !/* @__PURE__ */ isRef(subPatch) && !/* @__PURE__ */ isReactive(subPatch)) target[key] = mergeReactiveObjects(targetValue, subPatch); else target[key] = subPatch; } return target; } var skipHydrateSymbol = Symbol(); /** * Returns whether a value should be hydrated * * @param obj - target variable * @returns true if `obj` should be hydrated */ function shouldHydrate(obj) { return !isPlainObject$3(obj) || !obj.hasOwnProperty(skipHydrateSymbol); } var { assign } = Object; function isComputed(o) { return !!(/* @__PURE__ */ isRef(o) && o.effect); } function createOptionsStore(id, options, pinia, hot) { const { state, actions, getters } = options; const initialState = pinia.state.value[id]; let store; function setup() { if (!initialState && true) pinia.state.value[id] = state ? state() : {}; return assign(/* @__PURE__ */ toRefs(pinia.state.value[id]), actions, Object.keys(getters || {}).reduce((computedGetters, name) => { computedGetters[name] = markRaw(computed(() => { setActivePinia(pinia); const store = pinia._s.get(id); return getters[name].call(store, store); })); return computedGetters; }, {})); } store = createSetupStore(id, setup, options, pinia, hot, true); return store; } function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) { let scope; const optionsForPlugin = assign({ actions: {} }, options); const $subscribeOptions = { deep: true }; let isListening; let isSyncListening; let subscriptions = []; let actionSubscriptions = []; let debuggerEvents; const initialState = pinia.state.value[$id]; if (!isOptionsStore && !initialState && true) pinia.state.value[$id] = {}; let activeListener; function $patch(partialStateOrMutator) { let subscriptionMutation; isListening = isSyncListening = false; if (typeof partialStateOrMutator === "function") { partialStateOrMutator(pinia.state.value[$id]); subscriptionMutation = { type: MutationType.patchFunction, storeId: $id, events: debuggerEvents }; } else { mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator); subscriptionMutation = { type: MutationType.patchObject, payload: partialStateOrMutator, storeId: $id, events: debuggerEvents }; } const myListenerId = activeListener = Symbol(); nextTick().then(() => { if (activeListener === myListenerId) isListening = true; }); isSyncListening = true; triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]); } const $reset = isOptionsStore ? function $reset() { const { state } = options; const newState = state ? state() : {}; this.$patch(($state) => { assign($state, newState); }); } : noop$3; function $dispose() { scope.stop(); subscriptions = []; actionSubscriptions = []; pinia._s.delete($id); } /** * Helper that wraps function so it can be tracked with $onAction * @param fn - action to wrap * @param name - name of the action */ const action = (fn, name = "") => { if (ACTION_MARKER in fn) { fn[ACTION_NAME] = name; return fn; } const wrappedAction = function() { setActivePinia(pinia); const args = Array.from(arguments); const afterCallbackList = []; const onErrorCallbackList = []; function after(callback) { afterCallbackList.push(callback); } function onError(callback) { onErrorCallbackList.push(callback); } triggerSubscriptions(actionSubscriptions, { args, name: wrappedAction[ACTION_NAME], store, after, onError }); let ret; try { ret = fn.apply(this && this.$id === $id ? this : store, args); } catch (error) { triggerSubscriptions(onErrorCallbackList, error); throw error; } if (ret instanceof Promise) return ret.then((value) => { triggerSubscriptions(afterCallbackList, value); return value; }).catch((error) => { triggerSubscriptions(onErrorCallbackList, error); return Promise.reject(error); }); triggerSubscriptions(afterCallbackList, ret); return ret; }; wrappedAction[ACTION_MARKER] = true; wrappedAction[ACTION_NAME] = name; return wrappedAction; }; const store = /* @__PURE__ */ reactive({ _p: pinia, $id, $onAction: addSubscription.bind(null, actionSubscriptions), $patch, $reset, $subscribe(callback, options = {}) { const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher()); const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => { if (options.flush === "sync" ? isSyncListening : isListening) callback({ storeId: $id, type: MutationType.direct, events: debuggerEvents }, state); }, assign({}, $subscribeOptions, options))); return removeSubscription; }, $dispose }); pinia._s.set($id, store); const setupStore = (pinia._a && pinia._a.runWithContext || fallbackRunWithContext)(() => pinia._e.run(() => (scope = effectScope()).run(() => setup({ action })))); for (const key in setupStore) { const prop = setupStore[key]; if (/* @__PURE__ */ isRef(prop) && !isComputed(prop) || /* @__PURE__ */ isReactive(prop)) { if (!isOptionsStore) { if (initialState && shouldHydrate(prop)) if (/* @__PURE__ */ isRef(prop)) prop.value = initialState[key]; else mergeReactiveObjects(prop, initialState[key]); pinia.state.value[$id][key] = prop; } } else if (typeof prop === "function") { setupStore[key] = action(prop, key); optionsForPlugin.actions[key] = prop; } } assign(store, setupStore); assign(/* @__PURE__ */ toRaw(store), setupStore); Object.defineProperty(store, "$state", { get: () => pinia.state.value[$id], set: (state) => { $patch(($state) => { assign($state, state); }); } }); pinia._p.forEach((extender) => { assign(store, scope.run(() => extender({ store, app: pinia._a, pinia, options: optionsForPlugin }))); }); if (initialState && isOptionsStore && options.hydrate) options.hydrate(store.$state, initialState); isListening = true; isSyncListening = true; return store; } /*! #__NO_SIDE_EFFECTS__ */ function defineStore(idOrOptions, setup, setupOptions) { let id; let options; const isSetupStore = typeof setup === "function"; if (typeof idOrOptions === "string") { id = idOrOptions; options = isSetupStore ? setupOptions : setup; } else { options = idOrOptions; id = idOrOptions.id; } function useStore(pinia, hot) { const hasContext = hasInjectionContext(); pinia = pinia || (hasContext ? inject(piniaSymbol, null) : null); if (pinia) setActivePinia(pinia); pinia = activePinia; if (!pinia._s.has(id)) if (isSetupStore) createSetupStore(id, setup, options, pinia); else createOptionsStore(id, options, pinia); return pinia._s.get(id); } useStore.$id = id; return useStore; } /** * Creates an object of references with all the state, getters, and plugin-added * state properties of the store. Similar to `toRefs()` but specifically * designed for Pinia stores so methods and non reactive properties are * completely ignored. * * @param store - store to extract the refs from */ function storeToRefs(store) { { const rawStore = /* @__PURE__ */ toRaw(store); const refs = {}; for (const key in rawStore) { const value = rawStore[key]; if (value.effect) refs[key] = computed({ get: () => store[key], set(value) { store[key] = value; } }); else if (/* @__PURE__ */ isRef(value) || /* @__PURE__ */ isReactive(value)) refs[key] = /* @__PURE__ */ toRef(store, key); } return refs; } } //#endregion //#region ../send/frontend/src/apps/send/stores/config-store.ts var useConfigStore = defineStore("config", () => { const environmentName = getEnvName(); const isProd = environmentName === "production"; const isStaging = environmentName === "staging"; const isDev = environmentName === "development"; const isThunderbirdHost = computed(() => { return navigator.userAgent.includes("Thunderbird"); }); /** * Check if the URL is a moz-extension:// URL * This is the case for addons/extensions running inside Thunderbird */ const isExtension = computed(() => { return location.href.includes("moz-extension:"); }); /** * Checks if the name if the app is 'addon' * This is helpful to differentiate between the web app and the addon */ const isTbproExtension = computed(() => { return true; }); const _serverUrl = /* @__PURE__ */ ref("https://send-backend.tb.pro"); const _isPublicLogin = /* @__PURE__ */ ref(false); const serverUrl = computed(() => _serverUrl.value); const isPublicLogin = computed(() => _isPublicLogin.value); function setServerUrl(url) { _serverUrl.value = url; } function getAddonId() { const runtimeId = typeof browser !== "undefined" ? browser?.runtime?.id : void 0; if (runtimeId) return `ext-${runtimeId}`; if (serverUrl.value.includes("send-backend.tb.pro")) return "ext-tbpro-add-on@thunderbird.net"; else return "ext-tbpro-addon-stage@thunderbird.net"; } async function openManagementPage() {} return { isProd, isStaging, isDev, serverUrl, setServerUrl, isPublicLogin, isExtension, isTbproExtension, isThunderbirdHost, getAddonId, openManagementPage }; }); //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/objectSpread2-BvkFp-_Y.mjs var __create$1 = Object.create; var __defProp$2 = Object.defineProperty; var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor; var __getOwnPropNames$1 = Object.getOwnPropertyNames; var __getProtoOf$1 = Object.getPrototypeOf; var __hasOwnProp$2 = Object.prototype.hasOwnProperty; var __commonJS$1 = (cb, mod) => function() { return mod || (0, cb[__getOwnPropNames$1(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps$1 = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames$1(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp$2.call(to, key) && key !== except) __defProp$2(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc$1(from, key)) || desc.enumerable }); } return to; }; var __toESM$1 = (mod, isNodeMode, target) => (target = mod != null ? __create$1(__getProtoOf$1(mod)) : {}, __copyProps$1(isNodeMode || !mod || !mod.__esModule ? __defProp$2(target, "default", { value: mod, enumerable: true }) : target, mod)); var require_typeof$1 = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) { function _typeof$2(o) { "@babel/helpers - typeof"; return module.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) { return typeof o$1; } : function(o$1) { return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1; }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o); } module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_toPrimitive$1 = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) { var _typeof$1 = require_typeof$1()["default"]; function toPrimitive$1(t, r) { if ("object" != _typeof$1(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof$1(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_toPropertyKey$1 = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) { var _typeof = require_typeof$1()["default"]; var toPrimitive = require_toPrimitive$1(); function toPropertyKey$1(t) { var i = toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_defineProperty$1 = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) { var toPropertyKey = require_toPropertyKey$1(); function _defineProperty(e, r, t) { return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_objectSpread2$1 = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) { var defineProperty = require_defineProperty$1(); function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function(r$1) { return Object.getOwnPropertyDescriptor(e, r$1).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) { defineProperty(e, r$1, t[r$1]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) { Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1)); }); } return e; } module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); //#endregion //#region ../../node_modules/.pnpm/@trpc+server@11.17.0_typescript@5.9.3/node_modules/@trpc/server/dist/observable-UMO3vUa_.mjs /** @public */ function observable(subscribe) { const self = { subscribe(observer) { let teardownRef = null; let isDone = false; let unsubscribed = false; let teardownImmediately = false; function unsubscribe() { if (teardownRef === null) { teardownImmediately = true; return; } if (unsubscribed) return; unsubscribed = true; if (typeof teardownRef === "function") teardownRef(); else if (teardownRef) teardownRef.unsubscribe(); } teardownRef = subscribe({ next(value) { var _observer$next; if (isDone) return; (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value); }, error(err) { var _observer$error; if (isDone) return; isDone = true; (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, err); unsubscribe(); }, complete() { var _observer$complete; if (isDone) return; isDone = true; (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer); unsubscribe(); } }); if (teardownImmediately) unsubscribe(); return { unsubscribe }; }, pipe(...operations) { return operations.reduce(pipeReducer, self); } }; return self; } function pipeReducer(prev, fn) { return fn(prev); } /** @internal */ function observableToPromise(observable$1) { const ac = new AbortController(); return new Promise((resolve, reject) => { let isDone = false; function onDone() { if (isDone) return; isDone = true; obs$.unsubscribe(); } ac.signal.addEventListener("abort", () => { reject(ac.signal.reason); }); const obs$ = observable$1.subscribe({ next(data) { isDone = true; resolve(data); onDone(); }, error(data) { reject(data); }, complete() { ac.abort(); onDone(); } }); }); } //#endregion //#region ../../node_modules/.pnpm/@trpc+server@11.17.0_typescript@5.9.3/node_modules/@trpc/server/dist/observable-CUiPknO-.mjs function share(_opts) { return (source) => { let refCount = 0; let subscription = null; const observers = []; function startIfNeeded() { if (subscription) return; subscription = source.subscribe({ next(value) { for (const observer of observers) { var _observer$next; (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value); } }, error(error) { for (const observer of observers) { var _observer$error; (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, error); } }, complete() { for (const observer of observers) { var _observer$complete; (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer); } } }); } function resetIfNeeded() { if (refCount === 0 && subscription) { const _sub = subscription; subscription = null; _sub.unsubscribe(); } } return observable((subscriber) => { refCount++; observers.push(subscriber); startIfNeeded(); return { unsubscribe() { refCount--; resetIfNeeded(); const index = observers.findIndex((v) => v === subscriber); if (index > -1) observers.splice(index, 1); } }; }); }; } /** * @internal * An observable that maintains and provides a "current value" to subscribers * @see https://www.learnrxjs.io/learn-rxjs/subjects/behaviorsubject */ function behaviorSubject(initialValue) { let value = initialValue; const observerList = []; const addObserver = (observer) => { if (value !== void 0) observer.next(value); observerList.push(observer); }; const removeObserver = (observer) => { observerList.splice(observerList.indexOf(observer), 1); }; const obs = observable((observer) => { addObserver(observer); return () => { removeObserver(observer); }; }); obs.next = (nextValue) => { if (value === nextValue) return; value = nextValue; for (const observer of observerList) observer.next(nextValue); }; obs.get = () => value; return obs; } //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/splitLink-B7Cuf2c_.mjs /** @internal */ function createChain(opts) { return observable((observer) => { function execute(index = 0, op = opts.op) { const next = opts.links[index]; if (!next) throw new Error("No more links to execute - did you forget to add an ending link?"); return next({ op, next(nextOp) { return execute(index + 1, nextOp); } }); } return execute().subscribe(observer); }); } function asArray(value) { return Array.isArray(value) ? value : [value]; } function splitLink(opts) { return (runtime) => { const yes = asArray(opts.true).map((link) => link(runtime)); const no = asArray(opts.false).map((link) => link(runtime)); return (props) => { return observable((observer) => { const links = opts.condition(props.op) ? yes : no; return createChain({ op: props.op, links }).subscribe(observer); }); }; }; } //#endregion //#region ../../node_modules/.pnpm/@trpc+server@11.17.0_typescript@5.9.3/node_modules/@trpc/server/dist/codes-DagpWZLc.mjs /** * Check that value is object * @internal */ function isObject$1(value) { return !!value && !Array.isArray(value) && typeof value === "object"; } /** * Create an object without inheriting anything from `Object.prototype` * @internal */ function emptyObject() { return Object.create(null); } /** * Run an IIFE */ var run = (fn) => fn(); function sleep$1(ms = 0) { return new Promise((res) => setTimeout(res, ms)); } /** * JSON-RPC 2.0 Error codes * * `-32000` to `-32099` are reserved for implementation-defined server-errors. * For tRPC we're copying the last digits of HTTP 4XX errors. */ var TRPC_ERROR_CODES_BY_KEY = { PARSE_ERROR: -32700, BAD_REQUEST: -32600, INTERNAL_SERVER_ERROR: -32603, NOT_IMPLEMENTED: -32603, BAD_GATEWAY: -32603, SERVICE_UNAVAILABLE: -32603, GATEWAY_TIMEOUT: -32603, UNAUTHORIZED: -32001, PAYMENT_REQUIRED: -32002, FORBIDDEN: -32003, NOT_FOUND: -32004, METHOD_NOT_SUPPORTED: -32005, TIMEOUT: -32008, CONFLICT: -32009, PRECONDITION_FAILED: -32012, PAYLOAD_TOO_LARGE: -32013, UNSUPPORTED_MEDIA_TYPE: -32015, UNPROCESSABLE_CONTENT: -32022, PRECONDITION_REQUIRED: -32028, TOO_MANY_REQUESTS: -32029, CLIENT_CLOSED_REQUEST: -32099 }; TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY, TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE, TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT, TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR; //#endregion //#region ../../node_modules/.pnpm/@trpc+server@11.17.0_typescript@5.9.3/node_modules/@trpc/server/dist/getErrorShape-BPSzUA7W.mjs var __create = Object.create; var __defProp$1 = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp$1 = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp$1.call(to, key) && key !== except) __defProp$1(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp$1(target, "default", { value: mod, enumerable: true }) : target, mod)); var noop$2 = () => {}; var freezeIfAvailable = (obj) => { if (Object.freeze) Object.freeze(obj); }; function createInnerProxy(callback, path, memo) { var _memo$cacheKey; const cacheKey = path.join("."); (_memo$cacheKey = memo[cacheKey]) !== null && _memo$cacheKey !== void 0 || (memo[cacheKey] = new Proxy(noop$2, { get(_obj, key) { if (typeof key !== "string" || key === "then") return void 0; return createInnerProxy(callback, [...path, key], memo); }, apply(_1, _2, args) { const lastOfPath = path[path.length - 1]; if (lastOfPath === "valueOf" || lastOfPath === "toString" || lastOfPath === "toJSON") return `tRPC.proxy(${path.slice(0, -1).join(".")})`; let opts = { args, path }; if (lastOfPath === "call") opts = { args: args.length >= 2 ? [args[1]] : [], path: path.slice(0, -1) }; else if (lastOfPath === "apply") opts = { args: args.length >= 2 ? args[1] : [], path: path.slice(0, -1) }; freezeIfAvailable(opts.args); freezeIfAvailable(opts.path); return callback(opts); } })); return memo[cacheKey]; } /** * Creates a proxy that calls the callback with the path and arguments * * @internal */ var createRecursiveProxy = (callback) => createInnerProxy(callback, [], emptyObject()); /** * Used in place of `new Proxy` where each handler will map 1 level deep to another value. * * @internal */ var createFlatProxy = (callback) => { return new Proxy(noop$2, { get(_obj, name) { if (name === "then") return void 0; return callback(name); } }); }; var require_typeof = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) { function _typeof$2(o) { "@babel/helpers - typeof"; return module.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) { return typeof o$1; } : function(o$1) { return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1; }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o); } module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_toPrimitive = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) { var _typeof$1 = require_typeof()["default"]; function toPrimitive$1(t, r) { if ("object" != _typeof$1(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof$1(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_toPropertyKey = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) { var _typeof = require_typeof()["default"]; var toPrimitive = require_toPrimitive(); function toPropertyKey$1(t) { var i = toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_defineProperty = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) { var toPropertyKey = require_toPropertyKey(); function _defineProperty(e, r, t) { return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_objectSpread2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) { var defineProperty = require_defineProperty(); function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function(r$1) { return Object.getOwnPropertyDescriptor(e, r$1).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function(r$1) { defineProperty(e, r$1, t[r$1]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) { Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1)); }); } return e; } module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); __toESM(require_objectSpread2(), 1); __toESM(require_defineProperty(), 1); var import_objectSpread2$1$11 = __toESM(require_objectSpread2(), 1); /** @internal */ function transformResultInner(response, transformer) { if ("error" in response) { const error = transformer.deserialize(response.error); return { ok: false, error: (0, import_objectSpread2$1$11.default)((0, import_objectSpread2$1$11.default)({}, response), {}, { error }) }; } return { ok: true, result: (0, import_objectSpread2$1$11.default)((0, import_objectSpread2$1$11.default)({}, response.result), (!response.result.type || response.result.type === "data") && { type: "data", data: transformer.deserialize(response.result.data) }) }; } var TransformResultError = class extends Error { constructor() { super("Unable to transform response from server"); } }; /** * Transforms and validates that the result is a valid TRPCResponse * @internal */ function transformResult(response, transformer) { let result; try { result = transformResultInner(response, transformer); } catch (_unused) { throw new TransformResultError(); } if (!result.ok && (!isObject$1(result.error.error) || typeof result.error.error["code"] !== "number")) throw new TransformResultError(); if (result.ok && !isObject$1(result.result)) throw new TransformResultError(); return result; } __toESM(require_objectSpread2(), 1); //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/TRPCClientError-apv8gw59.mjs var import_defineProperty$5 = __toESM$1(require_defineProperty$1(), 1); var import_objectSpread2$10 = __toESM$1(require_objectSpread2$1(), 1); function isTRPCClientError(cause) { return cause instanceof TRPCClientError; } function isTRPCErrorResponse(obj) { return isObject$1(obj) && isObject$1(obj["error"]) && typeof obj["error"]["code"] === "number" && typeof obj["error"]["message"] === "string"; } function getMessageFromUnknownError(err, fallback) { if (typeof err === "string") return err; if (isObject$1(err) && typeof err["message"] === "string") return err["message"]; return fallback; } var TRPCClientError = class TRPCClientError extends Error { constructor(message, opts) { var _opts$result, _opts$result2; const cause = opts === null || opts === void 0 ? void 0 : opts.cause; super(message, { cause }); (0, import_defineProperty$5.default)(this, "cause", void 0); (0, import_defineProperty$5.default)(this, "shape", void 0); (0, import_defineProperty$5.default)(this, "data", void 0); (0, import_defineProperty$5.default)(this, "meta", void 0); this.meta = opts === null || opts === void 0 ? void 0 : opts.meta; this.cause = cause; this.shape = opts === null || opts === void 0 || (_opts$result = opts.result) === null || _opts$result === void 0 ? void 0 : _opts$result.error; this.data = opts === null || opts === void 0 || (_opts$result2 = opts.result) === null || _opts$result2 === void 0 ? void 0 : _opts$result2.error.data; this.name = "TRPCClientError"; Object.setPrototypeOf(this, TRPCClientError.prototype); } static from(_cause, opts = {}) { const cause = _cause; if (isTRPCClientError(cause)) { if (opts.meta) cause.meta = (0, import_objectSpread2$10.default)((0, import_objectSpread2$10.default)({}, cause.meta), opts.meta); return cause; } if (isTRPCErrorResponse(cause)) return new TRPCClientError(cause.error.message, (0, import_objectSpread2$10.default)((0, import_objectSpread2$10.default)({}, opts), {}, { result: cause, cause: opts.cause })); return new TRPCClientError(getMessageFromUnknownError(cause, "Unknown error"), (0, import_objectSpread2$10.default)((0, import_objectSpread2$10.default)({}, opts), {}, { cause })); } }; //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/unstable-internals-Bg7n9BBj.mjs /** * @internal */ /** * @internal */ function getTransformer(transformer) { const _transformer = transformer; if (!_transformer) return { input: { serialize: (data) => data, deserialize: (data) => data }, output: { serialize: (data) => data, deserialize: (data) => data } }; if ("input" in _transformer) return _transformer; return { input: _transformer, output: _transformer }; } //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/httpUtils-pyf5RF99.mjs var isFunction$1 = (fn) => typeof fn === "function"; function getFetch(customFetchImpl) { if (customFetchImpl) return customFetchImpl; if (typeof window !== "undefined" && isFunction$1(window.fetch)) return window.fetch; if (typeof globalThis !== "undefined" && isFunction$1(globalThis.fetch)) return globalThis.fetch; throw new Error("No fetch implementation found"); } var import_objectSpread2$9 = __toESM$1(require_objectSpread2$1(), 1); function resolveHTTPLinkOptions(opts) { return { url: opts.url.toString(), fetch: opts.fetch, transformer: getTransformer(opts.transformer), methodOverride: opts.methodOverride }; } function arrayToDict(array) { const dict = {}; for (let index = 0; index < array.length; index++) dict[index] = array[index]; return dict; } var METHOD = { query: "GET", mutation: "POST", subscription: "PATCH" }; function getInput(opts) { return "input" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input))); } var getUrl = (opts) => { const parts = opts.url.split("?"); let url = parts[0].replace(/\/$/, "") + "/" + opts.path; const queryParts = []; if (parts[1]) queryParts.push(parts[1]); if ("inputs" in opts) queryParts.push("batch=1"); if (opts.type === "query" || opts.type === "subscription") { const input = getInput(opts); if (input !== void 0 && opts.methodOverride !== "POST") queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`); } if (queryParts.length) url += "?" + queryParts.join("&"); return url; }; var getBody = (opts) => { if (opts.type === "query" && opts.methodOverride !== "POST") return void 0; const input = getInput(opts); return input !== void 0 ? JSON.stringify(input) : void 0; }; var jsonHttpRequester = (opts) => { return httpRequest((0, import_objectSpread2$9.default)((0, import_objectSpread2$9.default)({}, opts), {}, { contentTypeHeader: "application/json", getUrl, getBody })); }; /** * Polyfill for DOMException with AbortError name */ var AbortError = class extends Error { constructor() { const name = "AbortError"; super(name); this.name = name; this.message = name; } }; /** * Polyfill for `signal.throwIfAborted()` * * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted */ var throwIfAborted = (signal) => { var _signal$throwIfAborte; if (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) return; (_signal$throwIfAborte = signal.throwIfAborted) === null || _signal$throwIfAborte === void 0 || _signal$throwIfAborte.call(signal); if (typeof DOMException !== "undefined") throw new DOMException("AbortError", "AbortError"); throw new AbortError(); }; async function fetchHTTPResponse(opts) { var _opts$methodOverride, _opts$trpcAcceptHeade; throwIfAborted(opts.signal); const url = opts.getUrl(opts); const body = opts.getBody(opts); const method = (_opts$methodOverride = opts.methodOverride) !== null && _opts$methodOverride !== void 0 ? _opts$methodOverride : METHOD[opts.type]; const resolvedHeaders = await (async () => { const heads = await opts.headers(); if (Symbol.iterator in heads) return Object.fromEntries(heads); return heads; })(); const headers = (0, import_objectSpread2$9.default)((0, import_objectSpread2$9.default)((0, import_objectSpread2$9.default)({}, opts.contentTypeHeader && method !== "GET" ? { "content-type": opts.contentTypeHeader } : {}), opts.trpcAcceptHeader ? { [(_opts$trpcAcceptHeade = opts.trpcAcceptHeaderKey) !== null && _opts$trpcAcceptHeade !== void 0 ? _opts$trpcAcceptHeade : "trpc-accept"]: opts.trpcAcceptHeader } : void 0), resolvedHeaders); return getFetch(opts.fetch)(url, { method, signal: opts.signal, body, headers }); } async function httpRequest(opts) { const meta = {}; const res = await fetchHTTPResponse(opts); meta.response = res; const json = await res.json(); meta.responseJSON = json; return { json, meta }; } __toESM$1(require_objectSpread2$1(), 1); //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/httpBatchLink-LhidKAPw.mjs /** * A function that should never be called unless we messed something up. */ var throwFatalError = () => { throw new Error("Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new"); }; /** * Dataloader that's very inspired by https://github.com/graphql/dataloader * Less configuration, no caching, and allows you to cancel requests * When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled */ function dataLoader(batchLoader) { let pendingItems = null; let dispatchTimer = null; const destroyTimerAndPendingItems = () => { clearTimeout(dispatchTimer); dispatchTimer = null; pendingItems = null; }; /** * Iterate through the items and split them into groups based on the `batchLoader`'s validate function */ function groupItems(items) { const groupedItems = [[]]; let index = 0; while (true) { const item = items[index]; if (!item) break; const lastGroup = groupedItems[groupedItems.length - 1]; if (item.aborted) { var _item$reject; (_item$reject = item.reject) === null || _item$reject === void 0 || _item$reject.call(item, /* @__PURE__ */ new Error("Aborted")); index++; continue; } if (batchLoader.validate(lastGroup.concat(item).map((it) => it.key))) { lastGroup.push(item); index++; continue; } if (lastGroup.length === 0) { var _item$reject2; (_item$reject2 = item.reject) === null || _item$reject2 === void 0 || _item$reject2.call(item, /* @__PURE__ */ new Error("Input is too big for a single dispatch")); index++; continue; } groupedItems.push([]); } return groupedItems; } function dispatch() { const groupedItems = groupItems(pendingItems); destroyTimerAndPendingItems(); for (const items of groupedItems) { if (!items.length) continue; const batch = { items }; for (const item of items) item.batch = batch; batchLoader.fetch(batch.items.map((_item) => _item.key)).then(async (result) => { await Promise.all(result.map(async (valueOrPromise, index) => { const item = batch.items[index]; try { var _item$resolve; const value = await Promise.resolve(valueOrPromise); (_item$resolve = item.resolve) === null || _item$resolve === void 0 || _item$resolve.call(item, value); } catch (cause) { var _item$reject3; (_item$reject3 = item.reject) === null || _item$reject3 === void 0 || _item$reject3.call(item, cause); } item.batch = null; item.reject = null; item.resolve = null; })); for (const item of batch.items) { var _item$reject4; (_item$reject4 = item.reject) === null || _item$reject4 === void 0 || _item$reject4.call(item, /* @__PURE__ */ new Error("Missing result")); item.batch = null; } }).catch((cause) => { for (const item of batch.items) { var _item$reject5; (_item$reject5 = item.reject) === null || _item$reject5 === void 0 || _item$reject5.call(item, cause); item.batch = null; } }); } } function load(key) { var _dispatchTimer; const item = { aborted: false, key, batch: null, resolve: throwFatalError, reject: throwFatalError }; const promise = new Promise((resolve, reject) => { var _pendingItems; item.reject = reject; item.resolve = resolve; (_pendingItems = pendingItems) !== null && _pendingItems !== void 0 || (pendingItems = []); pendingItems.push(item); }); (_dispatchTimer = dispatchTimer) !== null && _dispatchTimer !== void 0 || (dispatchTimer = setTimeout(dispatch)); return promise; } return { load }; } /** * Like `Promise.all()` but for abort signals * - When all signals have been aborted, the merged signal will be aborted * - If one signal is `null`, no signal will be aborted */ function allAbortSignals(...signals) { const ac = new AbortController(); const count = signals.length; let abortedCount = 0; const onAbort = () => { if (++abortedCount === count) ac.abort(); }; for (const signal of signals) if (signal === null || signal === void 0 ? void 0 : signal.aborted) onAbort(); else signal === null || signal === void 0 || signal.addEventListener("abort", onAbort, { once: true }); return ac.signal; } var import_objectSpread2$7 = __toESM$1(require_objectSpread2$1(), 1); /** * @see https://trpc.io/docs/client/links/httpBatchLink */ function httpBatchLink(opts) { var _opts$maxURLLength, _opts$maxItems; const resolvedOpts = resolveHTTPLinkOptions(opts); const maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== void 0 ? _opts$maxURLLength : Infinity; const maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== void 0 ? _opts$maxItems : Infinity; return () => { const batchLoader = (type) => { return { validate(batchOps) { if (maxURLLength === Infinity && maxItems === Infinity) return true; if (batchOps.length > maxItems) return false; const path = batchOps.map((op) => op.path).join(","); const inputs = batchOps.map((op) => op.input); return getUrl((0, import_objectSpread2$7.default)((0, import_objectSpread2$7.default)({}, resolvedOpts), {}, { type, path, inputs, signal: null })).length <= maxURLLength; }, async fetch(batchOps) { const path = batchOps.map((op) => op.path).join(","); const inputs = batchOps.map((op) => op.input); const signal = allAbortSignals(...batchOps.map((op) => op.signal)); const res = await jsonHttpRequester((0, import_objectSpread2$7.default)((0, import_objectSpread2$7.default)({}, resolvedOpts), {}, { path, inputs, type, headers() { if (!opts.headers) return {}; if (typeof opts.headers === "function") return opts.headers({ opList: batchOps }); return opts.headers; }, signal })); return (Array.isArray(res.json) ? res.json : batchOps.map(() => res.json)).map((item) => ({ meta: res.meta, json: item })); } }; }; const loaders = { query: dataLoader(batchLoader("query")), mutation: dataLoader(batchLoader("mutation")) }; return ({ op }) => { return observable((observer) => { /* istanbul ignore if -- @preserve */ if (op.type === "subscription") throw new Error("Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`"); const promise = loaders[op.type].load(op); let _res = void 0; promise.then((res) => { _res = res; const transformed = transformResult(res.json, resolvedOpts.transformer.output); if (!transformed.ok) { observer.error(TRPCClientError.from(transformed.error, { meta: res.meta })); return; } observer.next({ context: res.meta, result: transformed.result }); observer.complete(); }).catch((err) => { observer.error(TRPCClientError.from(err, { meta: _res === null || _res === void 0 ? void 0 : _res.meta })); }); return () => {}; }); }; }; } __toESM$1(require_objectSpread2$1(), 1); //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/wsLink-DSf4KOdW.mjs var jsonEncoder = { encode: (data) => JSON.stringify(data), decode: (data) => { if (typeof data !== "string") throw new Error("jsonEncoder received binary data. JSON uses text frames. Use a binary encoder for binary data."); return JSON.parse(data); } }; var lazyDefaults = { enabled: false, closeMs: 0 }; var keepAliveDefaults = { enabled: false, pongTimeoutMs: 1e3, intervalMs: 5e3 }; /** * Calculates a delay for exponential backoff based on the retry attempt index. * The delay starts at 0 for the first attempt and doubles for each subsequent attempt, * capped at 30 seconds. */ var exponentialBackoff = (attemptIndex) => { return attemptIndex === 0 ? 0 : Math.min(1e3 * 2 ** attemptIndex, 3e4); }; /** * Get the result of a value or function that returns a value * It also optionally accepts typesafe arguments for the function */ var resultOf = (value, ...args) => { return typeof value === "function" ? value(...args) : value; }; var import_defineProperty$3 = __toESM$1(require_defineProperty$1(), 1); var TRPCWebSocketClosedError = class TRPCWebSocketClosedError extends Error { constructor(opts) { super(opts.message, { cause: opts.cause }); this.name = "TRPCWebSocketClosedError"; Object.setPrototypeOf(this, TRPCWebSocketClosedError.prototype); } }; /** * Utility class for managing a timeout that can be started, stopped, and reset. * Useful for scenarios where the timeout duration is reset dynamically based on events. */ var ResettableTimeout = class { constructor(onTimeout, timeoutMs) { this.onTimeout = onTimeout; this.timeoutMs = timeoutMs; (0, import_defineProperty$3.default)(this, "timeout", void 0); } /** * Resets the current timeout, restarting it with the same duration. * Does nothing if no timeout is active. */ reset() { if (!this.timeout) return; clearTimeout(this.timeout); this.timeout = setTimeout(this.onTimeout, this.timeoutMs); } start() { clearTimeout(this.timeout); this.timeout = setTimeout(this.onTimeout, this.timeoutMs); } stop() { clearTimeout(this.timeout); this.timeout = void 0; } }; function withResolvers() { let resolve; let reject; return { promise: new Promise((res, rej) => { resolve = res; reject = rej; }), resolve, reject }; } /** * Resolves a WebSocket URL and optionally appends connection parameters. * * If connectionParams are provided, appends 'connectionParams=1' query parameter. */ async function prepareUrl(urlOptions) { const url = await resultOf(urlOptions.url); if (!urlOptions.connectionParams) return url; return url + `${url.includes("?") ? "&" : "?"}connectionParams=1`; } async function buildConnectionMessage(connectionParams, encoder) { const message = { method: "connectionParams", data: await resultOf(connectionParams) }; return encoder.encode(message); } var import_defineProperty$2 = __toESM$1(require_defineProperty$1(), 1); /** * Manages WebSocket requests, tracking their lifecycle and providing utility methods * for handling outgoing and pending requests. * * - **Outgoing requests**: Requests that are queued and waiting to be sent. * - **Pending requests**: Requests that have been sent and are in flight awaiting a response. * For subscriptions, multiple responses may be received until the subscription is closed. */ var RequestManager = class { constructor() { (0, import_defineProperty$2.default)(this, "outgoingRequests", new Array()); (0, import_defineProperty$2.default)(this, "pendingRequests", {}); } /** * Registers a new request by adding it to the outgoing queue and setting up * callbacks for lifecycle events such as completion or error. * * @param message - The outgoing message to be sent. * @param callbacks - Callback functions to observe the request's state. * @returns A cleanup function to manually remove the request. */ register(message, callbacks) { const { promise: end, resolve } = withResolvers(); this.outgoingRequests.push({ id: String(message.id), message, end, callbacks: { next: callbacks.next, complete: () => { callbacks.complete(); resolve(); }, error: (e) => { callbacks.error(e); resolve(); } } }); return () => { this.delete(message.id); callbacks.complete(); resolve(); }; } /** * Deletes a request from both the outgoing and pending collections, if it exists. */ delete(messageId) { if (messageId === null) return; this.outgoingRequests = this.outgoingRequests.filter(({ id }) => id !== String(messageId)); delete this.pendingRequests[String(messageId)]; } /** * Moves all outgoing requests to the pending state and clears the outgoing queue. * * The caller is expected to handle the actual sending of the requests * (e.g., sending them over the network) after this method is called. * * @returns The list of requests that were transitioned to the pending state. */ flush() { const requests = this.outgoingRequests; this.outgoingRequests = []; for (const request of requests) this.pendingRequests[request.id] = request; return requests; } /** * Retrieves all currently pending requests, which are in flight awaiting responses * or handling ongoing subscriptions. */ getPendingRequests() { return Object.values(this.pendingRequests); } /** * Retrieves a specific pending request by its message ID. */ getPendingRequest(messageId) { if (messageId === null) return null; return this.pendingRequests[String(messageId)]; } /** * Retrieves all outgoing requests, which are waiting to be sent. */ getOutgoingRequests() { return this.outgoingRequests; } /** * Retrieves all requests, both outgoing and pending, with their respective states. * * @returns An array of all requests with their state ("outgoing" or "pending"). */ getRequests() { return [...this.getOutgoingRequests().map((request) => ({ state: "outgoing", message: request.message, end: request.end, callbacks: request.callbacks })), ...this.getPendingRequests().map((request) => ({ state: "pending", message: request.message, end: request.end, callbacks: request.callbacks }))]; } /** * Checks if there are any pending requests, including ongoing subscriptions. */ hasPendingRequests() { return this.getPendingRequests().length > 0; } /** * Checks if there are any pending subscriptions */ hasPendingSubscriptions() { return this.getPendingRequests().some((request) => request.message.method === "subscription"); } /** * Checks if there are any outgoing requests waiting to be sent. */ hasOutgoingRequests() { return this.outgoingRequests.length > 0; } }; var import_defineProperty$1 = __toESM$1(require_defineProperty$1(), 1); /** * Opens a WebSocket connection asynchronously and returns a promise * that resolves when the connection is successfully established. * The promise rejects if an error occurs during the connection attempt. */ function asyncWsOpen(ws) { const { promise, resolve, reject } = withResolvers(); ws.addEventListener("open", () => { ws.removeEventListener("error", reject); resolve(); }); ws.addEventListener("error", reject); return promise; } /** * Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive. * * - Sends "PING" messages at regular intervals defined by `intervalMs`. * - If a "PONG" response is not received within the `pongTimeoutMs`, the WebSocket is closed. * - The ping timer resets upon receiving any message to maintain activity. * - Automatically starts the ping process when the WebSocket connection is opened. * - Cleans up timers when the WebSocket is closed. * * @param ws - The WebSocket instance to manage. * @param options - Configuration options for ping-pong intervals and timeouts. */ function setupPingInterval(ws, { intervalMs, pongTimeoutMs }) { let pingTimeout; let pongTimeout; function start() { pingTimeout = setTimeout(() => { ws.send("PING"); pongTimeout = setTimeout(() => { ws.close(); }, pongTimeoutMs); }, intervalMs); } function reset() { clearTimeout(pingTimeout); start(); } function pong() { clearTimeout(pongTimeout); reset(); } ws.addEventListener("open", start); ws.addEventListener("message", ({ data }) => { clearTimeout(pingTimeout); start(); if (data === "PONG") pong(); }); ws.addEventListener("close", () => { clearTimeout(pingTimeout); clearTimeout(pongTimeout); }); } /** * Manages a WebSocket connection with support for reconnection, keep-alive mechanisms, * and observable state tracking. */ var WsConnection = class WsConnection { constructor(opts) { var _opts$WebSocketPonyfi; (0, import_defineProperty$1.default)(this, "id", ++WsConnection.connectCount); (0, import_defineProperty$1.default)(this, "WebSocketPonyfill", void 0); (0, import_defineProperty$1.default)(this, "urlOptions", void 0); (0, import_defineProperty$1.default)(this, "keepAliveOpts", void 0); (0, import_defineProperty$1.default)(this, "encoder", void 0); (0, import_defineProperty$1.default)(this, "wsObservable", behaviorSubject(null)); (0, import_defineProperty$1.default)(this, "openPromise", null); this.WebSocketPonyfill = (_opts$WebSocketPonyfi = opts.WebSocketPonyfill) !== null && _opts$WebSocketPonyfi !== void 0 ? _opts$WebSocketPonyfi : WebSocket; if (!this.WebSocketPonyfill) throw new Error("No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill"); this.urlOptions = opts.urlOptions; this.keepAliveOpts = opts.keepAlive; this.encoder = opts.encoder; } get ws() { return this.wsObservable.get(); } set ws(ws) { this.wsObservable.next(ws); } /** * Checks if the WebSocket connection is open and ready to communicate. */ isOpen() { return !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise; } /** * Checks if the WebSocket connection is closed or in the process of closing. */ isClosed() { return !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED); } async open() { var _this = this; if (_this.openPromise) return _this.openPromise; _this.id = ++WsConnection.connectCount; _this.openPromise = prepareUrl(_this.urlOptions).then((url) => new _this.WebSocketPonyfill(url)).then(async (ws) => { _this.ws = ws; ws.binaryType = "arraybuffer"; ws.addEventListener("message", function({ data }) { if (data === "PING") this.send("PONG"); }); if (_this.keepAliveOpts.enabled) setupPingInterval(ws, _this.keepAliveOpts); ws.addEventListener("close", () => { if (_this.ws === ws) _this.ws = null; }); await asyncWsOpen(ws); if (_this.urlOptions.connectionParams) ws.send(await buildConnectionMessage(_this.urlOptions.connectionParams, _this.encoder)); }); try { await _this.openPromise; } finally { _this.openPromise = null; } } /** * Closes the WebSocket connection gracefully. * Waits for any ongoing open operation to complete before closing. */ async close() { var _this2 = this; try { await _this2.openPromise; } finally { var _this$ws; (_this$ws = _this2.ws) === null || _this$ws === void 0 || _this$ws.close(); } } }; (0, import_defineProperty$1.default)(WsConnection, "connectCount", 0); /** * Provides a backward-compatible representation of the connection state. */ function backwardCompatibility(connection) { if (connection.isOpen()) return { id: connection.id, state: "open", ws: connection.ws }; if (connection.isClosed()) return { id: connection.id, state: "closed", ws: connection.ws }; if (!connection.ws) return null; return { id: connection.id, state: "connecting", ws: connection.ws }; } var import_defineProperty$4 = __toESM$1(require_defineProperty$1(), 1); var import_objectSpread2$5 = __toESM$1(require_objectSpread2$1(), 1); /** * A WebSocket client for managing TRPC operations, supporting lazy initialization, * reconnection, keep-alive, and request management. */ var WsClient = class { constructor(opts) { var _opts$experimental_en, _opts$retryDelayMs; (0, import_defineProperty$4.default)(this, "connectionState", void 0); (0, import_defineProperty$4.default)(this, "allowReconnect", false); (0, import_defineProperty$4.default)(this, "requestManager", new RequestManager()); (0, import_defineProperty$4.default)(this, "activeConnection", void 0); (0, import_defineProperty$4.default)(this, "reconnectRetryDelay", void 0); (0, import_defineProperty$4.default)(this, "inactivityTimeout", void 0); (0, import_defineProperty$4.default)(this, "callbacks", void 0); (0, import_defineProperty$4.default)(this, "lazyMode", void 0); (0, import_defineProperty$4.default)(this, "encoder", void 0); (0, import_defineProperty$4.default)(this, "reconnecting", null); this.encoder = (_opts$experimental_en = opts.experimental_encoder) !== null && _opts$experimental_en !== void 0 ? _opts$experimental_en : jsonEncoder; this.callbacks = { onOpen: opts.onOpen, onClose: opts.onClose, onError: opts.onError }; const lazyOptions = (0, import_objectSpread2$5.default)((0, import_objectSpread2$5.default)({}, lazyDefaults), opts.lazy); this.inactivityTimeout = new ResettableTimeout(() => { if (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) { this.inactivityTimeout.reset(); return; } this.close().catch(() => null); }, lazyOptions.closeMs); this.activeConnection = new WsConnection({ WebSocketPonyfill: opts.WebSocket, urlOptions: opts, keepAlive: (0, import_objectSpread2$5.default)((0, import_objectSpread2$5.default)({}, keepAliveDefaults), opts.keepAlive), encoder: this.encoder }); this.activeConnection.wsObservable.subscribe({ next: (ws) => { if (!ws) return; this.setupWebSocketListeners(ws); } }); this.reconnectRetryDelay = (_opts$retryDelayMs = opts.retryDelayMs) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : exponentialBackoff; this.lazyMode = lazyOptions.enabled; this.connectionState = behaviorSubject({ type: "state", state: lazyOptions.enabled ? "idle" : "connecting", error: null }); if (!this.lazyMode) this.open().catch(() => null); } /** * Opens the WebSocket connection. Handles reconnection attempts and updates * the connection state accordingly. */ async open() { var _this = this; _this.allowReconnect = true; if (_this.connectionState.get().state === "idle") _this.connectionState.next({ type: "state", state: "connecting", error: null }); try { await _this.activeConnection.open(); } catch (error) { _this.reconnect(new TRPCWebSocketClosedError({ message: "Initialization error", cause: error })); return _this.reconnecting; } } /** * Closes the WebSocket connection and stops managing requests. * Ensures all outgoing and pending requests are properly finalized. */ async close() { var _this2 = this; _this2.allowReconnect = false; _this2.inactivityTimeout.stop(); const requestsToAwait = []; for (const request of _this2.requestManager.getRequests()) if (request.message.method === "subscription") request.callbacks.complete(); else if (request.state === "outgoing") request.callbacks.error(TRPCClientError.from(new TRPCWebSocketClosedError({ message: "Closed before connection was established" }))); else requestsToAwait.push(request.end); await Promise.all(requestsToAwait).catch(() => null); await _this2.activeConnection.close().catch(() => null); _this2.connectionState.next({ type: "state", state: "idle", error: null }); } /** * Method to request the server. * Handles data transformation, batching of requests, and subscription lifecycle. * * @param op - The operation details including id, type, path, input and signal * @param transformer - Data transformer for serializing requests and deserializing responses * @param lastEventId - Optional ID of the last received event for subscriptions * * @returns An observable that emits operation results and handles cleanup */ request({ op: { id, type, path, input, signal }, transformer, lastEventId }) { return observable((observer) => { const abort = this.batchSend({ id, method: type, params: { input: transformer.input.serialize(input), path, lastEventId } }, (0, import_objectSpread2$5.default)((0, import_objectSpread2$5.default)({}, observer), {}, { next(event) { const transformed = transformResult(event, transformer.output); if (!transformed.ok) { observer.error(TRPCClientError.from(transformed.error)); return; } observer.next({ result: transformed.result }); } })); return () => { abort(); if (type === "subscription" && this.activeConnection.isOpen()) this.send({ id, method: "subscription.stop" }); signal === null || signal === void 0 || signal.removeEventListener("abort", abort); }; }); } get connection() { return backwardCompatibility(this.activeConnection); } reconnect(closedError) { var _this3 = this; this.connectionState.next({ type: "state", state: "connecting", error: TRPCClientError.from(closedError) }); if (this.reconnecting) return; const tryReconnect = async (attemptIndex) => { try { await sleep$1(_this3.reconnectRetryDelay(attemptIndex)); if (_this3.allowReconnect) { await _this3.activeConnection.close(); await _this3.activeConnection.open(); if (_this3.requestManager.hasPendingRequests()) _this3.send(_this3.requestManager.getPendingRequests().map(({ message }) => message)); } _this3.reconnecting = null; } catch (_unused) { await tryReconnect(attemptIndex + 1); } }; this.reconnecting = tryReconnect(0); } setupWebSocketListeners(ws) { var _this4 = this; const handleCloseOrError = (cause) => { const reqs = this.requestManager.getPendingRequests(); for (const { message, callbacks } of reqs) { if (message.method === "subscription") continue; callbacks.error(TRPCClientError.from(cause !== null && cause !== void 0 ? cause : new TRPCWebSocketClosedError({ message: "WebSocket closed", cause }))); this.requestManager.delete(message.id); } }; ws.addEventListener("open", () => { run(async () => { var _this$callbacks$onOpe, _this$callbacks; if (_this4.lazyMode) _this4.inactivityTimeout.start(); (_this$callbacks$onOpe = (_this$callbacks = _this4.callbacks).onOpen) === null || _this$callbacks$onOpe === void 0 || _this$callbacks$onOpe.call(_this$callbacks); _this4.connectionState.next({ type: "state", state: "pending", error: null }); }).catch((error) => { ws.close(3e3); handleCloseOrError(error); }); }); ws.addEventListener("message", ({ data }) => { this.inactivityTimeout.reset(); if (["PING", "PONG"].includes(data)) return; const incomingMessage = this.encoder.decode(data); if ("method" in incomingMessage) { this.handleIncomingRequest(incomingMessage); return; } this.handleResponseMessage(incomingMessage); }); ws.addEventListener("close", (event) => { var _this$callbacks$onClo, _this$callbacks2; handleCloseOrError(event); (_this$callbacks$onClo = (_this$callbacks2 = this.callbacks).onClose) === null || _this$callbacks$onClo === void 0 || _this$callbacks$onClo.call(_this$callbacks2, event); if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) this.reconnect(new TRPCWebSocketClosedError({ message: "WebSocket closed", cause: event })); }); ws.addEventListener("error", (event) => { var _this$callbacks$onErr, _this$callbacks3; handleCloseOrError(event); (_this$callbacks$onErr = (_this$callbacks3 = this.callbacks).onError) === null || _this$callbacks$onErr === void 0 || _this$callbacks$onErr.call(_this$callbacks3, event); this.reconnect(new TRPCWebSocketClosedError({ message: "WebSocket closed", cause: event })); }); } handleResponseMessage(message) { const request = this.requestManager.getPendingRequest(message.id); if (!request) return; request.callbacks.next(message); let completed = true; if ("result" in message && request.message.method === "subscription") { if (message.result.type === "data") request.message.params.lastEventId = message.result.id; if (message.result.type !== "stopped") completed = false; } if (completed) { request.callbacks.complete(); this.requestManager.delete(message.id); } } handleIncomingRequest(message) { if (message.method === "reconnect") this.reconnect(new TRPCWebSocketClosedError({ message: "Server requested reconnect" })); } /** * Sends a message or batch of messages directly to the server. */ send(messageOrMessages) { if (!this.activeConnection.isOpen()) throw new Error("Active connection is not open"); const messages = messageOrMessages instanceof Array ? messageOrMessages : [messageOrMessages]; this.activeConnection.ws.send(this.encoder.encode(messages.length === 1 ? messages[0] : messages)); } /** * Groups requests for batch sending. * * @returns A function to abort the batched request. */ batchSend(message, callbacks) { var _this5 = this; this.inactivityTimeout.reset(); run(async () => { if (!_this5.activeConnection.isOpen()) await _this5.open(); await sleep$1(0); if (!_this5.requestManager.hasOutgoingRequests()) return; _this5.send(_this5.requestManager.flush().map(({ message: message$1 }) => message$1)); }).catch((err) => { this.requestManager.delete(message.id); callbacks.error(TRPCClientError.from(err)); }); return this.requestManager.register(message, callbacks); } }; function createWSClient(opts) { return new WsClient(opts); } function wsLink(opts) { const { client } = opts; const transformer = getTransformer(opts.transformer); return () => { return ({ op }) => { return observable((observer) => { const connStateSubscription = op.type === "subscription" ? client.connectionState.subscribe({ next(result) { observer.next({ result, context: op.context }); } }) : null; const requestSubscription = client.request({ op, transformer }).subscribe(observer); return () => { requestSubscription.unsubscribe(); connStateSubscription === null || connStateSubscription === void 0 || connStateSubscription.unsubscribe(); }; }); }; }; } //#endregion //#region ../../node_modules/.pnpm/@trpc+client@11.17.0_@trpc+server@11.17.0_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/index.mjs var import_defineProperty = __toESM$1(require_defineProperty$1(), 1); var import_objectSpread2$4 = __toESM$1(require_objectSpread2$1(), 1); var TRPCUntypedClient = class { constructor(opts) { (0, import_defineProperty.default)(this, "links", void 0); (0, import_defineProperty.default)(this, "runtime", void 0); (0, import_defineProperty.default)(this, "requestId", void 0); this.requestId = 0; this.runtime = {}; this.links = opts.links.map((link) => link(this.runtime)); } $request(opts) { var _opts$context; return createChain({ links: this.links, op: (0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, opts), {}, { context: (_opts$context = opts.context) !== null && _opts$context !== void 0 ? _opts$context : {}, id: ++this.requestId }) }).pipe(share()); } async requestAsPromise(opts) { var _this = this; try { return (await observableToPromise(_this.$request(opts))).result.data; } catch (err) { throw TRPCClientError.from(err); } } query(path, input, opts) { return this.requestAsPromise({ type: "query", path, input, context: opts === null || opts === void 0 ? void 0 : opts.context, signal: opts === null || opts === void 0 ? void 0 : opts.signal }); } mutation(path, input, opts) { return this.requestAsPromise({ type: "mutation", path, input, context: opts === null || opts === void 0 ? void 0 : opts.context, signal: opts === null || opts === void 0 ? void 0 : opts.signal }); } subscription(path, input, opts) { return this.$request({ type: "subscription", path, input, context: opts.context, signal: opts.signal }).subscribe({ next(envelope) { switch (envelope.result.type) { case "state": var _opts$onConnectionSta; (_opts$onConnectionSta = opts.onConnectionStateChange) === null || _opts$onConnectionSta === void 0 || _opts$onConnectionSta.call(opts, envelope.result); break; case "started": var _opts$onStarted; (_opts$onStarted = opts.onStarted) === null || _opts$onStarted === void 0 || _opts$onStarted.call(opts, { context: envelope.context }); break; case "stopped": var _opts$onStopped; (_opts$onStopped = opts.onStopped) === null || _opts$onStopped === void 0 || _opts$onStopped.call(opts); break; case "data": case void 0: var _opts$onData; (_opts$onData = opts.onData) === null || _opts$onData === void 0 || _opts$onData.call(opts, envelope.result.data); break; } }, error(err) { var _opts$onError; (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, err); }, complete() { var _opts$onComplete; (_opts$onComplete = opts.onComplete) === null || _opts$onComplete === void 0 || _opts$onComplete.call(opts); } }); } }; var untypedClientSymbol = Symbol.for("trpc_untypedClient"); var clientCallTypeMap = { query: "query", mutate: "mutation", subscribe: "subscription" }; /** @internal */ var clientCallTypeToProcedureType = (clientCallType) => { return clientCallTypeMap[clientCallType]; }; /** * @internal */ function createTRPCClientProxy(client) { const proxy = createRecursiveProxy(({ path, args }) => { const pathCopy = [...path]; const procedureType = clientCallTypeToProcedureType(pathCopy.pop()); const fullPath = pathCopy.join("."); return client[procedureType](fullPath, ...args); }); return createFlatProxy((key) => { if (key === untypedClientSymbol) return client; return proxy[key]; }); } function createTRPCClient(opts) { return createTRPCClientProxy(new TRPCUntypedClient(opts)); } __toESM$1(require_objectSpread2$1(), 1); var import_objectSpread2$2 = __toESM$1(require_objectSpread2$1(), 1); function inputWithTrackedEventId(input, lastEventId) { if (!lastEventId) return input; if (input != null && typeof input !== "object") return input; return (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, input !== null && input !== void 0 ? input : {}), {}, { lastEventId }); } __toESM$1(__commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncIterator.js"(exports, module) { function _asyncIterator$1(r) { var n, t, o, e = 2; for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) { if (t && null != (n = r[t])) return n.call(r); if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r)); t = "@@asyncIterator", o = "@@iterator"; } throw new TypeError("Object is not async iterable"); } function AsyncFromSyncIterator(r) { function AsyncFromSyncIteratorContinuation(r$1) { if (Object(r$1) !== r$1) return Promise.reject(/* @__PURE__ */ new TypeError(r$1 + " is not an object.")); var n = r$1.done; return Promise.resolve(r$1.value).then(function(r$2) { return { value: r$2, done: n }; }); } return AsyncFromSyncIterator = function AsyncFromSyncIterator$1(r$1) { this.s = r$1, this.n = r$1.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, "return": function _return(r$1) { var n = this.s["return"]; return void 0 === n ? Promise.resolve({ value: r$1, done: !0 }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); }, "throw": function _throw(r$1) { var n = this.s["return"]; return void 0 === n ? Promise.reject(r$1) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(r); } module.exports = _asyncIterator$1, module.exports.__esModule = true, module.exports["default"] = module.exports; } })(), 1); var import_objectSpread2$1 = __toESM$1(require_objectSpread2$1(), 1); /** * @see https://trpc.io/docs/v11/client/links/retryLink */ function retryLink(opts) { return () => { return (callOpts) => { return observable((observer) => { let next$; let callNextTimeout = void 0; let lastEventId = void 0; attempt(1); function opWithLastEventId() { const op = callOpts.op; if (!lastEventId) return op; return (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, op), {}, { input: inputWithTrackedEventId(op.input, lastEventId) }); } function attempt(attempts) { const op = opWithLastEventId(); next$ = callOpts.next(op).subscribe({ error(error) { var _opts$retryDelayMs, _opts$retryDelayMs2; if (!opts.retry({ op, attempts, error })) { observer.error(error); return; } const delayMs = (_opts$retryDelayMs = (_opts$retryDelayMs2 = opts.retryDelayMs) === null || _opts$retryDelayMs2 === void 0 ? void 0 : _opts$retryDelayMs2.call(opts, attempts)) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : 0; if (delayMs <= 0) { attempt(attempts + 1); return; } callNextTimeout = setTimeout(() => attempt(attempts + 1), delayMs); }, next(envelope) { if ((!envelope.result.type || envelope.result.type === "data") && envelope.result.id) lastEventId = envelope.result.id; observer.next(envelope); }, complete() { observer.complete(); } }); } return () => { next$.unsubscribe(); clearTimeout(callNextTimeout); }; }); }; }; } var require_usingCtx = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js"(exports, module) { function _usingCtx() { var r = "function" == typeof SuppressedError ? SuppressedError : function(r$1, e$1) { var n$1 = Error(); return n$1.name = "SuppressedError", n$1.error = r$1, n$1.suppressed = e$1, n$1; }, e = {}, n = []; function using(r$1, e$1) { if (null != e$1) { if (Object(e$1) !== e$1) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined."); if (r$1) var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")]; if (void 0 === o && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1)) var t = o; if ("function" != typeof o) throw new TypeError("Object is not disposable."); t && (o = function o$1() { try { t.call(e$1); } catch (r$2) { return Promise.reject(r$2); } }), n.push({ v: e$1, d: o, a: r$1 }); } else r$1 && n.push({ d: e$1, a: r$1 }); return e$1; } return { e, u: using.bind(null, !1), a: using.bind(null, !0), d: function d() { var o, t = this.e, s = 0; function next() { for (; o = n.pop();) try { if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next); if (o.d) { var r$1 = o.d.call(o.v); if (o.a) return s |= 2, Promise.resolve(r$1).then(next, err); } else s |= 1; } catch (r$2) { return err(r$2); } if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve(); if (t !== e) throw t; } function err(n$1) { return t = t !== e ? new r(n$1, t) : n$1, next(); } return next(); } }; } module.exports = _usingCtx, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_OverloadYield = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/OverloadYield.js"(exports, module) { function _OverloadYield(e, d) { this.v = e, this.k = d; } module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_awaitAsyncGenerator = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/awaitAsyncGenerator.js"(exports, module) { var OverloadYield$1 = require_OverloadYield(); function _awaitAsyncGenerator$1(e) { return new OverloadYield$1(e, 0); } module.exports = _awaitAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); var require_wrapAsyncGenerator = __commonJS$1({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/wrapAsyncGenerator.js"(exports, module) { var OverloadYield = require_OverloadYield(); function _wrapAsyncGenerator$1(e) { return function() { return new AsyncGenerator(e.apply(this, arguments)); }; } function AsyncGenerator(e) { var r, t; function resume(r$1, t$1) { try { var n = e[r$1](t$1), o = n.value, u = o instanceof OverloadYield; Promise.resolve(u ? o.v : o).then(function(t$2) { if (u) { var i = "return" === r$1 ? "return" : "next"; if (!o.k || t$2.done) return resume(i, t$2); t$2 = e[i](t$2).value; } settle(n.done ? "return" : "normal", t$2); }, function(e$1) { resume("throw", e$1); }); } catch (e$1) { settle("throw", e$1); } } function settle(e$1, n) { switch (e$1) { case "return": r.resolve({ value: n, done: !0 }); break; case "throw": r.reject(n); break; default: r.resolve({ value: n, done: !1 }); } (r = r.next) ? resume(r.key, r.arg) : t = null; } this._invoke = function(e$1, n) { return new Promise(function(o, u) { var i = { key: e$1, arg: n, resolve: o, reject: u, next: null }; t ? t = t.next = i : (r = t = i, resume(e$1, n)); }); }, "function" != typeof e["return"] && (this["return"] = void 0); } AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() { return this; }, AsyncGenerator.prototype.next = function(e) { return this._invoke("next", e); }, AsyncGenerator.prototype["throw"] = function(e) { return this._invoke("throw", e); }, AsyncGenerator.prototype["return"] = function(e) { return this._invoke("return", e); }; module.exports = _wrapAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); __toESM$1(require_usingCtx(), 1); __toESM$1(require_awaitAsyncGenerator(), 1); __toESM$1(require_wrapAsyncGenerator(), 1); __toESM$1(require_objectSpread2$1(), 1); //#endregion //#region ../send/frontend/src/lib/config.ts var getIsEnvProd = (envVarObject) => { return envVarObject?.BASE_URL?.includes("https://send.tb.pro"); }; /** * Returns true if the environment is production * @param envVarObject - Object containing environment variables. You can use proces.env or import.meta.env, if executed from vite.config, use env that comes from loadEnv * @returns boolean indicating if environment is production */ var getEnvironmentName = (envVarObject) => { if (!envVarObject) throw new Error("Environment variables object is required"); if ((envVarObject.NODE_ENV || envVarObject.MODE) === "development") return "development"; if (getIsEnvProd(envVarObject)) return "production"; return "staging"; }; var TRPC_WS_PATH = `/trpc/ws`; //#endregion //#region \0vite/preload-helper.js var scriptRel = "modulepreload"; var assetsURL = function(dep) { return "/" + dep; }; var seen = {}; var __vitePreload = function preload(baseModule, deps, importerUrl) { let promise = Promise.resolve(); if (deps && deps.length > 0) { const links = document.getElementsByTagName("link"); const cspNonceMeta = document.querySelector("meta[property=csp-nonce]"); const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce"); function allSettled(promises) { return Promise.all(promises.map((p) => Promise.resolve(p).then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason })))); } promise = allSettled(deps.map((dep) => { dep = assetsURL(dep, importerUrl); if (dep in seen) return; seen[dep] = true; const isCss = dep.endsWith(".css"); const cssSelector = isCss ? "[rel=\"stylesheet\"]" : ""; if (!!importerUrl) for (let i = links.length - 1; i >= 0; i--) { const link = links[i]; if (link.href === dep && (!isCss || link.rel === "stylesheet")) return; } else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return; const link = document.createElement("link"); link.rel = isCss ? "stylesheet" : scriptRel; if (!isCss) link.as = "script"; link.crossOrigin = ""; link.href = dep; if (cspNonce) link.setAttribute("nonce", cspNonce); document.head.appendChild(link); if (isCss) return new Promise((res, rej) => { link.addEventListener("load", res); link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`))); }); })); } function handlePreloadError(err) { const e = new Event("vite:preloadError", { cancelable: true }); e.payload = err; window.dispatchEvent(e); if (!e.defaultPrevented) throw err; } return promise.then((res) => { for (const item of res || []) { if (item.status !== "rejected") continue; handlePreloadError(item.reason); } return baseModule().catch(handlePreloadError); }); }; //#endregion //#region ../send/frontend/src/lib/trpc.ts /** * This is the client-side code that uses the inferred types from the server */ var serverUrl = "https://send-backend.tb.pro".trim(); var refreshUrl = `${serverUrl}/api/auth/refresh`; var trpcUrl = `${serverUrl}/trpc`; /** * Detect whether we're running in a test/automation context, where the * WebSocket must stay closed. * * Unit tests inject `import.meta.env.VITE_TESTING`. When that build-time flag is * unavailable — as in the shipped background bundle — fall back to the presence * of the WebExtension `browser.test` API, which the Thunderbird/Firefox test * harness only exposes when the add-on is loaded under automation. This keeps a * logged-out automation profile from ever opening the socket at startup. */ function detectTesting() { return typeof browser !== "undefined" && Boolean(browser.test); } var isTesting = detectTesting(); /** * Decide how (and whether) to build the WebSocket client. * * Returns `null` — meaning "do not connect" — when running under unit tests or * when no backend host is configured (empty `serverUrl`). Otherwise returns the * client config with **lazy mode** enabled. * * Lazy mode is critical: the background page of the built-in/system add-on * imports this module on every Thunderbird launch, including fresh, * never-signed-in profiles. A non-lazy client opens the socket as a side effect * of construction (at module load), which under automation triggers a fatal * "non-local network connections are disabled" abort and crashes the process * before any feature is used. With lazy mode the connection is deferred until * the first subscription actually runs (i.e. an authenticated user is using a * feature) and is closed again after inactivity, so a logged-out profile makes * zero outbound connections at startup. */ function getWsClientConfig(url, testing) { const normalizedUrl = url.trim(); if (testing || normalizedUrl.length === 0) return null; return { url: `${normalizedUrl}${TRPC_WS_PATH}`, lazy: { enabled: true, closeMs: 1e3 } }; } var wsClientConfig = getWsClientConfig(serverUrl, isTesting); var wsClient = wsClientConfig ? createWSClient(wsClientConfig) : null; /** * We only import the `AppRouter` type from the server - this is not available at runtime */ async function fetchWithLogoutCheck(url, options) { async function getAuthStore() { const { useAuthStore } = await __vitePreload(async () => { const { useAuthStore } = await Promise.resolve().then(() => auth_store_exports); return { useAuthStore }; }, void 0); return useAuthStore(); } async function buildHeaders() { const headers = new Headers(options.headers); try { if (!headers.has("Authorization")) { const token = await (await getAuthStore()).getAccessToken(); if (token) headers.set("Authorization", `Bearer ${token}`); } } catch {} return headers; } const res = await fetch(url, { ...options, headers: await buildHeaders(), credentials: "include" }); if (res.headers?.get?.("x-logout")) try { if (await (await getAuthStore()).recoverOrForceLogout()) return await fetch(url, { ...options, headers: await buildHeaders(), credentials: "include" }); } catch (error) { console.error("Forced-logout handling failed:", error); } return res; } var trpc = createTRPCClient({ links: [splitLink({ condition: (op) => op.type === "subscription", false: [retryLink({ /** * Retry strategy for failed requests: * - For 401 unauthorized errors: Attempts to refresh the token and retries up to 3 times * - For queries (not mutations): Retries up to 3 times * - For all other cases: No retry */ retry(opts) { if (opts.error.data?.code === "UNAUTHORIZED") { if (opts.op.type !== "query") return false; fetch(refreshUrl, { credentials: "include" }).then(() => { console.info("revalidated token"); }).catch((err) => { console.info("could not revalidate token", err); }); return opts.attempts <= 3; } } }), httpBatchLink({ url: trpcUrl, fetch: fetchWithLogoutCheck })], true: wsClient ? [wsLink({ client: wsClient })] : [httpBatchLink({ url: trpcUrl, fetch: fetchWithLogoutCheck })] })] }); //#endregion //#region ../send/frontend/src/lib/api.ts var ApiConnection = class { constructor(serverUrl) { if (!serverUrl) throw Error("No Server URL provided."); const u = new URL(serverUrl); this.serverUrl = u.origin; this.getStorageType().then((isBucketStorage) => { this.isBucketStorage = isBucketStorage; }); } async getStorageType() { return true; } toString() { return this.serverUrl; } async removeAuthToken() { await this.call("api/auth/oidc/logout"); } async call(path, body = {}, method = "GET", headers = {}, options) { const url = `${this.serverUrl}/api/${path}`; const refreshTokenUrl = `${this.serverUrl}/api/auth/refresh`; const requestHeaders = { ...headers }; if (!requestHeaders["Authorization"]) try { const { useAuthStore } = await __vitePreload(async () => { const { useAuthStore } = await Promise.resolve().then(() => auth_store_exports); return { useAuthStore }; }, void 0); const accessToken = await useAuthStore().getAccessToken(); if (accessToken) requestHeaders["Authorization"] = `Bearer ${accessToken}`; } catch (error) { console.debug("Could not get OIDC token for request:", error); } const opts = { mode: "cors", credentials: "include", method, headers: { "content-type": "application/json", ...requestHeaders } }; if (method.trim().toUpperCase() === "POST") opts.body = JSON.stringify({ ...body }); let resp; try { resp = await fetch(url, opts); } catch (e) { console.log(e); options?.onFailure?.({ kind: "network", status: null, error: e }); return null; } if (resp.headers?.get?.("x-logout")) try { const { useAuthStore } = await __vitePreload(async () => { const { useAuthStore } = await Promise.resolve().then(() => auth_store_exports); return { useAuthStore }; }, void 0); const authStore = useAuthStore(); if (!await authStore.recoverOrForceLogout()) return null; const newToken = await authStore.getAccessToken(); if (newToken) { opts.headers["Authorization"] = `Bearer ${newToken}`; resp = await fetch(url, opts); } } catch (error) { console.error("Forced-logout handling failed:", error); return null; } else if (resp.status === 401) if (requestHeaders["Authorization"]) try { const { useAuthStore } = await __vitePreload(async () => { const { useAuthStore } = await Promise.resolve().then(() => auth_store_exports); return { useAuthStore }; }, void 0); const newToken = await useAuthStore().refreshToken(); if (newToken) { opts.headers["Authorization"] = `Bearer ${newToken}`; resp = await fetch(url, opts); } } catch (error) { console.error("Token refresh failed:", error); options?.onFailure?.({ kind: "network", status: null, error }); return null; } else try { await fetch(refreshTokenUrl, { credentials: "include", mode: "cors" }); resp = await fetch(url, opts); } catch (error) { console.log(error); options?.onFailure?.({ kind: "network", status: null, error }); return null; } if (!resp.ok) { let body; try { body = (await resp.text()).slice(0, 500); } catch { body = void 0; } options?.onFailure?.({ kind: "http", status: resp.status, statusText: resp.statusText, body }); return null; } if (!!options?.fullResponse) return resp; return resp.json(); } }; //#endregion //#region ../send/frontend/src/stores/api-store.ts var useApiStore = defineStore("api", () => { const url = useConfigStore().serverUrl; return { api: new ApiConnection(url) }; }); //#endregion //#region ../send/frontend/src/lib/init.ts /** * Loads user and keychain from storage; creates default folder if necessary. * @param {UserStore} userStore - Pinia store for managing user. * @param {Keychain} keychain - Instance of Keychain class. * @param {FolderStore} folderStore - Pinia store for managing folders. * @return {Promise} - Returns Promise of 0 (success) or an error code typed by INIT_ERRORS. */ async function _init(userStore, keychain, folderStore) { const hasUser = await userStore.loadFromLocalStorage(); const hasKeychain = await keychain.load(); if (!hasUser) return INIT_ERRORS.NO_USER; if (!hasKeychain) return INIT_ERRORS.NO_KEYCHAIN; try { const { api } = useApiStore(); await restoreKeysUsingLocalStorage(keychain, api); } catch (error) { console.warn("init(): could not restore keys before folder check", error); } await folderStore.sync(); const defaultFolder = folderStore?.defaultFolder; const defaultFolderKeyIsMissing = defaultFolder && !keychain.keys[defaultFolder.id]; if (defaultFolderKeyIsMissing) { console.warn(`Default folder ${defaultFolder.id} exists but has no key. Deleting orphaned container and recreating.`); await folderStore.deleteFolder(defaultFolder.id); } if (!defaultFolder || defaultFolderKeyIsMissing) { if (!(await folderStore.createFolder())?.id) return INIT_ERRORS.COULD_NOT_CREATE_DEFAULT_FOLDER; } return INIT_ERRORS.NONE; } var inFlight = null; function init$2(userStore, keychain, folderStore) { if (inFlight) return inFlight; inFlight = _init(userStore, keychain, folderStore).finally(() => { inFlight = null; }); return inFlight; } /*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */ //#endregion //#region ../send/frontend/src/lib/utils.ts var import_jszip_min = /* @__PURE__ */ __toESM$2((/* @__PURE__ */ __commonJSMin(((exports, module) => { (function(e) { if ("object" == typeof exports && "undefined" != typeof module) module.exports = e(); else if ("function" == typeof define && define.amd) define([], e); else ("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this).JSZip = e(); })(function() { return function s(a, o, h) { function u(r, e) { if (!o[r]) { if (!a[r]) { var t = "function" == typeof __require && __require; if (!e && t) return t(r, !0); if (l) return l(r, !0); var n = /* @__PURE__ */ new Error("Cannot find module '" + r + "'"); throw n.code = "MODULE_NOT_FOUND", n; } var i = o[r] = { exports: {} }; a[r][0].call(i.exports, function(e) { var t = a[r][1][e]; return u(t || e); }, i, i.exports, s, a, o, h); } return o[r].exports; } for (var l = "function" == typeof __require && __require, e = 0; e < h.length; e++) u(h[e]); return u; }({ 1: [function(e, t, r) { "use strict"; var d = e("./utils"), c = e("./support"), p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; r.encode = function(e) { for (var t, r, n, i, s, a, o, h = [], u = 0, l = e.length, f = l, c = "string" !== d.getTypeOf(e); u < e.length;) f = l - u, n = c ? (t = e[u++], r = u < l ? e[u++] : 0, u < l ? e[u++] : 0) : (t = e.charCodeAt(u++), r = u < l ? e.charCodeAt(u++) : 0, u < l ? e.charCodeAt(u++) : 0), i = t >> 2, s = (3 & t) << 4 | r >> 4, a = 1 < f ? (15 & r) << 2 | n >> 6 : 64, o = 2 < f ? 63 & n : 64, h.push(p.charAt(i) + p.charAt(s) + p.charAt(a) + p.charAt(o)); return h.join(""); }, r.decode = function(e) { var t, r, n, i, s, a, o = 0, h = 0, u = "data:"; if (e.substr(0, u.length) === u) throw new Error("Invalid base64 input, it looks like a data url."); var l, f = 3 * (e = e.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4; if (e.charAt(e.length - 1) === p.charAt(64) && f--, e.charAt(e.length - 2) === p.charAt(64) && f--, f % 1 != 0) throw new Error("Invalid base64 input, bad content length."); for (l = c.uint8array ? new Uint8Array(0 | f) : new Array(0 | f); o < e.length;) t = p.indexOf(e.charAt(o++)) << 2 | (i = p.indexOf(e.charAt(o++))) >> 4, r = (15 & i) << 4 | (s = p.indexOf(e.charAt(o++))) >> 2, n = (3 & s) << 6 | (a = p.indexOf(e.charAt(o++))), l[h++] = t, 64 !== s && (l[h++] = r), 64 !== a && (l[h++] = n); return l; }; }, { "./support": 30, "./utils": 32 }], 2: [function(e, t, r) { "use strict"; var n = e("./external"), i = e("./stream/DataWorker"), s = e("./stream/Crc32Probe"), a = e("./stream/DataLengthProbe"); function o(e, t, r, n, i) { this.compressedSize = e, this.uncompressedSize = t, this.crc32 = r, this.compression = n, this.compressedContent = i; } o.prototype = { getContentWorker: function() { var e = new i(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")), t = this; return e.on("end", function() { if (this.streamInfo.data_length !== t.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch"); }), e; }, getCompressedWorker: function() { return new i(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); } }, o.createWorkerFrom = function(e, t, r) { return e.pipe(new s()).pipe(new a("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression", t); }, t.exports = o; }, { "./external": 6, "./stream/Crc32Probe": 25, "./stream/DataLengthProbe": 26, "./stream/DataWorker": 27 }], 3: [function(e, t, r) { "use strict"; var n = e("./stream/GenericWorker"); r.STORE = { magic: "\0\0", compressWorker: function() { return new n("STORE compression"); }, uncompressWorker: function() { return new n("STORE decompression"); } }, r.DEFLATE = e("./flate"); }, { "./flate": 7, "./stream/GenericWorker": 28 }], 4: [function(e, t, r) { "use strict"; var n = e("./utils"); var o = function() { for (var e, t = [], r = 0; r < 256; r++) { e = r; for (var n = 0; n < 8; n++) e = 1 & e ? 3988292384 ^ e >>> 1 : e >>> 1; t[r] = e; } return t; }(); t.exports = function(e, t) { return void 0 !== e && e.length ? "string" !== n.getTypeOf(e) ? function(e, t, r, n) { var i = o, s = n + r; e ^= -1; for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t[a])]; return -1 ^ e; }(0 | t, e, e.length, 0) : function(e, t, r, n) { var i = o, s = n + r; e ^= -1; for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t.charCodeAt(a))]; return -1 ^ e; }(0 | t, e, e.length, 0) : 0; }; }, { "./utils": 32 }], 5: [function(e, t, r) { "use strict"; r.base64 = !1, r.binary = !1, r.dir = !1, r.createFolders = !0, r.date = null, r.compression = null, r.compressionOptions = null, r.comment = null, r.unixPermissions = null, r.dosPermissions = null; }, {}], 6: [function(e, t, r) { "use strict"; var n = null; n = "undefined" != typeof Promise ? Promise : e("lie"), t.exports = { Promise: n }; }, { lie: 37 }], 7: [function(e, t, r) { "use strict"; var n = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array, i = e("pako"), s = e("./utils"), a = e("./stream/GenericWorker"), o = n ? "uint8array" : "array"; function h(e, t) { a.call(this, "FlateWorker/" + e), this._pako = null, this._pakoAction = e, this._pakoOptions = t, this.meta = {}; } r.magic = "\b\0", s.inherits(h, a), h.prototype.processChunk = function(e) { this.meta = e.meta, null === this._pako && this._createPako(), this._pako.push(s.transformTo(o, e.data), !1); }, h.prototype.flush = function() { a.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], !0); }, h.prototype.cleanUp = function() { a.prototype.cleanUp.call(this), this._pako = null; }, h.prototype._createPako = function() { this._pako = new i[this._pakoAction]({ raw: !0, level: this._pakoOptions.level || -1 }); var t = this; this._pako.onData = function(e) { t.push({ data: e, meta: t.meta }); }; }, r.compressWorker = function(e) { return new h("Deflate", e); }, r.uncompressWorker = function() { return new h("Inflate", {}); }; }, { "./stream/GenericWorker": 28, "./utils": 32, pako: 38 }], 8: [function(e, t, r) { "use strict"; function A(e, t) { var r, n = ""; for (r = 0; r < t; r++) n += String.fromCharCode(255 & e), e >>>= 8; return n; } function n(e, t, r, n, i, s) { var a, o, h = e.file, u = e.compression, l = s !== O.utf8encode, f = I.transformTo("string", s(h.name)), c = I.transformTo("string", O.utf8encode(h.name)), d = h.comment, p = I.transformTo("string", s(d)), m = I.transformTo("string", O.utf8encode(d)), _ = c.length !== h.name.length, g = m.length !== d.length, b = "", v = "", y = "", w = h.dir, k = h.date, x = { crc32: 0, compressedSize: 0, uncompressedSize: 0 }; t && !r || (x.crc32 = e.crc32, x.compressedSize = e.compressedSize, x.uncompressedSize = e.uncompressedSize); var S = 0; t && (S |= 8), l || !_ && !g || (S |= 2048); var z = 0, C = 0; w && (z |= 16), "UNIX" === i ? (C = 798, z |= function(e, t) { var r = e; return e || (r = t ? 16893 : 33204), (65535 & r) << 16; }(h.unixPermissions, w)) : (C = 20, z |= function(e) { return 63 & (e || 0); }(h.dosPermissions)), a = k.getUTCHours(), a <<= 6, a |= k.getUTCMinutes(), a <<= 5, a |= k.getUTCSeconds() / 2, o = k.getUTCFullYear() - 1980, o <<= 4, o |= k.getUTCMonth() + 1, o <<= 5, o |= k.getUTCDate(), _ && (v = A(1, 1) + A(B(f), 4) + c, b += "up" + A(v.length, 2) + v), g && (y = A(1, 1) + A(B(p), 4) + m, b += "uc" + A(y.length, 2) + y); var E = ""; return E += "\n\0", E += A(S, 2), E += u.magic, E += A(a, 2), E += A(o, 2), E += A(x.crc32, 4), E += A(x.compressedSize, 4), E += A(x.uncompressedSize, 4), E += A(f.length, 2), E += A(b.length, 2), { fileRecord: R.LOCAL_FILE_HEADER + E + f + b, dirRecord: R.CENTRAL_FILE_HEADER + A(C, 2) + E + A(p.length, 2) + "\0\0\0\0" + A(z, 4) + A(n, 4) + f + b + p }; } var I = e("../utils"), i = e("../stream/GenericWorker"), O = e("../utf8"), B = e("../crc32"), R = e("../signature"); function s(e, t, r, n) { i.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t, this.zipPlatform = r, this.encodeFileName = n, this.streamFiles = e, this.accumulate = !1, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = []; } I.inherits(s, i), s.prototype.push = function(e) { var t = e.meta.percent || 0, r = this.entriesCount, n = this._sources.length; this.accumulate ? this.contentBuffer.push(e) : (this.bytesWritten += e.data.length, i.prototype.push.call(this, { data: e.data, meta: { currentFile: this.currentFile, percent: r ? (t + 100 * (r - n - 1)) / r : 100 } })); }, s.prototype.openedSource = function(e) { this.currentSourceOffset = this.bytesWritten, this.currentFile = e.file.name; var t = this.streamFiles && !e.file.dir; if (t) { var r = n(e, t, !1, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); this.push({ data: r.fileRecord, meta: { percent: 0 } }); } else this.accumulate = !0; }, s.prototype.closedSource = function(e) { this.accumulate = !1; var t = this.streamFiles && !e.file.dir, r = n(e, t, !0, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); if (this.dirRecords.push(r.dirRecord), t) this.push({ data: function(e) { return R.DATA_DESCRIPTOR + A(e.crc32, 4) + A(e.compressedSize, 4) + A(e.uncompressedSize, 4); }(e), meta: { percent: 100 } }); else for (this.push({ data: r.fileRecord, meta: { percent: 0 } }); this.contentBuffer.length;) this.push(this.contentBuffer.shift()); this.currentFile = null; }, s.prototype.flush = function() { for (var e = this.bytesWritten, t = 0; t < this.dirRecords.length; t++) this.push({ data: this.dirRecords[t], meta: { percent: 100 } }); var r = this.bytesWritten - e, n = function(e, t, r, n, i) { var s = I.transformTo("string", i(n)); return R.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A(e, 2) + A(e, 2) + A(t, 4) + A(r, 4) + A(s.length, 2) + s; }(this.dirRecords.length, r, e, this.zipComment, this.encodeFileName); this.push({ data: n, meta: { percent: 100 } }); }, s.prototype.prepareNextSource = function() { this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume(); }, s.prototype.registerPrevious = function(e) { this._sources.push(e); var t = this; return e.on("data", function(e) { t.processChunk(e); }), e.on("end", function() { t.closedSource(t.previous.streamInfo), t._sources.length ? t.prepareNextSource() : t.end(); }), e.on("error", function(e) { t.error(e); }), this; }, s.prototype.resume = function() { return !!i.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), !0) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), !0)); }, s.prototype.error = function(e) { var t = this._sources; if (!i.prototype.error.call(this, e)) return !1; for (var r = 0; r < t.length; r++) try { t[r].error(e); } catch (e) {} return !0; }, s.prototype.lock = function() { i.prototype.lock.call(this); for (var e = this._sources, t = 0; t < e.length; t++) e[t].lock(); }, t.exports = s; }, { "../crc32": 4, "../signature": 23, "../stream/GenericWorker": 28, "../utf8": 31, "../utils": 32 }], 9: [function(e, t, r) { "use strict"; var u = e("../compressions"), n = e("./ZipFileWorker"); r.generateWorker = function(e, a, t) { var o = new n(a.streamFiles, t, a.platform, a.encodeFileName), h = 0; try { e.forEach(function(e, t) { h++; var r = function(e, t) { var r = e || t, n = u[r]; if (!n) throw new Error(r + " is not a valid compression method !"); return n; }(t.options.compression, a.compression), n = t.options.compressionOptions || a.compressionOptions || {}, i = t.dir, s = t.date; t._compressWorker(r, n).withStreamInfo("file", { name: e, dir: i, date: s, comment: t.comment || "", unixPermissions: t.unixPermissions, dosPermissions: t.dosPermissions }).pipe(o); }), o.entriesCount = h; } catch (e) { o.error(e); } return o; }; }, { "../compressions": 3, "./ZipFileWorker": 8 }], 10: [function(e, t, r) { "use strict"; function n() { if (!(this instanceof n)) return new n(); if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); this.files = Object.create(null), this.comment = null, this.root = "", this.clone = function() { var e = new n(); for (var t in this) "function" != typeof this[t] && (e[t] = this[t]); return e; }; } (n.prototype = e("./object")).loadAsync = e("./load"), n.support = e("./support"), n.defaults = e("./defaults"), n.version = "3.10.1", n.loadAsync = function(e, t) { return new n().loadAsync(e, t); }, n.external = e("./external"), t.exports = n; }, { "./defaults": 5, "./external": 6, "./load": 11, "./object": 15, "./support": 30 }], 11: [function(e, t, r) { "use strict"; var u = e("./utils"), i = e("./external"), n = e("./utf8"), s = e("./zipEntries"), a = e("./stream/Crc32Probe"), l = e("./nodejsUtils"); function f(n) { return new i.Promise(function(e, t) { var r = n.decompressed.getContentWorker().pipe(new a()); r.on("error", function(e) { t(e); }).on("end", function() { r.streamInfo.crc32 !== n.decompressed.crc32 ? t(/* @__PURE__ */ new Error("Corrupted zip : CRC32 mismatch")) : e(); }).resume(); }); } t.exports = function(e, o) { var h = this; return o = u.extend(o || {}, { base64: !1, checkCRC32: !1, optimizedBinaryString: !1, createFolders: !1, decodeFileName: n.utf8decode }), l.isNode && l.isStream(e) ? i.Promise.reject(/* @__PURE__ */ new Error("JSZip can't accept a stream when loading a zip file.")) : u.prepareContent("the loaded zip file", e, !0, o.optimizedBinaryString, o.base64).then(function(e) { var t = new s(o); return t.load(e), t; }).then(function(e) { var t = [i.Promise.resolve(e)], r = e.files; if (o.checkCRC32) for (var n = 0; n < r.length; n++) t.push(f(r[n])); return i.Promise.all(t); }).then(function(e) { for (var t = e.shift(), r = t.files, n = 0; n < r.length; n++) { var i = r[n], s = i.fileNameStr, a = u.resolve(i.fileNameStr); h.file(a, i.decompressed, { binary: !0, optimizedBinaryString: !0, date: i.date, dir: i.dir, comment: i.fileCommentStr.length ? i.fileCommentStr : null, unixPermissions: i.unixPermissions, dosPermissions: i.dosPermissions, createFolders: o.createFolders }), i.dir || (h.file(a).unsafeOriginalName = s); } return t.zipComment.length && (h.comment = t.zipComment), h; }); }; }, { "./external": 6, "./nodejsUtils": 14, "./stream/Crc32Probe": 25, "./utf8": 31, "./utils": 32, "./zipEntries": 33 }], 12: [function(e, t, r) { "use strict"; var n = e("../utils"), i = e("../stream/GenericWorker"); function s(e, t) { i.call(this, "Nodejs stream input adapter for " + e), this._upstreamEnded = !1, this._bindStream(t); } n.inherits(s, i), s.prototype._bindStream = function(e) { var t = this; (this._stream = e).pause(), e.on("data", function(e) { t.push({ data: e, meta: { percent: 0 } }); }).on("error", function(e) { t.isPaused ? this.generatedError = e : t.error(e); }).on("end", function() { t.isPaused ? t._upstreamEnded = !0 : t.end(); }); }, s.prototype.pause = function() { return !!i.prototype.pause.call(this) && (this._stream.pause(), !0); }, s.prototype.resume = function() { return !!i.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), !0); }, t.exports = s; }, { "../stream/GenericWorker": 28, "../utils": 32 }], 13: [function(e, t, r) { "use strict"; var i = e("readable-stream").Readable; function n(e, t, r) { i.call(this, t), this._helper = e; var n = this; e.on("data", function(e, t) { n.push(e) || n._helper.pause(), r && r(t); }).on("error", function(e) { n.emit("error", e); }).on("end", function() { n.push(null); }); } e("../utils").inherits(n, i), n.prototype._read = function() { this._helper.resume(); }, t.exports = n; }, { "../utils": 32, "readable-stream": 16 }], 14: [function(e, t, r) { "use strict"; t.exports = { isNode: "undefined" != typeof Buffer, newBufferFrom: function(e, t) { if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e, t); if ("number" == typeof e) throw new Error("The \"data\" argument must not be a number"); return new Buffer(e, t); }, allocBuffer: function(e) { if (Buffer.alloc) return Buffer.alloc(e); var t = new Buffer(e); return t.fill(0), t; }, isBuffer: function(e) { return Buffer.isBuffer(e); }, isStream: function(e) { return e && "function" == typeof e.on && "function" == typeof e.pause && "function" == typeof e.resume; } }; }, {}], 15: [function(e, t, r) { "use strict"; function s(e, t, r) { var n, i = u.getTypeOf(t), s = u.extend(r || {}, f); s.date = s.date || /* @__PURE__ */ new Date(), null !== s.compression && (s.compression = s.compression.toUpperCase()), "string" == typeof s.unixPermissions && (s.unixPermissions = parseInt(s.unixPermissions, 8)), s.unixPermissions && 16384 & s.unixPermissions && (s.dir = !0), s.dosPermissions && 16 & s.dosPermissions && (s.dir = !0), s.dir && (e = g(e)), s.createFolders && (n = _(e)) && b.call(this, n, !0); var a = "string" === i && !1 === s.binary && !1 === s.base64; r && void 0 !== r.binary || (s.binary = !a), (t instanceof c && 0 === t.uncompressedSize || s.dir || !t || 0 === t.length) && (s.base64 = !1, s.binary = !0, t = "", s.compression = "STORE", i = "string"); var o = null; o = t instanceof c || t instanceof l ? t : p.isNode && p.isStream(t) ? new m(e, t) : u.prepareContent(e, t, s.binary, s.optimizedBinaryString, s.base64); var h = new d(e, o, s); this.files[e] = h; } var i = e("./utf8"), u = e("./utils"), l = e("./stream/GenericWorker"), a = e("./stream/StreamHelper"), f = e("./defaults"), c = e("./compressedObject"), d = e("./zipObject"), o = e("./generate"), p = e("./nodejsUtils"), m = e("./nodejs/NodejsStreamInputAdapter"), _ = function(e) { "/" === e.slice(-1) && (e = e.substring(0, e.length - 1)); var t = e.lastIndexOf("/"); return 0 < t ? e.substring(0, t) : ""; }, g = function(e) { return "/" !== e.slice(-1) && (e += "/"), e; }, b = function(e, t) { return t = void 0 !== t ? t : f.createFolders, e = g(e), this.files[e] || s.call(this, e, null, { dir: !0, createFolders: t }), this.files[e]; }; function h(e) { return "[object RegExp]" === Object.prototype.toString.call(e); } t.exports = { load: function() { throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); }, forEach: function(e) { var t, r, n; for (t in this.files) n = this.files[t], (r = t.slice(this.root.length, t.length)) && t.slice(0, this.root.length) === this.root && e(r, n); }, filter: function(r) { var n = []; return this.forEach(function(e, t) { r(e, t) && n.push(t); }), n; }, file: function(e, t, r) { if (1 !== arguments.length) return e = this.root + e, s.call(this, e, t, r), this; if (h(e)) { var n = e; return this.filter(function(e, t) { return !t.dir && n.test(e); }); } var i = this.files[this.root + e]; return i && !i.dir ? i : null; }, folder: function(r) { if (!r) return this; if (h(r)) return this.filter(function(e, t) { return t.dir && r.test(e); }); var e = this.root + r, t = b.call(this, e), n = this.clone(); return n.root = t.name, n; }, remove: function(r) { r = this.root + r; var e = this.files[r]; if (e || ("/" !== r.slice(-1) && (r += "/"), e = this.files[r]), e && !e.dir) delete this.files[r]; else for (var t = this.filter(function(e, t) { return t.name.slice(0, r.length) === r; }), n = 0; n < t.length; n++) delete this.files[t[n].name]; return this; }, generate: function() { throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); }, generateInternalStream: function(e) { var t, r = {}; try { if ((r = u.extend(e || {}, { streamFiles: !1, compression: "STORE", compressionOptions: null, type: "", platform: "DOS", comment: null, mimeType: "application/zip", encodeFileName: i.utf8encode })).type = r.type.toLowerCase(), r.compression = r.compression.toUpperCase(), "binarystring" === r.type && (r.type = "string"), !r.type) throw new Error("No output type specified."); u.checkSupport(r.type), "darwin" !== r.platform && "freebsd" !== r.platform && "linux" !== r.platform && "sunos" !== r.platform || (r.platform = "UNIX"), "win32" === r.platform && (r.platform = "DOS"); var n = r.comment || this.comment || ""; t = o.generateWorker(this, r, n); } catch (e) { (t = new l("error")).error(e); } return new a(t, r.type || "string", r.mimeType); }, generateAsync: function(e, t) { return this.generateInternalStream(e).accumulate(t); }, generateNodeStream: function(e, t) { return (e = e || {}).type || (e.type = "nodebuffer"), this.generateInternalStream(e).toNodejsStream(t); } }; }, { "./compressedObject": 2, "./defaults": 5, "./generate": 9, "./nodejs/NodejsStreamInputAdapter": 12, "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31, "./utils": 32, "./zipObject": 35 }], 16: [function(e, t, r) { "use strict"; t.exports = e("stream"); }, { stream: void 0 }], 17: [function(e, t, r) { "use strict"; var n = e("./DataReader"); function i(e) { n.call(this, e); for (var t = 0; t < this.data.length; t++) e[t] = 255 & e[t]; } e("../utils").inherits(i, n), i.prototype.byteAt = function(e) { return this.data[this.zero + e]; }, i.prototype.lastIndexOfSignature = function(e) { for (var t = e.charCodeAt(0), r = e.charCodeAt(1), n = e.charCodeAt(2), i = e.charCodeAt(3), s = this.length - 4; 0 <= s; --s) if (this.data[s] === t && this.data[s + 1] === r && this.data[s + 2] === n && this.data[s + 3] === i) return s - this.zero; return -1; }, i.prototype.readAndCheckSignature = function(e) { var t = e.charCodeAt(0), r = e.charCodeAt(1), n = e.charCodeAt(2), i = e.charCodeAt(3), s = this.readData(4); return t === s[0] && r === s[1] && n === s[2] && i === s[3]; }, i.prototype.readData = function(e) { if (this.checkOffset(e), 0 === e) return []; var t = this.data.slice(this.zero + this.index, this.zero + this.index + e); return this.index += e, t; }, t.exports = i; }, { "../utils": 32, "./DataReader": 18 }], 18: [function(e, t, r) { "use strict"; var n = e("../utils"); function i(e) { this.data = e, this.length = e.length, this.index = 0, this.zero = 0; } i.prototype = { checkOffset: function(e) { this.checkIndex(this.index + e); }, checkIndex: function(e) { if (this.length < this.zero + e || e < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e + "). Corrupted zip ?"); }, setIndex: function(e) { this.checkIndex(e), this.index = e; }, skip: function(e) { this.setIndex(this.index + e); }, byteAt: function() {}, readInt: function(e) { var t, r = 0; for (this.checkOffset(e), t = this.index + e - 1; t >= this.index; t--) r = (r << 8) + this.byteAt(t); return this.index += e, r; }, readString: function(e) { return n.transformTo("string", this.readData(e)); }, readData: function() {}, lastIndexOfSignature: function() {}, readAndCheckSignature: function() {}, readDate: function() { var e = this.readInt(4); return new Date(Date.UTC(1980 + (e >> 25 & 127), (e >> 21 & 15) - 1, e >> 16 & 31, e >> 11 & 31, e >> 5 & 63, (31 & e) << 1)); } }, t.exports = i; }, { "../utils": 32 }], 19: [function(e, t, r) { "use strict"; var n = e("./Uint8ArrayReader"); function i(e) { n.call(this, e); } e("../utils").inherits(i, n), i.prototype.readData = function(e) { this.checkOffset(e); var t = this.data.slice(this.zero + this.index, this.zero + this.index + e); return this.index += e, t; }, t.exports = i; }, { "../utils": 32, "./Uint8ArrayReader": 21 }], 20: [function(e, t, r) { "use strict"; var n = e("./DataReader"); function i(e) { n.call(this, e); } e("../utils").inherits(i, n), i.prototype.byteAt = function(e) { return this.data.charCodeAt(this.zero + e); }, i.prototype.lastIndexOfSignature = function(e) { return this.data.lastIndexOf(e) - this.zero; }, i.prototype.readAndCheckSignature = function(e) { return e === this.readData(4); }, i.prototype.readData = function(e) { this.checkOffset(e); var t = this.data.slice(this.zero + this.index, this.zero + this.index + e); return this.index += e, t; }, t.exports = i; }, { "../utils": 32, "./DataReader": 18 }], 21: [function(e, t, r) { "use strict"; var n = e("./ArrayReader"); function i(e) { n.call(this, e); } e("../utils").inherits(i, n), i.prototype.readData = function(e) { if (this.checkOffset(e), 0 === e) return new Uint8Array(0); var t = this.data.subarray(this.zero + this.index, this.zero + this.index + e); return this.index += e, t; }, t.exports = i; }, { "../utils": 32, "./ArrayReader": 17 }], 22: [function(e, t, r) { "use strict"; var n = e("../utils"), i = e("../support"), s = e("./ArrayReader"), a = e("./StringReader"), o = e("./NodeBufferReader"), h = e("./Uint8ArrayReader"); t.exports = function(e) { var t = n.getTypeOf(e); return n.checkSupport(t), "string" !== t || i.uint8array ? "nodebuffer" === t ? new o(e) : i.uint8array ? new h(n.transformTo("uint8array", e)) : new s(n.transformTo("array", e)) : new a(e); }; }, { "../support": 30, "../utils": 32, "./ArrayReader": 17, "./NodeBufferReader": 19, "./StringReader": 20, "./Uint8ArrayReader": 21 }], 23: [function(e, t, r) { "use strict"; r.LOCAL_FILE_HEADER = "PK", r.CENTRAL_FILE_HEADER = "PK", r.CENTRAL_DIRECTORY_END = "PK", r.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07", r.ZIP64_CENTRAL_DIRECTORY_END = "PK", r.DATA_DESCRIPTOR = "PK\x07\b"; }, {}], 24: [function(e, t, r) { "use strict"; var n = e("./GenericWorker"), i = e("../utils"); function s(e) { n.call(this, "ConvertWorker to " + e), this.destType = e; } i.inherits(s, n), s.prototype.processChunk = function(e) { this.push({ data: i.transformTo(this.destType, e.data), meta: e.meta }); }, t.exports = s; }, { "../utils": 32, "./GenericWorker": 28 }], 25: [function(e, t, r) { "use strict"; var n = e("./GenericWorker"), i = e("../crc32"); function s() { n.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0); } e("../utils").inherits(s, n), s.prototype.processChunk = function(e) { this.streamInfo.crc32 = i(e.data, this.streamInfo.crc32 || 0), this.push(e); }, t.exports = s; }, { "../crc32": 4, "../utils": 32, "./GenericWorker": 28 }], 26: [function(e, t, r) { "use strict"; var n = e("../utils"), i = e("./GenericWorker"); function s(e) { i.call(this, "DataLengthProbe for " + e), this.propName = e, this.withStreamInfo(e, 0); } n.inherits(s, i), s.prototype.processChunk = function(e) { if (e) { var t = this.streamInfo[this.propName] || 0; this.streamInfo[this.propName] = t + e.data.length; } i.prototype.processChunk.call(this, e); }, t.exports = s; }, { "../utils": 32, "./GenericWorker": 28 }], 27: [function(e, t, r) { "use strict"; var n = e("../utils"), i = e("./GenericWorker"); function s(e) { i.call(this, "DataWorker"); var t = this; this.dataIsReady = !1, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = !1, e.then(function(e) { t.dataIsReady = !0, t.data = e, t.max = e && e.length || 0, t.type = n.getTypeOf(e), t.isPaused || t._tickAndRepeat(); }, function(e) { t.error(e); }); } n.inherits(s, i), s.prototype.cleanUp = function() { i.prototype.cleanUp.call(this), this.data = null; }, s.prototype.resume = function() { return !!i.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = !0, n.delay(this._tickAndRepeat, [], this)), !0); }, s.prototype._tickAndRepeat = function() { this._tickScheduled = !1, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n.delay(this._tickAndRepeat, [], this), this._tickScheduled = !0)); }, s.prototype._tick = function() { if (this.isPaused || this.isFinished) return !1; var e = null, t = Math.min(this.max, this.index + 16384); if (this.index >= this.max) return this.end(); switch (this.type) { case "string": e = this.data.substring(this.index, t); break; case "uint8array": e = this.data.subarray(this.index, t); break; case "array": case "nodebuffer": e = this.data.slice(this.index, t); } return this.index = t, this.push({ data: e, meta: { percent: this.max ? this.index / this.max * 100 : 0 } }); }, t.exports = s; }, { "../utils": 32, "./GenericWorker": 28 }], 28: [function(e, t, r) { "use strict"; function n(e) { this.name = e || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = !0, this.isFinished = !1, this.isLocked = !1, this._listeners = { data: [], end: [], error: [] }, this.previous = null; } n.prototype = { push: function(e) { this.emit("data", e); }, end: function() { if (this.isFinished) return !1; this.flush(); try { this.emit("end"), this.cleanUp(), this.isFinished = !0; } catch (e) { this.emit("error", e); } return !0; }, error: function(e) { return !this.isFinished && (this.isPaused ? this.generatedError = e : (this.isFinished = !0, this.emit("error", e), this.previous && this.previous.error(e), this.cleanUp()), !0); }, on: function(e, t) { return this._listeners[e].push(t), this; }, cleanUp: function() { this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = []; }, emit: function(e, t) { if (this._listeners[e]) for (var r = 0; r < this._listeners[e].length; r++) this._listeners[e][r].call(this, t); }, pipe: function(e) { return e.registerPrevious(this); }, registerPrevious: function(e) { if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); this.streamInfo = e.streamInfo, this.mergeStreamInfo(), this.previous = e; var t = this; return e.on("data", function(e) { t.processChunk(e); }), e.on("end", function() { t.end(); }), e.on("error", function(e) { t.error(e); }), this; }, pause: function() { return !this.isPaused && !this.isFinished && (this.isPaused = !0, this.previous && this.previous.pause(), !0); }, resume: function() { if (!this.isPaused || this.isFinished) return !1; var e = this.isPaused = !1; return this.generatedError && (this.error(this.generatedError), e = !0), this.previous && this.previous.resume(), !e; }, flush: function() {}, processChunk: function(e) { this.push(e); }, withStreamInfo: function(e, t) { return this.extraStreamInfo[e] = t, this.mergeStreamInfo(), this; }, mergeStreamInfo: function() { for (var e in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e) && (this.streamInfo[e] = this.extraStreamInfo[e]); }, lock: function() { if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); this.isLocked = !0, this.previous && this.previous.lock(); }, toString: function() { var e = "Worker " + this.name; return this.previous ? this.previous + " -> " + e : e; } }, t.exports = n; }, {}], 29: [function(e, t, r) { "use strict"; var h = e("../utils"), i = e("./ConvertWorker"), s = e("./GenericWorker"), u = e("../base64"), n = e("../support"), a = e("../external"), o = null; if (n.nodestream) try { o = e("../nodejs/NodejsStreamOutputAdapter"); } catch (e) {} function l(e, o) { return new a.Promise(function(t, r) { var n = [], i = e._internalType, s = e._outputType, a = e._mimeType; e.on("data", function(e, t) { n.push(e), o && o(t); }).on("error", function(e) { n = [], r(e); }).on("end", function() { try { t(function(e, t, r) { switch (e) { case "blob": return h.newBlob(h.transformTo("arraybuffer", t), r); case "base64": return u.encode(t); default: return h.transformTo(e, t); } }(s, function(e, t) { var r, n = 0, i = null, s = 0; for (r = 0; r < t.length; r++) s += t[r].length; switch (e) { case "string": return t.join(""); case "array": return Array.prototype.concat.apply([], t); case "uint8array": for (i = new Uint8Array(s), r = 0; r < t.length; r++) i.set(t[r], n), n += t[r].length; return i; case "nodebuffer": return Buffer.concat(t); default: throw new Error("concat : unsupported type '" + e + "'"); } }(i, n), a)); } catch (e) { r(e); } n = []; }).resume(); }); } function f(e, t, r) { var n = t; switch (t) { case "blob": case "arraybuffer": n = "uint8array"; break; case "base64": n = "string"; } try { this._internalType = n, this._outputType = t, this._mimeType = r, h.checkSupport(n), this._worker = e.pipe(new i(n)), e.lock(); } catch (e) { this._worker = new s("error"), this._worker.error(e); } } f.prototype = { accumulate: function(e) { return l(this, e); }, on: function(e, t) { var r = this; return "data" === e ? this._worker.on(e, function(e) { t.call(r, e.data, e.meta); }) : this._worker.on(e, function() { h.delay(t, arguments, r); }), this; }, resume: function() { return h.delay(this._worker.resume, [], this._worker), this; }, pause: function() { return this._worker.pause(), this; }, toNodejsStream: function(e) { if (h.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method"); return new o(this, { objectMode: "nodebuffer" !== this._outputType }, e); } }, t.exports = f; }, { "../base64": 1, "../external": 6, "../nodejs/NodejsStreamOutputAdapter": 13, "../support": 30, "../utils": 32, "./ConvertWorker": 24, "./GenericWorker": 28 }], 30: [function(e, t, r) { "use strict"; if (r.base64 = !0, r.array = !0, r.string = !0, r.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r.nodebuffer = "undefined" != typeof Buffer, r.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r.blob = !1; else { var n = /* @__PURE__ */ new ArrayBuffer(0); try { r.blob = 0 === new Blob([n], { type: "application/zip" }).size; } catch (e) { try { var i = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); i.append(n), r.blob = 0 === i.getBlob("application/zip").size; } catch (e) { r.blob = !1; } } } try { r.nodestream = !!e("readable-stream").Readable; } catch (e) { r.nodestream = !1; } }, { "readable-stream": 16 }], 31: [function(e, t, s) { "use strict"; for (var o = e("./utils"), h = e("./support"), r = e("./nodejsUtils"), n = e("./stream/GenericWorker"), u = new Array(256), i = 0; i < 256; i++) u[i] = 252 <= i ? 6 : 248 <= i ? 5 : 240 <= i ? 4 : 224 <= i ? 3 : 192 <= i ? 2 : 1; u[254] = u[254] = 1; function a() { n.call(this, "utf-8 decode"), this.leftOver = null; } function l() { n.call(this, "utf-8 encode"); } s.utf8encode = function(e) { return h.nodebuffer ? r.newBufferFrom(e, "utf-8") : function(e) { var t, r, n, i, s, a = e.length, o = 0; for (i = 0; i < a; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), o += r < 128 ? 1 : r < 2048 ? 2 : r < 65536 ? 3 : 4; for (t = h.uint8array ? new Uint8Array(o) : new Array(o), i = s = 0; s < o; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), r < 128 ? t[s++] = r : (r < 2048 ? t[s++] = 192 | r >>> 6 : (r < 65536 ? t[s++] = 224 | r >>> 12 : (t[s++] = 240 | r >>> 18, t[s++] = 128 | r >>> 12 & 63), t[s++] = 128 | r >>> 6 & 63), t[s++] = 128 | 63 & r); return t; }(e); }, s.utf8decode = function(e) { return h.nodebuffer ? o.transformTo("nodebuffer", e).toString("utf-8") : function(e) { var t, r, n, i, s = e.length, a = new Array(2 * s); for (t = r = 0; t < s;) if ((n = e[t++]) < 128) a[r++] = n; else if (4 < (i = u[n])) a[r++] = 65533, t += i - 1; else { for (n &= 2 === i ? 31 : 3 === i ? 15 : 7; 1 < i && t < s;) n = n << 6 | 63 & e[t++], i--; 1 < i ? a[r++] = 65533 : n < 65536 ? a[r++] = n : (n -= 65536, a[r++] = 55296 | n >> 10 & 1023, a[r++] = 56320 | 1023 & n); } return a.length !== r && (a.subarray ? a = a.subarray(0, r) : a.length = r), o.applyFromCharCode(a); }(e = o.transformTo(h.uint8array ? "uint8array" : "array", e)); }, o.inherits(a, n), a.prototype.processChunk = function(e) { var t = o.transformTo(h.uint8array ? "uint8array" : "array", e.data); if (this.leftOver && this.leftOver.length) { if (h.uint8array) { var r = t; (t = new Uint8Array(r.length + this.leftOver.length)).set(this.leftOver, 0), t.set(r, this.leftOver.length); } else t = this.leftOver.concat(t); this.leftOver = null; } var n = function(e, t) { var r; for ((t = t || e.length) > e.length && (t = e.length), r = t - 1; 0 <= r && 128 == (192 & e[r]);) r--; return r < 0 ? t : 0 === r ? t : r + u[e[r]] > t ? r : t; }(t), i = t; n !== t.length && (h.uint8array ? (i = t.subarray(0, n), this.leftOver = t.subarray(n, t.length)) : (i = t.slice(0, n), this.leftOver = t.slice(n, t.length))), this.push({ data: s.utf8decode(i), meta: e.meta }); }, a.prototype.flush = function() { this.leftOver && this.leftOver.length && (this.push({ data: s.utf8decode(this.leftOver), meta: {} }), this.leftOver = null); }, s.Utf8DecodeWorker = a, o.inherits(l, n), l.prototype.processChunk = function(e) { this.push({ data: s.utf8encode(e.data), meta: e.meta }); }, s.Utf8EncodeWorker = l; }, { "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./support": 30, "./utils": 32 }], 32: [function(e, t, a) { "use strict"; var o = e("./support"), h = e("./base64"), r = e("./nodejsUtils"), u = e("./external"); function n(e) { return e; } function l(e, t) { for (var r = 0; r < e.length; ++r) t[r] = 255 & e.charCodeAt(r); return t; } e("setimmediate"), a.newBlob = function(t, r) { a.checkSupport("blob"); try { return new Blob([t], { type: r }); } catch (e) { try { var n = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); return n.append(t), n.getBlob(r); } catch (e) { throw new Error("Bug : can't construct the Blob."); } } }; var i = { stringifyByChunk: function(e, t, r) { var n = [], i = 0, s = e.length; if (s <= r) return String.fromCharCode.apply(null, e); for (; i < s;) "array" === t || "nodebuffer" === t ? n.push(String.fromCharCode.apply(null, e.slice(i, Math.min(i + r, s)))) : n.push(String.fromCharCode.apply(null, e.subarray(i, Math.min(i + r, s)))), i += r; return n.join(""); }, stringifyByChar: function(e) { for (var t = "", r = 0; r < e.length; r++) t += String.fromCharCode(e[r]); return t; }, applyCanBeUsed: { uint8array: function() { try { return o.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length; } catch (e) { return !1; } }(), nodebuffer: function() { try { return o.nodebuffer && 1 === String.fromCharCode.apply(null, r.allocBuffer(1)).length; } catch (e) { return !1; } }() } }; function s(e) { var t = 65536, r = a.getTypeOf(e), n = !0; if ("uint8array" === r ? n = i.applyCanBeUsed.uint8array : "nodebuffer" === r && (n = i.applyCanBeUsed.nodebuffer), n) for (; 1 < t;) try { return i.stringifyByChunk(e, r, t); } catch (e) { t = Math.floor(t / 2); } return i.stringifyByChar(e); } function f(e, t) { for (var r = 0; r < e.length; r++) t[r] = e[r]; return t; } a.applyFromCharCode = s; var c = {}; c.string = { string: n, array: function(e) { return l(e, new Array(e.length)); }, arraybuffer: function(e) { return c.string.uint8array(e).buffer; }, uint8array: function(e) { return l(e, new Uint8Array(e.length)); }, nodebuffer: function(e) { return l(e, r.allocBuffer(e.length)); } }, c.array = { string: s, array: n, arraybuffer: function(e) { return new Uint8Array(e).buffer; }, uint8array: function(e) { return new Uint8Array(e); }, nodebuffer: function(e) { return r.newBufferFrom(e); } }, c.arraybuffer = { string: function(e) { return s(new Uint8Array(e)); }, array: function(e) { return f(new Uint8Array(e), new Array(e.byteLength)); }, arraybuffer: n, uint8array: function(e) { return new Uint8Array(e); }, nodebuffer: function(e) { return r.newBufferFrom(new Uint8Array(e)); } }, c.uint8array = { string: s, array: function(e) { return f(e, new Array(e.length)); }, arraybuffer: function(e) { return e.buffer; }, uint8array: n, nodebuffer: function(e) { return r.newBufferFrom(e); } }, c.nodebuffer = { string: s, array: function(e) { return f(e, new Array(e.length)); }, arraybuffer: function(e) { return c.nodebuffer.uint8array(e).buffer; }, uint8array: function(e) { return f(e, new Uint8Array(e.length)); }, nodebuffer: n }, a.transformTo = function(e, t) { if (t = t || "", !e) return t; a.checkSupport(e); return c[a.getTypeOf(t)][e](t); }, a.resolve = function(e) { for (var t = e.split("/"), r = [], n = 0; n < t.length; n++) { var i = t[n]; "." === i || "" === i && 0 !== n && n !== t.length - 1 || (".." === i ? r.pop() : r.push(i)); } return r.join("/"); }, a.getTypeOf = function(e) { return "string" == typeof e ? "string" : "[object Array]" === Object.prototype.toString.call(e) ? "array" : o.nodebuffer && r.isBuffer(e) ? "nodebuffer" : o.uint8array && e instanceof Uint8Array ? "uint8array" : o.arraybuffer && e instanceof ArrayBuffer ? "arraybuffer" : void 0; }, a.checkSupport = function(e) { if (!o[e.toLowerCase()]) throw new Error(e + " is not supported by this platform"); }, a.MAX_VALUE_16BITS = 65535, a.MAX_VALUE_32BITS = -1, a.pretty = function(e) { var t, r, n = ""; for (r = 0; r < (e || "").length; r++) n += "\\x" + ((t = e.charCodeAt(r)) < 16 ? "0" : "") + t.toString(16).toUpperCase(); return n; }, a.delay = function(e, t, r) { setImmediate(function() { e.apply(r || null, t || []); }); }, a.inherits = function(e, t) { function r() {} r.prototype = t.prototype, e.prototype = new r(); }, a.extend = function() { var e, t, r = {}; for (e = 0; e < arguments.length; e++) for (t in arguments[e]) Object.prototype.hasOwnProperty.call(arguments[e], t) && void 0 === r[t] && (r[t] = arguments[e][t]); return r; }, a.prepareContent = function(r, e, n, i, s) { return u.Promise.resolve(e).then(function(n) { return o.blob && (n instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n))) && "undefined" != typeof FileReader ? new u.Promise(function(t, r) { var e = new FileReader(); e.onload = function(e) { t(e.target.result); }, e.onerror = function(e) { r(e.target.error); }, e.readAsArrayBuffer(n); }) : n; }).then(function(e) { var t = a.getTypeOf(e); return t ? ("arraybuffer" === t ? e = a.transformTo("uint8array", e) : "string" === t && (s ? e = h.decode(e) : n && !0 !== i && (e = function(e) { return l(e, o.uint8array ? new Uint8Array(e.length) : new Array(e.length)); }(e))), e) : u.Promise.reject(/* @__PURE__ */ new Error("Can't read the data of '" + r + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); }); }; }, { "./base64": 1, "./external": 6, "./nodejsUtils": 14, "./support": 30, setimmediate: 54 }], 33: [function(e, t, r) { "use strict"; var n = e("./reader/readerFor"), i = e("./utils"), s = e("./signature"), a = e("./zipEntry"), o = e("./support"); function h(e) { this.files = [], this.loadOptions = e; } h.prototype = { checkSignature: function(e) { if (!this.reader.readAndCheckSignature(e)) { this.reader.index -= 4; var t = this.reader.readString(4); throw new Error("Corrupted zip or bug: unexpected signature (" + i.pretty(t) + ", expected " + i.pretty(e) + ")"); } }, isSignature: function(e, t) { var r = this.reader.index; this.reader.setIndex(e); var n = this.reader.readString(4) === t; return this.reader.setIndex(r), n; }, readBlockEndOfCentral: function() { this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2); var e = this.reader.readData(this.zipCommentLength), t = o.uint8array ? "uint8array" : "array", r = i.transformTo(t, e); this.zipComment = this.loadOptions.decodeFileName(r); }, readBlockZip64EndOfCentral: function() { this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {}; for (var e, t, r, n = this.zip64EndOfCentralSize - 44; 0 < n;) e = this.reader.readInt(2), t = this.reader.readInt(4), r = this.reader.readData(t), this.zip64ExtensibleData[e] = { id: e, length: t, value: r }; }, readBlockZip64EndOfCentralLocator: function() { if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported"); }, readLocalFiles: function() { var e, t; for (e = 0; e < this.files.length; e++) t = this.files[e], this.reader.setIndex(t.localHeaderOffset), this.checkSignature(s.LOCAL_FILE_HEADER), t.readLocalPart(this.reader), t.handleUTF8(), t.processAttributes(); }, readCentralDir: function() { var e; for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);) (e = new a({ zip64: this.zip64 }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e); if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); }, readEndOfCentral: function() { var e = this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END); if (e < 0) throw !this.isSignature(0, s.LOCAL_FILE_HEADER) ? /* @__PURE__ */ new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : /* @__PURE__ */ new Error("Corrupted zip: can't find end of central directory"); this.reader.setIndex(e); var t = e; if (this.checkSignature(s.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i.MAX_VALUE_16BITS || this.centralDirRecords === i.MAX_VALUE_16BITS || this.centralDirSize === i.MAX_VALUE_32BITS || this.centralDirOffset === i.MAX_VALUE_32BITS) { if (this.zip64 = !0, (e = this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); if (this.reader.setIndex(e), this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral(); } var r = this.centralDirOffset + this.centralDirSize; this.zip64 && (r += 20, r += 12 + this.zip64EndOfCentralSize); var n = t - r; if (0 < n) this.isSignature(t, s.CENTRAL_FILE_HEADER) || (this.reader.zero = n); else if (n < 0) throw new Error("Corrupted zip: missing " + Math.abs(n) + " bytes."); }, prepareReader: function(e) { this.reader = n(e); }, load: function(e) { this.prepareReader(e), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles(); } }, t.exports = h; }, { "./reader/readerFor": 22, "./signature": 23, "./support": 30, "./utils": 32, "./zipEntry": 34 }], 34: [function(e, t, r) { "use strict"; var n = e("./reader/readerFor"), s = e("./utils"), i = e("./compressedObject"), a = e("./crc32"), o = e("./utf8"), h = e("./compressions"), u = e("./support"); function l(e, t) { this.options = e, this.loadOptions = t; } l.prototype = { isEncrypted: function() { return 1 == (1 & this.bitFlag); }, useUTF8: function() { return 2048 == (2048 & this.bitFlag); }, readLocalPart: function(e) { var t, r; if (e.skip(22), this.fileNameLength = e.readInt(2), r = e.readInt(2), this.fileName = e.readData(this.fileNameLength), e.skip(r), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)"); if (null === (t = function(e) { for (var t in h) if (Object.prototype.hasOwnProperty.call(h, t) && h[t].magic === e) return h[t]; return null; }(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s.pretty(this.compressionMethod) + " unknown (inner file : " + s.transformTo("string", this.fileName) + ")"); this.decompressed = new i(this.compressedSize, this.uncompressedSize, this.crc32, t, e.readData(this.compressedSize)); }, readCentralPart: function(e) { this.versionMadeBy = e.readInt(2), e.skip(2), this.bitFlag = e.readInt(2), this.compressionMethod = e.readString(2), this.date = e.readDate(), this.crc32 = e.readInt(4), this.compressedSize = e.readInt(4), this.uncompressedSize = e.readInt(4); var t = e.readInt(2); if (this.extraFieldsLength = e.readInt(2), this.fileCommentLength = e.readInt(2), this.diskNumberStart = e.readInt(2), this.internalFileAttributes = e.readInt(2), this.externalFileAttributes = e.readInt(4), this.localHeaderOffset = e.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported"); e.skip(t), this.readExtraFields(e), this.parseZIP64ExtraField(e), this.fileComment = e.readData(this.fileCommentLength); }, processAttributes: function() { this.unixPermissions = null, this.dosPermissions = null; var e = this.versionMadeBy >> 8; this.dir = !!(16 & this.externalFileAttributes), 0 == e && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = !0); }, parseZIP64ExtraField: function() { if (this.extraFields[1]) { var e = n(this.extraFields[1].value); this.uncompressedSize === s.MAX_VALUE_32BITS && (this.uncompressedSize = e.readInt(8)), this.compressedSize === s.MAX_VALUE_32BITS && (this.compressedSize = e.readInt(8)), this.localHeaderOffset === s.MAX_VALUE_32BITS && (this.localHeaderOffset = e.readInt(8)), this.diskNumberStart === s.MAX_VALUE_32BITS && (this.diskNumberStart = e.readInt(4)); } }, readExtraFields: function(e) { var t, r, n, i = e.index + this.extraFieldsLength; for (this.extraFields || (this.extraFields = {}); e.index + 4 < i;) t = e.readInt(2), r = e.readInt(2), n = e.readData(r), this.extraFields[t] = { id: t, length: r, value: n }; e.setIndex(i); }, handleUTF8: function() { var e = u.uint8array ? "uint8array" : "array"; if (this.useUTF8()) this.fileNameStr = o.utf8decode(this.fileName), this.fileCommentStr = o.utf8decode(this.fileComment); else { var t = this.findExtraFieldUnicodePath(); if (null !== t) this.fileNameStr = t; else { var r = s.transformTo(e, this.fileName); this.fileNameStr = this.loadOptions.decodeFileName(r); } var n = this.findExtraFieldUnicodeComment(); if (null !== n) this.fileCommentStr = n; else { var i = s.transformTo(e, this.fileComment); this.fileCommentStr = this.loadOptions.decodeFileName(i); } } }, findExtraFieldUnicodePath: function() { var e = this.extraFields[28789]; if (e) { var t = n(e.value); return 1 !== t.readInt(1) ? null : a(this.fileName) !== t.readInt(4) ? null : o.utf8decode(t.readData(e.length - 5)); } return null; }, findExtraFieldUnicodeComment: function() { var e = this.extraFields[25461]; if (e) { var t = n(e.value); return 1 !== t.readInt(1) ? null : a(this.fileComment) !== t.readInt(4) ? null : o.utf8decode(t.readData(e.length - 5)); } return null; } }, t.exports = l; }, { "./compressedObject": 2, "./compressions": 3, "./crc32": 4, "./reader/readerFor": 22, "./support": 30, "./utf8": 31, "./utils": 32 }], 35: [function(e, t, r) { "use strict"; function n(e, t, r) { this.name = e, this.dir = r.dir, this.date = r.date, this.comment = r.comment, this.unixPermissions = r.unixPermissions, this.dosPermissions = r.dosPermissions, this._data = t, this._dataBinary = r.binary, this.options = { compression: r.compression, compressionOptions: r.compressionOptions }; } var s = e("./stream/StreamHelper"), i = e("./stream/DataWorker"), a = e("./utf8"), o = e("./compressedObject"), h = e("./stream/GenericWorker"); n.prototype = { internalStream: function(e) { var t = null, r = "string"; try { if (!e) throw new Error("No output type specified."); var n = "string" === (r = e.toLowerCase()) || "text" === r; "binarystring" !== r && "text" !== r || (r = "string"), t = this._decompressWorker(); var i = !this._dataBinary; i && !n && (t = t.pipe(new a.Utf8EncodeWorker())), !i && n && (t = t.pipe(new a.Utf8DecodeWorker())); } catch (e) { (t = new h("error")).error(e); } return new s(t, r, ""); }, async: function(e, t) { return this.internalStream(e).accumulate(t); }, nodeStream: function(e, t) { return this.internalStream(e || "nodebuffer").toNodejsStream(t); }, _compressWorker: function(e, t) { if (this._data instanceof o && this._data.compression.magic === e.magic) return this._data.getCompressedWorker(); var r = this._decompressWorker(); return this._dataBinary || (r = r.pipe(new a.Utf8EncodeWorker())), o.createWorkerFrom(r, e, t); }, _decompressWorker: function() { return this._data instanceof o ? this._data.getContentWorker() : this._data instanceof h ? this._data : new i(this._data); } }; for (var u = [ "asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer" ], l = function() { throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); }, f = 0; f < u.length; f++) n.prototype[u[f]] = l; t.exports = n; }, { "./compressedObject": 2, "./stream/DataWorker": 27, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31 }], 36: [function(e, l, t) { (function(t) { "use strict"; var r, n, e = t.MutationObserver || t.WebKitMutationObserver; if (e) { var i = 0, s = new e(u), a = t.document.createTextNode(""); s.observe(a, { characterData: !0 }), r = function() { a.data = i = ++i % 2; }; } else if (t.setImmediate || void 0 === t.MessageChannel) r = "document" in t && "onreadystatechange" in t.document.createElement("script") ? function() { var e = t.document.createElement("script"); e.onreadystatechange = function() { u(), e.onreadystatechange = null, e.parentNode.removeChild(e), e = null; }, t.document.documentElement.appendChild(e); } : function() { setTimeout(u, 0); }; else { var o = new t.MessageChannel(); o.port1.onmessage = u, r = function() { o.port2.postMessage(0); }; } var h = []; function u() { var e, t; n = !0; for (var r = h.length; r;) { for (t = h, h = [], e = -1; ++e < r;) t[e](); r = h.length; } n = !1; } l.exports = function(e) { 1 !== h.push(e) || n || r(); }; }).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); }, {}], 37: [function(e, t, r) { "use strict"; var i = e("immediate"); function u() {} var l = {}, s = ["REJECTED"], a = ["FULFILLED"], n = ["PENDING"]; function o(e) { if ("function" != typeof e) throw new TypeError("resolver must be a function"); this.state = n, this.queue = [], this.outcome = void 0, e !== u && d(this, e); } function h(e, t, r) { this.promise = e, "function" == typeof t && (this.onFulfilled = t, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r && (this.onRejected = r, this.callRejected = this.otherCallRejected); } function f(t, r, n) { i(function() { var e; try { e = r(n); } catch (e) { return l.reject(t, e); } e === t ? l.reject(t, /* @__PURE__ */ new TypeError("Cannot resolve promise with itself")) : l.resolve(t, e); }); } function c(e) { var t = e && e.then; if (e && ("object" == typeof e || "function" == typeof e) && "function" == typeof t) return function() { t.apply(e, arguments); }; } function d(t, e) { var r = !1; function n(e) { r || (r = !0, l.reject(t, e)); } function i(e) { r || (r = !0, l.resolve(t, e)); } var s = p(function() { e(i, n); }); "error" === s.status && n(s.value); } function p(e, t) { var r = {}; try { r.value = e(t), r.status = "success"; } catch (e) { r.status = "error", r.value = e; } return r; } (t.exports = o).prototype.finally = function(t) { if ("function" != typeof t) return this; var r = this.constructor; return this.then(function(e) { return r.resolve(t()).then(function() { return e; }); }, function(e) { return r.resolve(t()).then(function() { throw e; }); }); }, o.prototype.catch = function(e) { return this.then(null, e); }, o.prototype.then = function(e, t) { if ("function" != typeof e && this.state === a || "function" != typeof t && this.state === s) return this; var r = new this.constructor(u); this.state !== n ? f(r, this.state === a ? e : t, this.outcome) : this.queue.push(new h(r, e, t)); return r; }, h.prototype.callFulfilled = function(e) { l.resolve(this.promise, e); }, h.prototype.otherCallFulfilled = function(e) { f(this.promise, this.onFulfilled, e); }, h.prototype.callRejected = function(e) { l.reject(this.promise, e); }, h.prototype.otherCallRejected = function(e) { f(this.promise, this.onRejected, e); }, l.resolve = function(e, t) { var r = p(c, t); if ("error" === r.status) return l.reject(e, r.value); var n = r.value; if (n) d(e, n); else { e.state = a, e.outcome = t; for (var i = -1, s = e.queue.length; ++i < s;) e.queue[i].callFulfilled(t); } return e; }, l.reject = function(e, t) { e.state = s, e.outcome = t; for (var r = -1, n = e.queue.length; ++r < n;) e.queue[r].callRejected(t); return e; }, o.resolve = function(e) { if (e instanceof this) return e; return l.resolve(new this(u), e); }, o.reject = function(e) { var t = new this(u); return l.reject(t, e); }, o.all = function(e) { var r = this; if ("[object Array]" !== Object.prototype.toString.call(e)) return this.reject(/* @__PURE__ */ new TypeError("must be an array")); var n = e.length, i = !1; if (!n) return this.resolve([]); var s = new Array(n), a = 0, t = -1, o = new this(u); for (; ++t < n;) h(e[t], t); return o; function h(e, t) { r.resolve(e).then(function(e) { s[t] = e, ++a !== n || i || (i = !0, l.resolve(o, s)); }, function(e) { i || (i = !0, l.reject(o, e)); }); } }, o.race = function(e) { var t = this; if ("[object Array]" !== Object.prototype.toString.call(e)) return this.reject(/* @__PURE__ */ new TypeError("must be an array")); var r = e.length, n = !1; if (!r) return this.resolve([]); var i = -1, s = new this(u); for (; ++i < r;) a = e[i], t.resolve(a).then(function(e) { n || (n = !0, l.resolve(s, e)); }, function(e) { n || (n = !0, l.reject(s, e)); }); var a; return s; }; }, { immediate: 36 }], 38: [function(e, t, r) { "use strict"; var n = {}; (0, e("./lib/utils/common").assign)(n, e("./lib/deflate"), e("./lib/inflate"), e("./lib/zlib/constants")), t.exports = n; }, { "./lib/deflate": 39, "./lib/inflate": 40, "./lib/utils/common": 41, "./lib/zlib/constants": 44 }], 39: [function(e, t, r) { "use strict"; var a = e("./zlib/deflate"), o = e("./utils/common"), h = e("./utils/strings"), i = e("./zlib/messages"), s = e("./zlib/zstream"), u = Object.prototype.toString, l = 0, f = -1, c = 0, d = 8; function p(e) { if (!(this instanceof p)) return new p(e); this.options = o.assign({ level: f, method: d, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: c, to: "" }, e || {}); var t = this.options; t.raw && 0 < t.windowBits ? t.windowBits = -t.windowBits : t.gzip && 0 < t.windowBits && t.windowBits < 16 && (t.windowBits += 16), this.err = 0, this.msg = "", this.ended = !1, this.chunks = [], this.strm = new s(), this.strm.avail_out = 0; var r = a.deflateInit2(this.strm, t.level, t.method, t.windowBits, t.memLevel, t.strategy); if (r !== l) throw new Error(i[r]); if (t.header && a.deflateSetHeader(this.strm, t.header), t.dictionary) { var n; if (n = "string" == typeof t.dictionary ? h.string2buf(t.dictionary) : "[object ArrayBuffer]" === u.call(t.dictionary) ? new Uint8Array(t.dictionary) : t.dictionary, (r = a.deflateSetDictionary(this.strm, n)) !== l) throw new Error(i[r]); this._dict_set = !0; } } function n(e, t) { var r = new p(t); if (r.push(e, !0), r.err) throw r.msg || i[r.err]; return r.result; } p.prototype.push = function(e, t) { var r, n, i = this.strm, s = this.options.chunkSize; if (this.ended) return !1; n = t === ~~t ? t : !0 === t ? 4 : 0, "string" == typeof e ? i.input = h.string2buf(e) : "[object ArrayBuffer]" === u.call(e) ? i.input = new Uint8Array(e) : i.input = e, i.next_in = 0, i.avail_in = i.input.length; do { if (0 === i.avail_out && (i.output = new o.Buf8(s), i.next_out = 0, i.avail_out = s), 1 !== (r = a.deflate(i, n)) && r !== l) return this.onEnd(r), !(this.ended = !0); 0 !== i.avail_out && (0 !== i.avail_in || 4 !== n && 2 !== n) || ("string" === this.options.to ? this.onData(h.buf2binstring(o.shrinkBuf(i.output, i.next_out))) : this.onData(o.shrinkBuf(i.output, i.next_out))); } while ((0 < i.avail_in || 0 === i.avail_out) && 1 !== r); return 4 === n ? (r = a.deflateEnd(this.strm), this.onEnd(r), this.ended = !0, r === l) : 2 !== n || (this.onEnd(l), !(i.avail_out = 0)); }, p.prototype.onData = function(e) { this.chunks.push(e); }, p.prototype.onEnd = function(e) { e === l && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o.flattenChunks(this.chunks)), this.chunks = [], this.err = e, this.msg = this.strm.msg; }, r.Deflate = p, r.deflate = n, r.deflateRaw = function(e, t) { return (t = t || {}).raw = !0, n(e, t); }, r.gzip = function(e, t) { return (t = t || {}).gzip = !0, n(e, t); }; }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/deflate": 46, "./zlib/messages": 51, "./zlib/zstream": 53 }], 40: [function(e, t, r) { "use strict"; var c = e("./zlib/inflate"), d = e("./utils/common"), p = e("./utils/strings"), m = e("./zlib/constants"), n = e("./zlib/messages"), i = e("./zlib/zstream"), s = e("./zlib/gzheader"), _ = Object.prototype.toString; function a(e) { if (!(this instanceof a)) return new a(e); this.options = d.assign({ chunkSize: 16384, windowBits: 0, to: "" }, e || {}); var t = this.options; t.raw && 0 <= t.windowBits && t.windowBits < 16 && (t.windowBits = -t.windowBits, 0 === t.windowBits && (t.windowBits = -15)), !(0 <= t.windowBits && t.windowBits < 16) || e && e.windowBits || (t.windowBits += 32), 15 < t.windowBits && t.windowBits < 48 && 0 == (15 & t.windowBits) && (t.windowBits |= 15), this.err = 0, this.msg = "", this.ended = !1, this.chunks = [], this.strm = new i(), this.strm.avail_out = 0; var r = c.inflateInit2(this.strm, t.windowBits); if (r !== m.Z_OK) throw new Error(n[r]); this.header = new s(), c.inflateGetHeader(this.strm, this.header); } function o(e, t) { var r = new a(t); if (r.push(e, !0), r.err) throw r.msg || n[r.err]; return r.result; } a.prototype.push = function(e, t) { var r, n, i, s, a, o, h = this.strm, u = this.options.chunkSize, l = this.options.dictionary, f = !1; if (this.ended) return !1; n = t === ~~t ? t : !0 === t ? m.Z_FINISH : m.Z_NO_FLUSH, "string" == typeof e ? h.input = p.binstring2buf(e) : "[object ArrayBuffer]" === _.call(e) ? h.input = new Uint8Array(e) : h.input = e, h.next_in = 0, h.avail_in = h.input.length; do { if (0 === h.avail_out && (h.output = new d.Buf8(u), h.next_out = 0, h.avail_out = u), (r = c.inflate(h, m.Z_NO_FLUSH)) === m.Z_NEED_DICT && l && (o = "string" == typeof l ? p.string2buf(l) : "[object ArrayBuffer]" === _.call(l) ? new Uint8Array(l) : l, r = c.inflateSetDictionary(this.strm, o)), r === m.Z_BUF_ERROR && !0 === f && (r = m.Z_OK, f = !1), r !== m.Z_STREAM_END && r !== m.Z_OK) return this.onEnd(r), !(this.ended = !0); h.next_out && (0 !== h.avail_out && r !== m.Z_STREAM_END && (0 !== h.avail_in || n !== m.Z_FINISH && n !== m.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i = p.utf8border(h.output, h.next_out), s = h.next_out - i, a = p.buf2string(h.output, i), h.next_out = s, h.avail_out = u - s, s && d.arraySet(h.output, h.output, i, s, 0), this.onData(a)) : this.onData(d.shrinkBuf(h.output, h.next_out)))), 0 === h.avail_in && 0 === h.avail_out && (f = !0); } while ((0 < h.avail_in || 0 === h.avail_out) && r !== m.Z_STREAM_END); return r === m.Z_STREAM_END && (n = m.Z_FINISH), n === m.Z_FINISH ? (r = c.inflateEnd(this.strm), this.onEnd(r), this.ended = !0, r === m.Z_OK) : n !== m.Z_SYNC_FLUSH || (this.onEnd(m.Z_OK), !(h.avail_out = 0)); }, a.prototype.onData = function(e) { this.chunks.push(e); }, a.prototype.onEnd = function(e) { e === m.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d.flattenChunks(this.chunks)), this.chunks = [], this.err = e, this.msg = this.strm.msg; }, r.Inflate = a, r.inflate = o, r.inflateRaw = function(e, t) { return (t = t || {}).raw = !0, o(e, t); }, r.ungzip = o; }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/constants": 44, "./zlib/gzheader": 47, "./zlib/inflate": 49, "./zlib/messages": 51, "./zlib/zstream": 53 }], 41: [function(e, t, r) { "use strict"; var n = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array; r.assign = function(e) { for (var t = Array.prototype.slice.call(arguments, 1); t.length;) { var r = t.shift(); if (r) { if ("object" != typeof r) throw new TypeError(r + "must be non-object"); for (var n in r) r.hasOwnProperty(n) && (e[n] = r[n]); } } return e; }, r.shrinkBuf = function(e, t) { return e.length === t ? e : e.subarray ? e.subarray(0, t) : (e.length = t, e); }; var i = { arraySet: function(e, t, r, n, i) { if (t.subarray && e.subarray) e.set(t.subarray(r, r + n), i); else for (var s = 0; s < n; s++) e[i + s] = t[r + s]; }, flattenChunks: function(e) { var t, r, n, i, s, a; for (t = n = 0, r = e.length; t < r; t++) n += e[t].length; for (a = new Uint8Array(n), t = i = 0, r = e.length; t < r; t++) s = e[t], a.set(s, i), i += s.length; return a; } }, s = { arraySet: function(e, t, r, n, i) { for (var s = 0; s < n; s++) e[i + s] = t[r + s]; }, flattenChunks: function(e) { return [].concat.apply([], e); } }; r.setTyped = function(e) { e ? (r.Buf8 = Uint8Array, r.Buf16 = Uint16Array, r.Buf32 = Int32Array, r.assign(r, i)) : (r.Buf8 = Array, r.Buf16 = Array, r.Buf32 = Array, r.assign(r, s)); }, r.setTyped(n); }, {}], 42: [function(e, t, r) { "use strict"; var h = e("./common"), i = !0, s = !0; try { String.fromCharCode.apply(null, [0]); } catch (e) { i = !1; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (e) { s = !1; } for (var u = new h.Buf8(256), n = 0; n < 256; n++) u[n] = 252 <= n ? 6 : 248 <= n ? 5 : 240 <= n ? 4 : 224 <= n ? 3 : 192 <= n ? 2 : 1; function l(e, t) { if (t < 65537 && (e.subarray && s || !e.subarray && i)) return String.fromCharCode.apply(null, h.shrinkBuf(e, t)); for (var r = "", n = 0; n < t; n++) r += String.fromCharCode(e[n]); return r; } u[254] = u[254] = 1, r.string2buf = function(e) { var t, r, n, i, s, a = e.length, o = 0; for (i = 0; i < a; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), o += r < 128 ? 1 : r < 2048 ? 2 : r < 65536 ? 3 : 4; for (t = new h.Buf8(o), i = s = 0; s < o; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), r < 128 ? t[s++] = r : (r < 2048 ? t[s++] = 192 | r >>> 6 : (r < 65536 ? t[s++] = 224 | r >>> 12 : (t[s++] = 240 | r >>> 18, t[s++] = 128 | r >>> 12 & 63), t[s++] = 128 | r >>> 6 & 63), t[s++] = 128 | 63 & r); return t; }, r.buf2binstring = function(e) { return l(e, e.length); }, r.binstring2buf = function(e) { for (var t = new h.Buf8(e.length), r = 0, n = t.length; r < n; r++) t[r] = e.charCodeAt(r); return t; }, r.buf2string = function(e, t) { var r, n, i, s, a = t || e.length, o = new Array(2 * a); for (r = n = 0; r < a;) if ((i = e[r++]) < 128) o[n++] = i; else if (4 < (s = u[i])) o[n++] = 65533, r += s - 1; else { for (i &= 2 === s ? 31 : 3 === s ? 15 : 7; 1 < s && r < a;) i = i << 6 | 63 & e[r++], s--; 1 < s ? o[n++] = 65533 : i < 65536 ? o[n++] = i : (i -= 65536, o[n++] = 55296 | i >> 10 & 1023, o[n++] = 56320 | 1023 & i); } return l(o, n); }, r.utf8border = function(e, t) { var r; for ((t = t || e.length) > e.length && (t = e.length), r = t - 1; 0 <= r && 128 == (192 & e[r]);) r--; return r < 0 ? t : 0 === r ? t : r + u[e[r]] > t ? r : t; }; }, { "./common": 41 }], 43: [function(e, t, r) { "use strict"; t.exports = function(e, t, r, n) { for (var i = 65535 & e | 0, s = e >>> 16 & 65535 | 0, a = 0; 0 !== r;) { for (r -= a = 2e3 < r ? 2e3 : r; s = s + (i = i + t[n++] | 0) | 0, --a;); i %= 65521, s %= 65521; } return i | s << 16 | 0; }; }, {}], 44: [function(e, t, r) { "use strict"; t.exports = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 }; }, {}], 45: [function(e, t, r) { "use strict"; var o = function() { for (var e, t = [], r = 0; r < 256; r++) { e = r; for (var n = 0; n < 8; n++) e = 1 & e ? 3988292384 ^ e >>> 1 : e >>> 1; t[r] = e; } return t; }(); t.exports = function(e, t, r, n) { var i = o, s = n + r; e ^= -1; for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t[a])]; return -1 ^ e; }; }, {}], 46: [function(e, t, r) { "use strict"; var h, c = e("../utils/common"), u = e("./trees"), d = e("./adler32"), p = e("./crc32"), n = e("./messages"), l = 0, f = 4, m = 0, _ = -2, g = -1, b = 4, i = 2, v = 8, y = 9, s = 286, a = 30, o = 19, w = 2 * s + 1, k = 15, x = 3, S = 258, z = S + x + 1, C = 42, E = 113, A = 1, I = 2, O = 3, B = 4; function R(e, t) { return e.msg = n[t], t; } function T(e) { return (e << 1) - (4 < e ? 9 : 0); } function D(e) { for (var t = e.length; 0 <= --t;) e[t] = 0; } function F(e) { var t = e.state, r = t.pending; r > e.avail_out && (r = e.avail_out), 0 !== r && (c.arraySet(e.output, t.pending_buf, t.pending_out, r, e.next_out), e.next_out += r, t.pending_out += r, e.total_out += r, e.avail_out -= r, t.pending -= r, 0 === t.pending && (t.pending_out = 0)); } function N(e, t) { u._tr_flush_block(e, 0 <= e.block_start ? e.block_start : -1, e.strstart - e.block_start, t), e.block_start = e.strstart, F(e.strm); } function U(e, t) { e.pending_buf[e.pending++] = t; } function P(e, t) { e.pending_buf[e.pending++] = t >>> 8 & 255, e.pending_buf[e.pending++] = 255 & t; } function L(e, t) { var r, n, i = e.max_chain_length, s = e.strstart, a = e.prev_length, o = e.nice_match, h = e.strstart > e.w_size - z ? e.strstart - (e.w_size - z) : 0, u = e.window, l = e.w_mask, f = e.prev, c = e.strstart + S, d = u[s + a - 1], p = u[s + a]; e.prev_length >= e.good_match && (i >>= 2), o > e.lookahead && (o = e.lookahead); do if (u[(r = t) + a] === p && u[r + a - 1] === d && u[r] === u[s] && u[++r] === u[s + 1]) { s += 2, r++; do ; while (u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && s < c); if (n = S - (c - s), s = c - S, a < n) { if (e.match_start = t, o <= (a = n)) break; d = u[s + a - 1], p = u[s + a]; } } while ((t = f[t & l]) > h && 0 != --i); return a <= e.lookahead ? a : e.lookahead; } function j(e) { var t, r, n, i, s, a, o, h, u, l, f = e.w_size; do { if (i = e.window_size - e.lookahead - e.strstart, e.strstart >= f + (f - z)) { for (c.arraySet(e.window, e.window, f, f, 0), e.match_start -= f, e.strstart -= f, e.block_start -= f, t = r = e.hash_size; n = e.head[--t], e.head[t] = f <= n ? n - f : 0, --r;); for (t = r = f; n = e.prev[--t], e.prev[t] = f <= n ? n - f : 0, --r;); i += f; } if (0 === e.strm.avail_in) break; if (a = e.strm, o = e.window, h = e.strstart + e.lookahead, u = i, l = void 0, l = a.avail_in, u < l && (l = u), r = 0 === l ? 0 : (a.avail_in -= l, c.arraySet(o, a.input, a.next_in, l, h), 1 === a.state.wrap ? a.adler = d(a.adler, o, l, h) : 2 === a.state.wrap && (a.adler = p(a.adler, o, l, h)), a.next_in += l, a.total_in += l, l), e.lookahead += r, e.lookahead + e.insert >= x) for (s = e.strstart - e.insert, e.ins_h = e.window[s], e.ins_h = (e.ins_h << e.hash_shift ^ e.window[s + 1]) & e.hash_mask; e.insert && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[s + x - 1]) & e.hash_mask, e.prev[s & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = s, s++, e.insert--, !(e.lookahead + e.insert < x));); } while (e.lookahead < z && 0 !== e.strm.avail_in); } function Z(e, t) { for (var r, n;;) { if (e.lookahead < z) { if (j(e), e.lookahead < z && t === l) return A; if (0 === e.lookahead) break; } if (r = 0, e.lookahead >= x && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), 0 !== r && e.strstart - r <= e.w_size - z && (e.match_length = L(e, r)), e.match_length >= x) if (n = u._tr_tally(e, e.strstart - e.match_start, e.match_length - x), e.lookahead -= e.match_length, e.match_length <= e.max_lazy_match && e.lookahead >= x) { for (e.match_length--; e.strstart++, e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart, 0 != --e.match_length;); e.strstart++; } else e.strstart += e.match_length, e.match_length = 0, e.ins_h = e.window[e.strstart], e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + 1]) & e.hash_mask; else n = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++; if (n && (N(e, !1), 0 === e.strm.avail_out)) return A; } return e.insert = e.strstart < x - 1 ? e.strstart : x - 1, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I; } function W(e, t) { for (var r, n, i;;) { if (e.lookahead < z) { if (j(e), e.lookahead < z && t === l) return A; if (0 === e.lookahead) break; } if (r = 0, e.lookahead >= x && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), e.prev_length = e.match_length, e.prev_match = e.match_start, e.match_length = x - 1, 0 !== r && e.prev_length < e.max_lazy_match && e.strstart - r <= e.w_size - z && (e.match_length = L(e, r), e.match_length <= 5 && (1 === e.strategy || e.match_length === x && 4096 < e.strstart - e.match_start) && (e.match_length = x - 1)), e.prev_length >= x && e.match_length <= e.prev_length) { for (i = e.strstart + e.lookahead - x, n = u._tr_tally(e, e.strstart - 1 - e.prev_match, e.prev_length - x), e.lookahead -= e.prev_length - 1, e.prev_length -= 2; ++e.strstart <= i && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), 0 != --e.prev_length;); if (e.match_available = 0, e.match_length = x - 1, e.strstart++, n && (N(e, !1), 0 === e.strm.avail_out)) return A; } else if (e.match_available) { if ((n = u._tr_tally(e, 0, e.window[e.strstart - 1])) && N(e, !1), e.strstart++, e.lookahead--, 0 === e.strm.avail_out) return A; } else e.match_available = 1, e.strstart++, e.lookahead--; } return e.match_available && (n = u._tr_tally(e, 0, e.window[e.strstart - 1]), e.match_available = 0), e.insert = e.strstart < x - 1 ? e.strstart : x - 1, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I; } function M(e, t, r, n, i) { this.good_length = e, this.max_lazy = t, this.nice_length = r, this.max_chain = n, this.func = i; } function H() { this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c.Buf16(2 * w), this.dyn_dtree = new c.Buf16(2 * (2 * a + 1)), this.bl_tree = new c.Buf16(2 * (2 * o + 1)), D(this.dyn_ltree), D(this.dyn_dtree), D(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c.Buf16(k + 1), this.heap = new c.Buf16(2 * s + 1), D(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c.Buf16(2 * s + 1), D(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0; } function G(e) { var t; return e && e.state ? (e.total_in = e.total_out = 0, e.data_type = i, (t = e.state).pending = 0, t.pending_out = 0, t.wrap < 0 && (t.wrap = -t.wrap), t.status = t.wrap ? C : E, e.adler = 2 === t.wrap ? 0 : 1, t.last_flush = l, u._tr_init(t), m) : R(e, _); } function K(e) { var t = G(e); return t === m && function(e) { e.window_size = 2 * e.w_size, D(e.head), e.max_lazy_match = h[e.level].max_lazy, e.good_match = h[e.level].good_length, e.nice_match = h[e.level].nice_length, e.max_chain_length = h[e.level].max_chain, e.strstart = 0, e.block_start = 0, e.lookahead = 0, e.insert = 0, e.match_length = e.prev_length = x - 1, e.match_available = 0, e.ins_h = 0; }(e.state), t; } function Y(e, t, r, n, i, s) { if (!e) return _; var a = 1; if (t === g && (t = 6), n < 0 ? (a = 0, n = -n) : 15 < n && (a = 2, n -= 16), i < 1 || y < i || r !== v || n < 8 || 15 < n || t < 0 || 9 < t || s < 0 || b < s) return R(e, _); 8 === n && (n = 9); var o = new H(); return (e.state = o).strm = e, o.wrap = a, o.gzhead = null, o.w_bits = n, o.w_size = 1 << o.w_bits, o.w_mask = o.w_size - 1, o.hash_bits = i + 7, o.hash_size = 1 << o.hash_bits, o.hash_mask = o.hash_size - 1, o.hash_shift = ~~((o.hash_bits + x - 1) / x), o.window = new c.Buf8(2 * o.w_size), o.head = new c.Buf16(o.hash_size), o.prev = new c.Buf16(o.w_size), o.lit_bufsize = 1 << i + 6, o.pending_buf_size = 4 * o.lit_bufsize, o.pending_buf = new c.Buf8(o.pending_buf_size), o.d_buf = 1 * o.lit_bufsize, o.l_buf = 3 * o.lit_bufsize, o.level = t, o.strategy = s, o.method = r, K(e); } h = [ new M(0, 0, 0, 0, function(e, t) { var r = 65535; for (r > e.pending_buf_size - 5 && (r = e.pending_buf_size - 5);;) { if (e.lookahead <= 1) { if (j(e), 0 === e.lookahead && t === l) return A; if (0 === e.lookahead) break; } e.strstart += e.lookahead, e.lookahead = 0; var n = e.block_start + r; if ((0 === e.strstart || e.strstart >= n) && (e.lookahead = e.strstart - n, e.strstart = n, N(e, !1), 0 === e.strm.avail_out)) return A; if (e.strstart - e.block_start >= e.w_size - z && (N(e, !1), 0 === e.strm.avail_out)) return A; } return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : (e.strstart > e.block_start && (N(e, !1), e.strm.avail_out), A); }), new M(4, 4, 8, 4, Z), new M(4, 5, 16, 8, Z), new M(4, 6, 32, 32, Z), new M(4, 4, 16, 16, W), new M(8, 16, 32, 32, W), new M(8, 16, 128, 128, W), new M(8, 32, 128, 256, W), new M(32, 128, 258, 1024, W), new M(32, 258, 258, 4096, W) ], r.deflateInit = function(e, t) { return Y(e, t, v, 15, 8, 0); }, r.deflateInit2 = Y, r.deflateReset = K, r.deflateResetKeep = G, r.deflateSetHeader = function(e, t) { return e && e.state ? 2 !== e.state.wrap ? _ : (e.state.gzhead = t, m) : _; }, r.deflate = function(e, t) { var r, n, i, s; if (!e || !e.state || 5 < t || t < 0) return e ? R(e, _) : _; if (n = e.state, !e.output || !e.input && 0 !== e.avail_in || 666 === n.status && t !== f) return R(e, 0 === e.avail_out ? -5 : _); if (n.strm = e, r = n.last_flush, n.last_flush = t, n.status === C) if (2 === n.wrap) e.adler = 0, U(n, 31), U(n, 139), U(n, 8), n.gzhead ? (U(n, (n.gzhead.text ? 1 : 0) + (n.gzhead.hcrc ? 2 : 0) + (n.gzhead.extra ? 4 : 0) + (n.gzhead.name ? 8 : 0) + (n.gzhead.comment ? 16 : 0)), U(n, 255 & n.gzhead.time), U(n, n.gzhead.time >> 8 & 255), U(n, n.gzhead.time >> 16 & 255), U(n, n.gzhead.time >> 24 & 255), U(n, 9 === n.level ? 2 : 2 <= n.strategy || n.level < 2 ? 4 : 0), U(n, 255 & n.gzhead.os), n.gzhead.extra && n.gzhead.extra.length && (U(n, 255 & n.gzhead.extra.length), U(n, n.gzhead.extra.length >> 8 & 255)), n.gzhead.hcrc && (e.adler = p(e.adler, n.pending_buf, n.pending, 0)), n.gzindex = 0, n.status = 69) : (U(n, 0), U(n, 0), U(n, 0), U(n, 0), U(n, 0), U(n, 9 === n.level ? 2 : 2 <= n.strategy || n.level < 2 ? 4 : 0), U(n, 3), n.status = E); else { var a = v + (n.w_bits - 8 << 4) << 8; a |= (2 <= n.strategy || n.level < 2 ? 0 : n.level < 6 ? 1 : 6 === n.level ? 2 : 3) << 6, 0 !== n.strstart && (a |= 32), a += 31 - a % 31, n.status = E, P(n, a), 0 !== n.strstart && (P(n, e.adler >>> 16), P(n, 65535 & e.adler)), e.adler = 1; } if (69 === n.status) if (n.gzhead.extra) { for (i = n.pending; n.gzindex < (65535 & n.gzhead.extra.length) && (n.pending !== n.pending_buf_size || (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending !== n.pending_buf_size));) U(n, 255 & n.gzhead.extra[n.gzindex]), n.gzindex++; n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), n.gzindex === n.gzhead.extra.length && (n.gzindex = 0, n.status = 73); } else n.status = 73; if (73 === n.status) if (n.gzhead.name) { i = n.pending; do { if (n.pending === n.pending_buf_size && (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending === n.pending_buf_size)) { s = 1; break; } s = n.gzindex < n.gzhead.name.length ? 255 & n.gzhead.name.charCodeAt(n.gzindex++) : 0, U(n, s); } while (0 !== s); n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), 0 === s && (n.gzindex = 0, n.status = 91); } else n.status = 91; if (91 === n.status) if (n.gzhead.comment) { i = n.pending; do { if (n.pending === n.pending_buf_size && (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending === n.pending_buf_size)) { s = 1; break; } s = n.gzindex < n.gzhead.comment.length ? 255 & n.gzhead.comment.charCodeAt(n.gzindex++) : 0, U(n, s); } while (0 !== s); n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), 0 === s && (n.status = 103); } else n.status = 103; if (103 === n.status && (n.gzhead.hcrc ? (n.pending + 2 > n.pending_buf_size && F(e), n.pending + 2 <= n.pending_buf_size && (U(n, 255 & e.adler), U(n, e.adler >> 8 & 255), e.adler = 0, n.status = E)) : n.status = E), 0 !== n.pending) { if (F(e), 0 === e.avail_out) return n.last_flush = -1, m; } else if (0 === e.avail_in && T(t) <= T(r) && t !== f) return R(e, -5); if (666 === n.status && 0 !== e.avail_in) return R(e, -5); if (0 !== e.avail_in || 0 !== n.lookahead || t !== l && 666 !== n.status) { var o = 2 === n.strategy ? function(e, t) { for (var r;;) { if (0 === e.lookahead && (j(e), 0 === e.lookahead)) { if (t === l) return A; break; } if (e.match_length = 0, r = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++, r && (N(e, !1), 0 === e.strm.avail_out)) return A; } return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I; }(n, t) : 3 === n.strategy ? function(e, t) { for (var r, n, i, s, a = e.window;;) { if (e.lookahead <= S) { if (j(e), e.lookahead <= S && t === l) return A; if (0 === e.lookahead) break; } if (e.match_length = 0, e.lookahead >= x && 0 < e.strstart && (n = a[i = e.strstart - 1]) === a[++i] && n === a[++i] && n === a[++i]) { s = e.strstart + S; do ; while (n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && i < s); e.match_length = S - (s - i), e.match_length > e.lookahead && (e.match_length = e.lookahead); } if (e.match_length >= x ? (r = u._tr_tally(e, 1, e.match_length - x), e.lookahead -= e.match_length, e.strstart += e.match_length, e.match_length = 0) : (r = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++), r && (N(e, !1), 0 === e.strm.avail_out)) return A; } return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I; }(n, t) : h[n.level].func(n, t); if (o !== O && o !== B || (n.status = 666), o === A || o === O) return 0 === e.avail_out && (n.last_flush = -1), m; if (o === I && (1 === t ? u._tr_align(n) : 5 !== t && (u._tr_stored_block(n, 0, 0, !1), 3 === t && (D(n.head), 0 === n.lookahead && (n.strstart = 0, n.block_start = 0, n.insert = 0))), F(e), 0 === e.avail_out)) return n.last_flush = -1, m; } return t !== f ? m : n.wrap <= 0 ? 1 : (2 === n.wrap ? (U(n, 255 & e.adler), U(n, e.adler >> 8 & 255), U(n, e.adler >> 16 & 255), U(n, e.adler >> 24 & 255), U(n, 255 & e.total_in), U(n, e.total_in >> 8 & 255), U(n, e.total_in >> 16 & 255), U(n, e.total_in >> 24 & 255)) : (P(n, e.adler >>> 16), P(n, 65535 & e.adler)), F(e), 0 < n.wrap && (n.wrap = -n.wrap), 0 !== n.pending ? m : 1); }, r.deflateEnd = function(e) { var t; return e && e.state ? (t = e.state.status) !== C && 69 !== t && 73 !== t && 91 !== t && 103 !== t && t !== E && 666 !== t ? R(e, _) : (e.state = null, t === E ? R(e, -3) : m) : _; }, r.deflateSetDictionary = function(e, t) { var r, n, i, s, a, o, h, u, l = t.length; if (!e || !e.state) return _; if (2 === (s = (r = e.state).wrap) || 1 === s && r.status !== C || r.lookahead) return _; for (1 === s && (e.adler = d(e.adler, t, l, 0)), r.wrap = 0, l >= r.w_size && (0 === s && (D(r.head), r.strstart = 0, r.block_start = 0, r.insert = 0), u = new c.Buf8(r.w_size), c.arraySet(u, t, l - r.w_size, r.w_size, 0), t = u, l = r.w_size), a = e.avail_in, o = e.next_in, h = e.input, e.avail_in = l, e.next_in = 0, e.input = t, j(r); r.lookahead >= x;) { for (n = r.strstart, i = r.lookahead - (x - 1); r.ins_h = (r.ins_h << r.hash_shift ^ r.window[n + x - 1]) & r.hash_mask, r.prev[n & r.w_mask] = r.head[r.ins_h], r.head[r.ins_h] = n, n++, --i;); r.strstart = n, r.lookahead = x - 1, j(r); } return r.strstart += r.lookahead, r.block_start = r.strstart, r.insert = r.lookahead, r.lookahead = 0, r.match_length = r.prev_length = x - 1, r.match_available = 0, e.next_in = o, e.input = h, e.avail_in = a, r.wrap = s, m; }, r.deflateInfo = "pako deflate (from Nodeca project)"; }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./messages": 51, "./trees": 52 }], 47: [function(e, t, r) { "use strict"; t.exports = function() { this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = !1; }; }, {}], 48: [function(e, t, r) { "use strict"; t.exports = function(e, t) { var r = e.state, n = e.next_in, i, s, a, o, h, u, l, f, c, d, p, m, _, g, b, v, y, w, k, x, S, z = e.input, C; i = n + (e.avail_in - 5), s = e.next_out, C = e.output, a = s - (t - e.avail_out), o = s + (e.avail_out - 257), h = r.dmax, u = r.wsize, l = r.whave, f = r.wnext, c = r.window, d = r.hold, p = r.bits, m = r.lencode, _ = r.distcode, g = (1 << r.lenbits) - 1, b = (1 << r.distbits) - 1; e: do { p < 15 && (d += z[n++] << p, p += 8, d += z[n++] << p, p += 8), v = m[d & g]; t: for (;;) { if (d >>>= y = v >>> 24, p -= y, 0 === (y = v >>> 16 & 255)) C[s++] = 65535 & v; else { if (!(16 & y)) { if (0 == (64 & y)) { v = m[(65535 & v) + (d & (1 << y) - 1)]; continue t; } if (32 & y) { r.mode = 12; break e; } e.msg = "invalid literal/length code", r.mode = 30; break e; } w = 65535 & v, (y &= 15) && (p < y && (d += z[n++] << p, p += 8), w += d & (1 << y) - 1, d >>>= y, p -= y), p < 15 && (d += z[n++] << p, p += 8, d += z[n++] << p, p += 8), v = _[d & b]; r: for (;;) { if (d >>>= y = v >>> 24, p -= y, !(16 & (y = v >>> 16 & 255))) { if (0 == (64 & y)) { v = _[(65535 & v) + (d & (1 << y) - 1)]; continue r; } e.msg = "invalid distance code", r.mode = 30; break e; } if (k = 65535 & v, p < (y &= 15) && (d += z[n++] << p, (p += 8) < y && (d += z[n++] << p, p += 8)), h < (k += d & (1 << y) - 1)) { e.msg = "invalid distance too far back", r.mode = 30; break e; } if (d >>>= y, p -= y, (y = s - a) < k) { if (l < (y = k - y) && r.sane) { e.msg = "invalid distance too far back", r.mode = 30; break e; } if (S = c, (x = 0) === f) { if (x += u - y, y < w) { for (w -= y; C[s++] = c[x++], --y;); x = s - k, S = C; } } else if (f < y) { if (x += u + f - y, (y -= f) < w) { for (w -= y; C[s++] = c[x++], --y;); if (x = 0, f < w) { for (w -= y = f; C[s++] = c[x++], --y;); x = s - k, S = C; } } } else if (x += f - y, y < w) { for (w -= y; C[s++] = c[x++], --y;); x = s - k, S = C; } for (; 2 < w;) C[s++] = S[x++], C[s++] = S[x++], C[s++] = S[x++], w -= 3; w && (C[s++] = S[x++], 1 < w && (C[s++] = S[x++])); } else { for (x = s - k; C[s++] = C[x++], C[s++] = C[x++], C[s++] = C[x++], 2 < (w -= 3);); w && (C[s++] = C[x++], 1 < w && (C[s++] = C[x++])); } break; } } break; } } while (n < i && s < o); n -= w = p >> 3, d &= (1 << (p -= w << 3)) - 1, e.next_in = n, e.next_out = s, e.avail_in = n < i ? i - n + 5 : 5 - (n - i), e.avail_out = s < o ? o - s + 257 : 257 - (s - o), r.hold = d, r.bits = p; }; }, {}], 49: [function(e, t, r) { "use strict"; var I = e("../utils/common"), O = e("./adler32"), B = e("./crc32"), R = e("./inffast"), T = e("./inftrees"), D = 1, F = 2, N = 0, U = -2, P = 1, n = 852, i = 592; function L(e) { return (e >>> 24 & 255) + (e >>> 8 & 65280) + ((65280 & e) << 8) + ((255 & e) << 24); } function s() { this.mode = 0, this.last = !1, this.wrap = 0, this.havedict = !1, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I.Buf16(320), this.work = new I.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0; } function a(e) { var t; return e && e.state ? (t = e.state, e.total_in = e.total_out = t.total = 0, e.msg = "", t.wrap && (e.adler = 1 & t.wrap), t.mode = P, t.last = 0, t.havedict = 0, t.dmax = 32768, t.head = null, t.hold = 0, t.bits = 0, t.lencode = t.lendyn = new I.Buf32(n), t.distcode = t.distdyn = new I.Buf32(i), t.sane = 1, t.back = -1, N) : U; } function o(e) { var t; return e && e.state ? ((t = e.state).wsize = 0, t.whave = 0, t.wnext = 0, a(e)) : U; } function h(e, t) { var r, n; return e && e.state ? (n = e.state, t < 0 ? (r = 0, t = -t) : (r = 1 + (t >> 4), t < 48 && (t &= 15)), t && (t < 8 || 15 < t) ? U : (null !== n.window && n.wbits !== t && (n.window = null), n.wrap = r, n.wbits = t, o(e))) : U; } function u(e, t) { var r, n; return e ? (n = new s(), (e.state = n).window = null, (r = h(e, t)) !== N && (e.state = null), r) : U; } var l, f, c = !0; function j(e) { if (c) { var t; for (l = new I.Buf32(512), f = new I.Buf32(32), t = 0; t < 144;) e.lens[t++] = 8; for (; t < 256;) e.lens[t++] = 9; for (; t < 280;) e.lens[t++] = 7; for (; t < 288;) e.lens[t++] = 8; for (T(D, e.lens, 0, 288, l, 0, e.work, { bits: 9 }), t = 0; t < 32;) e.lens[t++] = 5; T(F, e.lens, 0, 32, f, 0, e.work, { bits: 5 }), c = !1; } e.lencode = l, e.lenbits = 9, e.distcode = f, e.distbits = 5; } function Z(e, t, r, n) { var i, s = e.state; return null === s.window && (s.wsize = 1 << s.wbits, s.wnext = 0, s.whave = 0, s.window = new I.Buf8(s.wsize)), n >= s.wsize ? (I.arraySet(s.window, t, r - s.wsize, s.wsize, 0), s.wnext = 0, s.whave = s.wsize) : (n < (i = s.wsize - s.wnext) && (i = n), I.arraySet(s.window, t, r - n, i, s.wnext), (n -= i) ? (I.arraySet(s.window, t, r - n, n, 0), s.wnext = n, s.whave = s.wsize) : (s.wnext += i, s.wnext === s.wsize && (s.wnext = 0), s.whave < s.wsize && (s.whave += i))), 0; } r.inflateReset = o, r.inflateReset2 = h, r.inflateResetKeep = a, r.inflateInit = function(e) { return u(e, 15); }, r.inflateInit2 = u, r.inflate = function(e, t) { var r, n, i, s, a, o, h, u, l, f, c, d, p, m, _, g, b, v, y, w, k, x, S, z, C = 0, E = new I.Buf8(4), A = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!e || !e.state || !e.output || !e.input && 0 !== e.avail_in) return U; 12 === (r = e.state).mode && (r.mode = 13), a = e.next_out, i = e.output, h = e.avail_out, s = e.next_in, n = e.input, o = e.avail_in, u = r.hold, l = r.bits, f = o, c = h, x = N; e: for (;;) switch (r.mode) { case P: if (0 === r.wrap) { r.mode = 13; break; } for (; l < 16;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (2 & r.wrap && 35615 === u) { E[r.check = 0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0), l = u = 0, r.mode = 2; break; } if (r.flags = 0, r.head && (r.head.done = !1), !(1 & r.wrap) || (((255 & u) << 8) + (u >> 8)) % 31) { e.msg = "incorrect header check", r.mode = 30; break; } if (8 != (15 & u)) { e.msg = "unknown compression method", r.mode = 30; break; } if (l -= 4, k = 8 + (15 & (u >>>= 4)), 0 === r.wbits) r.wbits = k; else if (k > r.wbits) { e.msg = "invalid window size", r.mode = 30; break; } r.dmax = 1 << k, e.adler = r.check = 1, r.mode = 512 & u ? 10 : 12, l = u = 0; break; case 2: for (; l < 16;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (r.flags = u, 8 != (255 & r.flags)) { e.msg = "unknown compression method", r.mode = 30; break; } if (57344 & r.flags) { e.msg = "unknown header flags set", r.mode = 30; break; } r.head && (r.head.text = u >> 8 & 1), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0, r.mode = 3; case 3: for (; l < 32;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } r.head && (r.head.time = u), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, E[2] = u >>> 16 & 255, E[3] = u >>> 24 & 255, r.check = B(r.check, E, 4, 0)), l = u = 0, r.mode = 4; case 4: for (; l < 16;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } r.head && (r.head.xflags = 255 & u, r.head.os = u >> 8), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0, r.mode = 5; case 5: if (1024 & r.flags) { for (; l < 16;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } r.length = u, r.head && (r.head.extra_len = u), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0; } else r.head && (r.head.extra = null); r.mode = 6; case 6: if (1024 & r.flags && (o < (d = r.length) && (d = o), d && (r.head && (k = r.head.extra_len - r.length, r.head.extra || (r.head.extra = new Array(r.head.extra_len)), I.arraySet(r.head.extra, n, s, d, k)), 512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, r.length -= d), r.length)) break e; r.length = 0, r.mode = 7; case 7: if (2048 & r.flags) { if (0 === o) break e; for (d = 0; k = n[s + d++], r.head && k && r.length < 65536 && (r.head.name += String.fromCharCode(k)), k && d < o;); if (512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, k) break e; } else r.head && (r.head.name = null); r.length = 0, r.mode = 8; case 8: if (4096 & r.flags) { if (0 === o) break e; for (d = 0; k = n[s + d++], r.head && k && r.length < 65536 && (r.head.comment += String.fromCharCode(k)), k && d < o;); if (512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, k) break e; } else r.head && (r.head.comment = null); r.mode = 9; case 9: if (512 & r.flags) { for (; l < 16;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (u !== (65535 & r.check)) { e.msg = "header crc mismatch", r.mode = 30; break; } l = u = 0; } r.head && (r.head.hcrc = r.flags >> 9 & 1, r.head.done = !0), e.adler = r.check = 0, r.mode = 12; break; case 10: for (; l < 32;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } e.adler = r.check = L(u), l = u = 0, r.mode = 11; case 11: if (0 === r.havedict) return e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, 2; e.adler = r.check = 1, r.mode = 12; case 12: if (5 === t || 6 === t) break e; case 13: if (r.last) { u >>>= 7 & l, l -= 7 & l, r.mode = 27; break; } for (; l < 3;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } switch (r.last = 1 & u, l -= 1, 3 & (u >>>= 1)) { case 0: r.mode = 14; break; case 1: if (j(r), r.mode = 20, 6 !== t) break; u >>>= 2, l -= 2; break e; case 2: r.mode = 17; break; case 3: e.msg = "invalid block type", r.mode = 30; } u >>>= 2, l -= 2; break; case 14: for (u >>>= 7 & l, l -= 7 & l; l < 32;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if ((65535 & u) != (u >>> 16 ^ 65535)) { e.msg = "invalid stored block lengths", r.mode = 30; break; } if (r.length = 65535 & u, l = u = 0, r.mode = 15, 6 === t) break e; case 15: r.mode = 16; case 16: if (d = r.length) { if (o < d && (d = o), h < d && (d = h), 0 === d) break e; I.arraySet(i, n, s, d, a), o -= d, s += d, h -= d, a += d, r.length -= d; break; } r.mode = 12; break; case 17: for (; l < 14;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (r.nlen = 257 + (31 & u), u >>>= 5, l -= 5, r.ndist = 1 + (31 & u), u >>>= 5, l -= 5, r.ncode = 4 + (15 & u), u >>>= 4, l -= 4, 286 < r.nlen || 30 < r.ndist) { e.msg = "too many length or distance symbols", r.mode = 30; break; } r.have = 0, r.mode = 18; case 18: for (; r.have < r.ncode;) { for (; l < 3;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } r.lens[A[r.have++]] = 7 & u, u >>>= 3, l -= 3; } for (; r.have < 19;) r.lens[A[r.have++]] = 0; if (r.lencode = r.lendyn, r.lenbits = 7, S = { bits: r.lenbits }, x = T(0, r.lens, 0, 19, r.lencode, 0, r.work, S), r.lenbits = S.bits, x) { e.msg = "invalid code lengths set", r.mode = 30; break; } r.have = 0, r.mode = 19; case 19: for (; r.have < r.nlen + r.ndist;) { for (; g = (C = r.lencode[u & (1 << r.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (b < 16) u >>>= _, l -= _, r.lens[r.have++] = b; else { if (16 === b) { for (z = _ + 2; l < z;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (u >>>= _, l -= _, 0 === r.have) { e.msg = "invalid bit length repeat", r.mode = 30; break; } k = r.lens[r.have - 1], d = 3 + (3 & u), u >>>= 2, l -= 2; } else if (17 === b) { for (z = _ + 3; l < z;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } l -= _, k = 0, d = 3 + (7 & (u >>>= _)), u >>>= 3, l -= 3; } else { for (z = _ + 7; l < z;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } l -= _, k = 0, d = 11 + (127 & (u >>>= _)), u >>>= 7, l -= 7; } if (r.have + d > r.nlen + r.ndist) { e.msg = "invalid bit length repeat", r.mode = 30; break; } for (; d--;) r.lens[r.have++] = k; } } if (30 === r.mode) break; if (0 === r.lens[256]) { e.msg = "invalid code -- missing end-of-block", r.mode = 30; break; } if (r.lenbits = 9, S = { bits: r.lenbits }, x = T(D, r.lens, 0, r.nlen, r.lencode, 0, r.work, S), r.lenbits = S.bits, x) { e.msg = "invalid literal/lengths set", r.mode = 30; break; } if (r.distbits = 6, r.distcode = r.distdyn, S = { bits: r.distbits }, x = T(F, r.lens, r.nlen, r.ndist, r.distcode, 0, r.work, S), r.distbits = S.bits, x) { e.msg = "invalid distances set", r.mode = 30; break; } if (r.mode = 20, 6 === t) break e; case 20: r.mode = 21; case 21: if (6 <= o && 258 <= h) { e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, R(e, c), a = e.next_out, i = e.output, h = e.avail_out, s = e.next_in, n = e.input, o = e.avail_in, u = r.hold, l = r.bits, 12 === r.mode && (r.back = -1); break; } for (r.back = 0; g = (C = r.lencode[u & (1 << r.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (g && 0 == (240 & g)) { for (v = _, y = g, w = b; g = (C = r.lencode[w + ((u & (1 << v + y) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l);) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } u >>>= v, l -= v, r.back += v; } if (u >>>= _, l -= _, r.back += _, r.length = b, 0 === g) { r.mode = 26; break; } if (32 & g) { r.back = -1, r.mode = 12; break; } if (64 & g) { e.msg = "invalid literal/length code", r.mode = 30; break; } r.extra = 15 & g, r.mode = 22; case 22: if (r.extra) { for (z = r.extra; l < z;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } r.length += u & (1 << r.extra) - 1, u >>>= r.extra, l -= r.extra, r.back += r.extra; } r.was = r.length, r.mode = 23; case 23: for (; g = (C = r.distcode[u & (1 << r.distbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (0 == (240 & g)) { for (v = _, y = g, w = b; g = (C = r.distcode[w + ((u & (1 << v + y) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l);) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } u >>>= v, l -= v, r.back += v; } if (u >>>= _, l -= _, r.back += _, 64 & g) { e.msg = "invalid distance code", r.mode = 30; break; } r.offset = b, r.extra = 15 & g, r.mode = 24; case 24: if (r.extra) { for (z = r.extra; l < z;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } r.offset += u & (1 << r.extra) - 1, u >>>= r.extra, l -= r.extra, r.back += r.extra; } if (r.offset > r.dmax) { e.msg = "invalid distance too far back", r.mode = 30; break; } r.mode = 25; case 25: if (0 === h) break e; if (d = c - h, r.offset > d) { if ((d = r.offset - d) > r.whave && r.sane) { e.msg = "invalid distance too far back", r.mode = 30; break; } p = d > r.wnext ? (d -= r.wnext, r.wsize - d) : r.wnext - d, d > r.length && (d = r.length), m = r.window; } else m = i, p = a - r.offset, d = r.length; for (h < d && (d = h), h -= d, r.length -= d; i[a++] = m[p++], --d;); 0 === r.length && (r.mode = 21); break; case 26: if (0 === h) break e; i[a++] = r.length, h--, r.mode = 21; break; case 27: if (r.wrap) { for (; l < 32;) { if (0 === o) break e; o--, u |= n[s++] << l, l += 8; } if (c -= h, e.total_out += c, r.total += c, c && (e.adler = r.check = r.flags ? B(r.check, i, c, a - c) : O(r.check, i, c, a - c)), c = h, (r.flags ? u : L(u)) !== r.check) { e.msg = "incorrect data check", r.mode = 30; break; } l = u = 0; } r.mode = 28; case 28: if (r.wrap && r.flags) { for (; l < 32;) { if (0 === o) break e; o--, u += n[s++] << l, l += 8; } if (u !== (4294967295 & r.total)) { e.msg = "incorrect length check", r.mode = 30; break; } l = u = 0; } r.mode = 29; case 29: x = 1; break e; case 30: x = -3; break e; case 31: return -4; case 32: default: return U; } return e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, (r.wsize || c !== e.avail_out && r.mode < 30 && (r.mode < 27 || 4 !== t)) && Z(e, e.output, e.next_out, c - e.avail_out) ? (r.mode = 31, -4) : (f -= e.avail_in, c -= e.avail_out, e.total_in += f, e.total_out += c, r.total += c, r.wrap && c && (e.adler = r.check = r.flags ? B(r.check, i, c, e.next_out - c) : O(r.check, i, c, e.next_out - c)), e.data_type = r.bits + (r.last ? 64 : 0) + (12 === r.mode ? 128 : 0) + (20 === r.mode || 15 === r.mode ? 256 : 0), (0 == f && 0 === c || 4 === t) && x === N && (x = -5), x); }, r.inflateEnd = function(e) { if (!e || !e.state) return U; var t = e.state; return t.window && (t.window = null), e.state = null, N; }, r.inflateGetHeader = function(e, t) { var r; return e && e.state ? 0 == (2 & (r = e.state).wrap) ? U : ((r.head = t).done = !1, N) : U; }, r.inflateSetDictionary = function(e, t) { var r, n = t.length; return e && e.state ? 0 !== (r = e.state).wrap && 11 !== r.mode ? U : 11 === r.mode && O(1, t, n, 0) !== r.check ? -3 : Z(e, t, n, n) ? (r.mode = 31, -4) : (r.havedict = 1, N) : U; }, r.inflateInfo = "pako inflate (from Nodeca project)"; }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./inffast": 48, "./inftrees": 50 }], 50: [function(e, t, r) { "use strict"; var D = e("../utils/common"), F = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ], N = [ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ], U = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ], P = [ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; t.exports = function(e, t, r, n, i, s, a, o) { var h, u, l, f, c, d, p, m, _, g = o.bits, b = 0, v = 0, y = 0, w = 0, k = 0, x = 0, S = 0, z = 0, C = 0, E = 0, A = null, I = 0, O = new D.Buf16(16), B = new D.Buf16(16), R = null, T = 0; for (b = 0; b <= 15; b++) O[b] = 0; for (v = 0; v < n; v++) O[t[r + v]]++; for (k = g, w = 15; 1 <= w && 0 === O[w]; w--); if (w < k && (k = w), 0 === w) return i[s++] = 20971520, i[s++] = 20971520, o.bits = 1, 0; for (y = 1; y < w && 0 === O[y]; y++); for (k < y && (k = y), b = z = 1; b <= 15; b++) if (z <<= 1, (z -= O[b]) < 0) return -1; if (0 < z && (0 === e || 1 !== w)) return -1; for (B[1] = 0, b = 1; b < 15; b++) B[b + 1] = B[b] + O[b]; for (v = 0; v < n; v++) 0 !== t[r + v] && (a[B[t[r + v]]++] = v); if (d = 0 === e ? (A = R = a, 19) : 1 === e ? (A = F, I -= 257, R = N, T -= 257, 256) : (A = U, R = P, -1), b = y, c = s, S = v = E = 0, l = -1, f = (C = 1 << (x = k)) - 1, 1 === e && 852 < C || 2 === e && 592 < C) return 1; for (;;) { for (p = b - S, _ = a[v] < d ? (m = 0, a[v]) : a[v] > d ? (m = R[T + a[v]], A[I + a[v]]) : (m = 96, 0), h = 1 << b - S, y = u = 1 << x; i[c + (E >> S) + (u -= h)] = p << 24 | m << 16 | _ | 0, 0 !== u;); for (h = 1 << b - 1; E & h;) h >>= 1; if (0 !== h ? (E &= h - 1, E += h) : E = 0, v++, 0 == --O[b]) { if (b === w) break; b = t[r + a[v]]; } if (k < b && (E & f) !== l) { for (0 === S && (S = k), c += y, z = 1 << (x = b - S); x + S < w && !((z -= O[x + S]) <= 0);) x++, z <<= 1; if (C += 1 << x, 1 === e && 852 < C || 2 === e && 592 < C) return 1; i[l = E & f] = k << 24 | x << 16 | c - s | 0; } } return 0 !== E && (i[c + E] = b - S << 24 | 4194304), o.bits = k, 0; }; }, { "../utils/common": 41 }], 51: [function(e, t, r) { "use strict"; t.exports = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" }; }, {}], 52: [function(e, t, r) { "use strict"; var i = e("../utils/common"), o = 0, h = 1; function n(e) { for (var t = e.length; 0 <= --t;) e[t] = 0; } var s = 0, a = 29, u = 256, l = u + 1 + a, f = 30, c = 19, _ = 2 * l + 1, g = 15, d = 16, p = 7, m = 256, b = 16, v = 17, y = 18, w = [ 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 ], k = [ 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 ], x = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 ], S = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ], z = new Array(2 * (l + 2)); n(z); var C = new Array(2 * f); n(C); var E = new Array(512); n(E); var A = new Array(256); n(A); var I = new Array(a); n(I); var O, B, R, T = new Array(f); function D(e, t, r, n, i) { this.static_tree = e, this.extra_bits = t, this.extra_base = r, this.elems = n, this.max_length = i, this.has_stree = e && e.length; } function F(e, t) { this.dyn_tree = e, this.max_code = 0, this.stat_desc = t; } function N(e) { return e < 256 ? E[e] : E[256 + (e >>> 7)]; } function U(e, t) { e.pending_buf[e.pending++] = 255 & t, e.pending_buf[e.pending++] = t >>> 8 & 255; } function P(e, t, r) { e.bi_valid > d - r ? (e.bi_buf |= t << e.bi_valid & 65535, U(e, e.bi_buf), e.bi_buf = t >> d - e.bi_valid, e.bi_valid += r - d) : (e.bi_buf |= t << e.bi_valid & 65535, e.bi_valid += r); } function L(e, t, r) { P(e, r[2 * t], r[2 * t + 1]); } function j(e, t) { for (var r = 0; r |= 1 & e, e >>>= 1, r <<= 1, 0 < --t;); return r >>> 1; } function Z(e, t, r) { var n, i, s = new Array(g + 1), a = 0; for (n = 1; n <= g; n++) s[n] = a = a + r[n - 1] << 1; for (i = 0; i <= t; i++) { var o = e[2 * i + 1]; 0 !== o && (e[2 * i] = j(s[o]++, o)); } } function W(e) { var t; for (t = 0; t < l; t++) e.dyn_ltree[2 * t] = 0; for (t = 0; t < f; t++) e.dyn_dtree[2 * t] = 0; for (t = 0; t < c; t++) e.bl_tree[2 * t] = 0; e.dyn_ltree[2 * m] = 1, e.opt_len = e.static_len = 0, e.last_lit = e.matches = 0; } function M(e) { 8 < e.bi_valid ? U(e, e.bi_buf) : 0 < e.bi_valid && (e.pending_buf[e.pending++] = e.bi_buf), e.bi_buf = 0, e.bi_valid = 0; } function H(e, t, r, n) { var i = 2 * t, s = 2 * r; return e[i] < e[s] || e[i] === e[s] && n[t] <= n[r]; } function G(e, t, r) { for (var n = e.heap[r], i = r << 1; i <= e.heap_len && (i < e.heap_len && H(t, e.heap[i + 1], e.heap[i], e.depth) && i++, !H(t, n, e.heap[i], e.depth));) e.heap[r] = e.heap[i], r = i, i <<= 1; e.heap[r] = n; } function K(e, t, r) { var n, i, s, a, o = 0; if (0 !== e.last_lit) for (; n = e.pending_buf[e.d_buf + 2 * o] << 8 | e.pending_buf[e.d_buf + 2 * o + 1], i = e.pending_buf[e.l_buf + o], o++, 0 === n ? L(e, i, t) : (L(e, (s = A[i]) + u + 1, t), 0 !== (a = w[s]) && P(e, i -= I[s], a), L(e, s = N(--n), r), 0 !== (a = k[s]) && P(e, n -= T[s], a)), o < e.last_lit;); L(e, m, t); } function Y(e, t) { var r, n, i, s = t.dyn_tree, a = t.stat_desc.static_tree, o = t.stat_desc.has_stree, h = t.stat_desc.elems, u = -1; for (e.heap_len = 0, e.heap_max = _, r = 0; r < h; r++) 0 !== s[2 * r] ? (e.heap[++e.heap_len] = u = r, e.depth[r] = 0) : s[2 * r + 1] = 0; for (; e.heap_len < 2;) s[2 * (i = e.heap[++e.heap_len] = u < 2 ? ++u : 0)] = 1, e.depth[i] = 0, e.opt_len--, o && (e.static_len -= a[2 * i + 1]); for (t.max_code = u, r = e.heap_len >> 1; 1 <= r; r--) G(e, s, r); for (i = h; r = e.heap[1], e.heap[1] = e.heap[e.heap_len--], G(e, s, 1), n = e.heap[1], e.heap[--e.heap_max] = r, e.heap[--e.heap_max] = n, s[2 * i] = s[2 * r] + s[2 * n], e.depth[i] = (e.depth[r] >= e.depth[n] ? e.depth[r] : e.depth[n]) + 1, s[2 * r + 1] = s[2 * n + 1] = i, e.heap[1] = i++, G(e, s, 1), 2 <= e.heap_len;); e.heap[--e.heap_max] = e.heap[1], function(e, t) { var r, n, i, s, a, o, h = t.dyn_tree, u = t.max_code, l = t.stat_desc.static_tree, f = t.stat_desc.has_stree, c = t.stat_desc.extra_bits, d = t.stat_desc.extra_base, p = t.stat_desc.max_length, m = 0; for (s = 0; s <= g; s++) e.bl_count[s] = 0; for (h[2 * e.heap[e.heap_max] + 1] = 0, r = e.heap_max + 1; r < _; r++) p < (s = h[2 * h[2 * (n = e.heap[r]) + 1] + 1] + 1) && (s = p, m++), h[2 * n + 1] = s, u < n || (e.bl_count[s]++, a = 0, d <= n && (a = c[n - d]), o = h[2 * n], e.opt_len += o * (s + a), f && (e.static_len += o * (l[2 * n + 1] + a))); if (0 !== m) { do { for (s = p - 1; 0 === e.bl_count[s];) s--; e.bl_count[s]--, e.bl_count[s + 1] += 2, e.bl_count[p]--, m -= 2; } while (0 < m); for (s = p; 0 !== s; s--) for (n = e.bl_count[s]; 0 !== n;) u < (i = e.heap[--r]) || (h[2 * i + 1] !== s && (e.opt_len += (s - h[2 * i + 1]) * h[2 * i], h[2 * i + 1] = s), n--); } }(e, t), Z(s, u, e.bl_count); } function X(e, t, r) { var n, i, s = -1, a = t[1], o = 0, h = 7, u = 4; for (0 === a && (h = 138, u = 3), t[2 * (r + 1) + 1] = 65535, n = 0; n <= r; n++) i = a, a = t[2 * (n + 1) + 1], ++o < h && i === a || (o < u ? e.bl_tree[2 * i] += o : 0 !== i ? (i !== s && e.bl_tree[2 * i]++, e.bl_tree[2 * b]++) : o <= 10 ? e.bl_tree[2 * v]++ : e.bl_tree[2 * y]++, s = i, u = (o = 0) === a ? (h = 138, 3) : i === a ? (h = 6, 3) : (h = 7, 4)); } function V(e, t, r) { var n, i, s = -1, a = t[1], o = 0, h = 7, u = 4; for (0 === a && (h = 138, u = 3), n = 0; n <= r; n++) if (i = a, a = t[2 * (n + 1) + 1], !(++o < h && i === a)) { if (o < u) for (; L(e, i, e.bl_tree), 0 != --o;); else 0 !== i ? (i !== s && (L(e, i, e.bl_tree), o--), L(e, b, e.bl_tree), P(e, o - 3, 2)) : o <= 10 ? (L(e, v, e.bl_tree), P(e, o - 3, 3)) : (L(e, y, e.bl_tree), P(e, o - 11, 7)); s = i, u = (o = 0) === a ? (h = 138, 3) : i === a ? (h = 6, 3) : (h = 7, 4); } } n(T); var q = !1; function J(e, t, r, n) { P(e, (s << 1) + (n ? 1 : 0), 3), function(e, t, r, n) { M(e), n && (U(e, r), U(e, ~r)), i.arraySet(e.pending_buf, e.window, t, r, e.pending), e.pending += r; }(e, t, r, !0); } r._tr_init = function(e) { q || (function() { var e, t, r, n, i, s = new Array(g + 1); for (n = r = 0; n < a - 1; n++) for (I[n] = r, e = 0; e < 1 << w[n]; e++) A[r++] = n; for (A[r - 1] = n, n = i = 0; n < 16; n++) for (T[n] = i, e = 0; e < 1 << k[n]; e++) E[i++] = n; for (i >>= 7; n < f; n++) for (T[n] = i << 7, e = 0; e < 1 << k[n] - 7; e++) E[256 + i++] = n; for (t = 0; t <= g; t++) s[t] = 0; for (e = 0; e <= 143;) z[2 * e + 1] = 8, e++, s[8]++; for (; e <= 255;) z[2 * e + 1] = 9, e++, s[9]++; for (; e <= 279;) z[2 * e + 1] = 7, e++, s[7]++; for (; e <= 287;) z[2 * e + 1] = 8, e++, s[8]++; for (Z(z, l + 1, s), e = 0; e < f; e++) C[2 * e + 1] = 5, C[2 * e] = j(e, 5); O = new D(z, w, u + 1, l, g), B = new D(C, k, 0, f, g), R = new D(new Array(0), x, 0, c, p); }(), q = !0), e.l_desc = new F(e.dyn_ltree, O), e.d_desc = new F(e.dyn_dtree, B), e.bl_desc = new F(e.bl_tree, R), e.bi_buf = 0, e.bi_valid = 0, W(e); }, r._tr_stored_block = J, r._tr_flush_block = function(e, t, r, n) { var i, s, a = 0; 0 < e.level ? (2 === e.strm.data_type && (e.strm.data_type = function(e) { var t, r = 4093624447; for (t = 0; t <= 31; t++, r >>>= 1) if (1 & r && 0 !== e.dyn_ltree[2 * t]) return o; if (0 !== e.dyn_ltree[18] || 0 !== e.dyn_ltree[20] || 0 !== e.dyn_ltree[26]) return h; for (t = 32; t < u; t++) if (0 !== e.dyn_ltree[2 * t]) return h; return o; }(e)), Y(e, e.l_desc), Y(e, e.d_desc), a = function(e) { var t; for (X(e, e.dyn_ltree, e.l_desc.max_code), X(e, e.dyn_dtree, e.d_desc.max_code), Y(e, e.bl_desc), t = c - 1; 3 <= t && 0 === e.bl_tree[2 * S[t] + 1]; t--); return e.opt_len += 3 * (t + 1) + 5 + 5 + 4, t; }(e), i = e.opt_len + 3 + 7 >>> 3, (s = e.static_len + 3 + 7 >>> 3) <= i && (i = s)) : i = s = r + 5, r + 4 <= i && -1 !== t ? J(e, t, r, n) : 4 === e.strategy || s === i ? (P(e, 2 + (n ? 1 : 0), 3), K(e, z, C)) : (P(e, 4 + (n ? 1 : 0), 3), function(e, t, r, n) { var i; for (P(e, t - 257, 5), P(e, r - 1, 5), P(e, n - 4, 4), i = 0; i < n; i++) P(e, e.bl_tree[2 * S[i] + 1], 3); V(e, e.dyn_ltree, t - 1), V(e, e.dyn_dtree, r - 1); }(e, e.l_desc.max_code + 1, e.d_desc.max_code + 1, a + 1), K(e, e.dyn_ltree, e.dyn_dtree)), W(e), n && M(e); }, r._tr_tally = function(e, t, r) { return e.pending_buf[e.d_buf + 2 * e.last_lit] = t >>> 8 & 255, e.pending_buf[e.d_buf + 2 * e.last_lit + 1] = 255 & t, e.pending_buf[e.l_buf + e.last_lit] = 255 & r, e.last_lit++, 0 === t ? e.dyn_ltree[2 * r]++ : (e.matches++, t--, e.dyn_ltree[2 * (A[r] + u + 1)]++, e.dyn_dtree[2 * N(t)]++), e.last_lit === e.lit_bufsize - 1; }, r._tr_align = function(e) { P(e, 2, 3), L(e, m, z), function(e) { 16 === e.bi_valid ? (U(e, e.bi_buf), e.bi_buf = 0, e.bi_valid = 0) : 8 <= e.bi_valid && (e.pending_buf[e.pending++] = 255 & e.bi_buf, e.bi_buf >>= 8, e.bi_valid -= 8); }(e); }; }, { "../utils/common": 41 }], 53: [function(e, t, r) { "use strict"; t.exports = function() { this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0; }; }, {}], 54: [function(e, t, r) { (function(e) { (function(r, n) { "use strict"; if (!r.setImmediate) { var i, s, t, a, o = 1, h = {}, u = !1, l = r.document, e = Object.getPrototypeOf && Object.getPrototypeOf(r); e = e && e.setTimeout ? e : r, i = "[object process]" === {}.toString.call(r.process) ? function(e) { process.nextTick(function() { c(e); }); } : function() { if (r.postMessage && !r.importScripts) { var e = !0, t = r.onmessage; return r.onmessage = function() { e = !1; }, r.postMessage("", "*"), r.onmessage = t, e; } }() ? (a = "setImmediate$" + Math.random() + "$", r.addEventListener ? r.addEventListener("message", d, !1) : r.attachEvent("onmessage", d), function(e) { r.postMessage(a + e, "*"); }) : r.MessageChannel ? ((t = new MessageChannel()).port1.onmessage = function(e) { c(e.data); }, function(e) { t.port2.postMessage(e); }) : l && "onreadystatechange" in l.createElement("script") ? (s = l.documentElement, function(e) { var t = l.createElement("script"); t.onreadystatechange = function() { c(e), t.onreadystatechange = null, s.removeChild(t), t = null; }, s.appendChild(t); }) : function(e) { setTimeout(c, 0, e); }, e.setImmediate = function(e) { "function" != typeof e && (e = new Function("" + e)); for (var t = new Array(arguments.length - 1), r = 0; r < t.length; r++) t[r] = arguments[r + 1]; return h[o] = { callback: e, args: t }, i(o), o++; }, e.clearImmediate = f; } function f(e) { delete h[e]; } function c(e) { if (u) setTimeout(c, 0, e); else { var t = h[e]; if (t) { u = !0; try { (function(e) { var t = e.callback, r = e.args; switch (r.length) { case 0: t(); break; case 1: t(r[0]); break; case 2: t(r[0], r[1]); break; case 3: t(r[0], r[1], r[2]); break; default: t.apply(n, r); } })(t); } finally { f(e), u = !1; } } } } function d(e) { e.source === r && "string" == typeof e.data && 0 === e.data.indexOf(a) && c(+e.data.slice(a.length)); } })("undefined" == typeof self ? void 0 === e ? this : e : self); }).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); }, {}] }, {}, [10])(10); }); })))(), 1); /** * Generates a SHA-256 hash from a file blob. * * @param {Blob} fileBlob - The file blob to hash * @returns {Promise} - Returns a Promise that resolves to the hexadecimal hash string */ async function generateFileHash(fileBlob) { return sha256Hex(await fileBlob.arrayBuffer()); } /** * Hex-encodes the SHA-256 digest of an already-in-memory buffer. */ async function sha256Hex(buffer) { const hashBuffer = await crypto.subtle.digest("SHA-256", buffer); return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join(""); } async function canUserUpload(currentUploadSize) { const { active, limit } = await trpc.getTotalUsedStorage.query(); return active + currentUploadSize >= limit; } /** * Returns a promise that resolves after an amount of time has passed. * * @param { number } delayMs - number of milliseconds that must pass before the promise resolves */ function delay$1(delayMs = 100) { return new Promise((resolve) => setTimeout(resolve, delayMs)); } /** * Runs a function at an interval until it succeeds or the maximum wait time is reached. * * @param {function(): any} fn - The function to retry. Function can be `async`. * @param {number} waitTimeMs - How long to wait between each retry. * @param {number} maxWaitTimeMs - The maximum amount of time to retry until we give up. */ async function retryUntilSuccessOrTimeout(fn, waitTimeMs = 1e3, maxWaitTimeMs = 6e4) { for (let waitTotalMs = 0; waitTotalMs < maxWaitTimeMs; waitTotalMs += waitTimeMs) { await delay$1(waitTimeMs); try { if (!!await fn()) return; } catch (e) { console.error(`Error on waiting for the file to show up in storage: ${e}`); } } } async function streamToArrayBuffer(stream, size) { const reader = stream.getReader(); let state = await reader.read(); if (size) { const result = new Uint8Array(size); let offset = 0; while (!state.done) { result.set(state.value, offset); offset += state.value.length; state = await reader.read(); } return result.buffer; } const parts = []; let len = 0; while (!state.done) { parts.push(state.value); len += state.value.length; state = await reader.read(); } let offset = 0; const result = new Uint8Array(len); for (const part of parts) { result.set(part, offset); offset += part.length; } return result.buffer; } var ConnectionError = class extends Error { constructor(canceled, duration, size) { super(canceled ? "0" : "connection closed"); this.canceled = canceled; this.duration = duration; this.size = size; } }; function asyncInitWebSocket(serverUrl) { return new Promise((resolve, reject) => { try { const ws = new WebSocket(serverUrl); ws.addEventListener("open", () => resolve(ws), { once: true }); } catch (e) { reject(new ConnectionError(false)); } }); } async function listenForResponse(ws, canceler) { return new Promise((resolve, reject) => { function handleClose() { ws.removeEventListener("message", handleMessage); reject(new ConnectionError(canceler.canceled)); } function handleMessage(msg) { ws.removeEventListener("close", handleClose); try { const response = JSON.parse(msg.data); if (response.error) throw new Error(response.error); else resolve(response); } catch (e) { reject(e); } } ws.addEventListener("message", handleMessage, { once: true }); ws.addEventListener("close", handleClose, { once: true }); }); } function formatBytes(bytes, decimals = 2) { if (bytes == 0) return "0 Bytes"; const k = 1024, dm = decimals, sizes = [ "Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" ], i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i]; } /** * Zips `blob` under `filename` and returns the archive as a Blob. * * Why this is not just `zip.generateAsync({ type: 'blob' })`: * JSZip's one-shot blob output builds the entire archive as a single * `Uint8Array` and then calls `new Blob([thatArray])`. Firefox rejects any * single ArrayBuffer/ArrayBufferView Blob member larger than 2 GB with * "can't construct the Blob ... larger than 2 GB" — so zipping a file bigger * than ~2 GB (e.g. a typeless file wrapped by {@link formatBlob}) throws before * a single byte is uploaded (#981). Note this is a hard per-member limit, not an * out-of-memory condition: the same Firefox happily allocates a 6 GiB * ArrayBuffer, but refuses a >2 GB Blob member. * * Instead we consume JSZip's streaming output and hand the (individually * sub-2 GB) chunks to the Blob constructor as separate members. A Blob's *total* * size may exceed 2 GB as long as no single member does, so the archive can be * arbitrarily large. * * Backwards compatibility: `generateAsync` is itself implemented on top of this * same internal stream with the same default settings (STORE, no compression), * so the archive bytes are identical to the previous implementation. Files * zipped before and after this change are byte-for-byte interchangeable and the * download/unzip path is unaffected — this only changes how the output Blob is * assembled in memory, not its contents. */ async function zipBlob(blob, filename) { const zip = new import_jszip_min.default(); zip.file(filename, blob); const chunks = []; await new Promise((resolve, reject) => { zip.generateInternalStream({ type: "uint8array" }).on("data", (chunk) => chunks.push(chunk)).on("error", reject).on("end", () => resolve()).resume(); }); return new Blob(chunks, { type: "application/zip" }); } async function unzipMultipartPiece(arrayBuffer) { try { const zip = new import_jszip_min.default(); const buffer = arrayBuffer instanceof ArrayBuffer ? arrayBuffer : new ArrayBuffer(arrayBuffer.byteLength); if (!(arrayBuffer instanceof ArrayBuffer)) new Uint8Array(buffer).set(new Uint8Array(arrayBuffer)); const zipData = await zip.loadAsync(buffer); const fileNames = Object.keys(zipData.files); if (fileNames.length === 0) throw new Error("No files found in zip archive"); const targetFileName = fileNames[0]; const isMultipart = false; const file = zipData.files[targetFileName]; if (file.dir) throw new Error("Expected file but found directory in zip archive"); return { content: await file.async("arraybuffer"), isMultipart, partNumber: void 0 }; } catch (error) { console.error("Error unzipping multipart content:", error); const buffer = arrayBuffer instanceof ArrayBuffer ? arrayBuffer : new ArrayBuffer(arrayBuffer.byteLength); if (!(arrayBuffer instanceof ArrayBuffer)) new Uint8Array(buffer).set(new Uint8Array(arrayBuffer)); return { content: buffer, isMultipart: false }; } } var formatBlob = async (blob) => { if (blob.type === "") { const zippedBlob = await zipBlob(blob, blob.name); const compressedBlob = new Blob([zippedBlob], { type: "application/zip" }); compressedBlob.name = `${blob.name}.zip`; return compressedBlob; } return blob; }; /** * Checks a precomputed file hash against the suspicious-files list and blocks * the upload (alert + throw) if it matches. */ var assertNotSuspicious = async (api, fileHash) => { const { isSuspicious } = await api.call(`uploads/check-upload-hash/${fileHash}`); if (isSuspicious) { alert("Warning: This file has been reported as suspicious. You cannot upload it. If you believe this is an error, please contact support."); throw new Error("Suspicious file detected"); } }; var hashAndCheck = async (api, fileBlob) => { const fileHash = await generateFileHash(fileBlob); console.log("File hash (SHA-256):", fileHash); await assertNotSuspicious(api, fileHash); return fileHash; }; var hashFiles = async (api, fileBlob, maxSize, onProgress) => { const hashFromChunk = []; if (fileBlob.size <= maxSize) { const hashedBlob = await hashAndCheck(api, fileBlob); onProgress?.(1, 1); return [hashedBlob]; } const totalSize = fileBlob.size; const numChunks = Math.ceil(totalSize / maxSize); for (let i = 0; i < numChunks; i++) { const start = i * maxSize; const end = Math.min(start + maxSize, totalSize); const chunk = fileBlob.slice(start, end); const chunkBlob = new Blob([chunk], { type: fileBlob.type }); chunkBlob.name = `${fileBlob.name}`; const zippedChunk = await hashAndCheck(api, chunkBlob); hashFromChunk.push(zippedChunk); onProgress?.(i + 1, numChunks); } return hashFromChunk; }; /** * Streams a large file into upload-ready parts, one `maxSize` window at a time. * * Crucially, it reads the file **sequentially from offset 0 via * `fileBlob.stream()`** and never calls `.slice()`/`.arrayBuffer()` at a high * byte offset. The previous approach (hashFiles + splitIntoMultipleZips) sliced * the file at offsets past ~2 GiB, which Firefox rejects with a NotReadableError * / "can't construct the Blob" on files larger than ~2 GB (#981). Reading via a * ReadableStream keeps each in-memory buffer bounded to one window and avoids * the 2^31 offset boundary entirely. * * Parts are yielded **in order as they become ready**, so a caller can begin * uploading window 0 while later windows are still being read/hashed/zipped * (#980). * * For each window it hashes the raw bytes, runs the suspicious-file check, then * zips the window — producing the exact same wire format as * splitIntoMultipleZips (a zip of the raw chunk, named after the original file). */ async function* streamZippedParts(api, fileBlob, maxSize, onBytesHashed) { const reader = fileBlob.stream().getReader(); let windowChunks = []; let windowSize = 0; let totalHashed = 0; const flushWindow = async () => { const windowBytes = new Uint8Array(windowSize); let offset = 0; for (const piece of windowChunks) { windowBytes.set(piece, offset); offset += piece.byteLength; } windowChunks = []; windowSize = 0; const hash = await sha256Hex(windowBytes.buffer); await assertNotSuspicious(api, hash); const rawBlob = new Blob([windowBytes], { type: fileBlob.type }); rawBlob.name = fileBlob.name; const zipped = await zipBlob(rawBlob, fileBlob.name); const zippedBlob = new Blob([zipped], { type: "application/zip" }); zippedBlob.name = fileBlob.name; return { blob: zippedBlob, hash }; }; try { while (true) { const { done, value } = await reader.read(); if (done) break; let chunk = value; while (windowSize + chunk.byteLength >= maxSize) { const take = maxSize - windowSize; windowChunks.push(chunk.subarray(0, take)); windowSize += take; totalHashed += take; onBytesHashed?.(totalHashed); yield await flushWindow(); chunk = chunk.subarray(take); } if (chunk.byteLength > 0) { windowChunks.push(chunk); windowSize += chunk.byteLength; } } if (windowSize > 0) { totalHashed += windowSize; onBytesHashed?.(totalHashed); yield await flushWindow(); } } finally { reader.releaseLock(); } } var checkBlobSize = async (blob) => { console.log(blob); if (blob.size > 2e10) { console.warn("File too big"); return false; } return true; }; function getExpirationDate(selectedExpiration, customDateTime) { const now = /* @__PURE__ */ new Date(); switch (selectedExpiration) { case "never": return; case "24hours": now.setHours(now.getHours() + 24); return now.toISOString(); case "14days": now.setDate(now.getDate() + 14); return now.toISOString(); case "30days": now.setDate(now.getDate() + 30); return now.toISOString(); case "custom": if (!customDateTime) return void 0; try { return new Date(customDateTime).toISOString(); } catch (error) { console.error("Failed to parse custom date/time:", error); return; } default: return; } } //#endregion //#region ../send/frontend/src/lib/helpers.ts async function _download({ url, progressTracker, id }) { const endpoint = `https://send-backend.tb.pro/api/download`; const xhr = new XMLHttpRequest(); const { setProgress } = progressTracker; xhr.onprogress = (event) => { if (event.lengthComputable) { const downloadProgress = event.loaded; setProgress(downloadProgress); } }; return new Promise((resolve, reject) => { xhr.addEventListener("loadend", async function() { if (xhr.status !== 200) return reject(/* @__PURE__ */ new Error(`${xhr.status}`)); resolve(new Blob([xhr.response])); }); xhr.open("get", id ? `${endpoint}/${id}` : url); xhr.responseType = "blob"; xhr.send(); }); } async function _upload(stream, key, encryptedSize = -1, { canceler = {}, progressTracker }) { let host = "https://send-backend.tb.pro"; if (host) host = host.split("//")[1]; else throw new Error("no server url is set"); const ws = await asyncInitWebSocket(`wss://${host}/api/ws`); try { const fileMeta = { name: "filename", size: encryptedSize }; listenForResponse(ws, canceler); ws.send(JSON.stringify(fileMeta)); let size = 0; const completedResponse = listenForResponse(ws, canceler); if (key) stream = encryptStream(stream, key); const reader = stream.getReader(); let state = await reader.read(); while (!state.done) { if (canceler.cancelled) ws.close(); if (ws.readyState !== WebSocket.OPEN) break; const buf = state.value; ws.send(buf); size += buf.length; console.info("Uploaded", size, "bytes", "- timestamp:", Date.now()); progressTracker.setProgress(size); state = await reader.read(); while (ws.bufferedAmount > 65536 * 2 && ws.readyState === WebSocket.OPEN && !canceler.cancelled) await delay$1(); } if (ws.readyState === WebSocket.OPEN) ws.send(new Uint8Array([0])); return await completedResponse; } catch (e) { console.error(e); throw e; } finally { if (ws.readyState !== WebSocket.CLOSED && ws.readyState !== WebSocket.CLOSING) ws.close(); } } async function encrypt(stream, key) { try { let size = 0; const chunks = []; if (key) stream = encryptStream(stream, key); const reader = stream.getReader(); let state = await reader.read(); while (!state.done) { const buf = state.value; chunks.push(buf); size += buf.length; console.info("Encrypted", size, "bytes", "- timestamp:", Date.now()); state = await reader.read(); } return concatenateUint8Arrays(chunks); } catch (e) { console.error(e); } } function concatenateUint8Arrays(arrays) { const totalLength = arrays.reduce((acc, value) => acc + value.length, 0); const result = new Uint8Array(totalLength); let length = 0; for (const array of arrays) { result.set(array, length); length += array.length; } return result; } /** * Calculates the size of a file after encrypting. * * @param originalSize: number - the original file size. * @param recordSize: number - the size of each chunk of data that gets encrypted. * @returns number - the total size of the file after encryption. */ function calculateEncryptedSize(originalSize, recordSize = ECE_RECORD_SIZE) { const chunkSize = recordSize - 17; return originalSize + Math.ceil(originalSize / chunkSize) * 17 + 21; } var UPLOAD_ABORTED = "UPLOAD_ABORTED"; var UPLOAD_HTTP_RETRY_BASE_DELAY_MS = 1e3; /** * Exponential backoff with jitter for the upload PUT retry schedule: * delay = base * 2^attempt * (0.5 + Math.random() / 2) * The jitter factor is in [0.5, 1.0), so with the default 1000ms base the * per-attempt delays grow roughly ~1s, ~2s, ~4s while staying de-synchronized * across clients (avoids a thundering herd when B2 recovers). * * @param attempt - zero-based index of the attempt that just failed * @param baseDelayMs - base delay; defaults to UPLOAD_HTTP_RETRY_BASE_DELAY_MS */ function getUploadRetryDelayMs(attempt, baseDelayMs = UPLOAD_HTTP_RETRY_BASE_DELAY_MS) { const exponential = baseDelayMs * 2 ** attempt; const jitter = .5 + Math.random() / 2; return Math.floor(exponential * jitter); } var uploadWithTracker = ({ url, readableStream, progressTracker, signal }) => { const { setProgress } = progressTracker; const XHR_TIMEOUT_MS = 18e4; const attemptPut = (blob, attempt) => { if (signal?.aborted) return Promise.reject(/* @__PURE__ */ new Error(UPLOAD_ABORTED)); if (attempt > 0) setProgress(0); return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("PUT", url, true); xhr.setRequestHeader("Content-Type", "application/octet-stream"); xhr.timeout = XHR_TIMEOUT_MS; const onAbort = () => xhr.abort(); signal?.addEventListener("abort", onAbort, { once: true }); const cleanup = () => signal?.removeEventListener("abort", onAbort); xhr.upload.onprogress = (event) => { if (event.lengthComputable) { const uploadProgress = event.loaded; setProgress(uploadProgress); } }; xhr.onload = () => { cleanup(); if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response); else { console.error("Upload failed:"); reject(/* @__PURE__ */ new Error("UPLOAD_FAILED")); } }; xhr.onabort = () => { cleanup(); reject(/* @__PURE__ */ new Error(UPLOAD_ABORTED)); }; xhr.onerror = () => { cleanup(); reject(/* @__PURE__ */ new Error("XHR: UPLOAD_FAILED")); }; xhr.ontimeout = () => { cleanup(); reject(/* @__PURE__ */ new Error(`Upload timed out after ${XHR_TIMEOUT_MS / 1e3}s`)); }; xhr.send(blob); }).catch((error) => { if (!(signal?.aborted || error?.message === "UPLOAD_ABORTED") && attempt < 3) { const delayMs = getUploadRetryDelayMs(attempt); console.warn(`HTTP PUT attempt ${attempt + 1} failed, retrying in ${delayMs}ms...`, error.message); return new Promise((resolve) => setTimeout(resolve, delayMs)).then(() => attemptPut(blob, attempt + 1)); } throw error; }); }; return new Response(readableStream).blob().then((uploadBlob) => { return attemptPut(uploadBlob, 0); }); }; //#endregion //#region ../send/frontend/src/lib/filesync.ts async function _saveFile(file) { return new Promise(function(resolve) { const dataView = new DataView(file.plaintext); const blob = new Blob([dataView], { type: file.type }); const downloadUrl = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = downloadUrl; a.download = file.name; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(downloadUrl); resolve(); }, 0); }); } async function getBlob(id, size, key, isBucketStorage = true, filename = "dummy.file", type = "text/plain", api, progressTracker) { const { isSuspicious } = await api.call(`download/check-upload-id/${id}`); if (isSuspicious) throw new Error("File has been reported as suspicious"); if (!isBucketStorage) { const downloadedBlob = await _download({ id, progressTracker }); let plaintext; if (key) plaintext = await streamToArrayBuffer(decryptStream(blobStream(downloadedBlob), key), size); else plaintext = await downloadedBlob.arrayBuffer(); return await _saveFile({ plaintext, name: decodeURIComponent(filename), type }); } try { const bucketResponse = await api.call(`download/${id}/signed`); if (!bucketResponse?.url) throw new Error("BUCKET_URL_NOT_FOUND"); progressTracker.setUploadSize(size); progressTracker.setText("Downloading file"); const downloadedBlob = await _download({ url: bucketResponse.url, progressTracker }); let plaintext; if (key) plaintext = await streamToArrayBuffer(decryptStream(blobStream(downloadedBlob), key), size); else plaintext = await downloadedBlob.arrayBuffer(); return await _saveFile({ plaintext, name: decodeURIComponent(filename), type }); } catch (error) { console.error("DOWNLOAD_FAILED", error); throw error; } } async function sendBlob(blob, aesKey, api, progressTracker, isBucketStorage = true, options = {}) { const { signal, onUploadId } = options; const stream = blobStream(blob); if (!isBucketStorage) { const result = await _upload(stream, aesKey, calculateEncryptedSize(blob.size), { progressTracker }); const id = Array.isArray(result) ? result[0].id : result.id; onUploadId?.(id); return id; } try { const { id, url } = await api.call("uploads/signed", { type: "application/octet-stream" }, "POST"); onUploadId?.(id); progressTracker.setProcessStage("encrypting"); progressTracker.setText("Encrypting file"); const encrypted = await encrypt(stream, aesKey); progressTracker.setProcessStage("uploading"); progressTracker.setText("Uploading file"); await uploadWithTracker({ url, readableStream: new ReadableStream({ start(controller) { controller.enqueue(encrypted); controller.close(); } }), progressTracker, signal }); return id; } catch (error) { throw new Error("UPLOAD_FAILED", { cause: error }); } } async function _saveFileStream(file) { if ("showSaveFilePicker" in window) try { const writable = await (await window.showSaveFilePicker({ suggestedName: file.name, types: [{ description: file.type, accept: { [file.type]: [] } }] })).createWritable(); const reader = file.stream.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; await writable.write(value); } await writable.close(); return; } catch (error) { console.warn("File System Access API failed, falling back to blob approach:", error); } const blob = await new Response(file.stream).blob(); const typedBlob = new Blob([blob], { type: file.type }); return new Promise(function(resolve) { const downloadUrl = URL.createObjectURL(typedBlob); const a = document.createElement("a"); a.href = downloadUrl; a.download = file.name; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(downloadUrl); resolve(); }, 0); }); } //#endregion //#region ../send/frontend/src/lib/download.ts var Downloader = class { constructor(keychain, api) { this.keychain = keychain; this.api = api; } async doDownload(id, folderId, wrappedKeyStr, filename, metrics, progressTracker) { if (!id) return false; if (!folderId) return false; const { isSuspicious } = await this.api.call(`download/check-upload-id/${id}`); if (isSuspicious) throw new Error("File has been reported as suspicious"); const wrappingKey = await this.keychain.get(folderId); if (!wrappingKey) return false; const { size, type } = await this.api.call(`uploads/${id}/metadata`); if (!size) return false; const contentKey = await this.keychain.container.unwrapContentKey(wrappedKeyStr, wrappingKey); const isBucketStorage = this.api.isBucketStorage; try { progressTracker.setFileName(filename); progressTracker.setProcessStage("downloading"); await getBlob(id, size, contentKey, isBucketStorage, filename, type, this.api, progressTracker); metrics.capture("download.size", { size, type }); return true; } catch (e) { return false; } } }; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/debug-build.js /** * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ var DEBUG_BUILD$4 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/version.js var SDK_VERSION = "8.55.2"; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/worldwide.js /** Get's the global object for the current JavaScript runtime */ var GLOBAL_OBJ = globalThis; /** * Returns a global singleton contained in the global `__SENTRY__[]` object. * * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory * function and added to the `__SENTRY__` object. * * @param name name of the global singleton on __SENTRY__ * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value * @returns the singleton */ function getGlobalSingleton(name, creator, obj) { const gbl = obj || GLOBAL_OBJ; const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {}; const versionedCarrier = __SENTRY__[SDK_VERSION] = __SENTRY__["8.55.2"] || {}; return versionedCarrier[name] || (versionedCarrier[name] = creator()); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/debug-build.js /** * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ var DEBUG_BUILD$3 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/logger.js /** Prefix for logging strings */ var PREFIX = "Sentry Logger "; var CONSOLE_LEVELS = [ "debug", "info", "warn", "error", "log", "assert", "trace" ]; /** This may be mutated by the console instrumentation. */ var originalConsoleMethods = {}; /** JSDoc */ /** * Temporarily disable sentry console instrumentations. * * @param callback The function to run against the original `console` messages * @returns The results of the callback */ function consoleSandbox(callback) { if (!("console" in GLOBAL_OBJ)) return callback(); const console = GLOBAL_OBJ.console; const wrappedFuncs = {}; const wrappedLevels = Object.keys(originalConsoleMethods); wrappedLevels.forEach((level) => { const originalConsoleMethod = originalConsoleMethods[level]; wrappedFuncs[level] = console[level]; console[level] = originalConsoleMethod; }); try { return callback(); } finally { wrappedLevels.forEach((level) => { console[level] = wrappedFuncs[level]; }); } } function makeLogger() { let enabled = false; const logger = { enable: () => { enabled = true; }, disable: () => { enabled = false; }, isEnabled: () => enabled }; if (DEBUG_BUILD$3) CONSOLE_LEVELS.forEach((name) => { logger[name] = (...args) => { if (enabled) consoleSandbox(() => { GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); }); }; }); else CONSOLE_LEVELS.forEach((name) => { logger[name] = () => void 0; }); return logger; } /** * This is a logger singleton which either logs things or no-ops if logging is not enabled. * The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK. */ var logger$1 = getGlobalSingleton("logger", makeLogger); //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/stacktrace.js var STACKTRACE_FRAME_LIMIT = 50; var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/; var STRIP_FRAME_REGEXP = /captureMessage|captureException/; /** * Creates a stack parser with the supplied line parsers * * StackFrames are returned in the correct order for Sentry Exception * frames and with Sentry SDK internal frames removed from the top and bottom * */ function createStackParser(...parsers) { const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map((p) => p[1]); return (stack, skipFirstLines = 0, framesToPop = 0) => { const frames = []; const lines = stack.split("\n"); for (let i = skipFirstLines; i < lines.length; i++) { const line = lines[i]; 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)); }; } /** * Gets a stack parser implementation from Options.stackParser * @see Options * * If options contains an array of line parsers, it is converted into a parser */ function stackParserFromStackParserOptions(stackParser) { if (Array.isArray(stackParser)) return createStackParser(...stackParser); return stackParser; } /** * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames. * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the * function that caused the crash is the last frame in the array. * @hidden */ function stripSentryFramesAndReverse(stack) { if (!stack.length) return []; const localStack = Array.from(stack); 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 || "?" })); } function getLastStackFrame(arr) { return arr[arr.length - 1] || {}; } var defaultFunctionName = ""; /** * Safely extract function name from itself */ function getFunctionName(fn) { try { if (!fn || typeof fn !== "function") return defaultFunctionName; return fn.name || defaultFunctionName; } catch (e) { return defaultFunctionName; } } /** * Get's stack frames from an event without needing to check for undefined properties. */ function getFramesFromEvent(event) { const exception = event.exception; if (exception) { const frames = []; try { exception.values.forEach((value) => { if (value.stacktrace.frames) frames.push(...value.stacktrace.frames); }); return frames; } catch (_oO) { return; } } } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/instrument/handlers.js var handlers$1 = {}; var instrumented$1 = {}; /** Add a handler function. */ function addHandler$1(type, handler) { handlers$1[type] = handlers$1[type] || []; handlers$1[type].push(handler); } /** Maybe run an instrumentation function, unless it was already called. */ function maybeInstrument(type, instrumentFn) { if (!instrumented$1[type]) { instrumented$1[type] = true; try { instrumentFn(); } catch (e) { DEBUG_BUILD$3 && logger$1.error(`Error while instrumenting ${type}`, e); } } } /** Trigger handlers for a given instrumentation type. */ function triggerHandlers$1(type, data) { const typeHandlers = type && handlers$1[type]; if (!typeHandlers) return; for (const handler of typeHandlers) try { handler(data); } catch (e) { DEBUG_BUILD$3 && logger$1.error(`Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`, e); } } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalError.js var _oldOnErrorHandler = null; /** * Add an instrumentation handler for when an error is captured by the global error handler. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addGlobalErrorInstrumentationHandler(handler) { const type = "error"; addHandler$1(type, handler); maybeInstrument(type, instrumentError); } function instrumentError() { _oldOnErrorHandler = GLOBAL_OBJ.onerror; GLOBAL_OBJ.onerror = function(msg, url, line, column, error) { triggerHandlers$1("error", { column, error, line, msg, url }); if (_oldOnErrorHandler) return _oldOnErrorHandler.apply(this, arguments); return false; }; GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalUnhandledRejection.js var _oldOnUnhandledRejectionHandler = null; /** * Add an instrumentation handler for when an unhandled promise rejection is captured. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addGlobalUnhandledRejectionInstrumentationHandler(handler) { const type = "unhandledrejection"; addHandler$1(type, handler); maybeInstrument(type, instrumentUnhandledRejection); } function instrumentUnhandledRejection() { _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; GLOBAL_OBJ.onunhandledrejection = function(e) { triggerHandlers$1("unhandledrejection", e); if (_oldOnUnhandledRejectionHandler) return _oldOnUnhandledRejectionHandler.apply(this, arguments); return true; }; GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/carrier.js /** * An object that contains globally accessible properties and maintains a scope stack. * @hidden */ /** * Returns the global shim registry. * * FIXME: This function is problematic, because despite always returning a valid Carrier, * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. **/ function getMainCarrier() { getSentryCarrier(GLOBAL_OBJ); return GLOBAL_OBJ; } /** Will either get the existing sentry carrier, or create a new one. */ function getSentryCarrier(carrier) { const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {}; __SENTRY__.version = __SENTRY__.version || "8.55.2"; return __SENTRY__[SDK_VERSION] = __SENTRY__["8.55.2"] || {}; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/is.js var objectToString = Object.prototype.toString; /** * Checks whether given value's type is one of a few Error or Error-like * {@link isError}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isError(wat) { switch (objectToString.call(wat)) { case "[object Error]": case "[object Exception]": case "[object DOMException]": case "[object WebAssembly.Exception]": return true; default: return isInstanceOf(wat, Error); } } /** * Checks whether given value is an instance of the given built-in class. * * @param wat The value to be checked * @param className * @returns A boolean representing the result. */ function isBuiltin(wat, className) { return objectToString.call(wat) === `[object ${className}]`; } /** * Checks whether given value's type is ErrorEvent * {@link isErrorEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isErrorEvent$1(wat) { return isBuiltin(wat, "ErrorEvent"); } /** * Checks whether given value's type is DOMError * {@link isDOMError}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isDOMError(wat) { return isBuiltin(wat, "DOMError"); } /** * Checks whether given value's type is DOMException * {@link isDOMException}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isDOMException(wat) { return isBuiltin(wat, "DOMException"); } /** * Checks whether given value's type is a string * {@link isString}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isString(wat) { return isBuiltin(wat, "String"); } /** * Checks whether given string is parameterized * {@link isParameterizedString}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isParameterizedString(wat) { return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat; } /** * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) * {@link isPrimitive}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isPrimitive(wat) { return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function"; } /** * Checks whether given value's type is an object literal, or a class instance. * {@link isPlainObject}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isPlainObject$2(wat) { return isBuiltin(wat, "Object"); } /** * Checks whether given value's type is an Event instance * {@link isEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isEvent(wat) { return typeof Event !== "undefined" && isInstanceOf(wat, Event); } /** * Checks whether given value's type is an Element instance * {@link isElement}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isElement(wat) { return typeof Element !== "undefined" && isInstanceOf(wat, Element); } /** * Checks whether given value's type is an regexp * {@link isRegExp}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isRegExp(wat) { return isBuiltin(wat, "RegExp"); } /** * Checks whether given value has a then function. * @param wat A value to be checked. */ function isThenable(wat) { return Boolean(wat && wat.then && typeof wat.then === "function"); } /** * Checks whether given value's type is a SyntheticEvent * {@link isSyntheticEvent}. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isSyntheticEvent(wat) { return isPlainObject$2(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat; } /** * Checks whether given value's type is an instance of provided constructor. * {@link isInstanceOf}. * * @param wat A value to be checked. * @param base A constructor to be used in a check. * @returns A boolean representing the result. */ function isInstanceOf(wat, base) { try { return wat instanceof base; } catch (_e) { return false; } } /** * Checks whether given value's type is a Vue ViewModel. * * @param wat A value to be checked. * @returns A boolean representing the result. */ function isVueViewModel(wat) { return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue)); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/browser.js var WINDOW$4 = GLOBAL_OBJ; var DEFAULT_MAX_STRING_LENGTH = 80; /** * Given a child DOM element, returns a query-selector statement describing that * and its ancestors * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] * @returns generated DOM path */ function htmlTreeAsString(elem, options = {}) { if (!elem) return ""; try { let currentElem = elem; const MAX_TRAVERSE_HEIGHT = 5; const out = []; let height = 0; let len = 0; const separator = " > "; const sepLength = 3; let nextStr; const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; const maxStringLength = !Array.isArray(options) && options.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 ""; } } /** * Returns a simple, query-selector representation of a DOM element * e.g. [HTMLElement] => input#foo.btn[name=baz] * @returns generated DOM path */ function _htmlElementAsString(el, keyAttrs) { const elem = el; const out = []; if (!elem || !elem.tagName) return ""; if (WINDOW$4.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(className)) { const classes = className.split(/\s+/); for (const c of classes) out.push(`.${c}`); } } for (const k of [ "aria-label", "type", "name", "title", "alt" ]) { const attr = elem.getAttribute(k); if (attr) out.push(`[${k}="${attr}"]`); } return out.join(""); } /** * A safe form of location.href */ function getLocationHref() { try { return WINDOW$4.document.location.href; } catch (oO) { return ""; } } /** * Gets a DOM element by using document.querySelector. * * This wrapper will first check for the existence of the function before * actually calling it so that we don't have to take care of this check, * every time we want to access the DOM. * * Reason: DOM/querySelector is not available in all environments. * * We have to cast to any because utils can be consumed by a variety of environments, * and we don't want to break TS users. If you know what element will be selected by * `document.querySelector`, specify it as part of the generic call. For example, * `const element = getDomElement('selector');` * * @param selector the selector string passed on to document.querySelector * * @deprecated This method is deprecated and will be removed in the next major version. */ function getDomElement(selector) { if (WINDOW$4.document && WINDOW$4.document.querySelector) return WINDOW$4.document.querySelector(selector); return null; } /** * Given a DOM element, traverses up the tree until it finds the first ancestor node * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed. * * @returns a string representation of the component for the provided DOM element, or `null` if not found */ function getComponentName(elem) { if (!WINDOW$4.HTMLElement) return null; let currentElem = elem; const MAX_TRAVERSE_HEIGHT = 5; for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) { 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; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/string.js /** * Truncates given string to the maximum characters count * * @param str An object that contains serializable values * @param max Maximum number of characters in truncated string (0 = unlimited) * @returns string Encoded */ function truncate(str, max = 0) { if (typeof str !== "string" || max === 0) return str; return str.length <= max ? str : `${str.slice(0, max)}...`; } /** * Join values in array * @param input array of values to be joined together * @param delimiter string to be placed in-between values * @returns Joined values */ function safeJoin(input, delimiter) { if (!Array.isArray(input)) return ""; const output = []; for (let i = 0; i < input.length; i++) { const value = input[i]; try { if (isVueViewModel(value)) output.push("[VueViewModel]"); else output.push(String(value)); } catch (e) { output.push("[value cannot be serialized]"); } } return output.join(delimiter); } /** * Checks if the given value matches a regex or string * * @param value The string to test * @param pattern Either a regex or a string against which `value` will be matched * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match * `pattern` if it contains `pattern`. Only applies to string-type patterns. */ function isMatchingPattern(value, pattern, requireExactStringMatch = false) { if (!isString(value)) return false; if (isRegExp(pattern)) return pattern.test(value); if (isString(pattern)) return requireExactStringMatch ? value === pattern : value.includes(pattern); return false; } /** * Test the given string against an array of strings and regexes. By default, string matching is done on a * substring-inclusion basis rather than a strict equality basis * * @param testString The string to test * @param patterns The patterns against which to test the string * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to * count. If false, `testString` will match a string pattern if it contains that pattern. * @returns */ function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) { return patterns.some((pattern) => isMatchingPattern(testString, pattern, requireExactStringMatch)); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/object.js /** * Replace a method in an object with a wrapped version of itself. * * @param source An object that contains a method to be wrapped. * @param name The name of the method to be wrapped. * @param replacementFactory A higher-order function that takes the original version of the given method and returns a * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`. * @returns void */ function fill(source, name, replacementFactory) { if (!(name in source)) return; const original = source[name]; const wrapped = replacementFactory(original); if (typeof wrapped === "function") markFunctionWrapped(wrapped, original); try { source[name] = wrapped; } catch (e) { DEBUG_BUILD$3 && logger$1.log(`Failed to replace method "${name}" in object`, source); } } /** * Defines a non-enumerable property on the given object. * * @param obj The object on which to set the property * @param name The name of the property to be set * @param value The value to which to set the property */ function addNonEnumerableProperty(obj, name, value) { try { Object.defineProperty(obj, name, { value, writable: true, configurable: true }); } catch (o_O) { DEBUG_BUILD$3 && logger$1.log(`Failed to add non-enumerable property "${name}" to object`, obj); } } /** * Remembers the original function on the wrapped function and * patches up the prototype. * * @param wrapped the wrapper function * @param original the original function that gets wrapped */ function markFunctionWrapped(wrapped, original) { try { wrapped.prototype = original.prototype = original.prototype || {}; addNonEnumerableProperty(wrapped, "__sentry_original__", original); } catch (o_O) {} } /** * This extracts the original function if available. See * `markFunctionWrapped` for more information. * * @param func the function to unwrap * @returns the unwrapped version of the function if available. */ function getOriginalFunction(func) { return func.__sentry_original__; } /** * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their * non-enumerable properties attached. * * @param value Initial source that we have to transform in order for it to be usable by the serializer * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor * an Error. */ function convertToPlainObject(value) { if (isError(value)) return { message: value.message, name: value.name, stack: value.stack, ...getOwnProperties(value) }; else if (isEvent(value)) { const newObj = { type: value.type, target: serializeEventTarget(value.target), currentTarget: serializeEventTarget(value.currentTarget), ...getOwnProperties(value) }; if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) newObj.detail = value.detail; return newObj; } else return value; } /** Creates a string representation of the target of an `Event` object */ function serializeEventTarget(target) { try { return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target); } catch (_oO) { return ""; } } /** Filters out all but an object's own properties */ function getOwnProperties(obj) { if (typeof obj === "object" && obj !== null) { const extractedProps = {}; for (const property in obj) if (Object.prototype.hasOwnProperty.call(obj, property)) extractedProps[property] = obj[property]; return extractedProps; } else return {}; } /** * Given any captured exception, extract its keys and create a sorted * and truncated list that will be used inside the event message. * eg. `Non-error exception captured with keys: foo, bar, baz` */ function extractExceptionKeysForMessage(exception, maxLength = 40) { const keys = Object.keys(convertToPlainObject(exception)); keys.sort(); const firstKey = keys[0]; if (!firstKey) return "[object has no keys]"; if (firstKey.length >= maxLength) return truncate(firstKey, maxLength); for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { const serialized = keys.slice(0, includedKeys).join(", "); if (serialized.length > maxLength) continue; if (includedKeys === keys.length) return serialized; return truncate(serialized, maxLength); } return ""; } /** * Given any object, return a new object having removed all fields whose value was `undefined`. * Works recursively on objects and arrays. * * Attention: This function keeps circular references in the returned object. */ function dropUndefinedKeys(inputValue) { return _dropUndefinedKeys(inputValue, /* @__PURE__ */ new Map()); } 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((item) => { returnValue.push(_dropUndefinedKeys(item, memoizationMap)); }); return returnValue; } return inputValue; } function isPojo(input) { if (!isPlainObject$2(input)) return false; try { const name = Object.getPrototypeOf(input).constructor.name; return !name || name === "Object"; } catch (e2) { return true; } } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/time.js var ONE_SECOND_IN_MS = 1e3; /** * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} * for accessing a high-resolution monotonic clock. */ /** * Returns a timestamp in seconds since the UNIX epoch using the Date API. * * TODO(v8): Return type should be rounded. */ function dateTimestampInSeconds() { return Date.now() / ONE_SECOND_IN_MS; } /** * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not * support the API. * * Wrapping the native API works around differences in behavior from different browsers. */ function createUnixTimestampInSecondsFunc() { const { performance } = GLOBAL_OBJ; if (!performance || !performance.now) return dateTimestampInSeconds; const approxStartingTimeOrigin = Date.now() - performance.now(); const timeOrigin = performance.timeOrigin == void 0 ? approxStartingTimeOrigin : performance.timeOrigin; return () => { return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS; }; } /** * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the * availability of the Performance API. * * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The * skew can grow to arbitrary amounts like days, weeks or months. * See https://github.com/getsentry/sentry-javascript/issues/2590. */ var timestampInSeconds = createUnixTimestampInSecondsFunc(); /** * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the * performance API is available. */ var browserPerformanceTimeOrigin = (() => { const { performance } = GLOBAL_OBJ; if (!performance || !performance.now) return; const threshold = 3600 * 1e3; const performanceNow = performance.now(); const dateNow = Date.now(); const timeOriginDelta = performance.timeOrigin ? Math.abs(performance.timeOrigin + performanceNow - dateNow) : threshold; const timeOriginIsReliable = timeOriginDelta < threshold; const navigationStart = performance.timing && performance.timing.navigationStart; const navigationStartDelta = typeof navigationStart === "number" ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; if (timeOriginIsReliable || navigationStartDelta < threshold) if (timeOriginDelta <= navigationStartDelta) return performance.timeOrigin; else return navigationStart; return dateNow; })(); //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/misc.js /** * UUID4 generator * * @returns string Generated UUID4. */ function uuid4() { const gbl = GLOBAL_OBJ; const crypto = gbl.crypto || gbl.msCrypto; let getRandomByte = () => Math.random() * 16; try { if (crypto && crypto.randomUUID) return crypto.randomUUID().replace(/-/g, ""); if (crypto && crypto.getRandomValues) getRandomByte = () => { const typedArray = new Uint8Array(1); crypto.getRandomValues(typedArray); return typedArray[0]; }; } catch (_) {} return "10000000100040008000100000000000".replace(/[018]/g, (c) => (c ^ (getRandomByte() & 15) >> c / 4).toString(16)); } function getFirstException(event) { return event.exception && event.exception.values ? event.exception.values[0] : void 0; } /** * Extracts either message or type+value from an event that can be used for user-facing logs * @returns event's description */ function getEventDescription(event) { const { message, event_id: eventId } = event; if (message) return message; const firstException = getFirstException(event); if (firstException) { if (firstException.type && firstException.value) return `${firstException.type}: ${firstException.value}`; return firstException.type || firstException.value || eventId || ""; } return eventId || ""; } /** * Adds exception values, type and value to an synthetic Exception. * @param event The event to modify. * @param value Value of the exception. * @param type Type of the exception. * @hidden */ function addExceptionTypeValue(event, value, type) { const exception = event.exception = event.exception || {}; const values = exception.values = exception.values || []; const firstException = values[0] = values[0] || {}; if (!firstException.value) firstException.value = value || ""; if (!firstException.type) firstException.type = type || "Error"; } /** * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. * * @param event The event to modify. * @param newMechanism Mechanism data to add to the event. * @hidden */ function addExceptionMechanism(event, newMechanism) { const firstException = getFirstException(event); if (!firstException) return; const defaultMechanism = { type: "generic", handled: true }; const currentMechanism = firstException.mechanism; firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; if (newMechanism && "data" in newMechanism) { const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data }; firstException.mechanism.data = mergedData; } } /** * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object * in question), and marks it captured if not. * * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we * see it. * * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent * object wrapper forms so that this check will always work. However, because we need to flag the exact object which * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification * must be done before the exception captured. * * @param A thrown exception to check or flag as having been seen * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) */ function checkOrSetAlreadyCaught(exception) { if (isAlreadyCaptured(exception)) return true; try { addNonEnumerableProperty(exception, "__sentry_captured__", true); } catch (err) {} return false; } function isAlreadyCaptured(exception) { try { return exception.__sentry_captured__; } catch (e) {} } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/syncpromise.js /** SyncPromise internal states */ var States; (function(States) { /** Pending */ const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; /** Resolved / OK */ const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; /** Rejected / Error */ const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; })(States || (States = {})); /** * Creates a resolved sync promise. * * @param value the value to resolve the promise with * @returns the resolved sync promise */ function resolvedSyncPromise(value) { return new SyncPromise((resolve) => { resolve(value); }); } /** * Creates a rejected sync promise. * * @param value the value to reject the promise with * @returns the rejected sync promise */ function rejectedSyncPromise(reason) { return new SyncPromise((_, reject) => { reject(reason); }); } /** * Thenable class that behaves like a Promise and follows it's interface * but is not async internally */ var SyncPromise = class 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 (e) { this._reject(e); } } /** JSDoc */ then(onfulfilled, onrejected) { return new SyncPromise((resolve, reject) => { this._handlers.push([ false, (result) => { if (!onfulfilled) resolve(result); else try { resolve(onfulfilled(result)); } catch (e) { reject(e); } }, (reason) => { if (!onrejected) reject(reason); else try { resolve(onrejected(reason)); } catch (e) { reject(e); } } ]); this._executeHandlers(); }); } /** JSDoc */ catch(onrejected) { return this.then((val) => val, onrejected); } /** JSDoc */ finally(onfinally) { return new SyncPromise((resolve, reject) => { let val; let isRejected; return this.then((value) => { isRejected = false; val = value; if (onfinally) onfinally(); }, (reason) => { isRejected = true; val = reason; if (onfinally) onfinally(); }).then(() => { if (isRejected) { reject(val); return; } resolve(val); }); }); } /** JSDoc */ __init() { this._resolve = (value) => { this._setResult(States.RESOLVED, value); }; } /** JSDoc */ __init2() { this._reject = (reason) => { this._setResult(States.REJECTED, reason); }; } /** JSDoc */ __init3() { this._setResult = (state, value) => { if (this._state !== States.PENDING) return; if (isThenable(value)) { value.then(this._resolve, this._reject); return; } this._state = state; this._value = value; this._executeHandlers(); }; } /** JSDoc */ __init4() { this._executeHandlers = () => { if (this._state === States.PENDING) return; const cachedHandlers = this._handlers.slice(); this._handlers = []; cachedHandlers.forEach((handler) => { if (handler[0]) return; if (this._state === States.RESOLVED) handler[1](this._value); if (this._state === States.REJECTED) handler[2](this._value); handler[0] = true; }); }; } }; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/session.js /** * Creates a new `Session` object by setting certain default parameters. If optional @param context * is passed, the passed properties are applied to the session object. * * @param context (optional) additional properties to be applied to the returned session object * * @returns a new `Session` object */ function makeSession(context) { const startingTime = timestampInSeconds(); const session = { sid: uuid4(), init: true, timestamp: startingTime, started: startingTime, duration: 0, status: "ok", errors: 0, ignoreDuration: false, toJSON: () => sessionToJSON(session) }; if (context) updateSession(session, context); return session; } /** * Updates a session object with the properties passed in the context. * * Note that this function mutates the passed object and returns void. * (Had to do this instead of returning a new and updated session because closing and sending a session * makes an update to the session after it was passed to the sending logic. * @see BaseClient.captureSession ) * * @param session the `Session` to update * @param context the `SessionContext` holding the properties that should be updated in @param session */ 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; } /** * Closes a session by setting its status and updating the session object with it. * Internally calls `updateSession` to update the passed session object. * * Note that this function mutates the passed session (@see updateSession for explanation). * * @param session the `Session` object to be closed * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, * this function will keep the previously set status, unless it was `'ok'` in which case * it is changed to `'exited'`. */ function closeSession(session, status) { let context = {}; if (status) context = { status }; else if (session.status === "ok") context = { status: "exited" }; updateSession(session, context); } /** * Serializes a passed session object to a JSON object with a slightly different structure. * This is necessary because the Sentry backend requires a slightly different schema of a session * than the one the JS SDKs use internally. * * @param session the session to be converted * * @returns a JSON object of the passed session */ function sessionToJSON(session) { return dropUndefinedKeys({ sid: `${session.sid}`, init: session.init, started: (/* @__PURE__ */ new Date(session.started * 1e3)).toISOString(), timestamp: (/* @__PURE__ */ 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 } }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/propagationContext.js /** * Generate a random, valid trace ID. */ function generateTraceId() { return uuid4(); } /** * Generate a random, valid span ID. */ function generateSpanId() { return uuid4().substring(16); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/merge.js /** * Shallow merge two objects. * Does not mutate the passed in objects. * Undefined/empty values in the merge object will overwrite existing values. * * By default, this merges 2 levels deep. */ function merge(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(output[key], mergeObj[key], levels - 1); return output; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/spanOnScope.js var SCOPE_SPAN_FIELD = "_sentrySpan"; /** * Set the active span for a given scope. * NOTE: This should NOT be used directly, but is only used internally by the trace methods. */ function _setSpanForScope(scope, span) { if (span) addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, span); else delete scope[SCOPE_SPAN_FIELD]; } /** * Get the active span for a given scope. * NOTE: This should NOT be used directly, but is only used internally by the trace methods. */ function _getSpanForScope(scope) { return scope[SCOPE_SPAN_FIELD]; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/scope.js /** * Default value for maximum number of breadcrumbs added to an event. */ var DEFAULT_MAX_BREADCRUMBS = 100; /** * Holds additional event information. */ var Scope = class 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 */ /** The client on this scope */ /** Contains the last event id of a captured event. */ 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(lastEventId) { this._lastEventId = lastEventId; } /** * @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 */ getRequestSession() { return this._requestSession; } /** * @inheritDoc */ setRequestSession(requestSession) { this._requestSession = requestSession; return this; } /** * @inheritDoc */ setTags(tags) { this._tags = { ...this._tags, ...tags }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setTag(key, value) { this._tags = { ...this._tags, [key]: value }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setExtras(extras) { this._extra = { ...this._extra, ...extras }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setExtra(key, extra) { this._extra = { ...this._extra, [key]: extra }; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setFingerprint(fingerprint) { this._fingerprint = fingerprint; this._notifyScopeListeners(); return this; } /** * @inheritDoc */ setLevel(level) { this._level = level; this._notifyScopeListeners(); return this; } /** * Sets the transaction name on the scope so that the name of e.g. taken server route or * the page location is attached to future events. * * IMPORTANT: Calling this function does NOT change the name of the currently active * root span. If you want to change the name of the active root span, use * `Sentry.updateSpanName(rootSpan, 'new name')` instead. * * By default, the SDK updates the scope's transaction name automatically on sensible * occasions, such as a page navigation or when handling a new request on the server. */ setTransactionName(name) { this._transactionName = name; 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 ? [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()] : isPlainObject$2(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 }; this._breadcrumbs.push(mergedBreadcrumb); if (this._breadcrumbs.length > maxCrumbs) { this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs); if (this._client) this._client.recordDroppedEvent("buffer_overflow", "log_item"); } 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(this._sdkProcessingMetadata, newData, 2); return this; } /** * @inheritDoc */ setPropagationContext(context) { this._propagationContext = { 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$1.warn("No client configured on scope - will not capture exception!"); return eventId; } const syntheticException = /* @__PURE__ */ new Error("Sentry syntheticException"); this._client.captureException(exception, { originalException: exception, syntheticException, ...hint, event_id: eventId }, this); return eventId; } /** * @inheritDoc */ captureMessage(message, level, hint) { const eventId = hint && hint.event_id ? hint.event_id : uuid4(); if (!this._client) { logger$1.warn("No client configured on scope - will not capture message!"); return eventId; } const syntheticException = new Error(message); this._client.captureMessage(message, level, { originalException: message, 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$1.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; } } }; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/defaultScopes.js /** Get the default current scope. */ function getDefaultCurrentScope() { return getGlobalSingleton("defaultCurrentScope", () => new Scope()); } /** Get the default isolation scope. */ function getDefaultIsolationScope() { return getGlobalSingleton("defaultIsolationScope", () => new Scope()); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js /** * This is an object that holds a stack of scopes. */ var AsyncContextStack = class { 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 (e) { this._popScope(); throw e; } if (isThenable(maybePromiseResult)) return maybePromiseResult.then((res) => { this._popScope(); return res; }, (e) => { this._popScope(); throw e; }); 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(); } }; /** * Get the global async context stack. * This will be removed during the v8 cycle and is only here to make migration easier. */ function getAsyncContextStack() { const sentry = getSentryCarrier(getMainCarrier()); return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()); } function withScope$1(callback) { return getAsyncContextStack().withScope(callback); } function withSetScope(scope, callback) { const stack = getAsyncContextStack(); return stack.withScope(() => { stack.getStackTop().scope = scope; return callback(scope); }); } function withIsolationScope(callback) { return getAsyncContextStack().withScope(() => { return callback(getAsyncContextStack().getIsolationScope()); }); } /** * Get the stack-based async context strategy. */ function getStackAsyncContextStrategy() { return { withIsolationScope, withScope: withScope$1, withSetScope, withSetIsolationScope: (_isolationScope, callback) => { return withIsolationScope(callback); }, getCurrentScope: () => getAsyncContextStack().getScope(), getIsolationScope: () => getAsyncContextStack().getIsolationScope() }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/asyncContext/index.js /** * Get the current async context strategy. * If none has been setup, the default will be used. */ function getAsyncContextStrategy(carrier) { const sentry = getSentryCarrier(carrier); if (sentry.acs) return sentry.acs; return getStackAsyncContextStrategy(); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/currentScopes.js /** * Get the currently active scope. */ function getCurrentScope() { return getAsyncContextStrategy(getMainCarrier()).getCurrentScope(); } /** * Get the currently active isolation scope. * The isolation scope is active for the current execution context. */ function getIsolationScope() { return getAsyncContextStrategy(getMainCarrier()).getIsolationScope(); } /** * Get the global scope. * This scope is applied to _all_ events. */ function getGlobalScope() { return getGlobalSingleton("globalScope", () => new Scope()); } /** * Creates a new scope with and executes the given operation within. * The scope is automatically removed once the operation * finishes or throws. */ /** * Either creates a new active scope, or sets the given scope as active scope in the given callback. */ function withScope(...rest) { const acs = getAsyncContextStrategy(getMainCarrier()); if (rest.length === 2) { const [scope, callback] = rest; if (!scope) return acs.withScope(callback); return acs.withSetScope(scope, callback); } return acs.withScope(rest[0]); } /** * Get the currently active client. */ function getClient() { return getCurrentScope().getClient(); } /** * Get a trace context for the given scope. */ function getTraceContextFromScope(scope) { const { traceId, spanId, parentSpanId } = scope.getPropagationContext(); return dropUndefinedKeys({ trace_id: traceId, span_id: spanId, parent_span_id: parentSpanId }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/metrics/metric-summary.js /** * key: bucketKey * value: [exportKey, MetricSummary] */ var METRICS_SPAN_FIELD = "_sentryMetrics"; /** * Fetches the metric summary if it exists for the passed span */ function getMetricSummaryJsonForSpan(span) { const storage = span[METRICS_SPAN_FIELD]; if (!storage) return; const output = {}; for (const [, [exportKey, summary]] of storage) (output[exportKey] || (output[exportKey] = [])).push(dropUndefinedKeys(summary)); return output; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/semanticAttributes.js /** * Use this attribute to represent the source of a span. * Should be one of: custom, url, route, view, component, task, unknown * */ var SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source"; /** * Use this attribute to represent the sample rate used for a span. */ var SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate"; /** * Use this attribute to represent the operation of a span. */ var SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op"; /** * Use this attribute to represent the origin of a span. */ var SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin"; /** The reason why an idle span finished. */ var SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = "sentry.idle_span_finish_reason"; /** The unit of a measurement, which may be stored as a TimedEvent. */ var SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = "sentry.measurement_unit"; /** The value of a measurement, which may be stored as a TimedEvent. */ var SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = "sentry.measurement_value"; /** * A custom span name set by users guaranteed to be taken over any automatically * inferred name. This attribute is removed before the span is sent. * * @internal only meant for internal SDK usage * @hidden */ var SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = "sentry.custom_span_name"; /** * The id of the profile that this span occurred in. */ var SEMANTIC_ATTRIBUTE_PROFILE_ID = "sentry.profile_id"; var SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = "sentry.exclusive_time"; /** * Converts a HTTP status code into a sentry status with a message. * * @param httpStatus The HTTP response status code. * @returns The span status or unknown_error. */ function getSpanStatusFromHttpCode(httpStatus) { if (httpStatus < 400 && httpStatus >= 100) return { code: 1 }; if (httpStatus >= 400 && httpStatus < 500) switch (httpStatus) { case 401: return { code: 2, message: "unauthenticated" }; case 403: return { code: 2, message: "permission_denied" }; case 404: return { code: 2, message: "not_found" }; case 409: return { code: 2, message: "already_exists" }; case 413: return { code: 2, message: "failed_precondition" }; case 429: return { code: 2, message: "resource_exhausted" }; case 499: return { code: 2, message: "cancelled" }; default: return { code: 2, message: "invalid_argument" }; } if (httpStatus >= 500 && httpStatus < 600) switch (httpStatus) { case 501: return { code: 2, message: "unimplemented" }; case 503: return { code: 2, message: "unavailable" }; case 504: return { code: 2, message: "deadline_exceeded" }; default: return { code: 2, message: "internal_error" }; } return { code: 2, message: "unknown_error" }; } /** * Sets the Http status attributes on the current span based on the http code. * Additionally, the span's status is updated, depending on the http code. */ function setHttpStatus(span, httpStatus) { span.setAttribute("http.response.status_code", httpStatus); const spanStatus = getSpanStatusFromHttpCode(httpStatus); if (spanStatus.message !== "unknown_error") span.setStatus(spanStatus); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/baggage.js var SENTRY_BAGGAGE_KEY_PREFIX = "sentry-"; var SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; /** * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values * from it. * * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. */ function baggageHeaderToDynamicSamplingContext(baggageHeader) { const baggageObject = parseBaggageHeader(baggageHeader); if (!baggageObject) return; const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { const nonPrefixedKey = key.slice(7); acc[nonPrefixedKey] = value; } return acc; }, {}); if (Object.keys(dynamicSamplingContext).length > 0) return dynamicSamplingContext; else return; } /** * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". * * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is * `undefined` the function will return `undefined`. * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. */ function dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext) { if (!dynamicSamplingContext) return; return objectToBaggageHeader(Object.entries(dynamicSamplingContext).reduce((acc, [dscKey, dscValue]) => { if (dscValue) acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; return acc; }, {})); } /** * Take a baggage header and parse it into an object. */ function parseBaggageHeader(baggageHeader) { if (!baggageHeader || !isString(baggageHeader) && !Array.isArray(baggageHeader)) return; if (Array.isArray(baggageHeader)) return baggageHeader.reduce((acc, curr) => { const currBaggageObject = baggageHeaderToObject(curr); Object.entries(currBaggageObject).forEach(([key, value]) => { acc[key] = value; }); return acc; }, {}); return baggageHeaderToObject(baggageHeader); } /** * Will parse a baggage header, which is a simple key-value map, into a flat object. * * @param baggageHeader The baggage header to parse. * @returns a flat object containing all the key-value pairs from `baggageHeader`. */ function baggageHeaderToObject(baggageHeader) { return baggageHeader.split(",").map((baggageEntry) => baggageEntry.split("=").map((keyOrValue) => decodeURIComponent(keyOrValue.trim()))).reduce((acc, [key, value]) => { if (key && value) acc[key] = value; return acc; }, {}); } /** * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. * * @param object The object to turn into a baggage header. * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header * is not spec compliant. */ function objectToBaggageHeader(object) { if (Object.keys(object).length === 0) return; 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 > 8192) { DEBUG_BUILD$3 && logger$1.warn(`Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`); return baggageHeader; } else return newBaggageHeader; }, ""); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/tracing.js var TRACEPARENT_REGEXP = /* @__PURE__ */ new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$"); /** * Extract transaction context data from a `sentry-trace` header. * * @param traceparent Traceparent string * * @returns Object containing data from the header, or undefined if traceparent string is malformed */ function extractTraceparentData(traceparent) { if (!traceparent) return; const matches = traceparent.match(TRACEPARENT_REGEXP); if (!matches) return; let parentSampled; if (matches[3] === "1") parentSampled = true; else if (matches[3] === "0") parentSampled = false; return { traceId: matches[1], parentSampled, parentSpanId: matches[2] }; } /** * Create a propagation context from incoming headers or * creates a minimal new one if the headers are undefined. */ 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; return { traceId, parentSpanId, spanId: generateSpanId(), sampled: parentSampled, dsc: dynamicSamplingContext || {} }; } /** * Create sentry-trace header from span context values. */ function generateSentryTraceHeader(traceId = generateTraceId(), spanId = generateSpanId(), sampled) { let sampledString = ""; if (sampled !== void 0) sampledString = sampled ? "-1" : "-0"; return `${traceId}-${spanId}${sampledString}`; } var hasShownSpanDropWarning = false; /** * Convert a span to a trace context, which can be sent as the `trace` context in an event. * By default, this will only include trace_id, span_id & parent_span_id. * If `includeAllData` is true, it will also include data, op, status & origin. */ function spanToTransactionTraceContext(span) { const { spanId: span_id, traceId: trace_id } = span.spanContext(); const { data, op, parent_span_id, status, origin } = spanToJSON(span); return dropUndefinedKeys({ parent_span_id, span_id, trace_id, data, op, status, origin }); } /** * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event. */ function spanToTraceContext(span) { const { spanId, traceId: trace_id, isRemote } = span.spanContext(); return dropUndefinedKeys({ parent_span_id: isRemote ? spanId : spanToJSON(span).parent_span_id, span_id: isRemote ? generateSpanId() : spanId, trace_id }); } /** * Convert a Span to a Sentry trace header. */ function spanToTraceHeader(span) { const { traceId, spanId } = span.spanContext(); return generateSentryTraceHeader(traceId, spanId, spanIsSampled(span)); } /** * Convert a span time input into a timestamp in seconds. */ 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(); } /** * Converts a timestamp to second, if it was in milliseconds, or keeps it as second. */ function ensureTimestampInSeconds(timestamp) { return timestamp > 9999999999 ? timestamp / 1e3 : timestamp; } /** * Convert a span to a JSON representation. */ 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, endTime, parentSpanId, status } = span; return dropUndefinedKeys({ span_id, trace_id, data: attributes, description: name, parent_span_id: parentSpanId, start_timestamp: spanTimeInputToSeconds(startTime), 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 (e) { return {}; } } function spanIsOpenTelemetrySdkTraceBaseSpan(span) { const castSpan = span; return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status; } /** Exported only for tests. */ /** * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof. * :( So instead we approximate this by checking if it has the `getSpanJSON` method. */ function spanIsSentrySpan(span) { return typeof span.getSpanJSON === "function"; } /** * Returns true if a span is sampled. * In most cases, you should just use `span.isRecording()` instead. * However, this has a slightly different semantic, as it also returns false if the span is finished. * So in the case where this distinction is important, use this method. */ function spanIsSampled(span) { const { traceFlags } = span.spanContext(); return traceFlags === 1; } /** Get the status message to use for a JSON representation of a span. */ function getStatusMessage(status) { if (!status || status.code === 0) return; if (status.code === 1) return "ok"; return status.message || "unknown_error"; } var CHILD_SPANS_FIELD = "_sentryChildSpans"; var ROOT_SPAN_FIELD = "_sentryRootSpan"; /** * Adds an opaque child span reference to a span. */ function addChildSpanToSpan(span, childSpan) { addNonEnumerableProperty(childSpan, ROOT_SPAN_FIELD, span[ROOT_SPAN_FIELD] || span); if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].add(childSpan); else addNonEnumerableProperty(span, CHILD_SPANS_FIELD, new Set([childSpan])); } /** This is only used internally by Idle Spans. */ function removeChildSpanFromSpan(span, childSpan) { if (span[CHILD_SPANS_FIELD]) span[CHILD_SPANS_FIELD].delete(childSpan); } /** * Returns an array of the given span and all of its descendants. */ function getSpanDescendants(span) { const resultSet = /* @__PURE__ */ new Set(); function addSpanChildren(span) { if (resultSet.has(span)) return; else if (spanIsSampled(span)) { resultSet.add(span); const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : []; for (const childSpan of childSpans) addSpanChildren(childSpan); } } addSpanChildren(span); return Array.from(resultSet); } /** * Returns the root span of a given span. */ function getRootSpan(span) { return span[ROOT_SPAN_FIELD] || span; } /** * Returns the currently active span. */ function getActiveSpan() { const acs = getAsyncContextStrategy(getMainCarrier()); if (acs.getActiveSpan) return acs.getActiveSpan(); return _getSpanForScope(getCurrentScope()); } /** * Logs a warning once if `beforeSendSpan` is used to drop spans. * * todo(v9): Remove this once we've stopped dropping spans via `beforeSendSpan`. */ 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; } } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/errors.js var errorsInstrumented = false; /** * Ensure that global errors automatically set the active span status. */ function registerSpanErrorInstrumentation() { if (errorsInstrumented) return; errorsInstrumented = true; addGlobalErrorInstrumentationHandler(errorCallback); addGlobalUnhandledRejectionInstrumentationHandler(errorCallback); } /** * If an error or unhandled promise occurs, we mark the active root span as failed */ function errorCallback() { const activeSpan = getActiveSpan(); const rootSpan = activeSpan && getRootSpan(activeSpan); if (rootSpan) { const message = "internal_error"; DEBUG_BUILD$4 && logger$1.log(`[Tracing] Root span: ${message} -> Global error occurred`); rootSpan.setStatus({ code: 2, message }); } } errorCallback.tag = "sentry_tracingErrorCallback"; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/utils.js var SCOPE_ON_START_SPAN_FIELD = "_sentryScope"; var ISOLATION_SCOPE_ON_START_SPAN_FIELD = "_sentryIsolationScope"; /** Store the scope & isolation scope for a span, which can the be used when it is finished. */ function setCapturedScopesOnSpan(span, scope, isolationScope) { if (span) { addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope); addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope); } } /** * Grabs the scope and isolation scope off a span that were active when the span was started. */ function getCapturedScopesOnSpan(span) { return { scope: span[SCOPE_ON_START_SPAN_FIELD], isolationScope: span[ISOLATION_SCOPE_ON_START_SPAN_FIELD] }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/hasTracingEnabled.js /** * Determines if tracing is currently enabled. * * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. */ function hasTracingEnabled(maybeOptions) { if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) return false; const client = getClient(); const options = maybeOptions || client && client.getOptions(); return !!options && (options.enableTracing || "tracesSampleRate" in options || "tracesSampler" in options); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/sentryNonRecordingSpan.js /** * A Sentry Span that is non-recording, meaning it will not be sent to Sentry. */ var SentryNonRecordingSpan = class { constructor(spanContext = {}) { this._traceId = spanContext.traceId || generateTraceId(); this._spanId = spanContext.spanId || generateSpanId(); } /** @inheritdoc */ spanContext() { return { spanId: this._spanId, traceId: this._traceId, traceFlags: 0 }; } /** @inheritdoc */ 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) {} }; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/constants.js var DEFAULT_ENVIRONMENT = "production"; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js /** * If you change this value, also update the terser plugin config to * avoid minification of the object property! */ var FROZEN_DSC_FIELD = "_frozenDsc"; /** * Freeze the given DSC on the given span. */ function freezeDscOnSpan(span, dsc) { addNonEnumerableProperty(span, FROZEN_DSC_FIELD, dsc); } /** * Creates a dynamic sampling context from a client. * * Dispatches the `createDsc` lifecycle hook as a side effect. */ function getDynamicSamplingContextFromClient(trace_id, client) { const options = client.getOptions(); const { publicKey: public_key } = client.getDsn() || {}; const dsc = dropUndefinedKeys({ environment: options.environment || "production", release: options.release, public_key, trace_id }); client.emit("createDsc", dsc); return dsc; } /** * Get the dynamic sampling context for the currently active scopes. */ function getDynamicSamplingContextFromScope(client, scope) { const propagationContext = scope.getPropagationContext(); return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client); } /** * Creates a dynamic sampling context from a span (and client and scope) * * @param span the span from which a few values like the root span name and sample rate are extracted. * * @returns a dynamic sampling context */ 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 name = jsonSpan.description; if (source !== "url" && name) dsc.transaction = name; if (hasTracingEnabled()) dsc.sampled = String(spanIsSampled(rootSpan)); client.emit("createDsc", dsc, rootSpan); return dsc; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/logSpans.js /** * Print a log message for a started span. */ function logSpanStart(span) { if (!DEBUG_BUILD$4) 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 header = `[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, description } = spanToJSON(rootSpan); infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`); if (op) infoParts.push(`root op: ${op}`); if (description) infoParts.push(`root description: ${description}`); } logger$1.log(`${header} ${infoParts.join("\n ")}`); } /** * Print a log message for an ended span. */ function logSpanEnd(span) { if (!DEBUG_BUILD$4) return; const { description = "< unknown name >", op = "< unknown op >" } = spanToJSON(span); const { spanId } = span.spanContext(); const msg = `[Tracing] Finishing "${op}" ${getRootSpan(span) === span ? "root " : ""}span "${description}" with ID ${spanId}`; logger$1.log(msg); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/parseSampleRate.js /** * Parse a sample rate from a given value. * This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1). * If a string is passed, we try to convert it to a number. * * Any invalid sample rate will return `undefined`. */ 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$4 && logger$1.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; } return rate; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/sampling.js /** * Makes a sampling decision for the given options. * * Called every time a root span is created. Only root spans which emerge with a `sampled` value of `true` will be * sent to Sentry. */ function sampleSpan(options, samplingContext) { if (!hasTracingEnabled(options)) return [false]; const normalizedRequest = getIsolationScope().getScopeData().sdkProcessingMetadata.normalizedRequest; const enhancedSamplingContext = { ...samplingContext, normalizedRequest: samplingContext.normalizedRequest || normalizedRequest }; let sampleRate; if (typeof options.tracesSampler === "function") sampleRate = options.tracesSampler(enhancedSamplingContext); else if (enhancedSamplingContext.parentSampled !== void 0) sampleRate = enhancedSamplingContext.parentSampled; else if (typeof options.tracesSampleRate !== "undefined") sampleRate = options.tracesSampleRate; else sampleRate = 1; const parsedSampleRate = parseSampleRate(sampleRate); if (parsedSampleRate === void 0) { DEBUG_BUILD$4 && logger$1.warn("[Tracing] Discarding transaction because of invalid sample rate."); return [false]; } if (!parsedSampleRate) { DEBUG_BUILD$4 && logger$1.log(`[Tracing] Discarding transaction because ${typeof options.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"}`); return [false, parsedSampleRate]; } if (!(Math.random() < parsedSampleRate)) { DEBUG_BUILD$4 && logger$1.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(sampleRate)})`); return [false, parsedSampleRate]; } return [true, parsedSampleRate]; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/dsn.js /** Regular expression used to parse a Dsn. */ var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; function isValidProtocol(protocol) { return protocol === "http" || protocol === "https"; } /** * Renders the string representation of this Dsn. * * By default, this will render the public representation without the password * component. To get the deprecated private representation, set `withPassword` * to true. * * @param withPassword When set to true, the password will be included. */ function dsnToString(dsn, withPassword = false) { const { host, path, pass, port, projectId, protocol, publicKey } = dsn; return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`; } /** * Parses a Dsn from a given string. * * @param str A Dsn as string * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string */ function dsnFromString(str) { const match = DSN_REGEX.exec(str); if (!match) { consoleSandbox(() => { console.error(`Invalid Sentry Dsn: ${str}`); }); return; } const [protocol, publicKey, pass = "", host = "", port = "", lastPath = ""] = match.slice(1); let path = ""; let projectId = lastPath; const split = projectId.split("/"); if (split.length > 1) { path = split.slice(0, -1).join("/"); projectId = split.pop(); } if (projectId) { const projectMatch = projectId.match(/^\d+/); if (projectMatch) projectId = projectMatch[0]; } return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey }); } function dsnFromComponents(components) { return { protocol: components.protocol, publicKey: components.publicKey || "", pass: components.pass || "", host: components.host, port: components.port || "", path: components.path || "", projectId: components.projectId }; } function validateDsn(dsn) { if (!DEBUG_BUILD$3) return true; const { port, projectId, protocol } = dsn; if ([ "protocol", "publicKey", "host", "projectId" ].find((component) => { if (!dsn[component]) { logger$1.error(`Invalid Sentry Dsn: ${component} missing`); return true; } return false; })) return false; if (!projectId.match(/^\d+$/)) { logger$1.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); return false; } if (!isValidProtocol(protocol)) { logger$1.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); return false; } if (port && isNaN(parseInt(port, 10))) { logger$1.error(`Invalid Sentry Dsn: Invalid port ${port}`); return false; } return true; } /** * Creates a valid Sentry Dsn object, identifying a Sentry instance and project. * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source */ function makeDsn(from) { const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from); if (!components || !validateDsn(components)) return; return components; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/memo.js /** * Helper to decycle json objects * * @deprecated This function is deprecated and will be removed in the next major version. */ 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 i = 0; i < inner.length; i++) if (inner[i] === obj) return true; inner.push(obj); return false; } function unmemoize(obj) { if (hasWeakSet) inner.delete(obj); else for (let i = 0; i < inner.length; i++) if (inner[i] === obj) { inner.splice(i, 1); break; } } return [memoize, unmemoize]; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/normalize.js /** * Recursively normalizes the given object. * * - Creates a copy to prevent original input mutation * - Skips non-enumerable properties * - When stringifying, calls `toJSON` if implemented * - Removes circular references * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format * - Translates known global objects/classes to a string representations * - Takes care of `Error` object serialization * - Optionally limits depth of final output * - Optionally limits number of properties/elements included in any single object/array * * @param input The object to be normalized. * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) * @param maxProperties The max number of elements or properties to be included in any single array or * object in the normalized output. * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. */ function normalize(input, depth = 100, maxProperties = Infinity) { try { return visit("", input, depth, maxProperties); } catch (err) { return { ERROR: `**non-serializable** (${err})` }; } } /** JSDoc */ function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) { const normalized = normalize(object, depth); if (jsonSize(normalized) > maxSize) return normalizeToSize(object, depth - 1, maxSize); return normalized; } /** * Visits a node to perform normalization on it * * @param key The key corresponding to the given node * @param value The node to be visited * @param depth Optional number indicating the maximum recursion depth * @param maxProperties Optional maximum number of properties/elements included in any single object/array * @param memo Optional Memo class handling decycling */ function visit(key, value, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) { const [memoize, unmemoize] = memo; if (value == null || ["boolean", "string"].includes(typeof value) || typeof value === "number" && Number.isFinite(value)) return value; const stringified = stringifyValue(key, value); if (!stringified.startsWith("[object ")) return stringified; if (value["__sentry_skip_normalization__"]) return value; const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : depth; if (remainingDepth === 0) return stringified.replace("object ", ""); if (memoize(value)) return "[Circular ~]"; const valueWithToJSON = value; if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") try { return visit("", valueWithToJSON.toJSON(), remainingDepth - 1, maxProperties, memo); } catch (err) {} const normalized = Array.isArray(value) ? [] : {}; let numAdded = 0; const visitable = convertToPlainObject(value); 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(value); return normalized; } /** * Stringify the given value. Handles various known special values and types. * * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn * the number 1231 into "[Object Number]", nor on `null`, as it will throw. * * @param value The value to stringify * @returns A stringified representation of the given value */ function stringifyValue(key, value) { try { if (key === "domain" && value && typeof value === "object" && value._events) return "[Domain]"; if (key === "domainEmitter") return "[DomainEmitter]"; if (typeof global !== "undefined" && value === global) return "[Global]"; if (typeof window !== "undefined" && value === window) return "[Window]"; if (typeof document !== "undefined" && value === document) return "[Document]"; if (isVueViewModel(value)) return "[VueViewModel]"; if (isSyntheticEvent(value)) return "[SyntheticEvent]"; if (typeof value === "number" && !Number.isFinite(value)) return `[${value}]`; if (typeof value === "function") return `[Function: ${getFunctionName(value)}]`; if (typeof value === "symbol") return `[${String(value)}]`; if (typeof value === "bigint") return `[BigInt: ${String(value)}]`; const objName = getConstructorName(value); if (/^HTML(\w*)Element$/.test(objName)) return `[HTMLElement: ${objName}]`; return `[object ${objName}]`; } catch (err) { return `**non-serializable** (${err})`; } } function getConstructorName(value) { const prototype = Object.getPrototypeOf(value); return prototype ? prototype.constructor.name : "null prototype"; } /** Calculates bytes size of input string */ function utf8Length(value) { return ~-encodeURI(value).split(/%..|./).length; } /** Calculates bytes size of input object */ function jsonSize(value) { return utf8Length(JSON.stringify(value)); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/envelope.js /** * Creates an envelope. * Make sure to always explicitly provide the generic to this function * so that the envelope types resolve correctly. */ function createEnvelope(headers, items = []) { return [headers, items]; } /** * Add an item to an envelope. * Make sure to always explicitly provide the generic to this function * so that the envelope types resolve correctly. */ function addItemToEnvelope(envelope, newItem) { const [headers, items] = envelope; return [headers, [...items, newItem]]; } /** * Convenience function to loop through the items and item types of an envelope. * (This function was mostly created because working with envelope types is painful at the moment) * * If the callback returns true, the rest of the items will be skipped. */ function forEachEnvelopeItem(envelope, callback) { const envelopeItems = envelope[1]; for (const envelopeItem of envelopeItems) { const envelopeItemType = envelopeItem[0].type; if (callback(envelopeItem, envelopeItemType)) return true; } return false; } /** * Encode a string to UTF8 array. */ function encodeUTF8(input) { return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input) : new TextEncoder().encode(input); } /** * Serializes an envelope. */ function serializeEnvelope(envelope) { const [envHeaders, items] = envelope; let parts = JSON.stringify(envHeaders); function append(next) { if (typeof parts === "string") parts = typeof next === "string" ? parts + next : [encodeUTF8(parts), next]; else parts.push(typeof next === "string" ? encodeUTF8(next) : next); } for (const item of items) { const [itemHeaders, payload] = item; append(`\n${JSON.stringify(itemHeaders)}\n`); if (typeof payload === "string" || payload instanceof Uint8Array) append(payload); else { let stringifiedPayload; try { stringifiedPayload = JSON.stringify(payload); } catch (e) { stringifiedPayload = JSON.stringify(normalize(payload)); } append(stringifiedPayload); } } return typeof parts === "string" ? parts : concatBuffers(parts); } function concatBuffers(buffers) { const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); const merged = new Uint8Array(totalLength); let offset = 0; for (const buffer of buffers) { merged.set(buffer, offset); offset += buffer.length; } return merged; } /** * Creates envelope item for a single span */ function createSpanEnvelopeItem(spanJson) { return [{ type: "span" }, spanJson]; } /** * Creates attachment envelope items */ function createAttachmentEnvelopeItem(attachment) { const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data; return [dropUndefinedKeys({ type: "attachment", length: buffer.length, filename: attachment.filename, content_type: attachment.contentType, attachment_type: attachment.attachmentType }), buffer]; } var 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" }; /** * Maps the type of an envelope item to a data category. */ function envelopeItemTypeToDataCategory(type) { return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; } /** Extracts the minimal SDK info from the metadata or an events */ function getSdkMetadataForEnvelopeHeader(metadataOrEvent) { if (!metadataOrEvent || !metadataOrEvent.sdk) return; const { name, version } = metadataOrEvent.sdk; return { name, version }; } /** * Creates event envelope headers, based on event, sdk info and tunnel * Note: This function was extracted from the core package to make it available in Replay */ 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 }) } }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/envelope.js /** * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. * Merge with existing data if any. **/ function enhanceEventWithSdkInfo(event, sdkInfo) { if (!sdkInfo) return event; event.sdk = event.sdk || {}; event.sdk.name = event.sdk.name || sdkInfo.name; event.sdk.version = event.sdk.version || sdkInfo.version; event.sdk.integrations = [...event.sdk.integrations || [], ...sdkInfo.integrations || []]; event.sdk.packages = [...event.sdk.packages || [], ...sdkInfo.packages || []]; return event; } /** Creates an envelope from a Session */ function createSessionEnvelope(session, dsn, metadata, tunnel) { const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); return createEnvelope({ sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...sdkInfo && { sdk: sdkInfo }, ...!!tunnel && dsn && { dsn: dsnToString(dsn) } }, ["aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()]]); } /** * Create an Envelope from an event. */ 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; return createEnvelope(envelopeHeaders, [[{ type: eventType }, event]]); } /** * Create envelope from Span item. * * Takes an optional client and runs spans through `beforeSendSpan` if available. */ function createSpanEnvelope(spans, client) { function dscHasRequiredProps(dsc) { return !!dsc.trace_id && !!dsc.public_key; } 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 items = []; for (const span of spans) { const spanJson = convertToSpanJSON(span); if (spanJson) items.push(createSpanEnvelopeItem(spanJson)); } return createEnvelope(headers, items); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/measurement.js /** * Adds a measurement to the active transaction on the current global scope. You can optionally pass in a different span * as the 4th parameter. */ function setMeasurement(name, value, unit, activeSpan = getActiveSpan()) { const rootSpan = activeSpan && getRootSpan(activeSpan); if (rootSpan) { DEBUG_BUILD$4 && logger$1.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`); rootSpan.addEvent(name, { [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value, [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit }); } } /** * Convert timed events to measurements. */ function timedEventsToMeasurements(events) { if (!events || events.length === 0) return; const measurements = {}; events.forEach((event) => { const attributes = event.attributes || {}; const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]; const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]; if (typeof unit === "string" && typeof value === "number") measurements[event.name] = { value, unit }; }); return measurements; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/sentrySpan.js var MAX_SPAN_COUNT = 1e3; /** * Span contains all data about a span */ var SentrySpan = class { /** 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 ? 1 : 0 }; } /** @inheritdoc */ setAttribute(key, value) { if (value === void 0) delete this._attributes[key]; else this._attributes[key] = value; 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(value) { this._status = value; return this; } /** * @inheritDoc */ updateName(name) { this._name = name; 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(name, attributesOrStartTime, startTime) { DEBUG_BUILD$4 && logger$1.log("[Tracing] Adding an event to span:", name); const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds(); const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {}; const event = { name, 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); if (!(this._isStandaloneSpan || this === getRootSpan(this))) return; if (this._isStandaloneSpan) { if (this._sampled) sendSpanEnvelope(createSpanEnvelope([this], client)); else { DEBUG_BUILD$4 && logger$1.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) (getCapturedScopesOnSpan(this).scope || getCurrentScope()).captureEvent(transactionEvent); } /** * Finish the transaction & prepare the event to send to Sentry. */ _convertSpanToTransaction() { if (!isFullFinishedSpan(spanToJSON(this))) return; if (!this._name) { DEBUG_BUILD$4 && logger$1.warn("Transaction has no name, falling back to ``."); this._name = ""; } const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this); const client = (capturedSpanScope || getCurrentScope()).getClient() || getClient(); if (this._sampled !== true) { DEBUG_BUILD$4 && logger$1.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled."); if (client) client.recordDroppedEvent("sample_rate", "transaction"); return; } const spans = getSpanDescendants(this).filter((span) => span !== this && !isStandaloneSpan(span)).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["sentry.custom_span_name"]; }); const transaction = { contexts: { trace: spanToTransactionTraceContext(this) }, spans: spans.length > MAX_SPAN_COUNT ? spans.sort((a, b) => a.start_timestamp - b.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); if (measurements && Object.keys(measurements).length) { DEBUG_BUILD$4 && logger$1.log("[Measurements] Adding measurements to transaction event", JSON.stringify(measurements, void 0, 2)); transaction.measurements = measurements; } return transaction; } }; function isSpanTimeInput(value) { return value && typeof value === "number" || value instanceof Date || Array.isArray(value); } function isFullFinishedSpan(input) { return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id; } /** `SentrySpan`s can be sent as a standalone span rather than belonging to a transaction */ function isStandaloneSpan(span) { return span instanceof SentrySpan && span.isStandaloneSpan(); } /** * Sends a `SpanEnvelope`. * * Note: If the envelope's spans are dropped, e.g. via `beforeSendSpan`, * the envelope will not be sent either. */ 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); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/trace.js var SUPPRESS_TRACING_KEY = "__SENTRY_SUPPRESS_TRACING__"; /** * Creates a span. This span is not set as active, so will not get automatic instrumentation spans * as children or be able to be accessed via `Sentry.getActiveSpan()`. * * If you want to create a span that is set as active, use {@link startSpan}. * * This function will always return a span, * it may just be a non-recording span if the span is not sampled or if tracing is disabled. */ function startInactiveSpan(options) { const acs = getAcs(); if (acs.startInactiveSpan) return acs.startInactiveSpan(options); const spanArguments = parseSentrySpanArguments(options); const { forceTransaction, parentSpan: customParentSpan } = options; return (options.scope ? (callback) => withScope(options.scope, callback) : customParentSpan !== void 0 ? (callback) => withActiveSpan(customParentSpan, callback) : (callback) => callback())(() => { const scope = getCurrentScope(); const parentSpan = getParentSpan(scope); if (options.onlyIfParent && !parentSpan) return new SentryNonRecordingSpan(); return createChildOrRootSpan({ parentSpan, spanArguments, forceTransaction, scope }); }); } /** * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be * passed `null` to start an entirely new span tree. * * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed, * spans started within the callback will not be attached to a parent span. * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope. * @returns the value returned from the provided callback function. */ 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); }); } 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; } /** * This converts StartSpanOptions to SentrySpanArguments. * For the most part (for now) we accept the same options, * but some of them need to be transformed. */ function parseSentrySpanArguments(options) { const initialCtx = { isStandalone: (options.experimental || {}).standalone, ...options }; if (options.startTime) { const ctx = { ...initialCtx }; ctx.startTimestamp = spanTimeInputToSeconds(options.startTime); delete ctx.startTime; return ctx; } return initialCtx; } function getAcs() { return getAsyncContextStrategy(getMainCarrier()); } function _startRootSpan(spanArguments, scope, parentSampled) { const client = getClient(); const options = client && client.getOptions() || {}; const { name = "", attributes } = spanArguments; const [sampled, sampleRate] = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? [false] : sampleSpan(options, { name, parentSampled, attributes, transactionContext: { name, 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; } /** * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`. * This inherits the sampling decision from the parent span. */ 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; } function getParentSpan(scope) { const span = _getSpanForScope(scope); if (!span) return; const client = getClient(); if ((client ? client.getOptions() : {}).parentSpanIsAlwaysRootSpan) return getRootSpan(span); return span; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/tracing/idleSpan.js var TRACING_DEFAULTS = { idleTimeout: 1e3, finalTimeout: 3e4, childSpanTimeout: 15e3 }; var FINISH_REASON_HEARTBEAT_FAILED = "heartbeatFailed"; var FINISH_REASON_IDLE_TIMEOUT = "idleTimeout"; var FINISH_REASON_FINAL_TIMEOUT = "finalTimeout"; var FINISH_REASON_EXTERNAL_FINISH = "externalFinish"; /** * An idle span is a span that automatically finishes. It does this by tracking child spans as activities. * An idle span is always the active span. */ function startIdleSpan(startSpanOptions, options = {}) { const activities = /* @__PURE__ */ new Map(); let _finished = false; let _idleTimeoutID; let _finishReason = FINISH_REASON_EXTERNAL_FINISH; let _autoFinishAllowed = !options.disableAutoFinish; const _cleanupHooks = []; const { idleTimeout = TRACING_DEFAULTS.idleTimeout, finalTimeout = TRACING_DEFAULTS.finalTimeout, childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout, beforeSpanEnd } = options; const client = getClient(); if (!client || !hasTracingEnabled()) return new SentryNonRecordingSpan(); const scope = getCurrentScope(); 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 spanEndTimestamp = spanTimeInputToSeconds(definedEndTimestamp || timestampInSeconds()); const spans = getSpanDescendants(span).filter((child) => child !== span); if (!spans.length) { onIdleSpanEnded(spanEndTimestamp); return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]); } const childEndTimestamps = spans.map((span) => spanToJSON(span).timestamp).filter((timestamp) => !!timestamp); 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]); } }); /** * Cancels the existing idle timeout, if there is one. */ function _cancelIdleTimeout() { if (_idleTimeoutID) { clearTimeout(_idleTimeoutID); _idleTimeoutID = void 0; } } /** * Restarts idle timeout, if there is no running idle timeout it will start one. */ function _restartIdleTimeout(endTimestamp) { _cancelIdleTimeout(); _idleTimeoutID = setTimeout(() => { if (!_finished && activities.size === 0 && _autoFinishAllowed) { _finishReason = FINISH_REASON_IDLE_TIMEOUT; span.end(endTimestamp); } }, idleTimeout); } /** * Restarts child span timeout, if there is none running it will start one. */ function _restartChildSpanTimeout(endTimestamp) { _idleTimeoutID = setTimeout(() => { if (!_finished && _autoFinishAllowed) { _finishReason = FINISH_REASON_HEARTBEAT_FAILED; span.end(endTimestamp); } }, childSpanTimeout); } /** * Start tracking a specific activity. * @param spanId The span id that represents the activity */ function _pushActivity(spanId) { _cancelIdleTimeout(); activities.set(spanId, true); _restartChildSpanTimeout(timestampInSeconds() + childSpanTimeout / 1e3); } /** * Remove an activity from usage * @param spanId The span id that represents the activity */ function _popActivity(spanId) { if (activities.has(spanId)) activities.delete(spanId); if (activities.size === 0) _restartIdleTimeout(timestampInSeconds() + idleTimeout / 1e3); } 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; if (!(spanJSON.data || {})["sentry.idle_span_finish_reason"]) span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason); logger$1.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: 2, message: "cancelled" }); childSpan.end(endTimestamp); DEBUG_BUILD$4 && logger$1.log("[Tracing] Cancelling span since span ended early", JSON.stringify(childSpan, void 0, 2)); } const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = spanToJSON(childSpan); const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp; const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1e3; const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError; if (DEBUG_BUILD$4) { const stringifiedSpan = JSON.stringify(childSpan, void 0, 2); if (!spanStartedBeforeIdleSpanEnd) logger$1.log("[Tracing] Discarding span since it happened after idle span was finished", stringifiedSpan); else if (!spanEndedBeforeFinalTimeout) logger$1.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); } _cleanupHooks.push(client.on("spanStart", (startedSpan) => { if (_finished || startedSpan === span || !!spanToJSON(startedSpan).timestamp) return; if (getSpanDescendants(span).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 (!options.disableAutoFinish) _restartIdleTimeout(); setTimeout(() => { if (!_finished) { span.setStatus({ code: 2, message: "deadline_exceeded" }); _finishReason = FINISH_REASON_FINAL_TIMEOUT; span.end(); } }, finalTimeout); return span; } function _startIdleSpan(options) { const span = startInactiveSpan(options); _setSpanForScope(getCurrentScope(), span); DEBUG_BUILD$4 && logger$1.log("[Tracing] Started span is an idle span"); return span; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/eventProcessors.js /** * Process an array of event processors, returning the processed event (or `null` if the event was dropped). */ function notifyEventProcessors(processors, event, hint, index = 0) { return new SyncPromise((resolve, reject) => { const processor = processors[index]; if (event === null || typeof processor !== "function") resolve(event); else { const result = processor({ ...event }, hint); DEBUG_BUILD$4 && processor.id && result === null && logger$1.log(`Event processor "${processor.id}" dropped event`); if (isThenable(result)) result.then((final) => notifyEventProcessors(processors, final, hint, index + 1).then(resolve)).then(null, reject); else notifyEventProcessors(processors, result, hint, index + 1).then(resolve).then(null, reject); } }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/debug-ids.js var parsedStackResults; var lastKeysCount; var cachedFilenameDebugIds; /** * Returns a map of filenames to debug identifiers. */ 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 i = parsedStack.length - 1; i >= 0; i--) { const stackFrame = parsedStack[i]; const filename = stackFrame && stackFrame.filename; const debugId = debugIdMap[stackKey]; if (filename && debugId) { acc[filename] = debugId; parsedStackResults[stackKey] = [filename, debugId]; break; } } } return acc; }, {}); return cachedFilenameDebugIds; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/applyScopeDataToEvent.js /** * Applies data from the scope to the event and runs all event processors on it. */ function applyScopeDataToEvent(event, data) { const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data; applyDataToEvent(event, data); if (span) applySpanToEvent(event, span); applyFingerprintToEvent(event, fingerprint); applyBreadcrumbsToEvent(event, breadcrumbs); applySdkMetadataToEvent(event, sdkProcessingMetadata); } /** Merge data of two scopes together. */ function mergeScopeData(data, mergeData) { const { extra, tags, user, contexts, level, sdkProcessingMetadata, breadcrumbs, fingerprint, eventProcessors, attachments, propagationContext, transactionName, span } = mergeData; mergeAndOverwriteScopeData(data, "extra", extra); mergeAndOverwriteScopeData(data, "tags", tags); mergeAndOverwriteScopeData(data, "user", user); mergeAndOverwriteScopeData(data, "contexts", contexts); data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2); if (level) data.level = level; if (transactionName) data.transactionName = transactionName; if (span) data.span = span; if (breadcrumbs.length) data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs]; if (fingerprint.length) data.fingerprint = [...data.fingerprint, ...fingerprint]; if (eventProcessors.length) data.eventProcessors = [...data.eventProcessors, ...eventProcessors]; if (attachments.length) data.attachments = [...data.attachments, ...attachments]; data.propagationContext = { ...data.propagationContext, ...propagationContext }; } /** * Merges certain scope data. Undefined values will overwrite any existing values. * Exported only for tests. */ function mergeAndOverwriteScopeData(data, prop, mergeVal) { data[prop] = merge(data[prop], mergeVal, 1); } function applyDataToEvent(event, data) { const { extra, tags, user, contexts, level, transactionName } = data; 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; } function applyBreadcrumbsToEvent(event, breadcrumbs) { const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs]; event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : void 0; } function applySdkMetadataToEvent(event, sdkProcessingMetadata) { event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...sdkProcessingMetadata }; } function applySpanToEvent(event, span) { event.contexts = { trace: spanToTraceContext(span), ...event.contexts }; event.sdkProcessingMetadata = { dynamicSamplingContext: getDynamicSamplingContextFromSpan(span), ...event.sdkProcessingMetadata }; const transactionName = spanToJSON(getRootSpan(span)).description; if (transactionName && !event.transaction && event.type === "transaction") event.transaction = transactionName; } /** * Applies fingerprint from the scope to the event if there's one, * uses message if there's one instead or get rid of empty fingerprint */ 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; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/prepareEvent.js /** * This type makes sure that we get either a CaptureContext, OR an EventHint. * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed: * { user: { id: '123' }, mechanism: { handled: false } } */ /** * Adds common information to events. * * The information includes release and environment from `options`, * breadcrumbs and context (extra, tags and user) from the scope. * * Information that is already present in the event is never overwritten. For * nested objects, such as the context, keys are merged. * * @param event The original event. * @param hint May contain additional information about the original exception. * @param scope A scope containing event metadata. * @returns A new event with more information. * @hidden */ function prepareEvent(options, event, hint, scope, client, isolationScope) { const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options; const prepared = { ...event, event_id: event.event_id || hint.event_id || uuid4(), timestamp: event.timestamp || dateTimestampInSeconds() }; const integrations = hint.integrations || options.integrations.map((i) => i.name); applyClientOptions(prepared, options); applyIntegrationsMetadata(prepared, integrations); if (client) client.emit("applyFrameMetadata", event); if (event.type === void 0) applyDebugIds(prepared, options.stackParser); const finalScope = getFinalScope(scope, hint.captureContext); if (hint.mechanism) addExceptionMechanism(prepared, hint.mechanism); const clientEventProcessors = client ? client.getEventProcessors() : []; const data = getGlobalScope().getScopeData(); if (isolationScope) mergeScopeData(data, isolationScope.getScopeData()); if (finalScope) mergeScopeData(data, finalScope.getScopeData()); const attachments = [...hint.attachments || [], ...data.attachments]; if (attachments.length) hint.attachments = attachments; applyScopeDataToEvent(prepared, data); return notifyEventProcessors([...clientEventProcessors, ...data.eventProcessors], prepared, hint).then((evt) => { if (evt) applyDebugMeta(evt); if (typeof normalizeDepth === "number" && normalizeDepth > 0) return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); return evt; }); } /** * Enhances event using the client configuration. * It takes care of all "static" values like environment, release and `dist`, * as well as truncating overly long values. * * Only exported for tests. * * @param event event instance to be enhanced */ function applyClientOptions(event, options) { const { environment, release, dist, maxValueLength = 250 } = options; event.environment = event.environment || environment || "production"; if (!event.release && release) event.release = release; if (!event.dist && dist) event.dist = dist; 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); } /** * Puts debug IDs into the stack frames of an error event. */ 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 (e) {} } /** * Moves debug IDs from the stack frames of an error event into the debug_meta field. */ 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 (e) {} 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 }); }); } /** * This function adds all used integrations to the SDK info in the event. * @param event The event that will be filled with all integrations. */ function applyIntegrationsMetadata(event, integrationNames) { if (integrationNames.length > 0) { event.sdk = event.sdk || {}; event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames]; } } /** * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. * Normalized keys: * - `breadcrumbs.data` * - `user` * - `contexts` * - `extra` * @param event Event * @returns Normalized event */ function normalizeEvent(event, depth, maxBreadth) { if (!event) return null; const normalized = { ...event, ...event.breadcrumbs && { breadcrumbs: event.breadcrumbs.map((b) => ({ ...b, ...b.data && { data: normalize(b.data, depth, maxBreadth) } })) }, ...event.user && { user: normalize(event.user, depth, maxBreadth) }, ...event.contexts && { contexts: normalize(event.contexts, depth, maxBreadth) }, ...event.extra && { extra: normalize(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(event.contexts.trace.data, depth, maxBreadth); } if (event.spans) normalized.spans = event.spans.map((span) => { return { ...span, ...span.data && { data: normalize(span.data, depth, maxBreadth) } }; }); if (event.contexts && event.contexts.flags && normalized.contexts) normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth); return normalized; } function getFinalScope(scope, captureContext) { if (!captureContext) return scope; const finalScope = scope ? scope.clone() : new Scope(); finalScope.update(captureContext); return finalScope; } /** * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`. * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`. */ function parseEventHintOrCaptureContext(hint) { if (!hint) return; if (hintIsScopeOrFunction(hint)) return { captureContext: hint }; if (hintIsScopeContext(hint)) return { captureContext: hint }; return hint; } function hintIsScopeOrFunction(hint) { return hint instanceof Scope || typeof hint === "function"; } var captureContextKeys = [ "user", "level", "extra", "contexts", "tags", "fingerprint", "requestSession", "propagationContext" ]; function hintIsScopeContext(hint) { return Object.keys(hint).some((key) => captureContextKeys.includes(key)); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/exports.js /** * Captures an exception event and sends it to Sentry. * * @param exception The exception to capture. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured Sentry event. */ function captureException(exception, hint) { return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint)); } /** * Captures a message event and sends it to Sentry. * * @param message The message to send to Sentry. * @param captureContext Define the level of the message or pass in additional data to attach to the message. * @returns the id of the captured message. */ function captureMessage(message, captureContext) { const level = typeof captureContext === "string" ? captureContext : void 0; const context = typeof captureContext !== "string" ? { captureContext } : void 0; return getCurrentScope().captureMessage(message, level, context); } /** * Captures a manually created event and sends it to Sentry. * * @param event The event to send to Sentry. * @param hint Optional additional data to attach to the Sentry event. * @returns the id of the captured event. */ function captureEvent(event, hint) { return getCurrentScope().captureEvent(event, hint); } /** * Set key:value that will be sent as tags data with the event. * * Can also be used to unset a tag, by passing `undefined`. * * @param key String key of tag * @param value Value of tag */ function setTag(key, value) { getIsolationScope().setTag(key, value); } /** If the SDK is initialized & enabled. */ function isEnabled() { const client = getClient(); return !!client && client.getOptions().enabled !== false && !!client.getTransport(); } /** * Start a session on the current isolation scope. * * @param context (optional) additional properties to be applied to the returned session object * * @returns the new active session */ function startSession(context) { const client = getClient(); const isolationScope = getIsolationScope(); const currentScope = getCurrentScope(); const { release, environment = DEFAULT_ENVIRONMENT } = client && client.getOptions() || {}; const { userAgent } = GLOBAL_OBJ.navigator || {}; const session = makeSession({ 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; } /** * End the session on the current isolation scope. */ function endSession() { const isolationScope = getIsolationScope(); const currentScope = getCurrentScope(); const session = currentScope.getSession() || isolationScope.getSession(); if (session) closeSession(session); _sendSessionUpdate(); isolationScope.setSession(); currentScope.setSession(); } /** * Sends the current Session on the scope */ function _sendSessionUpdate() { const isolationScope = getIsolationScope(); const currentScope = getCurrentScope(); const client = getClient(); const session = currentScope.getSession() || isolationScope.getSession(); if (session && client) client.captureSession(session); } /** * Sends the current session on the scope to Sentry * * @param end If set the session will be marked as exited and removed from the scope. * Defaults to `false`. */ function captureSession(end = false) { if (end) { endSession(); return; } _sendSessionUpdate(); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/api.js var SENTRY_API_VERSION = "7"; /** Returns the prefix to construct Sentry ingestion API endpoints. */ function getBaseApiEndpoint(dsn) { const protocol = dsn.protocol ? `${dsn.protocol}:` : ""; const port = dsn.port ? `:${dsn.port}` : ""; return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`; } /** Returns the ingest API endpoint for target. */ function _getIngestEndpoint(dsn) { return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; } /** Returns a URL-encoded string with auth config suitable for a query string. */ function _encodedAuth(dsn, sdkInfo) { 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(); } /** * Returns the envelope endpoint URL with auth in the query string. * * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. */ function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) { return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/integration.js var installedIntegrations = []; /** Map of integrations assigned to a client */ /** * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to * preserve the order of integrations in the array. * * @private */ function filterDuplicates(integrations) { const integrationsByName = {}; integrations.forEach((currentInstance) => { const { name } = currentInstance; const existingInstance = integrationsByName[name]; if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) return; integrationsByName[name] = currentInstance; }); return Object.values(integrationsByName); } /** Gets integrations to install */ function getIntegrationsToSetup(options) { const defaultIntegrations = options.defaultIntegrations || []; const userIntegrations = options.integrations; 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; } /** * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default * integrations are added unless they were already provided before. * @param integrations array of integration instances * @param withDefault should enable default integrations */ function setupIntegrations(client, integrations) { const integrationIndex = {}; integrations.forEach((integration) => { if (integration) setupIntegration(client, integration, integrationIndex); }); return integrationIndex; } /** * Execute the `afterAllSetup` hooks of the given integrations. */ function afterSetupIntegrations(client, integrations) { for (const integration of integrations) if (integration && integration.afterAllSetup) integration.afterAllSetup(client); } /** Setup a single integration. */ function setupIntegration(client, integration, integrationIndex) { if (integrationIndex[integration.name]) { DEBUG_BUILD$4 && logger$1.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$4 && logger$1.log(`Integration installed: ${integration.name}`); } /** * Define an integration function that can be used to create an integration instance. * Note that this by design hides the implementation details of the integration, as they are considered internal. */ function defineIntegration(fn) { return fn; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/clientreport.js /** * Creates client report envelope * @param discarded_events An array of discard events * @param dsn A DSN that can be set on the header. Optional. */ function createClientReportEnvelope(discarded_events, dsn, timestamp) { const clientReportItem = [{ type: "client_report" }, { timestamp: timestamp || dateTimestampInSeconds(), discarded_events }]; return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/error.js /** An error emitted by Sentry SDKs and related utilities. */ var SentryError = class extends Error { constructor(message, logLevel = "warn") { super(message); this.message = message; this.logLevel = logLevel; } }; //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/baseclient.js var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; /** * Base implementation for all JavaScript SDK clients. * * Call the constructor with the corresponding options * specific to the client subclass. To access these options later, use * {@link Client.getOptions}. * * If a Dsn is specified in the options, it will be parsed and stored. Use * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is * invalid, the constructor will throw a {@link SentryException}. Note that * without a valid Dsn, the SDK will not send any events to Sentry. * * Before sending an event, it is passed through * {@link BaseClient._prepareEvent} to add SDK information and scope data * (breadcrumbs and context). To add more custom information, override this * method and extend the resulting prepared event. * * To issue automatically created events (e.g. via instrumentation), use * {@link Client.captureEvent}. It will prepare the event and pass it through * the callback lifecycle. To issue auto-breadcrumbs, use * {@link Client.addBreadcrumb}. * * @example * class NodeClient extends BaseClient { * public constructor(options: NodeOptions) { * super(options); * } * * // ... * } */ var BaseClient = class { /** 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 */ /** * Initializes this client instance. * * @param options Options for the client. */ constructor(options) { this._options = options; this._integrations = {}; this._numProcessing = 0; this._outcomes = {}; this._hooks = {}; this._eventProcessors = []; if (options.dsn) this._dsn = makeDsn(options.dsn); else DEBUG_BUILD$4 && logger$1.warn("No DSN provided, client will not send events."); if (this._dsn) { const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options.tunnel, options._metadata ? options._metadata.sdk : void 0); this._transport = options.transport({ tunnel: this._options.tunnel, recordDroppedEvent: this.recordDroppedEvent.bind(this), ...options.transportOptions, url }); } const undefinedOption = [ "enableTracing", "tracesSampleRate", "tracesSampler" ].find((option) => option in options && options[option] == 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$4 && logger$1.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(message, level, hint, currentScope) { const hintWithEventId = { event_id: uuid4(), ...hint }; const eventMessage = isParameterizedString(message) ? message : String(message); const promisedEvent = isPrimitive(message) ? this.eventFromMessage(eventMessage, level, hintWithEventId) : this.eventFromException(message, 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$4 && logger$1.log(ALREADY_SEEN_ERROR); return eventId; } const hintWithEventId = { event_id: eventId, ...hint }; const capturedSpanScope = (event.sdkProcessingMetadata || {}).capturedSpanScope; this._process(this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope)); return hintWithEventId.event_id; } /** * @inheritDoc */ captureSession(session) { if (!(typeof session.release === "string")) DEBUG_BUILD$4 && logger$1.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() || this._options.integrations.some(({ name }) => name.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$4 && logger$1.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ""}`); this._outcomes[key] = (this._outcomes[key] || 0) + count; } } /** @inheritdoc */ /** @inheritdoc */ on(hook, callback) { const hooks = this._hooks[hook] = this._hooks[hook] || []; hooks.push(callback); return () => { const cbIndex = hooks.indexOf(callback); if (cbIndex > -1) hooks.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$4 && logger$1.error("Error while sending envelope:", reason); return reason; }); DEBUG_BUILD$4 && logger$1.error("Transport disabled"); return resolvedSyncPromise({}); } /** 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 = event.level === "fatal"; 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"; if (sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed) { 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((resolve) => { let ticked = 0; const tick = 1; const interval = setInterval(() => { if (this._numProcessing == 0) { clearInterval(interval); resolve(true); } else { ticked += tick; if (timeout && ticked >= timeout) { clearInterval(interval); resolve(false); } } }, tick); }); } /** Determines whether this SDK is enabled and a 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(), isolationScope = getIsolationScope()) { const options = 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(options, event, hint, currentScope, this, isolationScope).then((evt) => { if (evt === null) return evt; evt.contexts = { trace: getTraceContextFromScope(currentScope), ...evt.contexts }; evt.sdkProcessingMetadata = { dynamicSamplingContext: getDynamicSamplingContextFromScope(this, currentScope), ...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$4) if (reason instanceof SentryError && reason.logLevel === "log") logger$1.log(reason.message); else logger$1.warn(reason); }); } /** * 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 options = this.getOptions(); const { sampleRate } = options; const isTransaction = isTransactionEvent(event); const isError = isErrorEvent(event); const eventType = event.type || "error"; const beforeSendLabel = `before send for type \`${eventType}\``; const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : parseSampleRate(sampleRate); if (isError && 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 capturedSpanIsolationScope = (event.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"); } if (hint.data && hint.data.__sentry__ === true) return prepared; return _validateBeforeSendResult(processBeforeSend(this, options, prepared, hint), beforeSendLabel); }).then((processedEvent) => { if (processedEvent === null) { this.recordDroppedEvent("before_send", dataCategory, event); if (isTransaction) { const spanCount = 1 + (event.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 droppedSpanCount = (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing || 0) - (processedEvent.spans ? processedEvent.spans.length : 0); 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.\nReason: ${reason}`); }); } /** * Occupies the client with processing and event */ _process(promise) { this._numProcessing++; promise.then((value) => { this._numProcessing--; return value; }, (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$4 && logger$1.log("Flushing outcomes..."); const outcomes = this._clearOutcomes(); if (outcomes.length === 0) { DEBUG_BUILD$4 && logger$1.log("No outcomes to send"); return; } if (!this._dsn) { DEBUG_BUILD$4 && logger$1.log("No dsn provided, will not send outcomes"); return; } DEBUG_BUILD$4 && logger$1.log("Sending outcomes:", outcomes); const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn)); this.sendEnvelope(envelope); } }; /** * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. */ function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) { const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`; if (isThenable(beforeSendResult)) return beforeSendResult.then((event) => { if (!isPlainObject$2(event) && event !== null) throw new SentryError(invalidValueError); return event; }, (e) => { throw new SentryError(`${beforeSendLabel} rejected with ${e}`); }); else if (!isPlainObject$2(beforeSendResult) && beforeSendResult !== null) throw new SentryError(invalidValueError); return beforeSendResult; } /** * Process the matching `beforeSendXXX` callback. */ function processBeforeSend(client, options, event, hint) { const { beforeSend, beforeSendTransaction, beforeSendSpan } = options; if (isErrorEvent(event) && beforeSend) return beforeSend(event, hint); if (isTransactionEvent(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; } function isErrorEvent(event) { return event.type === void 0; } function isTransactionEvent(event) { return event.type === "transaction"; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/sdk.js /** A class object that can instantiate Client objects. */ /** * Internal function to create a new SDK client instance. The client is * installed and then bound to the current scope. * * @param clientClass The client class to instantiate. * @param options Options to pass to the client. */ function initAndBind(clientClass, options) { if (options.debug === true) if (DEBUG_BUILD$4) logger$1.enable(); else consoleSandbox(() => { console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle."); }); getCurrentScope().update(options.initialScope); const client = new clientClass(options); setCurrentClient(client); client.init(); return client; } /** * Make the given client the current client. */ function setCurrentClient(client) { getCurrentScope().setClient(client); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/promisebuffer.js /** * Creates an new PromiseBuffer object with the specified limit * @param limit max number of promises that can be stored in the buffer */ function makePromiseBuffer(limit) { const buffer = []; function isReady() { return limit === void 0 || buffer.length < limit; } /** * Remove a promise from the queue. * * @param task Can be any PromiseLike * @returns Removed promise. */ function remove(task) { return buffer.splice(buffer.indexOf(task), 1)[0] || Promise.resolve(void 0); } /** * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. * * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task: * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer * limit check. * @returns The original promise. */ function add(taskProducer) { if (!isReady()) return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached.")); const task = taskProducer(); if (buffer.indexOf(task) === -1) buffer.push(task); task.then(() => remove(task)).then(null, () => remove(task).then(null, () => {})); return task; } /** * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. * * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to * `true`. * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and * `false` otherwise */ function drain(timeout) { return new SyncPromise((resolve, reject) => { let counter = buffer.length; if (!counter) return resolve(true); const capturedSetTimeout = setTimeout(() => { if (timeout && timeout > 0) resolve(false); }, timeout); buffer.forEach((item) => { resolvedSyncPromise(item).then(() => { if (!--counter) { clearTimeout(capturedSetTimeout); resolve(true); } }, reject); }); }); } return { $: buffer, add, drain }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/ratelimit.js var DEFAULT_RETRY_AFTER = 60 * 1e3; /** * Extracts Retry-After value from the request header or returns default value * @param header string representation of 'Retry-After' header * @param now current unix timestamp * */ function parseRetryAfterHeader(header, now = Date.now()) { const headerDelay = parseInt(`${header}`, 10); if (!isNaN(headerDelay)) return headerDelay * 1e3; const headerDate = Date.parse(`${header}`); if (!isNaN(headerDate)) return headerDate - now; return DEFAULT_RETRY_AFTER; } /** * Gets the time that the given category is disabled until for rate limiting. * In case no category-specific limit is set but a general rate limit across all categories is active, * that time is returned. * * @return the time in ms that the category is disabled until or 0 if there's no active rate limit. */ function disabledUntil(limits, dataCategory) { return limits[dataCategory] || limits.all || 0; } /** * Checks if a category is rate limited */ function isRateLimited(limits, dataCategory, now = Date.now()) { return disabledUntil(limits, dataCategory) > now; } /** * Update ratelimits from incoming headers. * * @return the updated RateLimits object. */ function updateRateLimits(limits, { statusCode, headers }, now = Date.now()) { const updatedRateLimits = { ...limits }; const rateLimitHeader = headers && headers["x-sentry-rate-limits"]; const retryAfterHeader = headers && headers["retry-after"]; if (rateLimitHeader) /** * rate limit headers are of the form *
,
,.. * where each
is of the form * : : : : * where * is a delay in seconds * is the event type(s) (error, transaction, etc) being rate limited and is of the form * ;;... * is what's being limited (org, project, or key) - ignored by SDK * is an arbitrary string like "org_quota" - ignored by SDK * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected. * Only present if rate limit applies to the metric_bucket data category. */ 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 = now + delay; else for (const category of categories.split(";")) if (category === "metric_bucket") { if (!namespaces || namespaces.split(";").includes("custom")) updatedRateLimits[category] = now + delay; } else updatedRateLimits[category] = now + delay; } else if (retryAfterHeader) updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); else if (statusCode === 429) updatedRateLimits.all = now + 60 * 1e3; return updatedRateLimits; } /** * Creates an instance of a Sentry `Transport` * * @param options * @param makeRequest */ function createTransport(options, makeRequest, buffer = makePromiseBuffer(options.bufferSize || 64)) { let rateLimits = {}; const flush = (timeout) => buffer.drain(timeout); function send(envelope) { const filteredEnvelopeItems = []; forEachEnvelopeItem(envelope, (item, type) => { const dataCategory = envelopeItemTypeToDataCategory(type); if (isRateLimited(rateLimits, dataCategory)) { const event = getEventForEnvelopeItem(item, type); options.recordDroppedEvent("ratelimit_backoff", dataCategory, event); } else filteredEnvelopeItems.push(item); }); if (filteredEnvelopeItems.length === 0) return resolvedSyncPromise({}); const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems); const recordEnvelopeLoss = (reason) => { forEachEnvelopeItem(filteredEnvelope, (item, type) => { const event = getEventForEnvelopeItem(item, type); options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event); }); }; const requestTask = () => makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then((response) => { if (response.statusCode !== void 0 && (response.statusCode < 200 || response.statusCode >= 300)) DEBUG_BUILD$4 && logger$1.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); rateLimits = updateRateLimits(rateLimits, response); return response; }, (error) => { recordEnvelopeLoss("network_error"); throw error; }); return buffer.add(requestTask).then((result) => result, (error) => { if (error instanceof SentryError) { DEBUG_BUILD$4 && logger$1.error("Skipped sending event because buffer is full."); recordEnvelopeLoss("queue_overflow"); return resolvedSyncPromise({}); } else throw error; }); } return { send, flush }; } function getEventForEnvelopeItem(item, type) { if (type !== "event" && type !== "transaction") return; return Array.isArray(item) ? item[1] : void 0; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/sdkMetadata.js /** * A builder for the SDK metadata in the options for the SDK initialization. * * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit. * We don't extract it for bundle size reasons. * @see https://github.com/getsentry/sentry-javascript/pull/7404 * @see https://github.com/getsentry/sentry-javascript/pull/4196 * * If you make changes to this function consider updating the others as well. * * @param options SDK options object that gets mutated * @param names list of package names */ function applySdkMetadata(options, name, names = [name], source = "npm") { const metadata = options._metadata || {}; if (!metadata.sdk) metadata.sdk = { name: `sentry.javascript.${name}`, packages: names.map((name) => ({ name: `${source}:@sentry/${name}`, version: SDK_VERSION })), version: SDK_VERSION }; options._metadata = metadata; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils/traceData.js /** * Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation * context) and serializes it to `sentry-trace` and `baggage` values to strings. These values can be used to propagate * a trace via our tracing Http headers or Html `` tags. * * This function also applies some validation to the generated sentry-trace and baggage values to ensure that * only valid strings are returned. * * @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header * or meta tag name. */ function getTraceData(options = {}) { const client = getClient(); if (!isEnabled() || !client) return {}; const acs = getAsyncContextStrategy(getMainCarrier()); if (acs.getTraceData) return acs.getTraceData(options); const scope = getCurrentScope(); const span = options.span || getActiveSpan(); const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope); const baggage = dynamicSamplingContextToSentryBaggageHeader(span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope)); if (!TRACEPARENT_REGEXP.test(sentryTrace)) { logger$1.warn("Invalid sentry-trace data. Cannot generate trace data"); return {}; } return { "sentry-trace": sentryTrace, baggage }; } /** * Get a sentry-trace header value for the given scope. */ function scopeToTraceHeader(scope) { const { traceId, sampled, spanId } = scope.getPropagationContext(); return generateSentryTraceHeader(traceId, spanId, sampled); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/breadcrumbs.js /** * Default maximum number of breadcrumbs added to an event. Can be overwritten * with {@link Options.maxBreadcrumbs}. */ var DEFAULT_BREADCRUMBS = 100; /** * Records a new breadcrumb which will be attached to future events. * * Breadcrumbs will be added to subsequent events to provide more context on * user's actions prior to an error or crash. */ 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 mergedBreadcrumb = { timestamp: dateTimestampInSeconds(), ...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); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/integrations/functiontostring.js var originalFunctionToString; var INTEGRATION_NAME$8 = "FunctionToString"; var SETUP_CLIENTS = /* @__PURE__ */ new WeakMap(); var _functionToStringIntegration = (() => { return { name: INTEGRATION_NAME$8, setupOnce() { originalFunctionToString = Function.prototype.toString; try { Function.prototype.toString = function(...args) { const originalFunction = getOriginalFunction(this); const context = SETUP_CLIENTS.has(getClient()) && originalFunction !== void 0 ? originalFunction : this; return originalFunctionToString.apply(context, args); }; } catch (e) {} }, setup(client) { SETUP_CLIENTS.set(client, true); } }; }); /** * Patch toString calls to return proper name for wrapped functions. * * ```js * Sentry.init({ * integrations: [ * functionToStringIntegration(), * ], * }); * ``` */ var functionToStringIntegration = defineIntegration(_functionToStringIntegration); //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/integrations/inboundfilters.js var DEFAULT_IGNORE_ERRORS = [ /^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/, /^ResizeObserver loop completed with undelivered notifications.$/, /^Cannot redefine property: googletag$/, /^Can't find variable: gmo$/, "undefined is not an object (evaluating 'a.L')", "can't redefine non-configurable property \"solana\"", "vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)", "Can't find variable: _AutofillCallbackHandler", /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/, /^Java exception was raised during method invocation$/ ]; /** Options for the InboundFilters integration */ var INTEGRATION_NAME$7 = "InboundFilters"; var _inboundFiltersIntegration = ((options = {}) => { return { name: INTEGRATION_NAME$7, processEvent(event, _hint, client) { return _shouldDropEvent$1(event, _mergeOptions(options, client.getOptions())) ? null : event; } }; }); var 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 }; } function _shouldDropEvent$1(event, options) { if (options.ignoreInternal && _isSentryError(event)) { DEBUG_BUILD$4 && logger$1.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${getEventDescription(event)}`); return true; } if (_isIgnoredError(event, options.ignoreErrors)) { DEBUG_BUILD$4 && logger$1.warn(`Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${getEventDescription(event)}`); return true; } if (_isUselessError(event)) { DEBUG_BUILD$4 && logger$1.warn(`Event dropped due to not having an error message, error type or stacktrace.\nEvent: ${getEventDescription(event)}`); return true; } if (_isIgnoredTransaction(event, options.ignoreTransactions)) { DEBUG_BUILD$4 && logger$1.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${getEventDescription(event)}`); return true; } if (_isDeniedUrl(event, options.denyUrls)) { DEBUG_BUILD$4 && logger$1.warn(`Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${getEventDescription(event)}.\nUrl: ${_getEventFilterUrl(event)}`); return true; } if (!_isAllowedUrl(event, options.allowUrls)) { DEBUG_BUILD$4 && logger$1.warn(`Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${getEventDescription(event)}.\nUrl: ${_getEventFilterUrl(event)}`); return true; } return false; } function _isIgnoredError(event, ignoreErrors) { if (event.type || !ignoreErrors || !ignoreErrors.length) return false; return _getPossibleEventMessages(event).some((message) => stringMatchesSomePattern(message, ignoreErrors)); } function _isIgnoredTransaction(event, ignoreTransactions) { if (event.type !== "transaction" || !ignoreTransactions || !ignoreTransactions.length) return false; const name = event.transaction; return name ? stringMatchesSomePattern(name, ignoreTransactions) : false; } function _isDeniedUrl(event, denyUrls) { if (!denyUrls || !denyUrls.length) return false; const url = _getEventFilterUrl(event); return !url ? false : stringMatchesSomePattern(url, denyUrls); } function _isAllowedUrl(event, allowUrls) { if (!allowUrls || !allowUrls.length) return true; const url = _getEventFilterUrl(event); return !url ? true : stringMatchesSomePattern(url, allowUrls); } 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 (e) {} if (lastException) { if (lastException.value) { possibleMessages.push(lastException.value); if (lastException.type) possibleMessages.push(`${lastException.type}: ${lastException.value}`); } } return possibleMessages; } function _isSentryError(event) { try { return event.exception.values[0].type === "SentryError"; } catch (e) {} return false; } function _getLastValidUrl(frames = []) { for (let i = frames.length - 1; i >= 0; i--) { const frame = frames[i]; if (frame && frame.filename !== "" && frame.filename !== "[native code]") return frame.filename || null; } return null; } function _getEventFilterUrl(event) { try { let frames; try { frames = event.exception.values[0].stacktrace.frames; } catch (e) {} return frames ? _getLastValidUrl(frames) : null; } catch (oO) { DEBUG_BUILD$4 && logger$1.error(`Cannot extract url for event ${getEventDescription(event)}`); return null; } } function _isUselessError(event) { if (event.type) return false; if (!event.exception || !event.exception.values || event.exception.values.length === 0) return false; return !event.message && !event.exception.values.some((value) => value.stacktrace || value.type && value.type !== "Error" || value.value); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/aggregate-errors.js /** * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter. */ 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); } function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error, key, prevExceptions, exception, exceptionId) { if (prevExceptions.length >= limit + 1) return prevExceptions; let newExceptions = [...prevExceptions]; if (isInstanceOf(error[key], Error)) { applyExceptionGroupFieldsForParentException(exception, exceptionId); const newException = exceptionFromErrorImplementation(parser, error[key]); const newExceptionId = newExceptions.length; applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId); newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error[key], key, [newException, ...newExceptions], newException, newExceptionId); } if (Array.isArray(error.errors)) error.errors.forEach((childError, i) => { if (isInstanceOf(childError, Error)) { applyExceptionGroupFieldsForParentException(exception, exceptionId); const newException = exceptionFromErrorImplementation(parser, childError); const newExceptionId = newExceptions.length; applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId); newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, childError, key, [newException, ...newExceptions], newException, newExceptionId); } }); return newExceptions; } 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 }; } 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 }; } /** * Truncate the message (exception.value) of all exceptions in the event. * Because this event processor is ran after `applyClientOptions`, * we need to truncate the message of the added exceptions here. */ function truncateAggregateExceptions(exceptions, maxValueLength) { return exceptions.map((exception) => { if (exception.value) exception.value = truncate(exception.value, maxValueLength); return exception; }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/url.js /** * Parses string form of URL into an object * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B * // intentionally using regex and not href parsing trick because React Native and other * // environments where DOM might not be available * @returns parsed URL object */ function parseUrl$1(url) { if (!url) return {}; const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); if (!match) return {}; const query = match[6] || ""; const fragment = match[8] || ""; return { host: match[4], path: match[5], protocol: match[2], search: query, hash: fragment, relative: match[5] + query + fragment }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/instrument/console.js /** * Add an instrumentation handler for when a console.xxx method is called. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addConsoleInstrumentationHandler(handler) { const type = "console"; addHandler$1(type, handler); maybeInstrument(type, instrumentConsole); } function instrumentConsole() { if (!("console" in GLOBAL_OBJ)) return; CONSOLE_LEVELS.forEach(function(level) { if (!(level in GLOBAL_OBJ.console)) return; fill(GLOBAL_OBJ.console, level, function(originalConsoleMethod) { originalConsoleMethods[level] = originalConsoleMethod; return function(...args) { triggerHandlers$1("console", { args, level }); const log = originalConsoleMethods[level]; log && log.apply(GLOBAL_OBJ.console, args); }; }); }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/severity.js /** * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. * * @param level String representation of desired `SeverityLevel`. * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. */ function severityLevelFromString(level) { return level === "warn" ? "warning" : [ "fatal", "error", "warning", "log", "info", "debug" ].includes(level) ? level : "log"; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/integrations/captureconsole.js var INTEGRATION_NAME$6 = "CaptureConsole"; var _captureConsoleIntegration = ((options = {}) => { const levels = options.levels || CONSOLE_LEVELS; const handled = !!options.handled; return { name: INTEGRATION_NAME$6, setup(client) { if (!("console" in GLOBAL_OBJ)) return; addConsoleInstrumentationHandler(({ args, level }) => { if (getClient() !== client || !levels.includes(level)) return; consoleHandler(args, level, handled); }); } }; }); /** * Send Console API calls as Sentry Events. */ var 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 message = `Assertion failed: ${safeJoin(args.slice(1), " ") || "console.assert"}`; scope.setExtra("arguments", args.slice(1)); captureMessage(message, captureContext); } return; } const error = args.find((arg) => arg instanceof Error); if (error) { captureException(error, captureContext); return; } captureMessage(safeJoin(args, " "), captureContext); }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/integrations/dedupe.js var INTEGRATION_NAME$5 = "Dedupe"; var _dedupeIntegration = (() => { let previousEvent; return { name: INTEGRATION_NAME$5, processEvent(currentEvent) { if (currentEvent.type) return currentEvent; try { if (_shouldDropEvent(currentEvent, previousEvent)) { DEBUG_BUILD$4 && logger$1.warn("Event dropped due to being a duplicate of previously captured event."); return null; } } catch (_oO) {} return previousEvent = currentEvent; } }; }); /** * Deduplication filter. */ var dedupeIntegration = defineIntegration(_dedupeIntegration); /** only exported for tests. */ function _shouldDropEvent(currentEvent, previousEvent) { if (!previousEvent) return false; if (_isSameMessageEvent(currentEvent, previousEvent)) return true; if (_isSameExceptionEvent(currentEvent, previousEvent)) return true; return false; } 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; } 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; } 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 i = 0; i < previousFrames.length; i++) { const frameA = previousFrames[i]; const frameB = currentFrames[i]; if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) return false; } return true; } 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; } } function _getExceptionFromEvent(event) { return event.exception && event.exception.values && event.exception.values[0]; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/fetch.js /** * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`. * * @returns Span if a span was created, otherwise void. */ function instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeaders, spans, spanOrigin = "auto.http.browser") { if (!handlerData.fetchData) return; const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(handlerData.fetchData.url); if (handlerData.endTimestamp && shouldCreateSpanResult) { const spanId = handlerData.fetchData.__span; if (!spanId) return; const span = spans[spanId]; if (span) { endSpan(span, handlerData); delete spans[spanId]; } return; } 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 (shouldAttachHeaders(handlerData.fetchData.url)) { const request = handlerData.args[0]; const options = handlerData.args[1] || {}; const headers = _addTracingHeadersToFetchRequest(request, options, hasTracingEnabled() && hasParent ? span : void 0); if (headers) { handlerData.args[1] = options; options.headers = headers; } } return span; } /** * Adds sentry-trace and baggage headers to the various forms of fetch headers. */ function _addTracingHeadersToFetchRequest(request, fetchOptionsObj, span) { const traceHeaders = getTraceData({ span }); const sentryTrace = traceHeaders["sentry-trace"]; const baggage = traceHeaders.baggage; if (!sentryTrace) return; const headers = fetchOptionsObj.headers || (isRequest(request) ? request.headers : void 0); if (!headers) return { ...traceHeaders }; else if (isHeaders(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", prevHeaderStrippedFromSentryBaggage ? `${prevHeaderStrippedFromSentryBaggage},${baggage}` : baggage); } else newHeaders.set("baggage", baggage); } return newHeaders; } else if (Array.isArray(headers)) { const newHeaders = [...headers.filter((header) => { return !(Array.isArray(header) && header[0] === "sentry-trace"); }).map((header) => { if (Array.isArray(header) && header[0] === "baggage" && typeof header[1] === "string") { const [headerName, headerValue, ...rest] = header; return [ headerName, stripBaggageHeaderOfSentryBaggageValues(headerValue), ...rest ]; } else return 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 }; } } function getFullURL$1(url) { try { return new URL(url).href; } catch (e) { return; } } 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: 2, message: "internal_error" }); span.end(); } function stripBaggageHeaderOfSentryBaggageValues(baggageHeader) { return baggageHeader.split(",").filter((baggageEntry) => !baggageEntry.split("=")[0].startsWith(SENTRY_BAGGAGE_KEY_PREFIX)).join(","); } function isRequest(request) { return typeof Request !== "undefined" && isInstanceOf(request, Request); } function isHeaders(headers) { return typeof Headers !== "undefined" && isInstanceOf(headers, Headers); } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/breadcrumb-log-level.js /** * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code. */ function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) { if (statusCode === void 0) return; else if (statusCode >= 400 && statusCode < 500) return "warning"; else if (statusCode >= 500) return "error"; else return; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/supports.js var WINDOW$3 = GLOBAL_OBJ; /** * Tells whether current environment supports Fetch API * {@link supportsFetch}. * * @returns Answer to the given question. */ function supportsFetch() { if (!("fetch" in WINDOW$3)) return false; try { new Headers(); new Request("http://www.example.com"); new Response(); return true; } catch (e) { return false; } } /** * isNative checks if the given function is a native implementation */ function isNativeFunction(func) { return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); } /** * Tells whether current environment supports Fetch API natively * {@link supportsNativeFetch}. * * @returns true if `window.fetch` is natively implemented, false otherwise */ function supportsNativeFetch() { if (typeof EdgeRuntime === "string") return true; if (!supportsFetch()) return false; if (isNativeFunction(WINDOW$3.fetch)) return true; let result = false; const doc = WINDOW$3.document; if (doc && typeof doc.createElement === "function") try { const sandbox = doc.createElement("iframe"); sandbox.hidden = true; doc.head.appendChild(sandbox); if (sandbox.contentWindow && sandbox.contentWindow.fetch) result = isNativeFunction(sandbox.contentWindow.fetch); doc.head.removeChild(sandbox); } catch (err) { DEBUG_BUILD$3 && logger$1.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err); } return result; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/instrument/fetch.js /** * Add an instrumentation handler for when a fetch request happens. * The handler function is called once when the request starts and once when it ends, * which can be identified by checking if it has an `endTimestamp`. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addFetchInstrumentationHandler(handler, skipNativeFetchCheck) { const type = "fetch"; addHandler$1(type, handler); maybeInstrument(type, () => instrumentFetch(void 0, skipNativeFetchCheck)); } /** * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch. * The handler will resolve the request body and emit the actual `endTimestamp`, so that the * span can be updated accordingly. * * Only used internally * @hidden */ function addFetchEndInstrumentationHandler(handler) { const type = "fetch-body-resolved"; addHandler$1(type, handler); maybeInstrument(type, () => instrumentFetch(streamHandler)); } function instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) { if (skipNativeFetchCheck && !supportsNativeFetch()) return; fill(GLOBAL_OBJ, "fetch", function(originalFetch) { return function(...args) { const virtualError = /* @__PURE__ */ new Error(); const { method, url } = parseFetchArgs(args); const handlerData = { args, fetchData: { method, url }, startTimestamp: timestampInSeconds() * 1e3, 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; }, (error) => { triggerHandlers$1("fetch", { ...handlerData, endTimestamp: timestampInSeconds() * 1e3, error }); if (isError(error) && error.stack === void 0) { error.stack = virtualError.stack; addNonEnumerableProperty(error, "framesToPop", 1); } throw error; }); }; }); } 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); 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 (error) { readingActive = false; } finally { clearTimeout(chunkTimeout); } } clearTimeout(maxFetchDurationTimeout); responseReader.releaseLock(); body.cancel().then(null, () => {}); } } function streamHandler(response) { let clonedResponseForResolving; try { clonedResponseForResolving = response.clone(); } catch (e) { return; } resolveResponse(clonedResponseForResolving, () => { triggerHandlers$1("fetch-body-resolved", { endTimestamp: timestampInSeconds() * 1e3, response }); }); } function hasProp(obj, prop) { return !!obj && typeof obj === "object" && !!obj[prop]; } 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 ""; } /** * Parses the fetch arguments to find the used Http method and the url of the request. * Exported for tests only. */ function parseFetchArgs(fetchArgs) { if (fetchArgs.length === 0) return { method: "GET", url: "" }; if (fetchArgs.length === 2) { const [url, options] = fetchArgs; return { url: getUrlFromResource(url), method: hasProp(options, "method") ? String(options.method).toUpperCase() : "GET" }; } const arg = fetchArgs[0]; return { url: getUrlFromResource(arg), method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET" }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/env.js /** * Get source of SDK. */ function getSDKSource() { return "npm"; } //#endregion //#region ../../node_modules/.pnpm/@sentry+core@8.55.2/node_modules/@sentry/core/build/esm/utils-hoist/vendor/supportsHistory.js var WINDOW$2 = GLOBAL_OBJ; /** * Tells whether current environment supports History API * {@link supportsHistory}. * * @returns Answer to the given question. */ function supportsHistory() { const chromeVar = WINDOW$2.chrome; const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime; const hasHistoryApi = "history" in WINDOW$2 && !!WINDOW$2.history.pushState && !!WINDOW$2.history.replaceState; return !isChromePackagedApp && hasHistoryApi; } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/helpers.js var WINDOW$1 = GLOBAL_OBJ; var ignoreOnError = 0; /** * @hidden */ function shouldIgnoreOnError() { return ignoreOnError > 0; } /** * @hidden */ function ignoreNextOnError() { ignoreOnError++; setTimeout(() => { ignoreOnError--; }); } /** * Instruments the given function and sends an event to Sentry every time the * function throws an exception. * * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always * has a correct `this` context. * @returns The wrapped function. * @hidden */ function wrap(fn, options = {}) { function isFunction(fn) { return typeof fn === "function"; } if (!isFunction(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 (e) { return fn; } const sentryWrapped = function(...args) { try { const wrappedArguments = args.map((arg) => wrap(arg, options)); return fn.apply(this, wrappedArguments); } catch (ex) { ignoreNextOnError(); withScope((scope) => { scope.addEventProcessor((event) => { if (options.mechanism) { addExceptionTypeValue(event, void 0, void 0); addExceptionMechanism(event, options.mechanism); } event.extra = { ...event.extra, arguments: args }; return event; }); captureException(ex); }); throw ex; } }; 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 { if (Object.getOwnPropertyDescriptor(sentryWrapped, "name").configurable) Object.defineProperty(sentryWrapped, "name", { get() { return fn.name; } }); } catch (e3) {} return sentryWrapped; } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/debug-build.js /** * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ var DEBUG_BUILD$2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/eventbuilder.js /** * This function creates an exception from a JavaScript Error */ 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; } 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; } function eventFromError(stackParser, ex) { return { exception: { values: [exceptionFromError(stackParser, ex)] } }; } /** Parses stack frames from an error */ 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 (e) {} return []; } var reactMinifiedRegexp = /Minified React error #\d+;/i; /** * Certain known React errors contain links that would be falsely * parsed as frames. This function check for these errors and * returns number of the stack string lines to skip. */ function getSkipFirstStackStringLines(ex) { if (ex && reactMinifiedRegexp.test(ex.message)) return 1; return 0; } /** * If error has `framesToPop` property, it means that the * creator tells us the first x frames will be useless * and should be discarded. Typically error from wrapper function * which don't point to the actual location in the developer's code. * * Example: https://github.com/zertosh/invariant/blob/master/invariant.js#L46 */ function getPopFirstTopFrames(ex) { if (typeof ex.framesToPop === "number") return ex.framesToPop; return 0; } function isWebAssemblyException(exception) { if (typeof WebAssembly !== "undefined" && typeof WebAssembly.Exception !== "undefined") return exception instanceof WebAssembly.Exception; else return false; } /** * Extracts from errors what we use as the exception `type` in error events. * * Usually, this is the `name` property on Error objects but WASM errors need to be treated differently. */ function extractType(ex) { const name = ex && ex.name; if (!name && isWebAssemblyException(ex)) return ex.message && Array.isArray(ex.message) && ex.message.length == 2 ? ex.message[0] : "WebAssembly.Exception"; return name; } /** * There are cases where stacktrace.message is an Event object * https://github.com/getsentry/sentry-javascript/issues/1949 * In this specific case we try to extract stacktrace.message.error.message */ function extractMessage(ex) { const message = ex && ex.message; if (!message) return "No error message"; if (message.error && typeof message.error.message === "string") return message.error.message; if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) return ex.message[1]; return message; } /** * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`. * @hidden */ function eventFromException(stackParser, exception, hint, attachStacktrace) { const event = eventFromUnknownInput(stackParser, exception, hint && hint.syntheticException || void 0, attachStacktrace); addExceptionMechanism(event); event.level = "error"; if (hint && hint.event_id) event.event_id = hint.event_id; return resolvedSyncPromise(event); } /** * Builds and Event from a Message * @hidden */ function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) { const event = eventFromString(stackParser, message, hint && hint.syntheticException || void 0, attachStacktrace); event.level = level; if (hint && hint.event_id) event.event_id = hint.event_id; return resolvedSyncPromise(event); } /** * @hidden */ function eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace, isUnhandledRejection) { let event; if (isErrorEvent$1(exception) && exception.error) return eventFromError(stackParser, exception.error); if (isDOMError(exception) || isDOMException(exception)) { const domException = exception; if ("stack" in exception) event = eventFromError(stackParser, exception); else { const name = domException.name || (isDOMError(domException) ? "DOMError" : "DOMException"); const message = domException.message ? `${name}: ${domException.message}` : name; event = eventFromString(stackParser, message, syntheticException, attachStacktrace); addExceptionTypeValue(event, message); } if ("code" in domException) event.tags = { ...event.tags, "DOMException.code": `${domException.code}` }; return event; } if (isError(exception)) return eventFromError(stackParser, exception); if (isPlainObject$2(exception) || isEvent(exception)) { event = eventFromPlainObject(stackParser, exception, 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; } function eventFromString(stackParser, message, syntheticException, attachStacktrace) { const event = {}; if (attachStacktrace && syntheticException) { const frames = parseStackFrames(stackParser, syntheticException); if (frames.length) event.exception = { values: [{ value: message, stacktrace: { frames } }] }; addExceptionMechanism(event, { synthetic: true }); } if (isParameterizedString(message)) { const { __sentry_template_string__, __sentry_template_values__ } = message; event.logentry = { message: __sentry_template_string__, params: __sentry_template_values__ }; return event; } event.message = message; return event; } function getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) { const keys = extractExceptionKeysForMessage(exception); const captureType = isUnhandledRejection ? "promise rejection" : "exception"; if (isErrorEvent$1(exception)) return `Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``; if (isEvent(exception)) return `Event \`${getObjectClassName(exception)}\` (type=${exception.type}) captured as ${captureType}`; return `Object captured as ${captureType} with keys: ${keys}`; } function getObjectClassName(obj) { try { const prototype = Object.getPrototypeOf(obj); return prototype ? prototype.constructor.name : void 0; } catch (e) {} } /** If a plain object has a property that is an `Error`, return this error. */ function getErrorPropertyFromObject(obj) { for (const prop in obj) if (Object.prototype.hasOwnProperty.call(obj, prop)) { const value = obj[prop]; if (value instanceof Error) return value; } } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/userfeedback.js /** * Creates an envelope from a user feedback. */ function createUserFeedbackEnvelope(feedback, { metadata, tunnel, dsn }) { return createEnvelope({ 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) } }, [createUserFeedbackEnvelopeItem(feedback)]); } function createUserFeedbackEnvelopeItem(feedback) { return [{ type: "user_report" }, feedback]; } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/client.js /** * Configuration options for the Sentry Browser SDK. * @see @sentry/core Options for more information. */ /** * The Sentry Browser SDK Client. * * @see BrowserOptions for documentation on configuration options. * @see SentryClient for usage documentation. */ var BrowserClient = class extends BaseClient { /** * Creates a new Browser SDK instance. * * @param options Configuration options for this SDK. */ constructor(options) { const opts = { parentSpanIsAlwaysRootSpan: true, ...options }; applySdkMetadata(opts, "browser", ["browser"], WINDOW$1.SENTRY_SDK_SOURCE || getSDKSource()); super(opts); if (opts.sendClientReports && WINDOW$1.document) WINDOW$1.document.addEventListener("visibilitychange", () => { if (WINDOW$1.document.visibilityState === "hidden") this._flushOutcomes(); }); } /** * @inheritDoc */ eventFromException(exception, hint) { return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace); } /** * @inheritDoc */ eventFromMessage(message, level = "info", hint) { return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace); } /** * Sends user feedback to Sentry. * * @deprecated Use `captureFeedback` instead. */ captureUserFeedback(feedback) { if (!this._isEnabled()) { DEBUG_BUILD$2 && logger$1.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); } }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js /** * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ var DEBUG_BUILD$1 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/bindReporter.js var getRating = (value, thresholds) => { if (value > thresholds[1]) return "poor"; if (value > thresholds[0]) return "needs-improvement"; return "good"; }; var bindReporter = (callback, metric, thresholds, reportAllChanges) => { let prevValue; let delta; return (forceReport) => { if (metric.value >= 0) { if (forceReport || reportAllChanges) { delta = metric.value - (prevValue || 0); if (delta || prevValue === void 0) { prevValue = metric.value; metric.delta = delta; metric.rating = getRating(metric.value, thresholds); callback(metric); } } } }; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/types.js var WINDOW = GLOBAL_OBJ; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/generateUniqueID.js /** * Performantly generate a unique, 30-char string by combining a version * number, the current timestamp with a 13-digit number integer. * @return {string} */ var generateUniqueID = () => { return `v4-${Date.now()}-${Math.floor(Math.random() * 8999999999999) + 0xe8d4a51000}`; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getNavigationEntry.js var getNavigationEntry = (checkResponseStart = true) => { const navigationEntry = WINDOW.performance && WINDOW.performance.getEntriesByType && WINDOW.performance.getEntriesByType("navigation")[0]; if (!checkResponseStart || navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now()) return navigationEntry; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getActivationStart.js var getActivationStart = () => { const navEntry = getNavigationEntry(); return navEntry && navEntry.activationStart || 0; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/initMetric.js var initMetric = (name, value) => { const navEntry = getNavigationEntry(); let navigationType = "navigate"; if (navEntry) { if (WINDOW.document && WINDOW.document.prerendering || getActivationStart() > 0) navigationType = "prerender"; else if (WINDOW.document && WINDOW.document.wasDiscarded) navigationType = "restore"; else if (navEntry.type) navigationType = navEntry.type.replace(/_/g, "-"); } return { name, value: typeof value === "undefined" ? -1 : value, rating: "good", delta: 0, entries: [], id: generateUniqueID(), navigationType }; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/observe.js /** * Takes a performance entry type and a callback function, and creates a * `PerformanceObserver` instance that will observe the specified entry type * with buffering enabled and call the callback _for each entry_. * * This function also feature-detects entry support and wraps the logic in a * try/catch to avoid errors in unsupporting browsers. */ var observe = (type, callback, opts) => { try { if (PerformanceObserver.supportedEntryTypes.includes(type)) { const po = new PerformanceObserver((list) => { Promise.resolve().then(() => { callback(list.getEntries()); }); }); po.observe(Object.assign({ type, buffered: true }, opts || {})); return po; } } catch (e) {} }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/onHidden.js var onHidden = (cb) => { const onHiddenOrPageHide = (event) => { if (event.type === "pagehide" || WINDOW.document && WINDOW.document.visibilityState === "hidden") cb(event); }; if (WINDOW.document) { addEventListener("visibilitychange", onHiddenOrPageHide, true); addEventListener("pagehide", onHiddenOrPageHide, true); } }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/runOnce.js var runOnce = (cb) => { let called = false; return () => { if (!called) { cb(); called = true; } }; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getVisibilityWatcher.js var firstHiddenTime = -1; var initHiddenTime = () => { return WINDOW.document.visibilityState === "hidden" && !WINDOW.document.prerendering ? 0 : Infinity; }; var onVisibilityUpdate = (event) => { if (WINDOW.document.visibilityState === "hidden" && firstHiddenTime > -1) { firstHiddenTime = event.type === "visibilitychange" ? event.timeStamp : 0; removeChangeListeners(); } }; var addChangeListeners = () => { addEventListener("visibilitychange", onVisibilityUpdate, true); addEventListener("prerenderingchange", onVisibilityUpdate, true); }; var removeChangeListeners = () => { removeEventListener("visibilitychange", onVisibilityUpdate, true); removeEventListener("prerenderingchange", onVisibilityUpdate, true); }; var getVisibilityWatcher = () => { if (WINDOW.document && firstHiddenTime < 0) { firstHiddenTime = initHiddenTime(); addChangeListeners(); } return { get firstHiddenTime() { return firstHiddenTime; } }; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenActivated.js var whenActivated = (callback) => { if (WINDOW.document && WINDOW.document.prerendering) addEventListener("prerenderingchange", () => callback(), true); else callback(); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/onFCP.js /** Thresholds for FCP. See https://web.dev/articles/fcp#what_is_a_good_fcp_score */ var FCPThresholds = [1800, 3e3]; /** * Calculates the [FCP](https://web.dev/articles/fcp) value for the current page and * calls the `callback` function once the value is ready, along with the * relevant `paint` performance entry used to determine the value. The reported * value is a `DOMHighResTimeStamp`. */ var onFCP = (onReport, opts = {}) => { whenActivated(() => { const visibilityWatcher = getVisibilityWatcher(); const metric = initMetric("FCP"); let report; const handleEntries = (entries) => { entries.forEach((entry) => { if (entry.name === "first-contentful-paint") { po.disconnect(); if (entry.startTime < visibilityWatcher.firstHiddenTime) { metric.value = Math.max(entry.startTime - getActivationStart(), 0); metric.entries.push(entry); report(true); } } }); }; const po = observe("paint", handleEntries); if (po) report = bindReporter(onReport, metric, FCPThresholds, opts.reportAllChanges); }); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getCLS.js /** Thresholds for CLS. See https://web.dev/articles/cls#what_is_a_good_cls_score */ var CLSThresholds = [.1, .25]; /** * Calculates the [CLS](https://web.dev/articles/cls) value for the current page and * calls the `callback` function once the value is ready to be reported, along * with all `layout-shift` performance entries that were used in the metric * value calculation. The reported value is a `double` (corresponding to a * [layout shift score](https://web.dev/articles/cls#layout_shift_score)). * * If the `reportAllChanges` configuration option is set to `true`, the * `callback` function will be called as soon as the value is initially * determined as well as any time the value changes throughout the page * lifespan. * * _**Important:** CLS should be continually monitored for changes throughout * the entire lifespan of a page—including if the user returns to the page after * it's been hidden/backgrounded. However, since browsers often [will not fire * additional callbacks once the user has backgrounded a * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden), * `callback` is always called when the page's visibility state changes to * hidden. As a result, the `callback` function might be called multiple times * during the same page load._ */ var onCLS = (onReport, opts = {}) => { onFCP(runOnce(() => { const metric = initMetric("CLS", 0); let report; let sessionValue = 0; let sessionEntries = []; const handleEntries = (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(); } }; const po = observe("layout-shift", handleEntries); if (po) { report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges); onHidden(() => { handleEntries(po.takeRecords()); report(true); }); setTimeout(report, 0); } })); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getFID.js /** Thresholds for FID. See https://web.dev/articles/fid#what_is_a_good_fid_score */ var FIDThresholds = [100, 300]; /** * Calculates the [FID](https://web.dev/articles/fid) value for the current page and * calls the `callback` function once the value is ready, along with the * relevant `first-input` performance entry used to determine the value. The * reported value is a `DOMHighResTimeStamp`. * * _**Important:** since FID is only reported after the user interacts with the * page, it's possible that it will not be reported for some page loads._ */ var onFID = (onReport, opts = {}) => { whenActivated(() => { const visibilityWatcher = getVisibilityWatcher(); const metric = initMetric("FID"); let report; const handleEntry = (entry) => { if (entry.startTime < visibilityWatcher.firstHiddenTime) { metric.value = entry.processingStart - entry.startTime; metric.entries.push(entry); report(true); } }; const handleEntries = (entries) => { entries.forEach(handleEntry); }; const po = observe("first-input", handleEntries); report = bindReporter(onReport, metric, FIDThresholds, opts.reportAllChanges); if (po) onHidden(runOnce(() => { handleEntries(po.takeRecords()); po.disconnect(); })); }); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.js var interactionCountEstimate = 0; var minKnownInteractionId = Infinity; var maxKnownInteractionId = 0; var updateEstimate = (entries) => { entries.forEach((e) => { if (e.interactionId) { minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId); maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId); interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0; } }); }; var po$2; /** * Returns the `interactionCount` value using the native API (if available) * or the polyfill estimate in this module. */ var getInteractionCount = () => { return po$2 ? interactionCountEstimate : performance.interactionCount || 0; }; /** * Feature detects native support or initializes the polyfill if needed. */ var initInteractionCountPolyfill = () => { if ("interactionCount" in performance || po$2) return; po$2 = observe("event", updateEstimate, { type: "event", buffered: true, durationThreshold: 0 }); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/interactions.js var longestInteractionList = []; var longestInteractionMap = /* @__PURE__ */ new Map(); var prevInteractionCount = 0; /** * Returns the interaction count since the last bfcache restore (or for the * full page lifecycle if there were no bfcache restores). */ var getInteractionCountForNavigation = () => { return getInteractionCount() - prevInteractionCount; }; /** * Returns the estimated p98 longest interaction based on the stored * interaction candidates and the interaction count for the current page. */ var estimateP98LongestInteraction = () => { return longestInteractionList[Math.min(longestInteractionList.length - 1, Math.floor(getInteractionCountForNavigation() / 50))]; }; var MAX_INTERACTIONS_TO_CONSIDER = 10; /** * A list of callback functions to run before each entry is processed. * Exposing this list allows the attribution build to hook into the * entry processing pipeline. */ var entryPreProcessingCallbacks = []; /** * Takes a performance entry and adds it to the list of worst interactions * if its duration is long enough to make it among the worst. If the * entry is part of an existing interaction, it is merged and the latency * and entries list is updated as needed. */ var processInteractionEntry = (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((a, b) => b.latency - a.latency); if (longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach((i) => longestInteractionMap.delete(i.id)); } }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenIdle.js /** * Runs the passed callback during the next idle period, or immediately * if the browser's visibility state is (or becomes) hidden. */ var whenIdle = (cb) => { const rIC = WINDOW.requestIdleCallback || WINDOW.setTimeout; let handle = -1; cb = runOnce(cb); if (WINDOW.document && WINDOW.document.visibilityState === "hidden") cb(); else { handle = rIC(cb); onHidden(cb); } return handle; }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getINP.js /** Thresholds for INP. See https://web.dev/articles/inp#what_is_a_good_inp_score */ var INPThresholds = [200, 500]; /** * Calculates the [INP](https://web.dev/articles/inp) value for the current * page and calls the `callback` function once the value is ready, along with * the `event` performance entries reported for that interaction. The reported * value is a `DOMHighResTimeStamp`. * * A custom `durationThreshold` configuration option can optionally be passed to * control what `event-timing` entries are considered for INP reporting. The * default threshold is `40`, which means INP scores of less than 40 are * reported as 0. Note that this will not affect your 75th percentile INP value * unless that value is also less than 40 (well below the recommended * [good](https://web.dev/articles/inp#what_is_a_good_inp_score) threshold). * * If the `reportAllChanges` configuration option is set to `true`, the * `callback` function will be called as soon as the value is initially * determined as well as any time the value changes throughout the page * lifespan. * * _**Important:** INP should be continually monitored for changes throughout * the entire lifespan of a page—including if the user returns to the page after * it's been hidden/backgrounded. However, since browsers often [will not fire * additional callbacks once the user has backgrounded a * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden), * `callback` is always called when the page's visibility state changes to * hidden. As a result, the `callback` function might be called multiple times * during the same page load._ */ var onINP = (onReport, opts = {}) => { if (!("PerformanceEventTiming" in WINDOW && "interactionId" in PerformanceEventTiming.prototype)) return; whenActivated(() => { initInteractionCountPolyfill(); const metric = initMetric("INP"); let report; const handleEntries = (entries) => { whenIdle(() => { entries.forEach(processInteractionEntry); const inp = estimateP98LongestInteraction(); if (inp && inp.latency !== metric.value) { metric.value = inp.latency; metric.entries = inp.entries; report(); } }); }; const po = observe("event", handleEntries, { durationThreshold: opts.durationThreshold != null ? opts.durationThreshold : 40 }); report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges); if (po) { po.observe({ type: "first-input", buffered: true }); onHidden(() => { handleEntries(po.takeRecords()); report(true); }); } }); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getLCP.js /** Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score */ var LCPThresholds = [2500, 4e3]; var reportedMetricIDs = {}; /** * Calculates the [LCP](https://web.dev/articles/lcp) value for the current page and * calls the `callback` function once the value is ready (along with the * relevant `largest-contentful-paint` performance entry used to determine the * value). The reported value is a `DOMHighResTimeStamp`. * * If the `reportAllChanges` configuration option is set to `true`, the * `callback` function will be called any time a new `largest-contentful-paint` * performance entry is dispatched, or once the final value of the metric has * been determined. */ var onLCP = (onReport, opts = {}) => { whenActivated(() => { const visibilityWatcher = getVisibilityWatcher(); const metric = initMetric("LCP"); let report; const handleEntries = (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(); } }); }; const po = observe("largest-contentful-paint", handleEntries); if (po) { report = bindReporter(onReport, metric, LCPThresholds, opts.reportAllChanges); const stopListening = runOnce(() => { if (!reportedMetricIDs[metric.id]) { handleEntries(po.takeRecords()); po.disconnect(); reportedMetricIDs[metric.id] = true; report(true); } }); ["keydown", "click"].forEach((type) => { if (WINDOW.document) addEventListener(type, () => whenIdle(stopListening), { once: true, capture: true }); }); onHidden(stopListening); } }); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/onTTFB.js /** Thresholds for TTFB. See https://web.dev/articles/ttfb#what_is_a_good_ttfb_score */ var TTFBThresholds = [800, 1800]; /** * Runs in the next task after the page is done loading and/or prerendering. * @param callback */ var whenReady = (callback) => { if (WINDOW.document && WINDOW.document.prerendering) whenActivated(() => whenReady(callback)); else if (WINDOW.document && WINDOW.document.readyState !== "complete") addEventListener("load", () => whenReady(callback), true); else setTimeout(callback, 0); }; /** * Calculates the [TTFB](https://web.dev/articles/ttfb) value for the * current page and calls the `callback` function once the page has loaded, * along with the relevant `navigation` performance entry used to determine the * value. The reported value is a `DOMHighResTimeStamp`. * * Note, this function waits until after the page is loaded to call `callback` * in order to ensure all properties of the `navigation` entry are populated. * This is useful if you want to report on other metrics exposed by the * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For * example, the TTFB metric starts from the page's [time * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it * includes time spent on DNS lookup, connection negotiation, network latency, * and server processing time. */ var onTTFB = (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); } }); }; //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/instrument.js var handlers = {}; var instrumented = {}; var _previousCls; var _previousFid; var _previousLcp; var _previousTtfb; var _previousInp; /** * Add a callback that will be triggered when a CLS metric is available. * Returns a cleanup callback which can be called to remove the instrumentation handler. * * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called. * This will lead to the CLS being finalized and frozen. */ function addClsInstrumentationHandler(callback, stopOnCallback = false) { return addMetricObserver("cls", callback, instrumentCls, _previousCls, stopOnCallback); } /** * Add a callback that will be triggered when a LCP metric is available. * Returns a cleanup callback which can be called to remove the instrumentation handler. * * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called. * This will lead to the LCP being finalized and frozen. */ function addLcpInstrumentationHandler(callback, stopOnCallback = false) { return addMetricObserver("lcp", callback, instrumentLcp, _previousLcp, stopOnCallback); } /** * Add a callback that will be triggered when a FID metric is available. * Returns a cleanup callback which can be called to remove the instrumentation handler. */ function addFidInstrumentationHandler(callback) { return addMetricObserver("fid", callback, instrumentFid, _previousFid); } /** * Add a callback that will be triggered when a FID metric is available. */ function addTtfbInstrumentationHandler(callback) { return addMetricObserver("ttfb", callback, instrumentTtfb, _previousTtfb); } /** * Add a callback that will be triggered when a INP metric is available. * Returns a cleanup callback which can be called to remove the instrumentation handler. */ function addInpInstrumentationHandler(callback) { return addMetricObserver("inp", callback, instrumentInp, _previousInp); } /** * Add a callback that will be triggered when a performance observer is triggered, * and receives the entries of the observer. * Returns a cleanup callback which can be called to remove the instrumentation handler. */ function addPerformanceInstrumentationHandler(type, callback) { addHandler(type, callback); if (!instrumented[type]) { instrumentPerformanceObserver(type); instrumented[type] = true; } return getCleanupCallback(type, callback); } /** Trigger all handlers of a given type. */ function triggerHandlers(type, data) { const typeHandlers = handlers[type]; if (!typeHandlers || !typeHandlers.length) return; for (const handler of typeHandlers) try { handler(data); } catch (e) { DEBUG_BUILD$1 && logger$1.error(`Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`, e); } } function instrumentCls() { return onCLS((metric) => { triggerHandlers("cls", { metric }); _previousCls = metric; }, { reportAllChanges: true }); } function instrumentFid() { return onFID((metric) => { triggerHandlers("fid", { metric }); _previousFid = metric; }); } function instrumentLcp() { return onLCP((metric) => { triggerHandlers("lcp", { metric }); _previousLcp = metric; }, { reportAllChanges: true }); } function instrumentTtfb() { return onTTFB((metric) => { triggerHandlers("ttfb", { metric }); _previousTtfb = metric; }); } function instrumentInp() { return onINP((metric) => { triggerHandlers("inp", { metric }); _previousInp = metric; }); } 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); } function instrumentPerformanceObserver(type) { const options = {}; if (type === "event") options.durationThreshold = 0; observe(type, (entries) => { triggerHandlers(type, { entries }); }, options); } function addHandler(type, handler) { handlers[type] = handlers[type] || []; handlers[type].push(handler); } function getCleanupCallback(type, callback, stopListening) { return () => { if (stopListening) stopListening(); const typeHandlers = handlers[type]; if (!typeHandlers) return; const index = typeHandlers.indexOf(callback); if (index !== -1) typeHandlers.splice(index, 1); }; } /** * Check if a PerformanceEntry is a PerformanceEventTiming by checking for the `duration` property. */ function isPerformanceEventTiming(entry) { return "duration" in entry; } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/utils.js /** * Checks if a given value is a valid measurement value. */ function isMeasurementValue(value) { return typeof value === "number" && isFinite(value); } /** * Helper function to start child on transactions. This function will make sure that the transaction will * use the start timestamp of the created child span if it is earlier than the transactions actual * start timestamp. */ function 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; }); } /** * Starts an inactive, standalone span used to send web vital values to Sentry. * DO NOT use this for arbitrary spans, as these spans require special handling * during ingestion to extract metrics. * * This function adds a bunch of attributes and data to the span that's shared * by all web vital standalone spans. However, you need to take care of adding * the actual web vital value as an event to the span. Also, you need to assign * a transaction name and some other values that are specific to the web vital. * * Ultimately, you also need to take care of ending the span to send it off. * * @param options * * @returns an inactive, standalone and NOT YET ended span */ function startStandaloneWebVitalSpan(options) { const client = getClient(); if (!client) return; const { name, transaction, attributes: passedAttributes, startTime } = options; const { release, environment } = client.getOptions(); const replay = client.getIntegrationByName("Replay"); const replayId = replay && replay.getReplayId(); const scope = getCurrentScope(); 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 (e) {} return startInactiveSpan({ name, attributes: { release, environment, user: userDisplay || void 0, profile_id: profileId || void 0, replay_id: replayId || void 0, transaction, "user_agent.original": WINDOW.navigator && WINDOW.navigator.userAgent, ...passedAttributes }, startTime, experimental: { standalone: true } }); } /** Get the browser performance API. */ function getBrowserPerformanceAPI() { return WINDOW && WINDOW.addEventListener && WINDOW.performance; } /** * Converts from milliseconds to seconds * @param time time in ms */ function msToSec(time) { return time / 1e3; } /** * Converts ALPN protocol ids to name and version. * * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids) * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol */ function extractNetworkProtocol(nextHopProtocol) { let name = "unknown"; let version = "unknown"; let _name = ""; for (const char of nextHopProtocol) { if (char === "/") { [name, version] = nextHopProtocol.split("/"); break; } if (!isNaN(Number(char))) { name = _name === "h" ? "http" : _name; version = nextHopProtocol.split(_name)[1]; break; } _name += char; } if (_name === nextHopProtocol) name = _name; return { name, version }; } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/cls.js /** * Starts tracking the Cumulative Layout Shift on the current page and collects the value once * * - the page visibility is hidden * - a navigation span is started (to stop CLS measurement for SPA soft navigations) * * Once either of these events triggers, the CLS value is sent as a standalone span and we stop * measuring CLS. */ 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(); } 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); } function sendStandaloneClsSpan(clsValue, entry, pageloadSpanId) { DEBUG_BUILD$1 && logger$1.log(`Sending CLS span (${clsValue})`); const startTime = msToSec((browserPerformanceTimeOrigin || 0) + (entry && entry.startTime || 0)); const routeName = getCurrentScope().getScopeData().transactionName; const span = startStandaloneWebVitalSpan({ name: entry ? htmlTreeAsString(entry.sources[0] && entry.sources[0].node) : "Layout shift", transaction: routeName, 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, "sentry.pageload.span_id": pageloadSpanId }), startTime }); if (span) { span.addEvent("cls", { [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "", [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: clsValue }); span.end(startTime); } } function supportsLayoutShift() { try { return PerformanceObserver.supportedEntryTypes.includes("layout-shift"); } catch (e) { return false; } } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/browserMetrics.js var MAX_INT_AS_BYTES = 2147483647; var _performanceCursor = 0; var _measurements = {}; var _lcpEntry; var _clsEntry; /** * Start tracking web vitals. * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured. * * @returns A function that forces web vitals collection */ function startTrackingWebVitals({ recordClsStandaloneSpans }) { const performance = getBrowserPerformanceAPI(); if (performance && browserPerformanceTimeOrigin) { if (performance.mark) WINDOW.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; } /** * Start tracking long tasks. */ 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" } }); } }); } /** * Start tracking long animation frames. */ function startTrackingLongAnimationFrames() { new PerformanceObserver((list) => { const parent = getActiveSpan(); if (!parent) return; for (const entry of list.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 { invoker, invokerType, sourceURL, sourceFunctionName, sourceCharPosition } = entry.scripts[0]; 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 }); } }).observe({ type: "long-animation-frame", buffered: true }); } /** * Start tracking interaction events. */ 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(entry.target); if (componentName) spanOptions.attributes["ui.component_name"] = componentName; startAndEndSpan(parent, startTime, startTime + duration, spanOptions); } }); } /** * Starts tracking the Cumulative Layout Shift on the current page and collects the value and last entry * to the `_measurements` object which ultimately is applied to the pageload span's measurements. */ 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); } /** Starts tracking the Largest Contentful Paint on the current page. */ 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); } /** Starts tracking the First Input Delay on the current page. */ 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" }; }); } function _trackTtfb() { return addTtfbInstrumentationHandler(({ metric }) => { if (!metric.entries[metric.entries.length - 1]) return; _measurements["ttfb"] = { value: metric.value, unit: "millisecond" }; }); } /** Add performance related spans to a transaction */ function addPerformanceEntries(span, options) { const performance = getBrowserPerformanceAPI(); if (!performance || !performance.getEntries || !browserPerformanceTimeOrigin) return; const timeOrigin = msToSec(browserPerformanceTimeOrigin); const performanceEntries = performance.getEntries(); const { op, start_timestamp: transactionStartTime } = spanToJSON(span); performanceEntries.slice(_performanceCursor).forEach((entry) => { const startTime = msToSec(entry.startTime); const duration = msToSec(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) || !options.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 = {}; } /** * Create measure related spans. * Exported only for tests. */ 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; } if (measureStartTimestamp <= measureEndTimestamp) startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, { name: entry.name, op: entry.entryType, attributes }); } /** Instrument navigation entries */ 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); } /** Create performance navigation related spans */ function _addPerformanceNavigationTiming(span, entry, event, timeOrigin, name = event) { const end = entry[_getEndPropertyNameForNavigationTiming(event)]; const start = entry[`${event}Start`]; if (!start || !end) return; startAndEndSpan(span, timeOrigin + msToSec(start), timeOrigin + msToSec(end), { op: `browser.${name}`, name: entry.name, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.browser.metrics" } }); } function _getEndPropertyNameForNavigationTiming(event) { if (event === "secureConnection") return "connectEnd"; if (event === "fetch") return "domainLookupStart"; return `${event}End`; } /** Create request and response related spans */ 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" } }); } } /** * Create resource-related spans. * Exported only for tests. */ 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.location.origin); const { name, version } = extractNetworkProtocol(entry.nextHopProtocol); attributes["network.protocol.name"] = name; attributes["network.protocol.version"] = version; const startTimestamp = timeOrigin + startTime; startAndEndSpan(span, startTimestamp, startTimestamp + duration, { name: resourceUrl.replace(WINDOW.location.origin, ""), op: entry.initiatorType ? `resource.${entry.initiatorType}` : "resource.other", attributes }); } /** * Capture the information of the user agent. */ function _trackNavigator(span) { const navigator = WINDOW.navigator; if (!navigator) return; const connection = navigator.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(navigator.deviceMemory)) span.setAttribute("deviceMemory", `${navigator.deviceMemory} GB`); if (isMeasurementValue(navigator.hardwareConcurrency)) span.setAttribute("hardwareConcurrency", String(navigator.hardwareConcurrency)); } /** Add LCP / CLS data to span to allow debugging */ 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, index) => span.setAttribute(`cls.source.${index + 1}`, htmlTreeAsString(source.node))); } function setResourceEntrySizeData(attributes, entry, key, dataKey) { const entryVal = entry[key]; if (entryVal != null && entryVal < MAX_INT_AS_BYTES) attributes[dataKey] = entryVal; } /** * Add ttfb request time information to measurements. * * ttfb information is added via vendored web vitals library. */ function _addTtfbRequestTimeToMeasurements(_measurements) { const navEntry = getNavigationEntry(false); if (!navEntry) return; const { responseStart, requestStart } = navEntry; if (requestStart <= responseStart) _measurements["ttfb.requestTime"] = { value: responseStart - requestStart, unit: "millisecond" }; } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/instrument/dom.js var DEBOUNCE_DURATION = 1e3; var debounceTimerID; var lastCapturedEventType; var lastCapturedEventTargetId; /** * Add an instrumentation handler for when a click or a keypress happens. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addClickKeypressInstrumentationHandler(handler) { const type = "dom"; addHandler$1(type, handler); maybeInstrument(type, instrumentDOM); } /** Exported for tests only. */ function instrumentDOM() { if (!WINDOW.document) return; const triggerDOMHandler = triggerHandlers$1.bind(null, "dom"); const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); WINDOW.document.addEventListener("click", globalDOMEventHandler, false); WINDOW.document.addEventListener("keypress", globalDOMEventHandler, false); ["EventTarget", "Node"].forEach((target) => { const targetObj = WINDOW[target]; const proto = targetObj && targetObj.prototype; if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) return; fill(proto, "addEventListener", function(originalAddEventListener) { return function(type, listener, options) { if (type === "click" || type == "keypress") try { const handlers = this.__sentry_instrumentation_handlers__ = this.__sentry_instrumentation_handlers__ || {}; const handlerForType = handlers[type] = handlers[type] || { refCount: 0 }; if (!handlerForType.handler) { const handler = makeDOMEventHandler(triggerDOMHandler); handlerForType.handler = handler; originalAddEventListener.call(this, type, handler, options); } handlerForType.refCount++; } catch (e) {} return originalAddEventListener.call(this, type, listener, options); }; }); fill(proto, "removeEventListener", function(originalRemoveEventListener) { return function(type, listener, options) { if (type === "click" || type == "keypress") try { const handlers = this.__sentry_instrumentation_handlers__ || {}; const handlerForType = handlers[type]; if (handlerForType) { handlerForType.refCount--; if (handlerForType.refCount <= 0) { originalRemoveEventListener.call(this, type, handlerForType.handler, options); handlerForType.handler = void 0; delete handlers[type]; } if (Object.keys(handlers).length === 0) delete this.__sentry_instrumentation_handlers__; } } catch (e) {} return originalRemoveEventListener.call(this, type, listener, options); }; }); }); } /** * Check whether the event is similar to the last captured one. For example, two click events on the same button. */ function isSimilarToLastCapturedEvent(event) { if (event.type !== lastCapturedEventType) return false; try { if (!event.target || event.target._sentryId !== lastCapturedEventTargetId) return false; } catch (e) {} return true; } /** * Decide whether an event should be captured. * @param event event to be captured */ 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; } /** * Wraps addEventListener to capture UI breadcrumbs */ function makeDOMEventHandler(handler, globalListener = false) { return (event) => { if (!event || event["_sentryCaptured"]) return; const target = getEventTarget(event); if (shouldSkipDOMEvent(event.type, target)) return; addNonEnumerableProperty(event, "_sentryCaptured", true); if (target && !target._sentryId) addNonEnumerableProperty(target, "_sentryId", uuid4()); const name = event.type === "keypress" ? "input" : event.type; if (!isSimilarToLastCapturedEvent(event)) { handler({ event, name, global: globalListener }); lastCapturedEventType = event.type; lastCapturedEventTargetId = target ? target._sentryId : void 0; } clearTimeout(debounceTimerID); debounceTimerID = WINDOW.setTimeout(() => { lastCapturedEventTargetId = void 0; lastCapturedEventType = void 0; }, DEBOUNCE_DURATION); }; } function getEventTarget(event) { try { return event.target; } catch (e) { return null; } } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/instrument/history.js var lastHref; /** * Add an instrumentation handler for when a fetch request happens. * The handler function is called once when the request starts and once when it ends, * which can be identified by checking if it has an `endTimestamp`. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addHistoryInstrumentationHandler(handler) { const type = "history"; addHandler$1(type, handler); maybeInstrument(type, instrumentHistory); } function instrumentHistory() { if (!supportsHistory()) return; const oldOnPopState = WINDOW.onpopstate; WINDOW.onpopstate = function(...args) { const to = WINDOW.location.href; const from = lastHref; lastHref = to; triggerHandlers$1("history", { from, to }); 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 from = lastHref; const to = String(url); lastHref = to; triggerHandlers$1("history", { from, to }); } return originalHistoryFunction.apply(this, args); }; } fill(WINDOW.history, "pushState", historyReplacementFunction); fill(WINDOW.history, "replaceState", historyReplacementFunction); } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/getNativeImplementation.js /** * We generally want to use window.fetch / window.setTimeout. * However, in some cases this may be wrapped (e.g. by Zone.js for Angular), * so we try to get an unpatched version of this from a sandboxed iframe. */ var cachedImplementations = {}; /** * Get the native implementation of a browser function. * * This can be used to ensure we get an unwrapped version of a function, in cases where a wrapped function can lead to problems. * * The following methods can be retrieved: * - `setTimeout`: This can be wrapped by e.g. Angular, causing change detection to be triggered. * - `fetch`: This can be wrapped by e.g. ad-blockers, causing an infinite loop when a request is blocked. */ function getNativeImplementation(name) { const cached = cachedImplementations[name]; if (cached) return cached; let impl = WINDOW[name]; if (isNativeFunction(impl)) return cachedImplementations[name] = impl.bind(WINDOW); const document = WINDOW.document; if (document && typeof document.createElement === "function") try { const sandbox = document.createElement("iframe"); sandbox.hidden = true; document.head.appendChild(sandbox); const contentWindow = sandbox.contentWindow; if (contentWindow && contentWindow[name]) impl = contentWindow[name]; document.head.removeChild(sandbox); } catch (e) { DEBUG_BUILD$1 && logger$1.warn(`Could not create sandbox iframe for ${name} check, bailing to window.${name}: `, e); } if (!impl) return impl; return cachedImplementations[name] = impl.bind(WINDOW); } /** Clear a cached implementation. */ function clearCachedImplementation(name) { cachedImplementations[name] = void 0; } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/instrument/xhr.js var SENTRY_XHR_DATA_KEY = "__sentry_xhr_v3__"; /** * Add an instrumentation handler for when an XHR request happens. * The handler function is called once when the request starts and once when it ends, * which can be identified by checking if it has an `endTimestamp`. * * Use at your own risk, this might break without changelog notice, only used internally. * @hidden */ function addXhrInstrumentationHandler(handler) { const type = "xhr"; addHandler$1(type, handler); maybeInstrument(type, instrumentXHR); } /** Exported only for tests. */ function instrumentXHR() { if (!WINDOW.XMLHttpRequest) return; const xhrproto = XMLHttpRequest.prototype; xhrproto.open = new Proxy(xhrproto.open, { apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) { const virtualError = /* @__PURE__ */ new Error(); const startTimestamp = timestampInSeconds() * 1e3; const method = isString(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 = () => { const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY]; if (!xhrInfo) return; if (xhrOpenThisArg.readyState === 4) { try { xhrInfo.status_code = xhrOpenThisArg.status; } catch (e) {} triggerHandlers$1("xhr", { endTimestamp: timestampInSeconds() * 1e3, startTimestamp, xhr: xhrOpenThisArg, virtualError }); } }; 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 [header, value] = setRequestHeaderArgArray; const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY]; if (xhrInfo && isString(header) && isString(value)) xhrInfo.request_headers[header.toLowerCase()] = value; 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]; triggerHandlers$1("xhr", { startTimestamp: timestampInSeconds() * 1e3, xhr: sendThisArg }); return originalSend.apply(sendThisArg, sendArgArray); } }); } function parseUrl(url) { if (isString(url)) return url; try { return url.toString(); } catch (e2) {} } //#endregion //#region ../../node_modules/.pnpm/@sentry-internal+browser-utils@8.55.2/node_modules/@sentry-internal/browser-utils/build/esm/metrics/inp.js var LAST_INTERACTIONS = []; var INTERACTIONS_SPAN_MAP = /* @__PURE__ */ new Map(); /** * Start tracking INP webvital events. */ function startTrackingINP() { if (getBrowserPerformanceAPI() && browserPerformanceTimeOrigin) { const inpCallback = _trackINP(); return () => { inpCallback(); }; } return () => void 0; } var 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" }; /** Starts tracking the Interaction to Next Paint on the current page. */ function _trackINP() { return addInpInstrumentationHandler(({ metric }) => { if (metric.value == void 0) return; const entry = metric.entries.find((entry) => entry.duration === metric.value && INP_ENTRY_MAP[entry.name]); if (!entry) return; const { interactionId } = entry; const interactionType = INP_ENTRY_MAP[entry.name]; /** Build the INP span, create an envelope from the span, and then send the envelope */ const startTime = msToSec(browserPerformanceTimeOrigin + entry.startTime); const duration = msToSec(metric.value); const activeSpan = getActiveSpan(); const rootSpan = activeSpan ? getRootSpan(activeSpan) : void 0; const spanToUse = (interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : void 0) || rootSpan; const routeName = spanToUse ? spanToJSON(spanToUse).description : getCurrentScope().getScopeData().transactionName; const span = startStandaloneWebVitalSpan({ name: htmlTreeAsString(entry.target), transaction: routeName, attributes: dropUndefinedKeys({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.browser.inp", [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `ui.interaction.${interactionType}`, [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry.duration }), startTime }); if (span) { span.addEvent("inp", { [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: "millisecond", [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: metric.value }); span.end(startTime + duration); } }); } /** * Register a listener to cache route information for INP interactions. * TODO(v9): `latestRoute` no longer needs to be passed in and will be removed in v9. */ function registerInpInteractionListener(_latestRoute) { const handleEntries = ({ 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); }); }; addPerformanceInstrumentationHandler("event", handleEntries); addPerformanceInstrumentationHandler("first-input", handleEntries); } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/transports/fetch.js /** * Creates a Transport that uses the Fetch API to send events to Sentry. */ function makeFetchTransport(options, 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: options.headers, keepalive: pendingBodySize <= 6e4 && pendingCount < 15, ...options.fetchOptions }; if (!nativeFetch) { clearCachedImplementation("fetch"); return rejectedSyncPromise("No fetch implementation available"); } try { return nativeFetch(options.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 (e) { clearCachedImplementation("fetch"); pendingBodySize -= requestSize; pendingCount--; return rejectedSyncPromise(e); } } return createTransport(options, makeRequest); } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/stack-parsers.js var CHROME_PRIORITY = 30; var GECKO_PRIORITY = 50; function createFrame(filename, func, lineno, colno) { const frame = { filename, function: func === "" ? "?" : func, in_app: true }; if (lineno !== void 0) frame.lineno = lineno; if (colno !== void 0) frame.colno = colno; return frame; } var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i; var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/; var chromeStackParserFn = (line) => { const noFnParts = chromeRegexNoFnName.exec(line); if (noFnParts) { const [, filename, line, col] = noFnParts; return createFrame(filename, "?", +line, +col); } const parts = chromeRegex.exec(line); if (parts) { if (parts[2] && parts[2].indexOf("eval") === 0) { const subMatch = chromeEvalRegex.exec(parts[2]); if (subMatch) { parts[2] = subMatch[1]; parts[3] = subMatch[2]; parts[4] = subMatch[3]; } } const [func, filename] = extractSafariExtensionDetails(parts[1] || "?", parts[2]); return createFrame(filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0); } }; var chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn]; var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i; var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; var gecko = (line) => { const parts = geckoREgex.exec(line); if (parts) { if (parts[3] && parts[3].indexOf(" > eval") > -1) { const subMatch = geckoEvalRegex.exec(parts[3]); if (subMatch) { parts[1] = parts[1] || "eval"; parts[3] = subMatch[1]; parts[4] = subMatch[2]; parts[5] = ""; } } let filename = parts[3]; let func = parts[1] || "?"; [func, filename] = extractSafariExtensionDetails(func, filename); return createFrame(filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0); } }; var defaultStackParser = createStackParser(...[chromeStackLineParser, [GECKO_PRIORITY, gecko]]); /** * Safari web extensions, starting version unknown, can produce "frames-only" stacktraces. * What it means, is that instead of format like: * * Error: wat * at function@url:row:col * at function@url:row:col * at function@url:row:col * * it produces something like: * * function@url:row:col * function@url:row:col * function@url:row:col * * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch. * This function is extracted so that we can use it in both places without duplicating the logic. * Unfortunately "just" changing RegExp is too complicated now and making it pass all tests * and fix this case seems like an impossible, or at least way too time-consuming task. */ var extractSafariExtensionDetails = (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] : "?", isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`] : [func, filename]; }; //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/integrations/breadcrumbs.js /** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */ var MAX_ALLOWED_STRING_LENGTH = 1024; var INTEGRATION_NAME$4 = "Breadcrumbs"; var _breadcrumbsIntegration = ((options = {}) => { const _options = { console: true, dom: true, fetch: true, history: true, sentry: true, xhr: true, ...options }; return { name: INTEGRATION_NAME$4, 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)); } }; }); var breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration); /** * Adds a breadcrumb for Sentry events or transactions if this option is enabled. */ function _getSentryBreadcrumbHandler(client) { return 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 }); }; } /** * A HOC that creates a function that creates breadcrumbs from DOM API calls. * This is a HOC so that we get access to dom options in the closure. */ function _getDomBreadcrumbHandler(client, dom) { return 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$2 && logger$1.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(element); } catch (e) { 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 }); }; } /** * Creates breadcrumbs from console API calls */ function _getConsoleBreadcrumbHandler(client) { return 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 }); }; } /** * Creates breadcrumbs from XHR API calls */ function _getXhrBreadcrumbHandler(client) { return 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 data = { method, url, status_code }; const hint = { xhr: handlerData.xhr, input: body, startTimestamp, endTimestamp }; addBreadcrumb({ category: "xhr", data, type: "http", level: getBreadcrumbLogLevelFromHttpStatusCode(status_code) }, hint); }; } /** * Creates breadcrumbs from fetch API calls */ function _getFetchBreadcrumbHandler(client) { return 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 data = handlerData.fetchData; const hint = { data: handlerData.error, input: handlerData.args, startTimestamp, endTimestamp }; addBreadcrumb({ category: "fetch", data, level: "error", type: "http" }, hint); } else { const response = handlerData.response; const data = { ...handlerData.fetchData, status_code: response && response.status }; const hint = { input: handlerData.args, response, startTimestamp, endTimestamp }; addBreadcrumb({ category: "fetch", data, type: "http", level: getBreadcrumbLogLevelFromHttpStatusCode(data.status_code) }, hint); } }; } /** * Creates breadcrumbs from history API calls */ function _getHistoryBreadcrumbHandler(client) { return function _historyBreadcrumb(handlerData) { if (getClient() !== client) return; let from = handlerData.from; let to = handlerData.to; const parsedLoc = parseUrl$1(WINDOW$1.location.href); let parsedFrom = from ? parseUrl$1(from) : 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) from = parsedFrom.relative; addBreadcrumb({ category: "navigation", data: { from, to } }); }; } function _isEvent(event) { return !!event && !!event.target; } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/integrations/browserapierrors.js var 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" ]; var INTEGRATION_NAME$3 = "BrowserApiErrors"; var _browserApiErrorsIntegration = ((options = {}) => { const _options = { XMLHttpRequest: true, eventTarget: true, requestAnimationFrame: true, setInterval: true, setTimeout: true, ...options }; return { name: INTEGRATION_NAME$3, setupOnce() { if (_options.setTimeout) fill(WINDOW$1, "setTimeout", _wrapTimeFunction); if (_options.setInterval) fill(WINDOW$1, "setInterval", _wrapTimeFunction); if (_options.requestAnimationFrame) fill(WINDOW$1, "requestAnimationFrame", _wrapRAF); if (_options.XMLHttpRequest && "XMLHttpRequest" in WINDOW$1) fill(XMLHttpRequest.prototype, "send", _wrapXHR); const eventTargetOption = _options.eventTarget; if (eventTargetOption) (Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET).forEach(_wrapEventTarget); } }; }); /** * Wrap timer functions and event targets to catch errors and provide better meta data. */ var browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration); function _wrapTimeFunction(original) { return function(...args) { const originalCallback = args[0]; args[0] = wrap(originalCallback, { mechanism: { data: { function: getFunctionName(original) }, handled: false, type: "instrument" } }); return original.apply(this, args); }; } function _wrapRAF(original) { return function(callback) { return original.apply(this, [wrap(callback, { mechanism: { data: { function: "requestAnimationFrame", handler: getFunctionName(original) }, handled: false, type: "instrument" } })]); }; } function _wrapXHR(originalSend) { return function(...args) { const xhr = this; [ "onload", "onerror", "onprogress", "onreadystatechange" ].forEach((prop) => { if (prop in xhr && typeof xhr[prop] === "function") fill(xhr, prop, function(original) { const wrapOptions = { mechanism: { data: { function: prop, handler: getFunctionName(original) }, handled: false, type: "instrument" } }; const originalFunction = getOriginalFunction(original); if (originalFunction) wrapOptions.mechanism.data.handler = getFunctionName(originalFunction); return wrap(original, wrapOptions); }); }); return originalSend.apply(this, args); }; } function _wrapEventTarget(target) { const targetObj = WINDOW$1[target]; const proto = targetObj && targetObj.prototype; if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) return; fill(proto, "addEventListener", function(original) { return function(eventName, fn, options) { try { if (isEventListenerObject(fn)) fn.handleEvent = wrap(fn.handleEvent, { mechanism: { data: { function: "handleEvent", handler: getFunctionName(fn), target }, handled: false, type: "instrument" } }); } catch (e2) {} return original.apply(this, [ eventName, wrap(fn, { mechanism: { data: { function: "addEventListener", handler: getFunctionName(fn), target }, handled: false, type: "instrument" } }), options ]); }; }); fill(proto, "removeEventListener", function(originalRemoveEventListener) { return function(eventName, fn, options) { /** * There are 2 possible scenarios here: * * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function * as a pass-through, and call original `removeEventListener` with it. * * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using * our wrapped version of `addEventListener`, which internally calls `wrap` helper. * This helper "wraps" whole callback inside a try/catch statement, and attached appropriate metadata to it, * in order for us to make a distinction between wrapped/non-wrapped functions possible. * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler. * * When someone adds a handler prior to initialization, and then do it again, but after, * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible * to get rid of the initial handler and it'd stick there forever. */ try { const originalEventHandler = fn.__sentry_wrapped__; if (originalEventHandler) originalRemoveEventListener.call(this, eventName, originalEventHandler, options); } catch (e) {} return originalRemoveEventListener.call(this, eventName, fn, options); }; }); } function isEventListenerObject(obj) { return typeof obj.handleEvent === "function"; } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/integrations/browsersession.js /** * When added, automatically creates sessions which allow you to track adoption and crashes (crash free rate) in your Releases in Sentry. * More information: https://docs.sentry.io/product/releases/health/ * * Note: In order for session tracking to work, you need to set up Releases: https://docs.sentry.io/product/releases/ */ var browserSessionIntegration = defineIntegration(() => { return { name: "BrowserSession", setupOnce() { if (typeof WINDOW$1.document === "undefined") { DEBUG_BUILD$2 && logger$1.warn("Using the `browserSessionIntegration` in non-browser environments is not supported."); return; } startSession({ ignoreDuration: true }); captureSession(); addHistoryInstrumentationHandler(({ from, to }) => { if (from !== void 0 && from !== to) { startSession({ ignoreDuration: true }); captureSession(); } }); } }; }); //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/integrations/globalhandlers.js var INTEGRATION_NAME$2 = "GlobalHandlers"; var _globalHandlersIntegration = ((options = {}) => { const _options = { onerror: true, onunhandledrejection: true, ...options }; return { name: INTEGRATION_NAME$2, setupOnce() { Error.stackTraceLimit = 50; }, setup(client) { if (_options.onerror) { _installGlobalOnErrorHandler(client); globalHandlerLog("onerror"); } if (_options.onunhandledrejection) { _installGlobalOnUnhandledRejectionHandler(client); globalHandlerLog("onunhandledrejection"); } } }; }); var globalHandlersIntegration = defineIntegration(_globalHandlersIntegration); function _installGlobalOnErrorHandler(client) { addGlobalErrorInstrumentationHandler((data) => { const { stackParser, attachStacktrace } = getOptions(); if (getClient() !== client || shouldIgnoreOnError()) return; const { msg, url, line, column, error } = data; const event = _enhanceEventWithInitialFrame(eventFromUnknownInput(stackParser, error || msg, void 0, attachStacktrace, false), url, line, column); event.level = "error"; captureEvent(event, { originalException: error, mechanism: { handled: false, type: "onerror" } }); }); } function _installGlobalOnUnhandledRejectionHandler(client) { addGlobalUnhandledRejectionInstrumentationHandler((e) => { const { stackParser, attachStacktrace } = getOptions(); if (getClient() !== client || shouldIgnoreOnError()) return; const error = _getUnhandledRejectionError(e); const event = isPrimitive(error) ? _eventFromRejectionWithPrimitive(error) : eventFromUnknownInput(stackParser, error, void 0, attachStacktrace, true); event.level = "error"; captureEvent(event, { originalException: error, mechanism: { handled: false, type: "onunhandledrejection" } }); }); } function _getUnhandledRejectionError(error) { if (isPrimitive(error)) return error; try { if ("reason" in error) return error.reason; if ("detail" in error && "reason" in error.detail) return error.detail.reason; } catch (e2) {} return error; } /** * Create an event from a promise rejection where the `reason` is a primitive. * * @param reason: The `reason` property of the promise rejection * @returns An Event object with an appropriate `exception` value */ function _eventFromRejectionWithPrimitive(reason) { return { exception: { values: [{ type: "UnhandledRejection", value: `Non-Error promise rejection captured with value: ${String(reason)}` }] } }; } function _enhanceEventWithInitialFrame(event, url, line, column) { const e = event.exception = event.exception || {}; const ev = e.values = e.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(url) && url.length > 0 ? url : getLocationHref(); if (ev0sf.length === 0) ev0sf.push({ colno, filename, function: "?", in_app: true, lineno }); return event; } function globalHandlerLog(type) { DEBUG_BUILD$2 && logger$1.log(`Global Handler attached: ${type}`); } function getOptions() { const client = getClient(); return client && client.getOptions() || { stackParser: () => [], attachStacktrace: false }; } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/integrations/httpcontext.js /** * Collects information about HTTP request headers and * attaches them to the event. */ var httpContextIntegration = defineIntegration(() => { return { name: "HttpContext", preprocessEvent(event) { if (!WINDOW$1.navigator && !WINDOW$1.location && !WINDOW$1.document) return; const url = event.request && event.request.url || WINDOW$1.location && WINDOW$1.location.href; const { referrer } = WINDOW$1.document || {}; const { userAgent } = WINDOW$1.navigator || {}; const headers = { ...event.request && event.request.headers, ...referrer && { Referer: referrer }, ...userAgent && { "User-Agent": userAgent } }; event.request = { ...event.request, ...url && { url }, headers }; } }; }); //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/integrations/linkederrors.js var DEFAULT_KEY = "cause"; var DEFAULT_LIMIT = 5; var INTEGRATION_NAME$1 = "LinkedErrors"; var _linkedErrorsIntegration = ((options = {}) => { const limit = options.limit || DEFAULT_LIMIT; const key = options.key || DEFAULT_KEY; return { name: INTEGRATION_NAME$1, preprocessEvent(event, hint, client) { const options = client.getOptions(); applyAggregateErrorsToEvent(exceptionFromError, options.stackParser, options.maxValueLength, key, limit, event, hint); } }; }); /** * Aggregrate linked errors in an event. */ var linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration); //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/sdk.js /** Get the default integrations for the browser SDK. */ function getDefaultIntegrations(options) { /** * Note: Please make sure this stays in sync with Angular SDK, which re-exports * `getDefaultIntegrations` but with an adjusted set of integrations. */ const integrations = [ inboundFiltersIntegration(), functionToStringIntegration(), browserApiErrorsIntegration(), breadcrumbsIntegration(), globalHandlersIntegration(), linkedErrorsIntegration(), dedupeIntegration(), httpContextIntegration() ]; if (options.autoSessionTracking !== false) integrations.push(browserSessionIntegration()); return integrations; } function applyDefaultOptions(optionsArg = {}) { const defaultOptions = { defaultIntegrations: getDefaultIntegrations(optionsArg), release: typeof __SENTRY_RELEASE__ === "string" ? __SENTRY_RELEASE__ : WINDOW$1.SENTRY_RELEASE && WINDOW$1.SENTRY_RELEASE.id ? WINDOW$1.SENTRY_RELEASE.id : void 0, autoSessionTracking: true, sendClientReports: true }; if (optionsArg.defaultIntegrations == null) delete optionsArg.defaultIntegrations; return { ...defaultOptions, ...optionsArg }; } function shouldShowBrowserExtensionError() { const windowWithMaybeExtension = typeof WINDOW$1.window !== "undefined" && WINDOW$1; if (!windowWithMaybeExtension) return false; const extensionObject = windowWithMaybeExtension[windowWithMaybeExtension.chrome ? "chrome" : "browser"]; const runtimeId = extensionObject && extensionObject.runtime && extensionObject.runtime.id; const href = WINDOW$1.location && WINDOW$1.location.href || ""; const isDedicatedExtensionPage = !!runtimeId && WINDOW$1 === WINDOW$1.top && [ "chrome-extension:", "moz-extension:", "ms-browser-extension:", "safari-web-extension:" ].some((protocol) => href.startsWith(`${protocol}//`)); const isNWjs = typeof windowWithMaybeExtension.nw !== "undefined"; return !!runtimeId && !isDedicatedExtensionPage && !isNWjs; } /** * A magic string that build tooling can leverage in order to inject a release value into the SDK. */ /** * The Sentry Browser SDK Client. * * To use this SDK, call the {@link init} function as early as possible when * loading the web page. To set context information or send manual events, use * the provided methods. * * @example * * ``` * * import { init } from '@sentry/browser'; * * init({ * dsn: '__DSN__', * // ... * }); * ``` * * @example * ``` * * import { addBreadcrumb } from '@sentry/browser'; * addBreadcrumb({ * message: 'My Breadcrumb', * // ... * }); * ``` * * @example * * ``` * * import * as Sentry from '@sentry/browser'; * Sentry.captureMessage('Hello, world!'); * Sentry.captureException(new Error('Good bye')); * Sentry.captureEvent({ * message: 'Manual', * stacktrace: [ * // ... * ], * }); * ``` * * @see {@link BrowserOptions} for documentation on configuration options. */ function init$1(browserOptions = {}) { const options = applyDefaultOptions(browserOptions); if (!options.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$2) { if (!supportsFetch()) logger$1.warn("No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill."); } return initAndBind(BrowserClient, { ...options, stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser), integrations: getIntegrationsToSetup(options), transport: options.transport || makeFetchTransport }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/tracing/request.js /** Options for Request Instrumentation */ var responseToSpanId = /* @__PURE__ */ new WeakMap(); var spanIdToEndTimestamp = /* @__PURE__ */ new Map(); var defaultRequestInstrumentationOptions = { traceFetch: true, traceXHR: true, enableHTTPTimings: true, trackFetchStreamPerformance: false }; /** Registers span creators for xhr and fetch requests */ 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 : (_) => true; const shouldAttachHeadersWithTargets = (url) => shouldAttachHeaders(url, tracePropagationTargets); 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); }); } function isPerformanceResourceTiming(entry) { return entry.entryType === "resource" && "initiatorType" in entry && typeof entry.nextHopProtocol === "string" && (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest"); } /** * Creates a temporary observer to listen to the next fetch/xhr resourcing timings, * so that when timings hit their per-browser limit they don't need to be removed. * * @param span A span that has yet to be finished, must contain `url` on data. */ 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)) { resourceTimingEntryToSpanData(entry).forEach((data) => span.setAttribute(...data)); setTimeout(cleanup); } }); }); } function getAbsoluteTime(time = 0) { return ((browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1e3; } function resourceTimingEntryToSpanData(resourceTiming) { const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol); const timingSpanData = []; timingSpanData.push(["network.protocol.version", version], ["network.protocol.name", name]); 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)] ]; } /** * A function that determines whether to attach tracing headers to a request. * We only export this function for testing purposes. */ function shouldAttachHeaders(targetUrl, tracePropagationTargets) { const href = WINDOW$1.location && WINDOW$1.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 (e) { return false; } const isSameOriginRequest = resolvedUrl.origin === currentOrigin; if (!tracePropagationTargets) return isSameOriginRequest; else return stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) || isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets); } } /** * Create and track xhr request spans * * @returns Span if a span was created, otherwise void. */ function xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeaders, spans) { const xhr = handlerData.xhr; const sentryXhrData = xhr && xhr["__sentry_xhr_v3__"]; if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) return; const shouldCreateSpanResult = hasTracingEnabled() && shouldCreateSpan(sentryXhrData.url); if (handlerData.endTimestamp && shouldCreateSpanResult) { const spanId = xhr.__sentry_xhr_span_id__; if (!spanId) return; const span = spans[spanId]; if (span && sentryXhrData.status_code !== void 0) { setHttpStatus(span, sentryXhrData.status_code); span.end(); delete spans[spanId]; } return; } 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 (shouldAttachHeaders(sentryXhrData.url)) addTracingHeadersToXhrRequest(xhr, hasTracingEnabled() && hasParent ? span : void 0); return span; } function addTracingHeadersToXhrRequest(xhr, span) { const { "sentry-trace": sentryTrace, baggage } = getTraceData({ span }); if (sentryTrace) setHeaderOnXhr(xhr, sentryTrace, baggage); } function setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader) { try { xhr.setRequestHeader("sentry-trace", sentryTraceHeader); if (sentryBaggageHeader) xhr.setRequestHeader("baggage", sentryBaggageHeader); } catch (_) {} } function getFullURL(url) { try { return new URL(url, WINDOW$1.location.origin).href; } catch (e2) { return; } } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/tracing/backgroundtab.js /** * Add a listener that cancels and finishes a transaction when the global * document is hidden. */ function registerBackgroundTabDetection() { if (WINDOW$1 && WINDOW$1.document) WINDOW$1.document.addEventListener("visibilitychange", () => { const activeSpan = getActiveSpan(); if (!activeSpan) return; const rootSpan = getRootSpan(activeSpan); if (WINDOW$1.document.hidden && rootSpan) { const cancelledStatus = "cancelled"; const { op, status } = spanToJSON(rootSpan); if (DEBUG_BUILD$2) logger$1.log(`[Tracing] Transaction: ${cancelledStatus} -> since tab moved to the background, op: ${op}`); if (!status) rootSpan.setStatus({ code: 2, message: cancelledStatus }); rootSpan.setAttribute("sentry.cancellation_reason", "document.hidden"); rootSpan.end(); } }); else DEBUG_BUILD$2 && logger$1.warn("[Tracing] Could not set up background tab detection due to lack of global document"); } //#endregion //#region ../../node_modules/.pnpm/@sentry+browser@8.55.2/node_modules/@sentry/browser/build/npm/esm/tracing/browserTracingIntegration.js var BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing"; var DEFAULT_BROWSER_TRACING_OPTIONS = { ...TRACING_DEFAULTS, instrumentNavigation: true, instrumentPageLoad: true, markBackgroundSpan: true, enableLongTask: true, enableLongAnimationFrame: true, enableInp: true, _experiments: {}, ...defaultRequestInstrumentationOptions }; /** * The Browser Tracing integration automatically instruments browser pageload/navigation * actions as transactions, and captures requests, metrics and errors as spans. * * The integration can be configured with a variety of options, and can be extended to use * any routing library. * * We explicitly export the proper type here, as this has to be extended in some cases. */ var browserTracingIntegration$1 = ((_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 }; /** Create routing idle transaction. */ 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, disableAutoFinish: isPageloadTransaction, beforeSpanEnd: (span) => { _collectWebVitals(); addPerformanceEntries(span, { recordClsOnPageloadSpan: !enableStandaloneClsSpans }); } }); function emitFinish() { if (["interactive", "complete"].includes(WINDOW$1.document.readyState)) client.emit("idleSpanEnableAutoFinish", idleSpan); } if (isPageloadTransaction && WINDOW$1.document) { WINDOW$1.document.addEventListener("readystatechange", () => { emitFinish(); }); emitFinish(); } return idleSpan; } return { name: BROWSER_TRACING_INTEGRATION_ID, afterAllSetup(client) { let activeSpan; let startingUrl = WINDOW$1.location && WINDOW$1.location.href; function maybeEndActiveSpan() { if (activeSpan && !spanToJSON(activeSpan).timestamp) { DEBUG_BUILD$2 && logger$1.log(`[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).op}`); activeSpan.end(); } } 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 propagationContext = propagationContextFromHeaders(traceOptions.sentryTrace || getMetaContent("sentry-trace"), traceOptions.baggage || getMetaContent("baggage")); getCurrentScope().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(); const oldPropagationContext = scope.getPropagationContext(); scope.setPropagationContext({ ...oldPropagationContext, sampled: oldPropagationContext.sampled !== void 0 ? oldPropagationContext.sampled : spanIsSampled(span), dsc: oldPropagationContext.dsc || getDynamicSamplingContextFromSpan(span) }); }); if (WINDOW$1.location) { if (instrumentPageLoad) startBrowserTracingPageLoadSpan(client, { name: WINDOW$1.location.pathname, startTime: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1e3 : void 0, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url", [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.browser" } }); if (instrumentNavigation) addHistoryInstrumentationHandler(({ to, from }) => { /** * This early return is there to account for some cases where a navigation transaction starts right after * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't * create an uneccessary navigation transaction. * * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also * only be caused in certain development environments where the usage of a hot module reloader is causing * errors. */ if (from === void 0 && startingUrl && startingUrl.indexOf(to) !== -1) { startingUrl = void 0; return; } if (from !== to) { startingUrl = void 0; startBrowserTracingNavigationSpan(client, { name: WINDOW$1.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 }); } }; }); /** * Manually start a page load span. * This will only do something if a browser tracing integration integration has been setup. * * If you provide a custom `traceOptions` object, it will be used to continue the trace * instead of the default behavior, which is to look it up on the tags. */ function startBrowserTracingPageLoadSpan(client, spanOptions, traceOptions) { client.emit("startPageLoadSpan", spanOptions, traceOptions); getCurrentScope().setTransactionName(spanOptions.name); const span = getActiveSpan(); return (span && spanToJSON(span).op) === "pageload" ? span : void 0; } /** * Manually start a navigation span. * This will only do something if a browser tracing integration has been setup. */ function startBrowserTracingNavigationSpan(client, spanOptions) { getIsolationScope().setPropagationContext({ traceId: generateTraceId() }); getCurrentScope().setPropagationContext({ traceId: generateTraceId() }); client.emit("startNavigationSpan", spanOptions); getCurrentScope().setTransactionName(spanOptions.name); const span = getActiveSpan(); return (span && spanToJSON(span).op) === "navigation" ? span : void 0; } /** Returns the value of a meta tag */ function getMetaContent(metaName) { const metaTag = getDomElement(`meta[name=${metaName}]`); return metaTag ? metaTag.getAttribute("content") : void 0; } /** Start listener for interaction transactions */ function registerInteractionListener(idleTimeout, finalTimeout, childSpanTimeout, latestRoute) { let inflightInteractionSpan; const registerInteractionTransaction = () => { 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$2 && logger$1.warn(`[Tracing] Did not create ${op} span because a pageload or navigation span is in progress.`); return; } } if (inflightInteractionSpan) { inflightInteractionSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, "interactionInterrupted"); inflightInteractionSpan.end(); inflightInteractionSpan = void 0; } if (!latestRoute.name) { DEBUG_BUILD$2 && logger$1.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`); return; } inflightInteractionSpan = startIdleSpan({ name: latestRoute.name, op, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.source || "url" } }, { idleTimeout, finalTimeout, childSpanTimeout }); }; if (WINDOW$1.document) addEventListener("click", registerInteractionTransaction, { once: false, capture: true }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/constants.js var DEFAULT_HOOKS = [ "activate", "mount", "update" ]; //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/debug-build.js /** * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/vendor/components.js var classifyRE = /(?:^|[-_])(\w)/g; var classify = (str) => str.replace(classifyRE, (c) => c.toUpperCase()).replace(/[-_]/g, ""); var ROOT_COMPONENT_NAME = ""; var ANONYMOUS_COMPONENT_NAME = ""; var repeat = (str, n) => { return str.repeat(n); }; var formatComponentName = (vm, includeFile) => { if (!vm) return ANONYMOUS_COMPONENT_NAME; if (vm.$root === vm) return ROOT_COMPONENT_NAME; if (!vm.$options) return ANONYMOUS_COMPONENT_NAME; const options = vm.$options; let name = options.name || options._componentTag || options.__name; const file = options.__file; if (!name && file) { const match = file.match(/([^/\\]+)\.vue$/); if (match) name = match[1]; } return (name ? `<${classify(name)}>` : ANONYMOUS_COMPONENT_NAME) + (file && includeFile !== false ? ` at ${file}` : ""); }; var generateComponentTrace = (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; } return `\n\nfound in\n\n${tree.map((vm, i) => `${(i === 0 ? "---> " : repeat(" ", 5 + i * 2)) + (Array.isArray(vm) ? `${formatComponentName(vm[0])}... (${vm[1]} recursive calls)` : formatComponentName(vm))}`).join("\n")}`; } return `\n\n(found in ${formatComponentName(vm)})`; }; //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/errorhandler.js var attachErrorHandler = (app, options) => { const { errorHandler: originalErrorHandler, warnHandler, silent } = app.config; app.config.errorHandler = (error, vm, lifecycleHook) => { const componentName = formatComponentName(vm, false); const trace = vm ? generateComponentTrace(vm) : ""; const metadata = { componentName, lifecycleHook, trace }; if (options.attachProps && vm) { if (vm.$options && vm.$options.propsData) metadata.propsData = vm.$options.propsData; else if (vm.$props) metadata.propsData = vm.$props; } setTimeout(() => { captureException(error, { captureContext: { contexts: { vue: metadata } }, mechanism: { handled: !!originalErrorHandler, type: "vue" } }); }); if (typeof originalErrorHandler === "function" && app.config.errorHandler) originalErrorHandler.call(app, error, vm, lifecycleHook); if (!originalErrorHandler) throw error; else if (options.logErrors) { const hasConsole = typeof console !== "undefined"; const message = `Error in ${lifecycleHook}: "${error && error.toString()}"`; if (warnHandler) warnHandler.call(null, message, vm, trace); else if (hasConsole && !silent) consoleSandbox(() => { console.error(`[Vue warn]: ${message}${trace}`); }); } }; }; //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/tracing.js var VUE_OP = "ui.vue"; var HOOKS = { activate: ["activated", "deactivated"], create: ["beforeCreate", "created"], unmount: ["beforeUnmount", "unmounted"], destroy: ["beforeDestroy", "destroyed"], mount: ["beforeMount", "mounted"], update: ["beforeUpdate", "updated"] }; /** Finish top-level span and activity with a debounce configured using `timeout` option */ function finishRootSpan(vm, timestamp, timeout) { if (vm.$_sentryRootSpanTimer) clearTimeout(vm.$_sentryRootSpanTimer); vm.$_sentryRootSpanTimer = setTimeout(() => { if (vm.$root && vm.$root.$_sentryRootSpan) { vm.$root.$_sentryRootSpan.end(timestamp); vm.$root.$_sentryRootSpan = void 0; } }, timeout); } /** Find if the current component exists in the provided `TracingOptions.trackComponents` array option. */ function findTrackComponent(trackComponents, formattedName) { function extractComponentName(name) { return name.replace(/^<([^\s]*)>(?: at [^\s]*)?$/, "$1"); } return trackComponents.some((compo) => { return extractComponentName(formattedName) === extractComponentName(compo); }); } var createTracingMixins = (options) => { const hooks = (options.hooks || []).concat(DEFAULT_HOOKS).filter((value, index, self) => self.indexOf(value) === index); const mixins = {}; for (const operation of hooks) { const internalHooks = HOOKS[operation]; if (!internalHooks) { DEBUG_BUILD && logger$1.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: { ["sentry.origin"]: "auto.ui.vue" }, onlyIfParent: true }); const name = formatComponentName(this, false); const shouldTrack = Array.isArray(options.trackComponents) ? findTrackComponent(options.trackComponents, name) : options.trackComponents; if (!isRoot && !shouldTrack) return; this.$_sentrySpans = this.$_sentrySpans || {}; if (internalHook == internalHooks[0]) { if (this.$root && this.$root.$_sentryRootSpan || getActiveSpan()) { const oldSpan = this.$_sentrySpans[operation]; if (oldSpan) oldSpan.end(); this.$_sentrySpans[operation] = startInactiveSpan({ name: `Vue ${name}`, op: `${VUE_OP}.${operation}`, attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.ui.vue" }, onlyIfParent: true }); } } else { const span = this.$_sentrySpans[operation]; if (!span) return; span.end(); finishRootSpan(this, timestampInSeconds(), options.timeout); } }; } return mixins; }; //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/integration.js var DEFAULT_CONFIG = { Vue: GLOBAL_OBJ.Vue, attachProps: true, logErrors: true, attachErrorHandler: true, hooks: DEFAULT_HOOKS, timeout: 2e3, trackComponents: false }; var INTEGRATION_NAME = "Vue"; var vueIntegration = defineIntegration((integrationOptions = {}) => { return { name: INTEGRATION_NAME, setup(client) { const options = { ...DEFAULT_CONFIG, ...client.getOptions(), ...integrationOptions }; if (!options.Vue && !options.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 (options.app) (Array.isArray(options.app) ? options.app : [options.app]).forEach((app) => vueInit(app, options)); else if (options.Vue) vueInit(options.Vue, options); } }; }); var vueInit = (app, options) => { if (DEBUG_BUILD) { const appWithInstance = app; if ((appWithInstance._instance && appWithInstance._instance.isMounted) === true) consoleSandbox(() => { console.warn("[@sentry/vue]: Misconfigured SDK. Vue app is already mounted. Make sure to call `app.mount()` after `Sentry.init()`."); }); } if (options.attachErrorHandler) attachErrorHandler(app, options); if (hasTracingEnabled(options)) app.mixin(createTracingMixins({ ...options, ...options.tracingOptions })); }; //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/sdk.js /** * Inits the Vue SDK */ function init(config = {}) { return init$1({ _metadata: { sdk: { name: "sentry.javascript.vue", packages: [{ name: "npm:@sentry/vue", version: SDK_VERSION }], version: SDK_VERSION } }, defaultIntegrations: [...getDefaultIntegrations(config), vueIntegration()], ...config }); } //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/router.js /** * Instrument the Vue router to create navigation spans. */ function instrumentVueRouter(router, options, startNavigationSpanFn) { let isFirstPageLoad = true; router.onError((error) => captureException(error, { mechanism: { handled: false } })); router.beforeEach((to, from, next) => { const isPageLoadNavigation = from.name == null && from.matched.length === 0 || from.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 value = to.query[key]; if (value) attributes[`query.${key}`] = value; } let spanName = to.path; let transactionSource = "url"; if (to.name && options.routeLabel !== "path") { spanName = to.name.toString(); transactionSource = "custom"; } else if (to.matched.length > 0) { const lastIndex = to.matched.length - 1; spanName = to.matched[lastIndex].path; transactionSource = "route"; } getCurrentScope().setTransactionName(spanName); if (options.instrumentPageLoad && isPageLoadNavigation) { const activeRootSpan = getActiveRootSpan(); if (activeRootSpan) { if ((spanToJSON(activeRootSpan).data || {})["sentry.source"] !== "custom") { activeRootSpan.updateName(spanName); activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, transactionSource); } activeRootSpan.setAttributes({ ...attributes, [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.pageload.vue" }); } } if (options.instrumentNavigation && !isPageLoadNavigation) { attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = transactionSource; attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] = "auto.navigation.vue"; startNavigationSpanFn({ name: spanName, op: "navigation", attributes }); } if (next) next(); }); } function getActiveRootSpan() { const span = getActiveSpan(); const rootSpan = span && getRootSpan(span); if (!rootSpan) return; const op = spanToJSON(rootSpan).op; return op === "navigation" || op === "pageload" ? rootSpan : void 0; } //#endregion //#region ../../node_modules/.pnpm/@sentry+vue@8.55.2_pinia@2.3.1_typescript@5.9.3_vue@3.5.33_typescript@5.9.3___vue@3.5.33_typescript@5.9.3_/node_modules/@sentry/vue/build/esm/browserTracingIntegration.js /** * A custom browser tracing integrations for Vue. */ function browserTracingIntegration(options = {}) { if (!options.router) return browserTracingIntegration$1(options); const integration = browserTracingIntegration$1({ ...options, instrumentNavigation: false }); const { router, instrumentNavigation = true, instrumentPageLoad = true, routeLabel = "name" } = options; return { ...integration, afterAllSetup(client) { integration.afterAllSetup(client); const startNavigationSpan = (options) => { startBrowserTracingNavigationSpan(client, options); }; instrumentVueRouter(router, { routeLabel, instrumentNavigation, instrumentPageLoad }, startNavigationSpan); } }; } //#endregion //#region ../send/frontend/src/lib/upload.ts /** * Turn the (optional) {@link ApiCallFailure} from the create-entry call into a * descriptive Error to use as the thrown error's `cause`, so the underlying * reason (network vs HTTP status/body) survives in Sentry instead of being a * bare "Failed to create upload entry". */ function createEntryFailureToCause(failure) { if (failure?.kind === "http") { const suffix = failure.body ? `: ${failure.body}` : ""; return /* @__PURE__ */ new Error(`create-entry HTTP ${failure.status} ${failure.statusText}${suffix}`); } if (failure?.kind === "network") return failure.error instanceof Error ? failure.error : /* @__PURE__ */ new Error(`create-entry network error: ${String(failure.error)}`); return /* @__PURE__ */ new Error("create-entry returned no result"); } var Uploader = class { constructor(user, keychain, api) { this.user = user; this.keychain = keychain; this.api = api; } /** * Asks the backend to delete every part this upload attempt wrote to storage. * Called when a multipart upload fails partway so that already-uploaded (and * partially-uploaded) parts don't linger as orphaned bytes in the bucket. */ async deleteWrittenUploads(api, ids) { if (ids.length === 0) return; await api.call("uploads/cleanup", { ids }, "POST"); } /** * Fire-and-forget cleanup for use during page teardown (pagehide), when an * upload is still in flight and the normal `if (fatalError)` cleanup will * never run. Uses a `keepalive` fetch so the request survives the page being * torn down, and cookie auth (`credentials: 'include'`) since requireJWT reads * the auth cookie — a Bearer header can't be attached reliably at unload time. * Best-effort only: hard kills/crashes still rely on the server-side reaper. */ teardownCleanup(api, ids) { if (ids.length === 0) return; try { fetch(`${api.serverUrl}/api/uploads/cleanup`, { method: "POST", keepalive: true, credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify({ ids }) }); } catch {} } /** * Creates a multipart progress tracker that manages overall progress across all parts */ createMultipartProgressTracker(mainTracker, blobSizes, isMultipart, originalFileSize) { const totalBlobSize = blobSizes.reduce((sum, size) => sum + size, 0); const partProgress = new Array(blobSizes.length).fill(0); const updateOverallProgress = () => { if (!isMultipart || blobSizes.length === 1) mainTracker.setProgress(Math.min(partProgress[0], originalFileSize)); else { const overallProgress = partProgress.reduce((sum, progress) => sum + progress, 0) / totalBlobSize * originalFileSize; mainTracker.setProgress(Math.min(overallProgress, originalFileSize)); } }; return { getPartTracker: (partIndex) => { const partSize = blobSizes[partIndex]; return { total: mainTracker.total, progressed: mainTracker.progressed, percentage: mainTracker.percentage, error: mainTracker.error, text: mainTracker.text, fileName: mainTracker.fileName, processStage: mainTracker.processStage, initialize: () => {}, setUploadSize: () => {}, setFileName: (name) => { mainTracker.setFileName(name); }, setProcessStage: (stage) => { mainTracker.setProcessStage(stage); }, setText: (message) => { mainTracker.setText(message); }, setProgress: (progress) => { partProgress[partIndex] = Math.min(progress, partSize); updateOverallProgress(); } }; }, markPartComplete: (partIndex) => { partProgress[partIndex] = blobSizes[partIndex]; updateOverallProgress(); } }; } async doUpload(fileBlob, containerId, api, progressTracker) { if (!containerId) return null; if (!fileBlob) return null; const wrappingKey = await this.keychain.get(containerId); if (!wrappingKey) return null; const key = await this.keychain.content.generateKey(); const wrappedKeyStr = await this.keychain.container.wrapContentKey(key, wrappingKey); const shouldSplit = fileBlob.size > SPLIT_SIZE; const numChunks = shouldSplit ? Math.ceil(fileBlob.size / SPLIT_SIZE) : 1; const partSizes = Array.from({ length: numChunks }, (_, i) => Math.min(SPLIT_SIZE, fileBlob.size - i * SPLIT_SIZE)); progressTracker.setUploadSize(fileBlob.size); progressTracker.setProcessStage("hashing"); progressTracker.setText("Hashing file"); const parts = new Array(numChunks); const hashes = new Array(numChunks); const partReady = Array.from({ length: numChunks }, () => { let resolve; let reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); promise.catch(() => {}); return { promise, resolve, reject }; }); if (shouldSplit) (async () => { let produced = 0; try { for await (const part of streamZippedParts(api, fileBlob, SPLIT_SIZE, (bytesHashed) => { if (parts[0] !== void 0) return; const pct = Math.round(bytesHashed / fileBlob.size * 100); progressTracker.setText(`Hashing file (${pct}%)`); })) { parts[produced] = part.blob; hashes[produced] = part.hash; partReady[produced].resolve(); produced++; } if (produced < numChunks) { const err = /* @__PURE__ */ new Error(`Streaming produced ${produced} of ${numChunks} expected parts`); for (let i = produced; i < numChunks; i++) partReady[i].reject(err); } } catch (err) { for (let i = produced; i < numChunks; i++) partReady[i].reject(err); } })(); else { const [singleHash] = await hashFiles(api, fileBlob, SPLIT_SIZE); parts[0] = fileBlob; hashes[0] = singleHash; partReady[0].resolve(); } const multipartTracker = this.createMultipartProgressTracker(progressTracker, partSizes, shouldSplit, fileBlob.size); const abortController = new AbortController(); const writtenUploadIds = /* @__PURE__ */ new Set(); const uploadPart = async (blob, index) => { const filename = blob.name; const isBucketStorage = api.isBucketStorage; const partTracker = multipartTracker.getPartTracker(index); const part = shouldSplit ? index + 1 : void 0; const id = await sendBlob(blob, key, api, partTracker, isBucketStorage, { signal: abortController.signal, onUploadId: (uploadId) => writtenUploadIds.add(uploadId) }); if (!id) throw new Error("Failed to send blob"); await retryUntilSuccessOrTimeout(async () => { const { size } = await this.api.call(`uploads/${id}/stat`); return !!size; }, 2e3, 18e4); let uploadResult = null; let upload = null; let retryCount = 0; const maxRetries = 5; while (retryCount < maxRetries && !uploadResult) { if (abortController.signal.aborted) throw new Error("Upload aborted"); try { if (!upload) { let createEntryFailure; const result = await this.api.call("uploads", { id, size: blob.size, ownerId: this.user.id, type: blob.type, containerId, part, fileHash: hashes[index] }, "POST", {}, { onFailure: (failure) => { createEntryFailure = failure; } }); if (!result) { const cause = createEntryFailureToCause(createEntryFailure); captureException(cause, { tags: { upload_stage: "create_entry", create_entry_failure_kind: createEntryFailure?.kind ?? "unknown", ...createEntryFailure?.kind === "http" ? { create_entry_http_status: String(createEntryFailure.status) } : {} }, contexts: { create_entry: { kind: createEntryFailure?.kind ?? "unknown", status: createEntryFailure?.kind === "http" ? createEntryFailure.status : null, statusText: createEntryFailure?.kind === "http" ? createEntryFailure.statusText : void 0, body: createEntryFailure?.kind === "http" ? createEntryFailure.body : void 0 } } }); throw new Error("Failed to create upload entry", { cause }); } upload = result.upload; } const itemObj = await this.api.call(`containers/${containerId}/item`, { uploadId: upload.id, name: filename, type: "MESSAGE", wrappedKey: wrappedKeyStr, multipart: shouldSplit ? true : false, totalSize: fileBlob.size }, "POST"); if (!itemObj) throw new Error("Failed to create item object"); uploadResult = { upload, itemObj }; } catch (error) { retryCount++; console.error(`Create-entry attempt ${retryCount} failed:`, error); if (retryCount >= maxRetries) { const failureMessage = `Upload failed for ${fileBlob.name} after ${maxRetries} attempts` + (part ? ` (part ${part})` : ""); console.error(failureMessage, error); throw new Error(failureMessage); } await new Promise((resolve) => setTimeout(resolve, Math.pow(2, retryCount) * 1e3)); } } const { itemObj } = uploadResult; const item = { ...itemObj, upload: { size: blob.size, type: blob.type, part } }; multipartTracker.markPartComplete(index); return item; }; const uploadResponses = new Array(numChunks); let nextIndex = 0; let fatalError = null; const runWorker = async () => { while (true) { if (fatalError) return; const index = nextIndex++; if (index >= numChunks) return; try { await partReady[index].promise; const item = await uploadPart(parts[index], index); if (!item) throw new Error(`Upload part ${index} returned no item`); uploadResponses[index] = item; parts[index] = void 0; } catch (error) { if (!fatalError) fatalError = error; abortController.abort(); return; } } }; const onPageHide = () => this.teardownCleanup(api, [...writtenUploadIds]); window.addEventListener("pagehide", onPageHide); try { const workerCount = Math.min(4, numChunks); await Promise.all(Array.from({ length: workerCount }, () => runWorker())); if (fatalError) { await this.deleteWrittenUploads(api, [...writtenUploadIds]).catch(() => {}); const failureMessage = fatalError instanceof Error ? fatalError.message : `Upload failed for ${fileBlob.name}`; progressTracker.setProcessStage("error"); progressTracker.setText(failureMessage); progressTracker.error = failureMessage; throw fatalError instanceof Error ? fatalError : new Error(failureMessage); } return uploadResponses; } finally { window.removeEventListener("pagehide", onPageHide); } } }; //#endregion //#region ../send/frontend/src/stores/keychain-store.ts var useKeychainStore = defineStore("keychain", () => { const keychain = new Keychain(new Storage$1()); function resetKeychain() { keychain._init(); } async function addKey(id, key) { await keychain.add(id, key); } async function getKey(id) { return await keychain.get(id); } function removeKey(id) { keychain.remove(id); } async function newKeyForContainer(id) { await keychain.newKeyForContainer(id); } return { keychain, resetKeychain, addKey, getKey, removeKey, newKeyForContainer }; }); //#endregion //#region ../send/frontend/src/types.ts var UserTier = /* @__PURE__ */ function(UserTier) { UserTier[UserTier["FREE"] = 1] = "FREE"; UserTier[UserTier["EPHEMERAL"] = 2] = "EPHEMERAL"; UserTier[UserTier["PRO"] = 3] = "PRO"; return UserTier; }({}); //#endregion //#region ../send/frontend/src/stores/user-store.ts var EMPTY_USER = { id: void 0, tier: UserTier.FREE, email: "", thundermailEmail: "" }; var useUserStore = defineStore("user", () => { const { api } = useApiStore(); const storage = new Storage$1(); const user = /* @__PURE__ */ reactive({ ...EMPTY_USER }); function populateUser(userData) { user.id = userData.id; user.tier = userData.tier; user.email = userData.email; user.thundermailEmail = userData.thundermailEmail; user.name = userData.name; if (userData.uniqueHash) user.uniqueHash = userData.uniqueHash; if (userData.thundermailEmail) user.thundermailEmail = userData.thundermailEmail; } async function createUser(email, jwkPublicKey, isEphemeral = false) { const resp = await api.call(`users`, { email, publicKey: jwkPublicKey, tier: isEphemeral ? UserTier.EPHEMERAL : UserTier.PRO }, "POST"); if (!resp) return null; return { id: resp.user.id, tier: resp.user.tier, email, thundermailEmail: resp.user.thundermailEmail, uniqueHash: resp.user.uniqueHash }; } async function login(loginEmail = user.email) { console.log(`logging in as ${loginEmail}`); const resp = await api.call(`users/login`, { email: loginEmail }, "POST"); if (!resp) return null; populateUser(resp); return resp; } async function loadFromLocalStorage() { try { const userFromStorage = await storage.getUserFromLocalStorage(); if (!userFromStorage) return false; const { id, tier, email, thundermailEmail, name } = userFromStorage; populateUser({ id, email, tier, thundermailEmail, name }); return true; } catch (e) { return false; } } async function store(newId, newTier, newEmail, newThundermailEmail, newName) { let { id, tier, email, thundermailEmail, name } = user; id = newId ?? id; tier = newTier ?? tier; email = newEmail ?? email; name = newName ?? name; thundermailEmail = newThundermailEmail ?? thundermailEmail; if (!id) return; await storage.storeUser({ id, tier, email, thundermailEmail, name }); } async function populateFromBackend() { if (user.id) return true; const userResp = await api.call(`users/me`); if (!userResp?.user) return false; populateUser(userResp.user); return true; } async function getPublicKey() { return (await api.call(`users/publickey/${user.id}`)).publicKey; } async function updatePublicKey(jwkPublicKey) { return (await api.call(`users/publickey`, { publicKey: jwkPublicKey }, "POST")).update?.publicKey; } async function createBackup(userId, keys, keypair, keystring, salt) { return await api.call(`users/${userId}/backup`, { keys, keypair, keystring, salt }, "POST"); } async function getBackup() { return await api.call(`users/backup`); } async function setUserToDefault() { Object.entries(EMPTY_USER).forEach(([key, value]) => { user[key] = value; }); } async function clearUserFromStorage() { storage.clear(); setUserToDefault(); } return { user, createUser, login, store, loadFromLocalStorage, populateFromBackend, getPublicKey, updatePublicKey, createBackup, getBackup, clearUserFromStorage }; }); //#endregion //#region ../send/frontend/src/lib/messages.ts var CLIENT_MESSAGES = { SHOULD_LOG_IN: `You need to log into your mozilla account. Make sure you're in the allow list for alpha access.`, FILE_TOO_BIG: `Your file size is not supported, please try with files smaller than ${MAX_FILE_SIZE_HUMAN_READABLE}`, UPLOAD_FAILED: `Upload failed. Please try again.`, STORAGE_LIMIT_EXCEEDED: `Uploading this file would exceed your storage limit. Please delete some files and try again.` }; //#endregion //#region ../send/frontend/src/lib/folderView.ts /** * This function is meant for managing files in a folder, handling multipart file deduplication * @returns Computed property containing unique files with multipart suffix removed */ var organizeFiles = (files) => { const items = []; if (!files) return []; files.forEach((item) => { if (!item?.multipart) { items.push(item); return; } if (item.upload.part === 1) items.push({ ...item, upload: { ...item.upload, size: item.totalSize } }); }); return items; }; //#endregion //#region ../../node_modules/.pnpm/posthog-js@1.372.5/node_modules/posthog-js/dist/module.js var t = "undefined" != typeof window ? window : void 0, e = "undefined" != typeof globalThis ? globalThis : t; "undefined" == typeof self && (e.self = e), "undefined" == typeof File && (e.File = function() {}); var i$1 = null == e ? void 0 : e.navigator, r$1 = null == e ? void 0 : e.document, s$1 = null == e ? void 0 : e.location, n$2 = null == e ? void 0 : e.fetch, o$1 = null != e && e.XMLHttpRequest && "withCredentials" in new e.XMLHttpRequest() ? e.XMLHttpRequest : void 0, a$1 = null == e ? void 0 : e.AbortController, l$1 = null == e ? void 0 : e.CompressionStream, u$1 = null == i$1 ? void 0 : i$1.userAgent, h$2 = null != t ? t : {}, d$2 = "1.372.5", v$1 = { DEBUG: !1, LIB_VERSION: d$2, LIB_NAME: "web", JS_SDK_VERSION: d$2 }; function c$2(t, e, i, r, s, n, o) { try { var a = t[n](o), l = a.value; } catch (t) { i(t); return; } a.done ? e(l) : Promise.resolve(l).then(r, s); } function p$1(t) { return function() { var e = this, i = arguments; return new Promise((function(r, s) { var n = t.apply(e, i); function o(t) { c$2(n, r, s, o, a, "next", t); } function a(t) { c$2(n, r, s, o, a, "throw", t); } o(void 0); })); }; } function f$1() { return f$1 = Object.assign ? Object.assign.bind() : function(t) { for (var e = 1; arguments.length > e; e++) { var i = arguments[e]; for (var r in i) ({}).hasOwnProperty.call(i, r) && (t[r] = i[r]); } return t; }, f$1.apply(null, arguments); } function _$1(t, e) { if (null == t) return {}; var i = {}; for (var r in t) if ({}.hasOwnProperty.call(t, r)) { if (-1 !== e.indexOf(r)) continue; i[r] = t[r]; } return i; } function g$2() { return g$2 = p$1((function* (t, e, i) { void 0 === e && (e = !0); try { var r = new CompressionStream("gzip"), s = r.writable.getWriter(), n = s.write(new TextEncoder().encode(t)).then((() => s.close())).catch(function() { var t = p$1((function* (t) { try { yield s.abort(t); } catch (t) {} throw t; })); return function(e) { return t.apply(this, arguments); }; }()), o = new Response(r.readable).blob(), [a] = yield Promise.all([o, n]); return a; } catch (t) { if (null != i && i.rethrow) throw t; return e && console.error("Failed to gzip compress data", t), null; } })), g$2.apply(this, arguments); } var m$2 = [ "amazonbot", "amazonproductbot", "app.hypefactors.com", "applebot", "archive.org_bot", "awariobot", "backlinksextendedbot", "baiduspider", "bingbot", "bingpreview", "chrome-lighthouse", "dataforseobot", "deepscan", "duckduckbot", "facebookexternal", "facebookcatalog", "http://yandex.com/bots", "hubspot", "ia_archiver", "leikibot", "linkedinbot", "meta-externalagent", "mj12bot", "msnbot", "nessus", "petalbot", "pinterest", "prerender", "rogerbot", "screaming frog", "sebot-wa", "sitebulb", "slackbot", "slurp", "trendictionbot", "turnitin", "twitterbot", "vercel-screenshot", "vercelbot", "yahoo! slurp", "yandexbot", "zoombot", "bot.htm", "bot.php", "(bot;", "bot/", "crawler", "ahrefsbot", "ahrefssiteaudit", "semrushbot", "siteauditbot", "splitsignalbot", "gptbot", "oai-searchbot", "chatgpt-user", "perplexitybot", "better uptime bot", "sentryuptimebot", "uptimerobot", "headlesschrome", "cypress", "google-hoteladsverifier", "adsbot-google", "apis-google", "duplexweb-google", "feedfetcher-google", "google favicon", "google web preview", "google-read-aloud", "googlebot", "googleother", "google-cloudvertexbot", "googleweblight", "mediapartners-google", "storebot-google", "google-inspectiontool", "bytespider" ], b$2 = function(t, e) { if (void 0 === e && (e = []), !t) return !1; var i = t.toLowerCase(); return m$2.concat(e).some(((t) => { var e = t.toLowerCase(); return -1 !== i.indexOf(e); })); }, y$2 = [ "$snapshot", "$pageview", "$pageleave", "$set", "survey dismissed", "survey sent", "survey shown", "$identify", "$groupidentify", "$create_alias", "$$client_ingestion_warning", "$web_experiment_applied", "$feature_enrollment_update", "$feature_flag_called" ]; function w$1(t, e) { return -1 !== t.indexOf(e); } var x$2 = function(t) { return t.trim(); }, E$2 = function(t) { return t.replace(/^\$/, ""); }, S$2 = Object.prototype, T$1 = S$2.hasOwnProperty, k$1 = S$2.toString, R$1 = Array.isArray || function(t) { return "[object Array]" === k$1.call(t); }, P$1 = (t) => "function" == typeof t, O$1 = (t) => t === Object(t) && !R$1(t), I = (t) => { if (O$1(t)) { for (var e in t) if (T$1.call(t, e)) return !1; return !0; } return !1; }, C$2 = (t) => void 0 === t, F$1 = (t) => "[object String]" == k$1.call(t), A$1 = (t) => F$1(t) && 0 === t.trim().length, M = (t) => null === t, D$1 = (t) => C$2(t) || M(t), L$1 = (t) => "[object Number]" == k$1.call(t) && t == t, U = (t) => L$1(t) && t > 0, N = (t) => "[object Boolean]" === k$1.call(t), j$1 = (t) => t instanceof FormData, z$1 = (t) => w$1(y$2, t); function B$2(t) { return null === t || "object" != typeof t; } function H$3(t, e) { return {}.toString.call(t) === "[object " + e + "]"; } function q$2(t) { return "undefined" != typeof Event && function(t, e) { try { return t instanceof e; } catch (t) { return !1; } }(t, Event); } var V = [ !0, "true", 1, "1", "yes" ], W$2 = (t) => w$1(V, t), G$2 = [ !1, "false", 0, "0", "no" ]; function Y$1(t, e, i, r, s) { return e > i && (r.warn("min cannot be greater than max."), e = i), L$1(t) ? t > i ? (r.warn(" cannot be greater than max: " + i + ". Using max value instead."), i) : e > t ? (r.warn(" cannot be less than min: " + e + ". Using min value instead."), e) : t : (r.warn(" must be a number. using max or fallback. max: " + i + ", fallback: " + s), Y$1(s || i, e, i, r)); } var J = class { constructor(t) { this.$t = {}, this.zt = t.zt, this.Ut = Y$1(t.bucketSize, 0, 100, t.Gt), this.Wt = Y$1(t.refillRate, 0, this.Ut, t.Gt), this.Xt = Y$1(t.refillInterval, 0, 864e5, t.Gt); } Jt(t, e) { var i = Math.floor((e - t.lastAccess) / this.Xt); i > 0 && (t.tokens = Math.min(t.tokens + i * this.Wt, this.Ut), t.lastAccess = t.lastAccess + i * this.Xt); } consumeRateLimit(t) { var e, i = Date.now(), r = String(t), s = this.$t[r]; return s ? this.Jt(s, i) : this.$t[r] = s = { tokens: this.Ut, lastAccess: i }, 0 === s.tokens || (s.tokens--, 0 === s.tokens && (null == (e = this.zt) || e.call(this, t)), 0 === s.tokens); } stop() { this.$t = {}; } }; var K$2, X$2, Q$1, Z$2 = "Mobile", tt$1 = "iOS", et$1 = "Android", it$1 = "Tablet", rt$1 = et$1 + " " + it$1, st$1 = "iPad", nt$1 = "Apple", ot$1 = nt$1 + " Watch", at = "Safari", lt$1 = "BlackBerry", ut = "Samsung", ht$1 = ut + "Browser", dt$1 = ut + " Internet", vt$1 = "Chrome", ct$1 = vt$1 + " OS", pt$1 = vt$1 + " " + tt$1, ft = "Internet Explorer", _t$1 = ft + " " + Z$2, gt$1 = "Opera", mt$1 = gt$1 + " Mini", bt$1 = "Edge", yt$1 = "Microsoft " + bt$1, wt$1 = "Firefox", xt = wt$1 + " " + tt$1, Et$1 = "Nintendo", St$1 = "PlayStation", $t$1 = "Xbox", Tt$1 = et$1 + " " + Z$2, kt$1 = Z$2 + " " + at, Rt$1 = "Windows", Pt$1 = Rt$1 + " Phone", Ot$1 = "Nokia", It$1 = "Ouya", Ct$1 = "Generic", Ft$1 = Ct$1 + " " + Z$2.toLowerCase(), At = Ct$1 + " " + it$1.toLowerCase(), Mt$1 = "Konqueror", Dt$1 = "(\\d+(\\.\\d+)?)", Lt$1 = new RegExp("Version/" + Dt$1), Ut = new RegExp($t$1, "i"), Nt = new RegExp(St$1 + " \\w+", "i"), jt$1 = new RegExp(Et$1 + " \\w+", "i"), zt = new RegExp(lt$1 + "|PlayBook|BB10", "i"), Bt$1 = { "NT3.51": "NT 3.11", "NT4.0": "NT 4.0", "5.0": "2000", 5.1: "XP", 5.2: "XP", "6.0": "Vista", 6.1: "7", 6.2: "8", 6.3: "8.1", 6.4: "10", "10.0": "10" }, Ht$1 = function(t, e) { return e = e || "", w$1(t, " OPR/") && w$1(t, "Mini") ? mt$1 : w$1(t, " OPR/") ? gt$1 : zt.test(t) ? lt$1 : w$1(t, "IE" + Z$2) || w$1(t, "WPDesktop") ? _t$1 : w$1(t, ht$1) ? dt$1 : w$1(t, bt$1) || w$1(t, "Edg/") ? yt$1 : w$1(t, "FBIOS") ? "Facebook " + Z$2 : w$1(t, "UCWEB") || w$1(t, "UCBrowser") ? "UC Browser" : w$1(t, "CriOS") ? pt$1 : w$1(t, "CrMo") || w$1(t, vt$1) ? vt$1 : w$1(t, et$1) && w$1(t, at) ? Tt$1 : w$1(t, "FxiOS") ? xt : w$1(t.toLowerCase(), Mt$1.toLowerCase()) ? Mt$1 : ((t, e) => e && w$1(e, nt$1) || function(t) { return w$1(t, at) && !w$1(t, vt$1) && !w$1(t, et$1); }(t))(t, e) ? w$1(t, Z$2) ? kt$1 : at : w$1(t, wt$1) ? wt$1 : w$1(t, "MSIE") || w$1(t, "Trident/") ? ft : w$1(t, "Gecko") ? wt$1 : ""; }, qt = { [_t$1]: [new RegExp("rv:" + Dt$1)], [yt$1]: [new RegExp(bt$1 + "?\\/" + Dt$1)], [vt$1]: [new RegExp("(" + vt$1 + "|CrMo)\\/" + Dt$1)], [pt$1]: [new RegExp("CriOS\\/" + Dt$1)], "UC Browser": [new RegExp("(UCBrowser|UCWEB)\\/" + Dt$1)], [at]: [Lt$1], [kt$1]: [Lt$1], [gt$1]: [new RegExp("(Opera|OPR)\\/" + Dt$1)], [wt$1]: [new RegExp(wt$1 + "\\/" + Dt$1)], [xt]: [new RegExp("FxiOS\\/" + Dt$1)], [Mt$1]: [new RegExp("Konqueror[:/]?" + Dt$1, "i")], [lt$1]: [new RegExp(lt$1 + " " + Dt$1), Lt$1], [Tt$1]: [new RegExp("android\\s" + Dt$1, "i")], [dt$1]: [new RegExp(ht$1 + "\\/" + Dt$1)], [ft]: [new RegExp("(rv:|MSIE )" + Dt$1)], Mozilla: [new RegExp("rv:" + Dt$1)] }, Vt$1 = function(t, e) { var r = qt[Ht$1(t, e)]; if (C$2(r)) return null; for (var s = 0; r.length > s; s++) { var n = t.match(r[s]); if (n) return parseFloat(n[n.length - 2]); } return null; }, Wt$1 = [ [new RegExp($t$1 + "; " + $t$1 + " (.*?)[);]", "i"), (t) => [$t$1, t && t[1] || ""]], [new RegExp(Et$1, "i"), [Et$1, ""]], [new RegExp(St$1, "i"), [St$1, ""]], [zt, [lt$1, ""]], [new RegExp(Rt$1, "i"), (t, e) => { if (/Phone/.test(e) || /WPDesktop/.test(e)) return [Pt$1, ""]; if (new RegExp(Z$2).test(e) && !/IEMobile\b/.test(e)) return [Rt$1 + " " + Z$2, ""]; var i = /Windows NT ([0-9.]+)/i.exec(e); if (i && i[1]) { var r = Bt$1[i[1]] || ""; return /arm/i.test(e) && (r = "RT"), [Rt$1, r]; } return [Rt$1, ""]; }], [/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/, (t) => t && t[3] ? [tt$1, [ t[3], t[4], t[5] || "0" ].join(".")] : [tt$1, ""]], [/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i, (t) => { var e = ""; return t && t.length >= 3 && (e = C$2(t[2]) ? t[3] : t[2]), ["watchOS", e]; }], [new RegExp("(" + et$1 + " (\\d+)\\.(\\d+)\\.?(\\d+)?|" + et$1 + ")", "i"), (t) => t && t[2] ? [et$1, [ t[2], t[3], t[4] || "0" ].join(".")] : [et$1, ""]], [/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i, (t) => { var e = ["Mac OS X", ""]; return t && t[1] && (e[1] = [ t[1], t[2], t[3] || "0" ].join(".")), e; }], [/Mac/i, ["Mac OS X", ""]], [/CrOS/, [ct$1, ""]], [/Linux|debian/i, ["Linux", ""]] ], Gt$1 = function(t) { return jt$1.test(t) ? Et$1 : Nt.test(t) ? St$1 : Ut.test(t) ? $t$1 : new RegExp(It$1, "i").test(t) ? It$1 : new RegExp("(" + Pt$1 + "|WPDesktop)", "i").test(t) ? Pt$1 : /iPad/.test(t) ? st$1 : /iPod/.test(t) ? "iPod Touch" : /iPhone/.test(t) ? "iPhone" : /(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t) ? ot$1 : zt.test(t) ? lt$1 : /(kobo)\s(ereader|touch)/i.test(t) ? "Kobo" : new RegExp(Ot$1, "i").test(t) ? Ot$1 : /(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t) || /(kf[a-z]+)( bui|\)).+silk\//i.test(t) ? "Kindle Fire" : /(Android|ZTE)/i.test(t) ? new RegExp(Z$2).test(t) && !/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t) || /pixel[\daxl ]{1,6}/i.test(t) && !/pixel c/i.test(t) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t) || /lmy47v/i.test(t) && !/QTAQZ3/i.test(t) ? et$1 : rt$1 : new RegExp("(pda|" + Z$2 + ")", "i").test(t) ? Ft$1 : new RegExp(it$1, "i").test(t) && !new RegExp(it$1 + " pc", "i").test(t) ? At : ""; }, Yt = (t) => t instanceof Error, Jt = { trace: { text: "TRACE", number: 1 }, debug: { text: "DEBUG", number: 5 }, info: { text: "INFO", number: 9 }, warn: { text: "WARN", number: 13 }, error: { text: "ERROR", number: 17 }, fatal: { text: "FATAL", number: 21 } }, Kt = Jt.info; function Xt(t) { if (N(t)) return { boolValue: t }; if ("number" == typeof t) return Number.isFinite(t) ? Number.isInteger(t) ? { intValue: t } : { doubleValue: t } : { stringValue: String(t) }; if ("string" == typeof t) return { stringValue: t }; if (R$1(t)) return { arrayValue: { values: t.map(((t) => Xt(t))) } }; try { return { stringValue: JSON.stringify(t) }; } catch (e) { return { stringValue: String(t) }; } } function Qt(t) { var e = []; for (var i in t) { var r = t[i]; M(r) || C$2(r) || e.push({ key: i, value: Xt(r) }); } return e; } function Zt(t) { var e = globalThis._posthogChunkIds; if (e) { var i = Object.keys(e); return Q$1 && i.length === X$2 || (X$2 = i.length, Q$1 = i.reduce(((i, r) => { K$2 || (K$2 = {}); var s = K$2[r]; if (s) i[s[0]] = s[1]; else for (var n = t(r), o = n.length - 1; o >= 0; o--) { var a = n[o], l = null == a ? void 0 : a.filename, u = e[r]; if (l && u) { i[l] = u, K$2[r] = [l, u]; break; } } return i; }), {})), Q$1; } } var te$1 = class { constructor(t, e, i) { void 0 === i && (i = []), this.coercers = t, this.stackParser = e, this.modifiers = i; } buildFromUnknown(t, e) { void 0 === e && (e = {}); var i = e && e.mechanism || { handled: !0, type: "generic" }, r = this.buildCoercingContext(i, e, 0).apply(t), s = this.buildParsingContext(e), n = this.parseStacktrace(r, s); return { $exception_list: this.convertToExceptionList(n, i), $exception_level: "error" }; } modifyFrames(t) { var e = this; return p$1((function* () { for (var i of t) i.stacktrace && i.stacktrace.frames && R$1(i.stacktrace.frames) && (i.stacktrace.frames = yield e.applyModifiers(i.stacktrace.frames)); return t; }))(); } coerceFallback(t) { var e; return { type: "Error", value: "Unknown error", stack: null == (e = t.syntheticException) ? void 0 : e.stack, synthetic: !0 }; } parseStacktrace(t, e) { var i, r; return null != t.cause && (i = this.parseStacktrace(t.cause, e)), "" != t.stack && null != t.stack && (r = this.applyChunkIds(this.stackParser(t.stack, t.synthetic ? e.skipFirstLines : 0), e.chunkIdMap)), f$1({}, t, { cause: i, stack: r }); } applyChunkIds(t, e) { return t.map(((t) => (t.filename && e && (t.chunk_id = e[t.filename]), t))); } applyCoercers(t, e) { for (var i of this.coercers) if (i.match(t)) return i.coerce(t, e); return this.coerceFallback(e); } applyModifiers(t) { var e = this; return p$1((function* () { var i = t; for (var r of e.modifiers) i = yield r(i); return i; }))(); } convertToExceptionList(t, e) { var i, r, s, n = { type: t.type, value: t.value, mechanism: { type: null !== (i = e.type) && void 0 !== i ? i : "generic", handled: null === (r = e.handled) || void 0 === r || r, synthetic: null !== (s = t.synthetic) && void 0 !== s && s } }; t.stack && (n.stacktrace = { type: "raw", frames: t.stack }); var o = [n]; return null != t.cause && o.push(...this.convertToExceptionList(t.cause, f$1({}, e, { handled: !0 }))), o; } buildParsingContext(t) { var e; return { chunkIdMap: Zt(this.stackParser), skipFirstLines: null !== (e = t.skipFirstLines) && void 0 !== e ? e : 1 }; } buildCoercingContext(t, e, i) { void 0 === i && (i = 0); var r = (i, r) => { if (4 >= r) { var s = this.buildCoercingContext(t, e, r); return this.applyCoercers(i, s); } }; return f$1({}, e, { syntheticException: 0 == i ? e.syntheticException : void 0, mechanism: t, apply: (t) => r(t, i), next: (t) => r(t, i + 1) }); } }; var ee$1 = "?"; function ie$1(t, e, i, r, s) { var n = { platform: t, filename: e, function: "" === i ? ee$1 : i, in_app: !0 }; return C$2(r) || (n.lineno = r), C$2(s) || (n.colno = s), n; } var re$1 = (t, e) => { var i = -1 !== t.indexOf("safari-extension"), r = -1 !== t.indexOf("safari-web-extension"); return i || r ? [-1 !== t.indexOf("@") ? t.split("@")[0] : ee$1, i ? "safari-extension:" + e : "safari-web-extension:" + e] : [t, e]; }, se$1 = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i, ne$1 = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, oe$2 = /\((\S*)(?::(\d+))(?::(\d+))\)/, ae$1 = (t, e) => { var i = se$1.exec(t); if (i) { var [, r, s, n] = i; return ie$1(e, r, ee$1, +s, +n); } var o = ne$1.exec(t); if (o) { if (o[2] && 0 === o[2].indexOf("eval")) { var a = oe$2.exec(o[2]); a && (o[2] = a[1], o[3] = a[2], o[4] = a[3]); } var [l, u] = re$1(o[1] || ee$1, o[2]); return ie$1(e, u, l, o[3] ? +o[3] : void 0, o[4] ? +o[4] : void 0); } }, le$2 = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i, ue$1 = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i, he$1 = (t, e) => { var i = le$2.exec(t); if (i) { if (i[3] && i[3].indexOf(" > eval") > -1) { var r = ue$1.exec(i[3]); r && (i[1] = i[1] || "eval", i[3] = r[1], i[4] = r[2], i[5] = ""); } var s = i[3], n = i[1] || ee$1; return [n, s] = re$1(n, s), ie$1(e, s, n, i[4] ? +i[4] : void 0, i[5] ? +i[5] : void 0); } }, de$1 = /\(error: (.*)\)/; var ve$1 = class { match(t) { return this.isDOMException(t) || this.isDOMError(t); } coerce(t, e) { var i = F$1(t.stack); return { type: this.getType(t), value: this.getValue(t), stack: i ? t.stack : void 0, cause: t.cause ? e.next(t.cause) : void 0, synthetic: !1 }; } getType(t) { return this.isDOMError(t) ? "DOMError" : "DOMException"; } getValue(t) { var e = t.name || (this.isDOMError(t) ? "DOMError" : "DOMException"); return t.message ? e + ": " + t.message : e; } isDOMException(t) { return H$3(t, "DOMException"); } isDOMError(t) { return H$3(t, "DOMError"); } }; var ce$1 = class { match(t) { return ((t) => t instanceof Error)(t); } coerce(t, e) { return { type: this.getType(t), value: this.getMessage(t, e), stack: this.getStack(t), cause: t.cause ? e.next(t.cause) : void 0, synthetic: !1 }; } getType(t) { return t.name || t.constructor.name; } getMessage(t, e) { var i = t.message; return String(i.error && "string" == typeof i.error.message ? i.error.message : i); } getStack(t) { return t.stacktrace || t.stack || void 0; } }; var pe$1 = class { constructor() {} match(t) { return H$3(t, "ErrorEvent") && null != t.error; } coerce(t, e) { var i; return e.apply(t.error) || { type: "ErrorEvent", value: t.message, stack: null == (i = e.syntheticException) ? void 0 : i.stack, synthetic: !0 }; } }; var fe$2 = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i; var _e$1 = class { match(t) { return "string" == typeof t; } coerce(t, e) { var i, [r, s] = this.getInfos(t); return { type: null != r ? r : "Error", value: null != s ? s : t, stack: null == (i = e.syntheticException) ? void 0 : i.stack, synthetic: !0 }; } getInfos(t) { var e = "Error", i = t, r = t.match(fe$2); return r && (e = r[1], i = r[2]), [e, i]; } }; var ge$1 = [ "fatal", "error", "warning", "log", "info", "debug" ]; function me$1(t, e) { void 0 === e && (e = 40); var i = Object.keys(t); if (i.sort(), !i.length) return "[object has no keys]"; for (var r = i.length; r > 0; r--) { var s = i.slice(0, r).join(", "); if (e >= s.length) return r === i.length ? s : s.length > e ? s.slice(0, e) + "..." : s; } return ""; } var be$2 = class { match(t) { return "object" == typeof t && null !== t; } coerce(t, e) { var i, r = this.getErrorPropertyFromObject(t); return r ? e.apply(r) : { type: this.getType(t), value: this.getValue(t), stack: null == (i = e.syntheticException) ? void 0 : i.stack, level: this.isSeverityLevel(t.level) ? t.level : "error", synthetic: !0 }; } getType(t) { return q$2(t) ? t.constructor.name : "Error"; } getValue(t) { if ("name" in t && "string" == typeof t.name) { var e = "'" + t.name + "' captured as exception"; return "message" in t && "string" == typeof t.message && (e += " with message: '" + t.message + "'"), e; } if ("message" in t && "string" == typeof t.message) return t.message; var i = this.getObjectClassName(t); return (i && "Object" !== i ? "'" + i + "'" : "Object") + " captured as exception with keys: " + me$1(t); } isSeverityLevel(t) { return F$1(t) && !A$1(t) && ge$1.indexOf(t) >= 0; } getErrorPropertyFromObject(t) { for (var e in t) if ({}.hasOwnProperty.call(t, e)) { var i = t[e]; if (Yt(i)) return i; } } getObjectClassName(t) { try { var e = Object.getPrototypeOf(t); return e ? e.constructor.name : void 0; } catch (t) { return; } } }; var ye$1 = class { match(t) { return q$2(t); } coerce(t, e) { var i, r = t.constructor.name; return { type: r, value: r + " captured as exception with keys: " + me$1(t), stack: null == (i = e.syntheticException) ? void 0 : i.stack, synthetic: !0 }; } }; var we$1 = class { match(t) { return B$2(t); } coerce(t, e) { var i; return { type: "Error", value: "Primitive value captured as exception: " + String(t), stack: null == (i = e.syntheticException) ? void 0 : i.stack, synthetic: !0 }; } }; var xe = class { match(t) { return H$3(t, "PromiseRejectionEvent") || this.isCustomEventWrappingRejection(t); } isCustomEventWrappingRejection(t) { if (!q$2(t)) return !1; try { var e = t.detail; return null != e && "object" == typeof e && "reason" in e; } catch (t) { return !1; } } coerce(t, e) { var i, r = this.getUnhandledRejectionReason(t); return B$2(r) ? { type: "UnhandledRejection", value: "Non-Error promise rejection captured with value: " + String(r), stack: null == (i = e.syntheticException) ? void 0 : i.stack, synthetic: !0 } : e.apply(r); } getUnhandledRejectionReason(t) { try { if ("reason" in t) return t.reason; if ("detail" in t && null != t.detail && "object" == typeof t.detail && "reason" in t.detail) return t.detail.reason; } catch (t) {} return t; } }; var Ee = "$message", Se$1 = "$timestamp", $e = new Set([Ee, Se$1]), Te$1 = { enabled: !0, max_bytes: 32768 }; function ke(t) { var e; return t ? { enabled: null !== (e = t.enabled) && void 0 !== e ? e : Te$1.enabled, max_bytes: Pe$1(t.max_bytes, Te$1.max_bytes) } : f$1({}, Te$1); } var Re = class { constructor(t) { this.Kt = [], this.Qt = 0, this.Bt = ke(t); } setConfig(t) { this.Bt = ke(t), this.er(); } add(t) { var e = function(t) { var e = function(t) { var e = /* @__PURE__ */ new WeakSet(); try { return JSON.stringify(t, ((t, i) => { if ("bigint" == typeof i) return i.toString(); if ("function" != typeof i && "symbol" != typeof i) { if (i instanceof Date) return i.toISOString(); if (i instanceof Error) return { name: i.name, message: i.message, stack: i.stack }; if (i && "object" == typeof i) { if (e.has(i)) return "[Circular]"; e.add(i); } return i; } })); } catch (t) { return; } }(t); if (e) try { var i = JSON.parse(e); if (!O$1(i)) return; var r = i, s = r[Ee], n = r[Se$1]; if (!F$1(s) || 0 === s.trim().length) return; if (!F$1(n) && !L$1(n)) return; return { step: r, json: e }; } catch (t) { return; } }(t); if (e) { var i = function(t) { if ("undefined" != typeof TextEncoder) return new TextEncoder().encode(t).length; for (var e = encodeURIComponent(t), i = 0, r = 0; e.length > r; r++) "%" === e[r] ? (i += 1, r += 2) : i += 1; return i; }(e.json); i > this.Bt.max_bytes || (this.Kt.push({ step: e.step, bytes: i }), this.Qt += i, this.er()); } } getAttachable() { return this.Kt.map(((t) => t.step)); } clear() { this.Kt = [], this.Qt = 0; } size() { return this.Kt.length; } er() { for (; this.Qt > this.Bt.max_bytes && this.Kt.length > 0;) { var t = this.Kt.shift(); t && (this.Qt -= t.bytes); } } }; function Pe$1(t, e) { if (!L$1(t) || t === Infinity || t === -Infinity) return e; var i = Math.floor(t); return 0 > i ? e : i; } var Oe$2 = function(e, i) { var { debugEnabled: r } = void 0 === i ? {} : i, s = { C(i) { if (t && (v$1.DEBUG || h$2.POSTHOG_DEBUG || r) && !C$2(t.console) && t.console) { for (var s = ("__rrweb_original__" in t.console[i]) ? t.console[i].__rrweb_original__ : t.console[i], n = arguments.length, o = new Array(n > 1 ? n - 1 : 0), a = 1; n > a; a++) o[a - 1] = arguments[a]; s(e, ...o); } }, info() { for (var t = arguments.length, e = new Array(t), i = 0; t > i; i++) e[i] = arguments[i]; s.C("log", ...e); }, warn() { for (var t = arguments.length, e = new Array(t), i = 0; t > i; i++) e[i] = arguments[i]; s.C("warn", ...e); }, error() { for (var t = arguments.length, e = new Array(t), i = 0; t > i; i++) e[i] = arguments[i]; s.C("error", ...e); }, critical() { for (var t = arguments.length, i = new Array(t), r = 0; t > r; r++) i[r] = arguments[r]; console.error(e, ...i); }, uninitializedWarning(t) { s.error("You must initialize PostHog before calling " + t); }, createLogger: (t, i) => Oe$2(e + " " + t, i) }; return s; }, Ie = Oe$2("[PostHog.js]"), Ce$1 = Ie.createLogger, Fe = Ce$1("[ExternalScriptsLoader]"), Ae$1 = (t, e, i) => { if (t.config.disable_external_dependency_loading) return Fe.warn(e + " was requested but loading of external scripts is disabled."), i("Loading of external scripts is disabled"); var s = null == r$1 ? void 0 : r$1.querySelectorAll("script"); if (s) { for (var n, o = function() { if (s[a].src === e) { var t = s[a]; return t.__posthog_loading_callback_fired ? { v: i() } : (t.addEventListener("load", ((e) => { t.__posthog_loading_callback_fired = !0, i(void 0, e); })), t.onerror = (t) => i(t), { v: void 0 }); } }, a = 0; s.length > a; a++) if (n = o()) return n.v; } var l = () => { if (!r$1) return i("document not found"); var s = r$1.createElement("script"); if (s.type = "text/javascript", s.crossOrigin = "anonymous", s.src = e, s.onload = (t) => { s.__posthog_loading_callback_fired = !0, i(void 0, t); }, s.onerror = (t) => i(t), t.config.prepare_external_dependency_script && (s = t.config.prepare_external_dependency_script(s)), !s) return i("prepare_external_dependency_script returned null"); if ("head" === t.config.external_scripts_inject_target) r$1.head.appendChild(s); else { var n, o = r$1.querySelectorAll("body > script"); o.length > 0 ? null == (n = o[0].parentNode) || n.insertBefore(s, o[0]) : r$1.body.appendChild(s); } }; null != r$1 && r$1.body ? l() : r$1?.addEventListener("DOMContentLoaded", l); }; h$2.__PosthogExtensions__ = h$2.__PosthogExtensions__ || {}, h$2.__PosthogExtensions__.loadExternalDependency = (t, e, i) => { if ("remote-config" !== e) { var r; if (t.config.__preview_external_dependency_versioned_paths) r = t.requestRouter.endpointFor("assets", "/static/" + t.version + "/" + e + ".js"); else { var s = "/static/" + e + ".js?v=" + t.version; if ("toolbar" === e) { var n = 3e5; s = s + "&t=" + Math.floor(Date.now() / n) * n; } r = t.requestRouter.endpointFor("assets", s); } Ae$1(t, r, i); } else Ae$1(t, t.requestRouter.endpointFor("assets", "/array/" + t.config.token + "/config.js"), i); }, h$2.__PosthogExtensions__.loadSiteApp = (t, e, i) => { Ae$1(t, t.requestRouter.endpointFor("api", e), i); }; var Me$1 = "$people_distinct_id", De$1 = "$device_id", Le = "__alias", Ue = "__timers", Ne$2 = "$autocapture_disabled_server_side", je$1 = "$heatmaps_enabled_server_side", ze$1 = "$exception_capture_enabled_server_side", Be$1 = "$error_tracking_suppression_rules", He$2 = "$error_tracking_capture_extension_exceptions", qe = "$web_vitals_enabled_server_side", Ve = "$dead_clicks_enabled_server_side", We = "$product_tours_enabled_server_side", Ge = "$web_vitals_allowed_metrics", Ye$1 = "$session_recording_remote_config", Je = "$replay_override_sampling", Ke = "$replay_override_linked_flag", Xe = "$replay_override_url_trigger", Qe = "$replay_override_event_trigger", Ze$1 = "$sesid", ti = "$session_is_sampled", ei = "$enabled_feature_flags", ii = "$active_feature_flags", ri = "$early_access_features", si = "$feature_flag_details", ni = "$feature_flag_payloads", oi = "$feature_flag_request_id", ai = "$override_feature_flags", li = "$override_feature_flag_payloads", ui = "$stored_person_properties", hi = "$stored_group_properties", di = "$surveys", vi = "$surveys_activated", ci = "ph_product_tours", pi = "$flag_call_reported", fi = "$flag_call_reported_session_id", _i = "$feature_flag_errors", gi = "$feature_flag_evaluated_at", mi = "$user_state", bi = "$client_session_props", yi = "$capture_rate_limit", wi = "$initial_campaign_params", xi = "$initial_referrer_info", Ei = "$initial_person_info", Si = "$epp", $i = "__POSTHOG_TOOLBAR__", Ti = "$posthog_cookieless", ki = "$sdk_debug_extensions_init_method", Ri = "$sdk_debug_extensions_init_time_ms", Pi = "$sdk_debug_recording_script_not_loaded", Oi = "PostHog loadExternalDependency extension not found.", Ii = "on_reject", Ci = "always", Fi = "anonymous", Ai = "identified", Mi = "identified_only", Di = "visibilitychange", Li = "beforeunload", Ui = "$pageview", Ni = "$pageleave", ji = "$identify", zi = "$groupidentify"; function Bi(t, e) { R$1(t) && t.forEach(e); } function Hi(t, e) { if (!D$1(t)) if (R$1(t)) t.forEach(e); else if (j$1(t)) t.forEach(((t, i) => e(t, i))); else for (var i in t) T$1.call(t, i) && e(t[i], i); } var qi = function(t) { for (var e = arguments.length, i = new Array(e > 1 ? e - 1 : 0), r = 1; e > r; r++) i[r - 1] = arguments[r]; for (var s of i) for (var n in s) void 0 !== s[n] && (t[n] = s[n]); return t; }; function Vi(t) { for (var e = Object.keys(t), i = e.length, r = new Array(i); i--;) r[i] = [e[i], t[e[i]]]; return r; } var Wi = function(t) { try { return t(); } catch (t) { return; } }, Gi = function(t) { return function() { try { for (var e = arguments.length, i = new Array(e), r = 0; e > r; r++) i[r] = arguments[r]; return t.apply(this, i); } catch (t) { Ie.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."), Ie.critical(t); } }; }, Yi = function(t) { var e = {}; return Hi(t, (function(t, i) { (F$1(t) && t.length > 0 || L$1(t)) && (e[i] = t); })), e; }; var Ji = [ "herokuapp.com", "vercel.app", "netlify.app" ]; function Ki(t) { var e = null == t ? void 0 : t.hostname; if (!F$1(e)) return !1; var i = e.split(".").slice(-2).join("."); for (var r of Ji) if (i === r) return !1; return !0; } function Xi(t, e, i, r) { var { capture: s = !1, passive: n = !0 } = null != r ? r : {}; t?.addEventListener(e, i, { capture: s, passive: n }); } function Qi(t) { return "ph_toolbar_internal" === t.name; } Math.trunc || (Math.trunc = function(t) { return 0 > t ? Math.ceil(t) : Math.floor(t); }), Number.isInteger || (Number.isInteger = function(t) { return L$1(t) && isFinite(t) && Math.floor(t) === t; }); var Zi = class Zi { constructor(t) { if (this.bytes = t, 16 !== t.length) throw new TypeError("not 128-bit length"); } static fromFieldsV7(t, e, i, r) { if (!Number.isInteger(t) || !Number.isInteger(e) || !Number.isInteger(i) || !Number.isInteger(r) || 0 > t || 0 > e || 0 > i || 0 > r || t > 0xffffffffffff || e > 4095 || i > 1073741823 || r > 4294967295) throw new RangeError("invalid field value"); var s = new Uint8Array(16); return s[0] = t / Math.pow(2, 40), s[1] = t / Math.pow(2, 32), s[2] = t / Math.pow(2, 24), s[3] = t / Math.pow(2, 16), s[4] = t / Math.pow(2, 8), s[5] = t, s[6] = 112 | e >>> 8, s[7] = e, s[8] = 128 | i >>> 24, s[9] = i >>> 16, s[10] = i >>> 8, s[11] = i, s[12] = r >>> 24, s[13] = r >>> 16, s[14] = r >>> 8, s[15] = r, new Zi(s); } toString() { for (var t = "", e = 0; this.bytes.length > e; e++) t = t + (this.bytes[e] >>> 4).toString(16) + (15 & this.bytes[e]).toString(16), 3 !== e && 5 !== e && 7 !== e && 9 !== e || (t += "-"); if (36 !== t.length) throw new Error("Invalid UUIDv7 was generated"); return t; } clone() { return new Zi(this.bytes.slice(0)); } equals(t) { return 0 === this.compareTo(t); } compareTo(t) { for (var e = 0; 16 > e; e++) { var i = this.bytes[e] - t.bytes[e]; if (0 !== i) return Math.sign(i); } return 0; } }; var tr = class { constructor() { this.I = 0, this.S = 0, this.k = new rr(); } generate() { var t = this.generateOrAbort(); if (C$2(t)) { this.I = 0; var e = this.generateOrAbort(); if (C$2(e)) throw new Error("Could not generate UUID after timestamp reset"); return e; } return t; } generateOrAbort() { var t = Date.now(); if (t > this.I) this.I = t, this.A(); else { if (this.I >= t + 1e4) return; this.S++, this.S > 4398046511103 && (this.I++, this.A()); } return Zi.fromFieldsV7(this.I, Math.trunc(this.S / Math.pow(2, 30)), this.S & Math.pow(2, 30) - 1, this.k.nextUint32()); } A() { this.S = 1024 * this.k.nextUint32() + (1023 & this.k.nextUint32()); } }; var er, ir = (t) => { if ("undefined" != typeof UUIDV7_DENY_WEAK_RNG && UUIDV7_DENY_WEAK_RNG) throw new Error("no cryptographically strong RNG available"); for (var e = 0; t.length > e; e++) t[e] = 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random()); return t; }; t && !C$2(t.crypto) && crypto.getRandomValues && (ir = (t) => crypto.getRandomValues(t)); var rr = class { constructor() { this.T = new Uint32Array(8), this.N = Infinity; } nextUint32() { return this.T.length > this.N || (ir(this.T), this.N = 0), this.T[this.N++]; } }; var sr = () => nr().toString(), nr = () => (er || (er = new tr())).generate(), or = "", ar = /[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i; var lr = { R: () => !!r$1, B(t) { Ie.error("cookieStore error: " + t); }, O(t) { if (r$1) { try { for (var e = t + "=", i = r$1.cookie.split(";").filter(((t) => t.length)), s = 0; i.length > s; s++) { for (var n = i[s]; " " == n.charAt(0);) n = n.substring(1, n.length); if (0 === n.indexOf(e)) return decodeURIComponent(n.substring(e.length, n.length)); } } catch (t) {} return null; } }, Z(t) { var e; try { e = JSON.parse(lr.O(t)) || {}; } catch (t) {} return e; }, M(t, e, i, s, n) { if (r$1) try { var o = "", a = "", l = function(t, e) { if (e) { var i = function(t, e) { if (void 0 === e && (e = r$1), or) return or; if (!e) return ""; if (["localhost", "127.0.0.1"].includes(t)) return ""; for (var i = t.split("."), s = Math.min(i.length, 8), n = "dmn_chk_" + sr(); !or && s--;) { var o = i.slice(s).join("."), a = n + "=1;domain=." + o + ";path=/"; e.cookie = a + ";max-age=3", e.cookie.includes(n) && (e.cookie = a + ";max-age=0", or = o); } return or; }(t); if (!i) { var s = ((t) => { var e = t.match(ar); return e ? e[0] : ""; })(t); s !== i && Ie.info("Warning: cookie subdomain discovery mismatch", s, i), i = s; } return i ? "; domain=." + i : ""; } return ""; }(r$1.location.hostname, s); if (i) { var u = /* @__PURE__ */ new Date(); u.setTime(u.getTime() + 864e5 * i), o = "; expires=" + u.toUTCString(); } n && (a = "; secure"); var h = t + "=" + encodeURIComponent(JSON.stringify(e)) + o + "; SameSite=Lax; path=/" + l + a; return h.length > 3686.4 && Ie.warn("cookieStore warning: large cookie, len=" + h.length), r$1.cookie = h, h; } catch (t) { return; } }, F(t, e) { if (null != r$1 && r$1.cookie) try { lr.M(t, "", -1, e); } catch (t) { return; } } }, ur = null, hr = { R() { if (!M(ur)) return ur; var e = !0; if (C$2(t)) e = !1; else try { var i = "__mplssupport__"; hr.M(i, "xyz"), "\"xyz\"" !== hr.O(i) && (e = !1), hr.F(i); } catch (t) { e = !1; } return e || Ie.error("localStorage unsupported; falling back to cookie store"), ur = e, e; }, B(t) { Ie.error("localStorage error: " + t); }, O(e) { try { return null == t ? void 0 : t.localStorage.getItem(e); } catch (t) { hr.B(t); } return null; }, Z(t) { try { return JSON.parse(hr.O(t)) || {}; } catch (t) {} return null; }, M(e, i) { try { t?.localStorage.setItem(e, JSON.stringify(i)); } catch (t) { hr.B(t); } }, F(e) { try { t?.localStorage.removeItem(e); } catch (t) { hr.B(t); } } }, dr = [ De$1, "distinct_id", Ze$1, ti, Si, Ei, mi ], vr = {}, cr = { R: () => !0, B(t) { Ie.error("memoryStorage error: " + t); }, O: (t) => vr[t] || null, Z: (t) => vr[t] || null, M(t, e) { vr[t] = e; }, F(t) { delete vr[t]; } }, pr = null, fr = { R() { if (!M(pr)) return pr; if (pr = !0, C$2(t)) pr = !1; else try { var e = "__support__"; fr.M(e, "xyz"), "\"xyz\"" !== fr.O(e) && (pr = !1), fr.F(e); } catch (t) { pr = !1; } return pr; }, B(t) { Ie.error("sessionStorage error: ", t); }, O(e) { try { return null == t ? void 0 : t.sessionStorage.getItem(e); } catch (t) { fr.B(t); } return null; }, Z(t) { try { return JSON.parse(fr.O(t)) || null; } catch (t) {} return null; }, M(e, i) { try { t?.sessionStorage.setItem(e, JSON.stringify(i)); } catch (t) { fr.B(t); } }, F(e) { try { t?.sessionStorage.removeItem(e); } catch (t) { fr.B(t); } } }; var _r = class { constructor(t) { this._instance = t; } get Bt() { return this._instance.config; } get consent() { return this.rr() ? 0 : this.ir; } isOptedOut() { return this.Bt.cookieless_mode === Ci || this.isRejected() || -1 === this.consent && this.Bt.cookieless_mode === Ii; } isOptedIn() { return !this.isOptedOut(); } isExplicitlyOptedOut() { return 0 === this.consent; } isRejected() { return 0 === this.consent || -1 === this.consent && this.Bt.opt_out_capturing_by_default; } optInOut(t) { this.nr.M(this.sr, t ? 1 : 0, this.Bt.cookie_expiration, this.Bt.cross_subdomain_cookie, this.Bt.secure_cookie); } reset() { this.nr.F(this.sr, this.Bt.cross_subdomain_cookie); } get sr() { var { token: t, opt_out_capturing_cookie_prefix: e, consent_persistence_name: i } = this._instance.config; return i || (e ? e + t : "__ph_opt_in_out_" + t); } get ir() { var t = this.nr.O(this.sr); return W$2(t) ? 1 : w$1(G$2, t) ? 0 : -1; } get nr() { var t = this.Bt.opt_out_capturing_persistence_type, e = "localStorage" === t ? hr : lr; if (!this.ar || this.ar !== e) { this.ar = e; var i = "localStorage" === t ? lr : hr; i.O(this.sr) && (this.ar.O(this.sr) || this.optInOut(W$2(i.O(this.sr))), i.F(this.sr, this.Bt.cross_subdomain_cookie)); } return this.ar; } rr() { return !!this.Bt.respect_dnt && [ null == i$1 ? void 0 : i$1.doNotTrack, null == i$1 ? void 0 : i$1.msDoNotTrack, h$2.doNotTrack ].some(((t) => W$2(t))); } }; var gr = Ce$1("[Dead Clicks]"), mr = () => !0, br = (t) => { var e, i = !(null == (e = t.instance.persistence) || !e.get_property(Ve)), r = t.instance.config.capture_dead_clicks; return N(r) ? r : !!O$1(r) || i; }; var yr = class { get lazyLoadedDeadClicksAutocapture() { return this.lr; } constructor(t, e, i) { this.instance = t, this.isEnabled = e, this.onCapture = i, this.startIfEnabledOrStop(); } onRemoteConfig(t) { "captureDeadClicks" in t && (this.instance.persistence && this.instance.persistence.register({ [Ve]: t.captureDeadClicks }), this.startIfEnabledOrStop()); } startIfEnabledOrStop() { this.isEnabled(this) ? this.ur((() => { this.hr(); })) : this.stop(); } ur(t) { var e, i; null != (e = h$2.__PosthogExtensions__) && e.initDeadClicksAutocapture && t(), null == (i = h$2.__PosthogExtensions__) || null == i.loadExternalDependency || i.loadExternalDependency(this.instance, "dead-clicks-autocapture", ((e) => { e ? gr.error("failed to load script", e) : t(); })); } hr() { var t; if (r$1) { if (!this.lr && null != (t = h$2.__PosthogExtensions__) && t.initDeadClicksAutocapture) { var e = O$1(this.instance.config.capture_dead_clicks) ? this.instance.config.capture_dead_clicks : {}; e.__onCapture = this.onCapture, this.lr = h$2.__PosthogExtensions__.initDeadClicksAutocapture(this.instance, e), this.lr.start(r$1), gr.info("starting..."); } } else gr.error("`document` not found. Cannot start."); } stop() { this.lr && (this.lr.stop(), this.lr = void 0, gr.info("stopping...")); } }; var wr = Ce$1("[SegmentIntegration]"); var xr = "posthog-js"; function Er(t, e) { var { organization: i, projectId: r, prefix: s, severityAllowList: n = ["error"], sendExceptionsToPostHog: o = !0 } = void 0 === e ? {} : e; return (e) => { var a, l, u, h, d; if ("*" !== n && !n.includes(e.level) || !t.__loaded) return e; e.tags || (e.tags = {}); var v = t.requestRouter.endpointFor("ui", "/project/" + t.config.token + "/person/" + t.get_distinct_id()); e.tags["PostHog Person URL"] = v, t.sessionRecordingStarted() && (e.tags["PostHog Recording URL"] = t.get_session_replay_url({ withTimestamp: !0 })); var c, p = (null == (a = e.exception) ? void 0 : a.values) || [], _ = p.map(((t) => f$1({}, t, { stacktrace: t.stacktrace ? f$1({}, t.stacktrace, { type: "raw", frames: (t.stacktrace.frames || []).map(((t) => f$1({}, t, { platform: "web:javascript" }))) }) : void 0 }))), g = { $exception_message: (null == (l = p[0]) ? void 0 : l.value) || e.message, $exception_type: null == (u = p[0]) ? void 0 : u.type, $exception_level: e.level, $exception_list: _, $sentry_event_id: e.event_id, $sentry_exception: e.exception, $sentry_exception_message: (null == (h = p[0]) ? void 0 : h.value) || e.message, $sentry_exception_type: null == (d = p[0]) ? void 0 : d.type, $sentry_tags: e.tags }; return i && r && (g.$sentry_url = (s || "https://sentry.io/organizations/") + i + "/issues/?project=" + r + "&query=" + e.event_id), o && (null == (c = t.exceptions) || c.sendExceptionEvent(g)), e; }; } var Sr = class { constructor(t, e, i, r, s, n) { this.name = xr, this.setupOnce = function(o) { o(Er(t, { organization: e, projectId: i, prefix: r, severityAllowList: s, sendExceptionsToPostHog: null == n || n })); }; } }; var $r = class { constructor(t) { this.cr = (t, e, i) => { i && (i.noSessionId || i.activityTimeout || i.sessionPastMaximumLength) && (Ie.info("[PageViewManager] Session rotated, clearing pageview state", { sessionId: t, changeReason: i }), this.dr = void 0, this._instance.scrollManager.resetContext()); }, this._instance = t, this.vr(); } vr() { var t; this.pr = null == (t = this._instance.sessionManager) ? void 0 : t.onSessionId(this.cr); } destroy() { var t; null == (t = this.pr) || t.call(this), this.pr = void 0; } doPageView(e, i) { var r, s = this.gr(e, i); return this.dr = { pathname: null !== (r = null == t ? void 0 : t.location.pathname) && void 0 !== r ? r : "", pageViewId: i, timestamp: e }, this._instance.scrollManager.resetContext(), s; } doPageLeave(t) { var e; return this.gr(t, null == (e = this.dr) ? void 0 : e.pageViewId); } doEvent() { var t; return { $pageview_id: null == (t = this.dr) ? void 0 : t.pageViewId }; } gr(t, e) { var i = this.dr; if (!i) return { $pageview_id: e }; var r = { $pageview_id: e, $prev_pageview_id: i.pageViewId }, s = this._instance.scrollManager.getContext(); if (s && !this._instance.config.disable_scroll_properties) { var { maxScrollHeight: n, lastScrollY: o, maxScrollY: a, maxContentHeight: l, lastContentY: u, maxContentY: h } = s; if (!(C$2(n) || C$2(o) || C$2(a) || C$2(l) || C$2(u) || C$2(h))) { n = Math.ceil(n), o = Math.ceil(o), a = Math.ceil(a), l = Math.ceil(l), u = Math.ceil(u), h = Math.ceil(h); var d = n > 1 ? Y$1(o / n, 0, 1, Ie) : 1, v = n > 1 ? Y$1(a / n, 0, 1, Ie) : 1, c = l > 1 ? Y$1(u / l, 0, 1, Ie) : 1, p = l > 1 ? Y$1(h / l, 0, 1, Ie) : 1; r = qi(r, { $prev_pageview_last_scroll: o, $prev_pageview_last_scroll_percentage: d, $prev_pageview_max_scroll: a, $prev_pageview_max_scroll_percentage: v, $prev_pageview_last_content: u, $prev_pageview_last_content_percentage: c, $prev_pageview_max_content: h, $prev_pageview_max_content_percentage: p }); } } return i.pathname && (r.$prev_pageview_pathname = i.pathname), i.timestamp && (r.$prev_pageview_duration = (t.getTime() - i.timestamp.getTime()) / 1e3), r; } }; var Tr = { [Me$1]: { exposure: "hidden" }, [Le]: { exposure: "hidden" }, __cmpns: { exposure: "hidden" }, [Ue]: { exposure: "hidden" }, [Ne$2]: { exposure: "event" }, [je$1]: { exposure: "hidden" }, [ze$1]: { exposure: "event" }, [Be$1]: { exposure: "hidden" }, [He$2]: { exposure: "event" }, [qe]: { exposure: "event" }, [Ve]: { exposure: "event" }, [We]: { exposure: "hidden" }, [Ge]: { exposure: "event" }, [Ye$1]: { exposure: "hidden" }, $session_recording_enabled_server_side: { exposure: "hidden" }, [Ze$1]: { exposure: "hidden" }, [ti]: { exposure: "event" }, $session_past_minimum_duration: { exposure: "event" }, $session_recording_url_trigger_activated_session: { exposure: "event" }, $session_recording_event_trigger_activated_session: { exposure: "event" }, $debug_first_full_snapshot_timestamp: { exposure: "event" }, [ei]: { exposure: "derived", shouldSkipFromEventProperties: (t, e) => e(), transformToEventProperties(t) { if (!O$1(t)) return {}; for (var e = {}, i = Object.keys(t), r = 0; i.length > r; r++) e["$feature/" + i[r]] = t[i[r]]; return e; } }, [ii]: { exposure: "event" }, [ri]: { exposure: "hidden" }, [si]: { exposure: "hidden" }, [ni]: { exposure: "event" }, [oi]: { exposure: "event" }, [ai]: { exposure: "event" }, [li]: { exposure: "hidden" }, [ui]: { exposure: "hidden" }, [hi]: { exposure: "hidden" }, [di]: { exposure: "hidden" }, [vi]: { exposure: "event" }, [ci]: { exposure: "hidden" }, $product_tours_activated: { exposure: "hidden" }, $conversations_widget_session_id: { exposure: "event" }, $conversations_ticket_id: { exposure: "event" }, $conversations_widget_state: { exposure: "event" }, $conversations_user_traits: { exposure: "event" }, [pi]: { exposure: "hidden" }, [fi]: { exposure: "hidden" }, [_i]: { exposure: "hidden" }, [gi]: { exposure: "hidden" }, [mi]: { exposure: "hidden" }, [bi]: { exposure: "hidden" }, [yi]: { exposure: "hidden" }, [wi]: { exposure: "hidden" }, [xi]: { exposure: "hidden" }, [Ei]: { exposure: "hidden" }, [Si]: { exposure: "hidden" }, [Je]: { exposure: "event" }, [Ke]: { exposure: "event" }, [Xe]: { exposure: "event" }, [Qe]: { exposure: "event" }, [ki]: { exposure: "event" }, [Ri]: { exposure: "event" }, [Pi]: { exposure: "event" }, $sdk_debug_replay_event_trigger_status: { exposure: "event" }, $sdk_debug_replay_linked_flag_trigger_status: { exposure: "event" }, $sdk_debug_replay_matched_recording_trigger_groups: { exposure: "event" }, $sdk_debug_replay_remote_trigger_matching_config: { exposure: "event" }, $sdk_debug_replay_trigger_groups_count: { exposure: "event" }, $sdk_debug_replay_url_trigger_status: { exposure: "event" }, $session_recording_start_reason: { exposure: "event" } }, kr = [ ["$posthog_sr_group_event_trigger_", { exposure: "hidden" }], ["$posthog_sr_group_url_trigger_", { exposure: "hidden" }], ["$posthog_sr_group_sampling_", { exposure: "hidden" }] ], Rr = (t) => { var e = null == r$1 ? void 0 : r$1.createElement("a"); return C$2(e) ? null : (e.href = t, e); }, Pr = function(t, e) { for (var i, r = ((t.split("#")[0] || "").split(/\?(.*)/)[1] || "").replace(/^\?+/g, "").split("&"), s = 0; r.length > s; s++) { var n = r[s].split("="); if (n[0] === e) { i = n; break; } } if (!R$1(i) || 2 > i.length) return ""; var o = i[1]; try { o = decodeURIComponent(o); } catch (t) { Ie.error("Skipping decoding for malformed query param: " + o); } return o.replace(/\+/g, " "); }, Or = function(t, e, i) { if (!t || !e || !e.length) return t; for (var r = t.split("#"), s = r[1], n = (r[0] || "").split("?"), o = n[1], a = n[0], l = (o || "").split("&"), u = [], h = 0; l.length > h; h++) { var d = l[h].split("="); R$1(d) && (e.includes(d[0]) ? u.push(d[0] + "=" + i) : u.push(l[h])); } var v = a; return null != o && (v += "?" + u.join("&")), null != s && (v += "#" + s), v; }, Ir = function(t, e) { var i = t.match(new RegExp(e + "=([^&]*)")); return i ? i[1] : null; }, Cr = "https?://(.*)", Fr = [ "gclid", "gclsrc", "dclid", "gbraid", "wbraid", "fbclid", "msclkid", "twclid", "li_fat_id", "igshid", "ttclid", "rdt_cid", "epik", "qclid", "sccid", "irclid", "_kx" ], Ar = [ "utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term", "gad_source", "mc_cid", ...Fr ], Mr = "", Dr = ["li_fat_id"]; function Lr(t, e, i) { if (!r$1) return {}; var s, n = e ? [...Fr, ...i || []] : [], o = Ur(Or(r$1.URL, n, Mr), t); return qi((s = {}, Hi(Dr, (function(t) { var e = lr.O(t); s[t] = e || null; })), s), o); } function Ur(t, e) { var i = Ar.concat(e || []), r = {}; return Hi(i, (function(e) { r[e] = Pr(t, e) || null; })), r; } function Nr(t) { var e = function(t) { return t ? 0 === t.search(Cr + "google.([^/?]*)") ? "google" : 0 === t.search(Cr + "bing.com") ? "bing" : 0 === t.search(Cr + "yahoo.com") ? "yahoo" : 0 === t.search(Cr + "duckduckgo.com") ? "duckduckgo" : null : null; }(t), i = "yahoo" != e ? "q" : "p", s = {}; if (!M(e)) { s.$search_engine = e; var n = r$1 ? Pr(r$1.referrer, i) : ""; n.length && (s.ph_keyword = n); } return s; } function jr() { return navigator.language || navigator.userLanguage; } var zr = "$direct"; function Br() { return (null == r$1 ? void 0 : r$1.referrer) || zr; } function Hr(t, e) { var i = t ? [...Fr, ...e || []] : [], r = null == s$1 ? void 0 : s$1.href.substring(0, 1e3); return { r: Br().substring(0, 1e3), u: r ? Or(r, i, Mr) : void 0 }; } function qr(t) { var e, { r: i, u: r } = t, s = { $referrer: i, $referring_domain: null == i ? void 0 : i == zr ? zr : null == (e = Rr(i)) ? void 0 : e.host }; if (r) { s.$current_url = r; var n = Rr(r); s.$host = null == n ? void 0 : n.host, s.$pathname = null == n ? void 0 : n.pathname; qi(s, Ur(r)); } if (i) qi(s, Nr(i)); return s; } function Vr() { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch (t) { return; } } function Wr() { try { return (/* @__PURE__ */ new Date()).getTimezoneOffset(); } catch (t) { return; } } var Gr = [ "cookie", "localstorage", "localstorage+cookie", "sessionstorage", "memory" ]; var Yr = class { constructor(t, e) { this.Bt = t, this.props = {}, this.mr = !1, this.yr = ((t) => { var e = ""; return t.token && (e = t.token.replace(/\+/g, "PL").replace(/\//g, "SL").replace(/=/g, "EQ")), t.persistence_name ? "ph_" + t.persistence_name : "ph_" + e + "_posthog"; })(t), this.nr = this.br(t), this.load(), t.debug && Ie.info("Persistence loaded", t.persistence, f$1({}, this.props)), this.update_config(t, t, e), this.save(); } isDisabled() { return !!this._r; } br(e) { -1 === Gr.indexOf(e.persistence.toLowerCase()) && (Ie.critical("Unknown persistence type " + e.persistence + "; falling back to localStorage+cookie"), e.persistence = "localStorage+cookie"); var i = function(e) { void 0 === e && (e = []); var i = [...dr, ...e]; return f$1({}, hr, { Z(t) { try { var e = {}; try { e = lr.Z(t) || {}; } catch (t) {} var i = qi(e, JSON.parse(hr.O(t) || "{}")); return hr.M(t, i), i; } catch (t) {} return null; }, M(t, e, r, s, n, o) { try { hr.M(t, e, void 0, void 0, o); var a = {}; i.forEach(((t) => { e[t] && (a[t] = e[t]); })), Object.keys(a).length && lr.M(t, a, r, s, n, o); } catch (t) { hr.B(t); } }, F(e, i) { try { t?.localStorage.removeItem(e), lr.F(e, i); } catch (t) { hr.B(t); } } }); }(e.cookie_persisted_properties || []), r = e.persistence.toLowerCase(); return "localstorage" === r && hr.R() ? hr : "localstorage+cookie" === r && i.R() ? i : "sessionstorage" === r && fr.R() ? fr : "memory" === r ? cr : "cookie" === r ? lr : i.R() ? i : lr; } wr(t) { var e = null != t ? t : this.Bt.feature_flag_cache_ttl_ms; if (!e || 0 >= e) return !1; var i = this.props[gi]; return !i || "number" != typeof i || Date.now() - i > e; } properties() { var t = {}; return Hi(this.props, ((e, i) => { var r = ((t) => { var e = Tr[t]; if (e) return e; for (var [i, r] of kr) if (0 === t.indexOf(i)) return r; })(i); if ("derived" === (null == r ? void 0 : r.exposure)) { if (null != r.shouldSkipFromEventProperties && r.shouldSkipFromEventProperties(e, i === ei ? () => this.wr() : () => !1)) return; r.transformToEventProperties && qi(t, r.transformToEventProperties(e)); } else r && "event" !== r.exposure || (t[i] = e); })), t; } load() { if (!this._r) { var t = this.nr.Z(this.yr); t && (this.props = qi({}, t)); } } save() { this._r || this.nr.M(this.yr, this.props, this.Ir, this.Cr, this.Sr, this.Bt.debug); } remove() { this.nr.F(this.yr, !1), this.nr.F(this.yr, !0); } clear() { this.remove(), this.props = {}; } register_once(t, e, i) { if (O$1(t)) { C$2(e) && (e = "None"), this.Ir = C$2(i) ? this.kr : i; var r = !1; if (Hi(t, ((t, i) => { this.props.hasOwnProperty(i) && this.props[i] !== e || (this.Tr(i, t), r = !0); })), r) return this.save(), !0; } return !1; } register(t, e) { if (O$1(t)) { this.Ir = C$2(e) ? this.kr : e; var i = !1; if (Hi(t, ((e, r) => { t.hasOwnProperty(r) && this.props[r] !== e && (this.Tr(r, e), i = !0); })), i) return this.save(), !0; } return !1; } unregister(t) { t in this.props && (this.Ar(t), this.save()); } update_campaign_params() { if (!this.mr) { var t = Lr(this.Bt.custom_campaign_params, this.Bt.mask_personal_data_properties, this.Bt.custom_personal_data_properties); I(Yi(t)) || this.register(t), this.mr = !0; } } update_search_keyword() { var t; this.register((t = null == r$1 ? void 0 : r$1.referrer) ? Nr(t) : {}); } update_referrer_info() { var t; this.register_once({ $referrer: Br(), $referring_domain: null != r$1 && r$1.referrer && (null == (t = Rr(r$1.referrer)) ? void 0 : t.host) || zr }, void 0); } set_initial_person_info() { this.props[wi] || this.props[xi] || this.register_once({ [Ei]: Hr(this.Bt.mask_personal_data_properties, this.Bt.custom_personal_data_properties) }, void 0); } get_initial_props() { var t = {}; Hi([xi, wi], ((e) => { var i = this.props[e]; i && Hi(i, (function(e, i) { t["$initial_" + E$2(i)] = e; })); })); var e, i, r = this.props[Ei]; if (r) qi(t, (e = qr(r), i = {}, Hi(e, (function(t, e) { i["$initial_" + E$2(e)] = t; })), i)); return t; } safe_merge(t) { return Hi(this.props, (function(e, i) { i in t || (t[i] = e); })), t; } update_config(t, e, i) { if (this.kr = this.Ir = t.cookie_expiration, this.set_disabled(t.disable_persistence || !!i), this.set_cross_subdomain(t.cross_subdomain_cookie), this.set_secure(t.secure_cookie), t.persistence !== e.persistence || !((t, e) => { if (t.length !== e.length) return !1; var i = [...t].sort(), r = [...e].sort(); return i.every(((t, e) => t === r[e])); })(t.cookie_persisted_properties || [], e.cookie_persisted_properties || [])) { var r = this.br(t), s = this.props; this.clear(), this.nr = r, this.props = s, this.save(); } } set_disabled(t) { this._r = t, this._r ? this.remove() : this.save(); } set_cross_subdomain(t) { t !== this.Cr && (this.Cr = t, this.remove(), this.save()); } set_secure(t) { t !== this.Sr && (this.Sr = t, this.remove(), this.save()); } set_event_timer(t, e) { var i = this.props[Ue] || {}; i[t] = e, this.Tr(Ue, i), this.save(); } remove_event_timer(t) { var e = this.props[Ue] || {}, i = e[t]; return C$2(i) || (delete e[t], this.Tr(Ue, e), this.save()), i; } get_property(t) { return this.props[t]; } set_property(t, e) { this.Tr(t, e), this.save(); } Tr(t, e) { this.props[t] = e; } Ar(t) { delete this.props[t]; } }, Jr = { Activation: "events", Cancellation: "cancelEvents" }, Zr = { Popover: "popover", API: "api", Widget: "widget", ExternalSurvey: "external_survey" }, rs = { SHOWN: "survey shown", DISMISSED: "survey dismissed", SENT: "survey sent", ABANDONED: "survey abandoned" }, ss = { SURVEY_ID: "$survey_id", SURVEY_NAME: "$survey_name", SURVEY_RESPONSE: "$survey_response", SURVEY_ITERATION: "$survey_iteration", SURVEY_ITERATION_START_DATE: "$survey_iteration_start_date", SURVEY_PARTIALLY_COMPLETED: "$survey_partially_completed", SURVEY_SUBMISSION_ID: "$survey_submission_id", SURVEY_QUESTIONS: "$survey_questions", SURVEY_COMPLETED: "$survey_completed", PRODUCT_TOUR_ID: "$product_tour_id", SURVEY_LAST_SEEN_DATE: "$survey_last_seen_date", SURVEY_LANGUAGE: "$survey_language" }, ns = { Popover: "popover", Inline: "inline" }, as = { SHOWN: "product tour shown", DISMISSED: "product tour dismissed", COMPLETED: "product tour completed", STEP_SHOWN: "product tour step shown", STEP_COMPLETED: "product tour step completed", BUTTON_CLICKED: "product tour button clicked", STEP_SELECTOR_FAILED: "product tour step selector failed", BANNER_CONTAINER_SELECTOR_FAILED: "product tour banner container selector failed", BANNER_ACTION_CLICKED: "product tour banner action clicked" }, ls = { TOUR_ID: "$product_tour_id", TOUR_NAME: "$product_tour_name", TOUR_ITERATION: "$product_tour_iteration", TOUR_RENDER_REASON: "$product_tour_render_reason", TOUR_STEP_ID: "$product_tour_step_id", TOUR_STEP_ORDER: "$product_tour_step_order", TOUR_STEP_TYPE: "$product_tour_step_type", TOUR_DISMISS_REASON: "$product_tour_dismiss_reason", TOUR_BUTTON_TEXT: "$product_tour_button_text", TOUR_BUTTON_ACTION: "$product_tour_button_action", TOUR_BUTTON_LINK: "$product_tour_button_link", TOUR_BUTTON_TOUR_ID: "$product_tour_button_tour_id", TOUR_STEPS_COUNT: "$product_tour_steps_count", TOUR_STEP_SELECTOR: "$product_tour_step_selector", TOUR_STEP_SELECTOR_FOUND: "$product_tour_step_selector_found", TOUR_STEP_ELEMENT_TAG: "$product_tour_step_element_tag", TOUR_STEP_ELEMENT_ID: "$product_tour_step_element_id", TOUR_STEP_ELEMENT_CLASSES: "$product_tour_step_element_classes", TOUR_STEP_ELEMENT_TEXT: "$product_tour_step_element_text", TOUR_ERROR: "$product_tour_error", TOUR_MATCHES_COUNT: "$product_tour_matches_count", TOUR_FAILURE_PHASE: "$product_tour_failure_phase", TOUR_WAITED_FOR_ELEMENT: "$product_tour_waited_for_element", TOUR_WAIT_DURATION_MS: "$product_tour_wait_duration_ms", TOUR_BANNER_SELECTOR: "$product_tour_banner_selector", TOUR_LINKED_SURVEY_ID: "$product_tour_linked_survey_id", USE_MANUAL_SELECTOR: "$use_manual_selector", INFERENCE_DATA_PRESENT: "$inference_data_present", TOUR_LAST_SEEN_DATE: "$product_tour_last_seen_date", TOUR_TYPE: "$product_tour_type" }, us = Ce$1("[RateLimiter]"); var hs = class { constructor(t) { this.serverLimits = {}, this.lastEventRateLimited = !1, this.checkForLimiting = (t) => { var e = t.text; if (e && e.length) try { (JSON.parse(e).quota_limited || []).forEach(((t) => { us.info((t || "events") + " is quota limited."), this.serverLimits[t] = (/* @__PURE__ */ new Date()).getTime() + 6e4; })); } catch (t) { us.warn("could not rate limit - continuing. Error: \"" + (null == t ? void 0 : t.message) + "\"", { text: e }); return; } }, this.instance = t, this.lastEventRateLimited = this.clientRateLimitContext(!0).isRateLimited; } get captureEventsPerSecond() { var t; return (null == (t = this.instance.config.rate_limiting) ? void 0 : t.events_per_second) || 10; } get captureEventsBurstLimit() { var t; return Math.max((null == (t = this.instance.config.rate_limiting) ? void 0 : t.events_burst_limit) || 10 * this.captureEventsPerSecond, this.captureEventsPerSecond); } clientRateLimitContext(t) { var e, i, r; void 0 === t && (t = !1); var { captureEventsBurstLimit: s, captureEventsPerSecond: n } = this, o = (/* @__PURE__ */ new Date()).getTime(), a = null !== (e = null == (i = this.instance.persistence) ? void 0 : i.get_property(yi)) && void 0 !== e ? e : { tokens: s, last: o }; a.tokens += (o - a.last) / 1e3 * n, a.last = o, a.tokens > s && (a.tokens = s); var l = 1 > a.tokens; return l || t || (a.tokens = Math.max(0, a.tokens - 1)), !l || this.lastEventRateLimited || t || this.instance.capture("$$client_ingestion_warning", { $$client_ingestion_warning_message: "posthog-js client rate limited. Config is set to " + n + " events per second and " + s + " events burst limit." }, { skip_client_rate_limiting: !0 }), this.lastEventRateLimited = l, null == (r = this.instance.persistence) || r.set_property(yi, a), { isRateLimited: l, remainingTokens: a.tokens }; } isServerRateLimited(t) { var e = this.serverLimits[t || "events"] || !1; return !1 !== e && (/* @__PURE__ */ new Date()).getTime() < e; } }; var ds = Ce$1("[RemoteConfig]"); var vs = class { constructor(t) { this._instance = t; } get remoteConfig() { var t; return null == (t = h$2._POSTHOG_REMOTE_CONFIG) || null == (t = t[this._instance.config.token]) ? void 0 : t.config; } Er(t) { var e, i; null != (e = h$2.__PosthogExtensions__) && e.loadExternalDependency ? null == (i = h$2.__PosthogExtensions__) || null == i.loadExternalDependency || i.loadExternalDependency(this._instance, "remote-config", (() => t(this.remoteConfig))) : t(); } Rr(t) { this._instance._send_request({ method: "GET", url: this._instance.requestRouter.endpointFor("assets", "/array/" + this._instance.config.token + "/config"), callback(e) { t(e.json); } }); } load() { try { if (this.remoteConfig) return ds.info("Using preloaded remote config", this.remoteConfig), this.Nr(this.remoteConfig), void this.Mr(); if (this._instance.Fr()) return void ds.warn("Remote config is disabled. Falling back to local config."); this.Er(((t) => { if (!t) return ds.info("No config found after loading remote JS config. Falling back to JSON."), void this.Rr(((t) => { this.Nr(t), this.Mr(); })); this.Nr(t), this.Mr(); })); } catch (t) { ds.error("Error loading remote config", t); } } stop() { this.Or && (clearInterval(this.Or), this.Or = void 0); } refresh() { this._instance.Fr() || "hidden" === (null == r$1 ? void 0 : r$1.visibilityState) || this._instance.reloadFeatureFlags(); } Mr() { var t; if (!this.Or) { var e = null !== (t = this._instance.config.remote_config_refresh_interval_ms) && void 0 !== t ? t : 3e5; 0 !== e && (this.Or = setInterval((() => { this.refresh(); }), e)); } } Nr(t) { var e; t || ds.error("Failed to fetch remote config from PostHog."), this._instance.Nr(null != t ? t : {}), !1 !== (null == t ? void 0 : t.hasFeatureFlags) && (this._instance.config.advanced_disable_feature_flags_on_first_load || null == (e = this._instance.featureFlags) || e.ensureFlagsLoaded()); } }, ps = { GZipJS: "gzip-js", Base64: "base64" }, fs = Uint8Array, _s = Uint16Array, gs = Uint32Array, ms = new fs([ 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 ]), bs = new fs([ 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 ]), ys = new fs([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]), ws = function(t, e) { for (var i = new _s(31), r = 0; 31 > r; ++r) i[r] = e += 1 << t[r - 1]; var s = new gs(i[30]); for (r = 1; 30 > r; ++r) for (var n = i[r]; i[r + 1] > n; ++n) s[n] = n - i[r] << 5 | r; return [i, s]; }, xs = ws(ms, 2), Es = xs[1]; xs[0][28] = 258, Es[258] = 28; for (var Ss = ws(bs, 0)[1], $s = new _s(32768), Ts = 0; 32768 > Ts; ++Ts) { var ks = (43690 & Ts) >>> 1 | (21845 & Ts) << 1; $s[Ts] = ((65280 & (ks = (61680 & (ks = (52428 & ks) >>> 2 | (13107 & ks) << 2)) >>> 4 | (3855 & ks) << 4)) >>> 8 | (255 & ks) << 8) >>> 1; } var Rs = function(t, e, i) { for (var r = t.length, s = 0, n = new _s(e); r > s; ++s) ++n[t[s] - 1]; var o, a = new _s(e); for (s = 0; e > s; ++s) a[s] = a[s - 1] + n[s - 1] << 1; if (i) { o = new _s(1 << e); var l = 15 - e; for (s = 0; r > s; ++s) if (t[s]) for (var u = s << 4 | t[s], h = e - t[s], d = a[t[s] - 1]++ << h, v = d | (1 << h) - 1; v >= d; ++d) o[$s[d] >>> l] = u; } else for (o = new _s(r), s = 0; r > s; ++s) o[s] = $s[a[t[s] - 1]++] >>> 15 - t[s]; return o; }, Ps = new fs(288); for (Ts = 0; 144 > Ts; ++Ts) Ps[Ts] = 8; for (Ts = 144; 256 > Ts; ++Ts) Ps[Ts] = 9; for (Ts = 256; 280 > Ts; ++Ts) Ps[Ts] = 7; for (Ts = 280; 288 > Ts; ++Ts) Ps[Ts] = 8; var Os = new fs(32); for (Ts = 0; 32 > Ts; ++Ts) Os[Ts] = 5; var Is = Rs(Ps, 9, 0), Cs = Rs(Os, 5, 0), Fs = function(t) { return (t / 8 >> 0) + (7 & t && 1); }, As = function(t, e, i) { (null == i || i > t.length) && (i = t.length); var r = new (t instanceof _s ? _s : t instanceof gs ? gs : fs)(i - e); return r.set(t.subarray(e, i)), r; }, Ms = function(t, e, i) { var r = e / 8 >> 0; t[r] |= i <<= 7 & e, t[r + 1] |= i >>> 8; }, Ds = function(t, e, i) { var r = e / 8 >> 0; t[r] |= i <<= 7 & e, t[r + 1] |= i >>> 8, t[r + 2] |= i >>> 16; }, Ls = function(t, e) { for (var i = [], r = 0; t.length > r; ++r) t[r] && i.push({ s: r, f: t[r] }); var s = i.length, n = i.slice(); if (!s) return [new fs(0), 0]; if (1 == s) { var o = new fs(i[0].s + 1); return o[i[0].s] = 1, [o, 1]; } i.sort((function(t, e) { return t.f - e.f; })), i.push({ s: -1, f: 25001 }); var a = i[0], l = i[1], u = 0, h = 1, d = 2; for (i[0] = { s: -1, f: a.f + l.f, l: a, r: l }; h != s - 1;) a = i[i[d].f > i[u].f ? u++ : d++], l = i[u != h && i[d].f > i[u].f ? u++ : d++], i[h++] = { s: -1, f: a.f + l.f, l: a, r: l }; var v = n[0].s; for (r = 1; s > r; ++r) n[r].s > v && (v = n[r].s); var c = new _s(v + 1), p = Us(i[h - 1], c, 0); if (p > e) { r = 0; var f = 0, _ = p - e, g = 1 << _; for (n.sort((function(t, e) { return c[e.s] - c[t.s] || t.f - e.f; })); s > r; ++r) { var m = n[r].s; if (e >= c[m]) break; f += g - (1 << p - c[m]), c[m] = e; } for (f >>>= _; f > 0;) { var b = n[r].s; e > c[b] ? f -= 1 << e - c[b]++ - 1 : ++r; } for (; r >= 0 && f; --r) { var y = n[r].s; c[y] == e && (--c[y], ++f); } p = e; } return [new fs(c), p]; }, Us = function(t, e, i) { return -1 == t.s ? Math.max(Us(t.l, e, i + 1), Us(t.r, e, i + 1)) : e[t.s] = i; }, Ns = function(t) { for (var e = t.length; e && !t[--e];); for (var i = new _s(++e), r = 0, s = t[0], n = 1, o = function(t) { i[r++] = t; }, a = 1; e >= a; ++a) if (t[a] == s && a != e) ++n; else { if (!s && n > 2) { for (; n > 138; n -= 138) o(32754); n > 2 && (o(n > 10 ? n - 11 << 5 | 28690 : n - 3 << 5 | 12305), n = 0); } else if (n > 3) { for (o(s), --n; n > 6; n -= 6) o(8304); n > 2 && (o(n - 3 << 5 | 8208), n = 0); } for (; n--;) o(s); n = 1, s = t[a]; } return [i.subarray(0, r), e]; }, js = function(t, e) { for (var i = 0, r = 0; e.length > r; ++r) i += t[r] * e[r]; return i; }, zs = function(t, e, i) { var r = i.length, s = Fs(e + 2); t[s] = 255 & r, t[s + 1] = r >>> 8, t[s + 2] = 255 ^ t[s], t[s + 3] = 255 ^ t[s + 1]; for (var n = 0; r > n; ++n) t[s + n + 4] = i[n]; return 8 * (s + 4 + r); }, Bs = function(t, e, i, r, s, n, o, a, l, u, h) { Ms(e, h++, i), ++s[256]; for (var d = Ls(s, 15), v = d[0], c = d[1], p = Ls(n, 15), f = p[0], _ = p[1], g = Ns(v), m = g[0], b = g[1], y = Ns(f), w = y[0], x = y[1], E = new _s(19), S = 0; m.length > S; ++S) E[31 & m[S]]++; for (S = 0; w.length > S; ++S) E[31 & w[S]]++; for (var T = Ls(E, 7), k = T[0], R = T[1], P = 19; P > 4 && !k[ys[P - 1]]; --P); var O, I, C, F, A = u + 5 << 3, M = js(s, Ps) + js(n, Os) + o, D = js(s, v) + js(n, f) + o + 14 + 3 * P + js(E, k) + (2 * E[16] + 3 * E[17] + 7 * E[18]); if (M >= A && D >= A) return zs(e, h, t.subarray(l, l + u)); if (Ms(e, h, 1 + (M > D)), h += 2, M > D) { O = Rs(v, c, 0), I = v, C = Rs(f, _, 0), F = f; var L = Rs(k, R, 0); for (Ms(e, h, b - 257), Ms(e, h + 5, x - 1), Ms(e, h + 10, P - 4), h += 14, S = 0; P > S; ++S) Ms(e, h + 3 * S, k[ys[S]]); h += 3 * P; for (var U = [m, w], N = 0; 2 > N; ++N) { var j = U[N]; for (S = 0; j.length > S; ++S) Ms(e, h, L[z = 31 & j[S]]), h += k[z], z > 15 && (Ms(e, h, j[S] >>> 5 & 127), h += j[S] >>> 12); } } else O = Is, I = Ps, C = Cs, F = Os; for (S = 0; a > S; ++S) if (r[S] > 255) { var z; Ds(e, h, O[257 + (z = r[S] >>> 18 & 31)]), h += I[z + 257], z > 7 && (Ms(e, h, r[S] >>> 23 & 31), h += ms[z]); var B = 31 & r[S]; Ds(e, h, C[B]), h += F[B], B > 3 && (Ds(e, h, r[S] >>> 5 & 8191), h += bs[B]); } else Ds(e, h, O[r[S]]), h += I[r[S]]; return Ds(e, h, O[256]), h + I[256]; }, Hs = new gs([ 65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632 ]), qs = function() { for (var t = new gs(256), e = 0; 256 > e; ++e) { for (var i = e, r = 9; --r;) i = (1 & i && 3988292384) ^ i >>> 1; t[e] = i; } return t; }(), Vs = function(t, e, i) { for (; i; ++e) t[e] = i, i >>>= 8; }; function Ws(t, e) { void 0 === e && (e = {}); var i = function() { var t = 4294967295; return { p(e) { for (var i = t, r = 0; e.length > r; ++r) i = qs[255 & i ^ e[r]] ^ i >>> 8; t = i; }, d() { return 4294967295 ^ t; } }; }(), r = t.length; i.p(t); var s, n, o, a, l, u = (a = 10 + ((s = e).filename && s.filename.length + 1 || 0), l = 8, function(t, e, i, r, s, n) { var o = t.length, a = new fs(r + o + 5 * (1 + Math.floor(o / 7e3)) + s), l = a.subarray(r, a.length - s), u = 0; if (!e || 8 > o) for (var h = 0; o >= h; h += 65535) { var d = h + 65535; o > d ? u = zs(l, u, t.subarray(h, d)) : (l[h] = !0, u = zs(l, u, t.subarray(h, o))); } else { for (var v = Hs[e - 1], c = v >>> 13, p = 8191 & v, f = (1 << i) - 1, _ = new _s(32768), g = new _s(f + 1), m = Math.ceil(i / 3), b = 2 * m, y = function(e) { return (t[e] ^ t[e + 1] << m ^ t[e + 2] << b) & f; }, w = new gs(25e3), x = new _s(288), E = new _s(32), S = 0, T = 0, k = (h = 0, 0), R = 0, P = 0; o > h; ++h) { var O = y(h), I = 32767 & h, C = g[O]; if (_[I] = C, g[O] = I, h >= R) { var F = o - h; if ((S > 7e3 || k > 24576) && F > 423) { u = Bs(t, l, 0, w, x, E, T, k, P, h - P, u), k = S = T = 0, P = h; for (var A = 0; 286 > A; ++A) x[A] = 0; for (A = 0; 30 > A; ++A) E[A] = 0; } var M = 2, D = 0, L = p, U = I - C & 32767; if (F > 2 && O == y(h - U)) for (var N = Math.min(c, F) - 1, j = Math.min(32767, h), z = Math.min(258, F); j >= U && --L && I != C;) { if (t[h + M] == t[h + M - U]) { for (var B = 0; z > B && t[h + B] == t[h + B - U]; ++B); if (B > M) { if (M = B, D = U, B > N) break; var H = Math.min(U, B - 2), q = 0; for (A = 0; H > A; ++A) { var V = h - U + A + 32768 & 32767, W = V - _[V] + 32768 & 32767; W > q && (q = W, C = V); } } } U += (I = C) - (C = _[I]) + 32768 & 32767; } if (D) { w[k++] = 268435456 | Es[M] << 18 | Ss[D]; var G = 31 & Es[M], Y = 31 & Ss[D]; T += ms[G] + bs[Y], ++x[257 + G], ++E[Y], R = h + M, ++S; } else w[k++] = t[h], ++x[t[h]]; } } u = Bs(t, l, !0, w, x, E, T, k, P, h - P, u); } return As(a, 0, r + Fs(u) + s); }(n = t, null == (o = e).level ? 6 : o.level, null == o.mem ? Math.ceil(1.5 * Math.max(8, Math.min(13, Math.log(n.length)))) : 12 + o.mem, a, l)), h = u.length; return function(t, e) { var i = e.filename; if (t[0] = 31, t[1] = 139, t[2] = 8, t[8] = 2 > e.level ? 4 : 9 == e.level ? 2 : 0, t[9] = 3, 0 != e.mtime && Vs(t, 4, Math.floor(new Date(e.mtime || Date.now()) / 1e3)), i) { t[3] = 8; for (var r = 0; i.length >= r; ++r) t[r + 10] = i.charCodeAt(r); } }(u, e), Vs(u, h - 8, i.d()), Vs(u, h - 4, r), u; } var Gs = !!o$1 || !!n$2, Ys = "text/plain", Js = !1, Ks = function(t, e, i) { var r; void 0 === i && (i = !0); var [s, n] = t.split("?"), o = f$1({}, e), a = null !== (r = null == n ? void 0 : n.split("&").map(((t) => { var e, [r, s] = t.split("="), n = i && null !== (e = o[r]) && void 0 !== e ? e : s; return delete o[r], r + "=" + n; }))) && void 0 !== r ? r : [], l = function(t, e) { var i, r; void 0 === e && (e = "&"); var s = []; return Hi(t, (function(t, e) { C$2(t) || C$2(e) || "undefined" === e || (i = encodeURIComponent(((t) => t instanceof File)(t) ? t.name : t.toString()), r = encodeURIComponent(e), s[s.length] = r + "=" + i); })), s.join(e); }(o); return l && a.push(l), s + "?" + a.join("&"); }, Xs = (t, e) => JSON.stringify(t, ((t, e) => "bigint" == typeof e ? e.toString() : e), e), Qs = (t) => { if (t.tr) return t.tr; var { data: e, compression: i } = t; if (e) { if (i === ps.GZipJS) { var r = Ws(function(t, e) { var i = t.length; if ("undefined" != typeof TextEncoder) return new TextEncoder().encode(t); for (var r = new fs(t.length + (t.length >>> 1)), s = 0, n = function(t) { r[s++] = t; }, o = 0; i > o; ++o) { if (s + 5 > r.length) { var a = new fs(s + 8 + (i - o << 1)); a.set(r), r = a; } var l = t.charCodeAt(o); 128 > l ? n(l) : 2048 > l ? (n(192 | l >>> 6), n(128 | 63 & l)) : l > 55295 && 57344 > l ? (n(240 | (l = 65536 + (1047552 & l) | 1023 & t.charCodeAt(++o)) >>> 18), n(128 | l >>> 12 & 63), n(128 | l >>> 6 & 63), n(128 | 63 & l)) : (n(224 | l >>> 12), n(128 | l >>> 6 & 63), n(128 | 63 & l)); } return As(r, 0, s); }(Xs(e)), { mtime: 0 }); return { contentType: Ys, body: r.buffer.slice(r.byteOffset, r.byteOffset + r.byteLength), estimatedSize: r.byteLength }; } if (i === ps.Base64) { var n = ((t) => "data=" + encodeURIComponent("string" == typeof t ? t : Xs(t)))(function(t) { return t ? btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g, ((t, e) => String.fromCharCode(parseInt(e, 16))))) : t; }(Xs(e))); return { contentType: "application/x-www-form-urlencoded", body: n, estimatedSize: new Blob([n]).size }; } var o = Xs(e); return { contentType: "application/json", body: o, estimatedSize: new Blob([o]).size }; } }, Zs = function() { var t = p$1((function* (t) { var i = yield function(t, e, i) { return g$2.apply(this, arguments); }(Xs(t.data), v$1.DEBUG, { rethrow: !0 }); if (!i) return t; var r = yield i.arrayBuffer(); return f$1({}, t, { tr: { contentType: Ys, body: r, estimatedSize: r.byteLength } }); })); return function(e) { return t.apply(this, arguments); }; }(), tn = (t, e) => Ks(t, { _: (/* @__PURE__ */ new Date()).getTime().toString(), ver: v$1.JS_SDK_VERSION, compression: e }), en = []; n$2 && en.push({ transport: "fetch", method(t) { var e, i, { contentType: r, body: s, estimatedSize: o } = null !== (e = Qs(t)) && void 0 !== e ? e : {}, l = new Headers(); Hi(t.headers, (function(t, e) { l.append(e, t); })), r && l.append("Content-Type", r); var u = t.url, h = null; if (a$1) { var d = new a$1(); h = { signal: d.signal, timeout: setTimeout((() => d.abort()), t.timeout) }; } n$2(u, f$1({ method: (null == t ? void 0 : t.method) || "GET", headers: l, keepalive: "POST" === t.method && 52428.8 > (o || 0), body: s, signal: null == (i = h) ? void 0 : i.signal }, t.fetchOptions)).then(((e) => e.text().then(((i) => { var r = { statusCode: e.status, text: i }; if (200 === e.status) try { r.json = JSON.parse(i); } catch (t) { Ie.error(t); } null == t.callback || t.callback(r); })))).catch(((e) => { Ie.error(e), null == t.callback || t.callback({ statusCode: 0, error: e }); })).finally((() => h ? clearTimeout(h.timeout) : null)); } }), o$1 && en.push({ transport: "XHR", method(t) { var e, i = new o$1(); i.open(t.method || "GET", t.url, !0); var { contentType: r, body: s } = null !== (e = Qs(t)) && void 0 !== e ? e : {}; Hi(t.headers, (function(t, e) { i.setRequestHeader(e, t); })), r && i.setRequestHeader("Content-Type", r), t.timeout && (i.timeout = t.timeout), t.disableXHRCredentials || (i.withCredentials = !0), i.onreadystatechange = () => { if (4 === i.readyState) { var e = { statusCode: i.status, text: i.responseText }; if (200 === i.status) try { e.json = JSON.parse(i.responseText); } catch (t) {} null == t.callback || t.callback(e); } }, i.send(s); } }), null != i$1 && i$1.sendBeacon && en.push({ transport: "sendBeacon", method(t) { var e = Ks(t.url, { beacon: "1" }); try { var r, { contentType: s, body: n } = null !== (r = Qs(t)) && void 0 !== r ? r : {}; if (!n) return; var o = n instanceof Blob ? n : new Blob([n], { type: s }); i$1.sendBeacon(e, o); } catch (t) {} } }); var rn = 3e3; var sn = class { constructor(t, e) { this.Pr = !0, this.Lr = [], this.Dr = Y$1((null == e ? void 0 : e.flush_interval_ms) || rn, 250, 5e3, Ie.createLogger("flush interval"), rn), this.Br = t; } enqueue(t) { this.Lr.push(t), this.jr || this.$r(); } unload() { this.qr(); var t = this.Lr.length > 0 ? this.Zr() : {}, e = Object.values(t); [...e.filter(((t) => 0 === t.url.indexOf("/e"))), ...e.filter(((t) => 0 !== t.url.indexOf("/e")))].map(((t) => { this.Br(f$1({}, t, { transport: "sendBeacon" })); })); } enable() { this.Pr = !1, this.$r(); } $r() { var t = this; this.Pr || (this.jr = setTimeout((() => { if (this.qr(), this.Lr.length > 0) { var e = this.Zr(), i = function() { var i = e[r], s = (/* @__PURE__ */ new Date()).getTime(); i.data && R$1(i.data) && Hi(i.data, ((t) => { t.offset = Math.abs(t.timestamp - s), delete t.timestamp; })), t.Br(i); }; for (var r in e) i(); } }), this.Dr)); } qr() { clearTimeout(this.jr), this.jr = void 0; } Zr() { var t = {}; return Hi(this.Lr, ((e) => { var i, r = e, s = (r ? r.batchKey : null) || r.url; C$2(t[s]) && (t[s] = f$1({}, r, { data: [] })), null == (i = t[s].data) || i.push(r.data); })), this.Lr = [], t; } }; var nn = ["retriesPerformedSoFar"]; var on = class { constructor(e) { this.Vr = !1, this.Hr = 3e3, this.Lr = [], this._instance = e, this.Lr = [], this.zr = !0, !C$2(t) && "onLine" in t.navigator && (this.zr = t.navigator.onLine, this.Ur = () => { this.zr = !0, this.Yr(); }, this.Gr = () => { this.zr = !1; }, Xi(t, "online", this.Ur), Xi(t, "offline", this.Gr)); } get length() { return this.Lr.length; } retriableRequest(t) { var { retriesPerformedSoFar: e } = t, i = _$1(t, nn); U(e) && (i.url = Ks(i.url, { retry_count: e })), this._instance._send_request(f$1({}, i, { callback: (t) => { 200 === t.statusCode || t.statusCode >= 400 && 500 > t.statusCode || (null != e ? e : 0) >= 10 ? null == i.callback || i.callback(t) : this.Wr(f$1({ retriesPerformedSoFar: e }, i)); } })); } Wr(t) { var e = t.retriesPerformedSoFar || 0; t.retriesPerformedSoFar = e + 1; var i = function(t) { var e = 3e3 * Math.pow(2, t), i = e / 2, r = Math.min(18e5, e), s = Math.random() - .5; return Math.ceil(r + s * (r - i)); }(e), r = Date.now() + i; this.Lr.push({ retryAt: r, requestOptions: t }); var s = "Enqueued failed request for retry in " + i; navigator.onLine || (s += " (Browser is offline)"), Ie.warn(s), this.Vr || (this.Vr = !0, this.Xr()); } Xr() { if (this.Jr && clearTimeout(this.Jr), 0 === this.Lr.length) return this.Vr = !1, void (this.Jr = void 0); this.Jr = setTimeout((() => { this.zr && this.Lr.length > 0 && this.Yr(), this.Xr(); }), this.Hr); } Yr() { var t = Date.now(), e = [], i = this.Lr.filter(((i) => t > i.retryAt || (e.push(i), !1))); if (this.Lr = e, i.length > 0) for (var { requestOptions: r } of i) this.retriableRequest(r); } unload() { for (var { requestOptions: e } of (this.Jr && (clearTimeout(this.Jr), this.Jr = void 0), this.Vr = !1, C$2(t) || (this.Ur && (t.removeEventListener("online", this.Ur), this.Ur = void 0), this.Gr && (t.removeEventListener("offline", this.Gr), this.Gr = void 0)), this.Lr)) try { this._instance._send_request(f$1({}, e, { transport: "sendBeacon" })); } catch (t) { Ie.error(t); } this.Lr = []; } }; var an = class { constructor(t) { this.Kr = () => { var t, e, i, r; this.Qr || (this.Qr = {}); var s = this.scrollElement(), n = this.scrollY(), o = s ? Math.max(0, s.scrollHeight - s.clientHeight) : 0, a = n + ((null == s ? void 0 : s.clientHeight) || 0), l = (null == s ? void 0 : s.scrollHeight) || 0; this.Qr.lastScrollY = Math.ceil(n), this.Qr.maxScrollY = Math.max(n, null !== (t = this.Qr.maxScrollY) && void 0 !== t ? t : 0), this.Qr.maxScrollHeight = Math.max(o, null !== (e = this.Qr.maxScrollHeight) && void 0 !== e ? e : 0), this.Qr.lastContentY = a, this.Qr.maxContentY = Math.max(a, null !== (i = this.Qr.maxContentY) && void 0 !== i ? i : 0), this.Qr.maxContentHeight = Math.max(l, null !== (r = this.Qr.maxContentHeight) && void 0 !== r ? r : 0); }, this._instance = t; } get ei() { return this._instance.config.scroll_root_selector; } getContext() { return this.Qr; } resetContext() { var t = this.Qr; return setTimeout(this.Kr, 0), t; } startMeasuringScrollPosition() { Xi(t, "scroll", this.Kr, { capture: !0 }), Xi(t, "scrollend", this.Kr, { capture: !0 }), Xi(t, "resize", this.Kr); } scrollElement() { if (!this.ei) return null == t ? void 0 : t.document.documentElement; for (var i of R$1(this.ei) ? this.ei : [this.ei]) { var r = null == t ? void 0 : t.document.querySelector(i); if (r) return r; } } scrollY() { if (this.ei) { var e = this.scrollElement(); return e && e.scrollTop || 0; } return t && (t.scrollY || t.pageYOffset || t.document.documentElement.scrollTop) || 0; } scrollX() { if (this.ei) { var e = this.scrollElement(); return e && e.scrollLeft || 0; } return t && (t.scrollX || t.pageXOffset || t.document.documentElement.scrollLeft) || 0; } }; var ln = (t) => Hr(null == t ? void 0 : t.config.mask_personal_data_properties, null == t ? void 0 : t.config.custom_personal_data_properties); var un = class { constructor(t, e, i, r) { this.ti = (t) => { var e = this.ri(); if (!e || e.sessionId !== t) { var i = { sessionId: t, props: this.ii(this._instance) }; this.ni.register({ [bi]: i }); } }, this._instance = t, this.si = e, this.ni = i, this.ii = r || ln, this.si.onSessionId(this.ti); } ri() { return this.ni.props[bi]; } getSetOnceProps() { var t, e = null == (t = this.ri()) ? void 0 : t.props; return e ? "r" in e ? qr(e) : { $referring_domain: e.referringDomain, $pathname: e.initialPathName, utm_source: e.utm_source, utm_campaign: e.utm_campaign, utm_medium: e.utm_medium, utm_content: e.utm_content, utm_term: e.utm_term } : {}; } getSessionProps() { var t = {}; return Hi(Yi(this.getSetOnceProps()), ((e, i) => { "$current_url" === i && (i = "url"), t["$session_entry_" + E$2(i)] = e; })), t; } }; var hn = class { constructor() { this.oi = {}; } on(t, e) { return this.oi[t] || (this.oi[t] = []), this.oi[t].push(e), () => { this.oi[t] = this.oi[t].filter(((t) => t !== e)); }; } emit(t, e) { for (var i of this.oi[t] || []) i(e); for (var r of this.oi["*"] || []) r(t, e); } }; var dn = Ce$1("[SessionId]"); var vn = class { on(t, e) { return this.ai.on(t, e); } constructor(t, e, i) { var r; if (this.li = [], this.ui = void 0, this.ai = new hn(), this.hi = (t, e) => !(!U(t) || !U(e)) && Math.abs(t - e) > this.sessionTimeoutMs, !t.persistence) throw new Error("SessionIdManager requires a PostHogPersistence instance"); if (t.config.cookieless_mode === Ci) throw new Error("SessionIdManager cannot be used with cookieless_mode=\"always\""); this.Bt = t.config, this.ni = t.persistence, this.ci = void 0, this.di = void 0, this._sessionStartTimestamp = null, this._sessionActivityTimestamp = null, this.vi = e || sr, this.fi = i || sr; var s = this.Bt.persistence_name || this.Bt.token; if (this._sessionTimeoutMs = 1e3 * Y$1(this.Bt.session_idle_timeout_seconds || 1800, 60, 36e3, dn.createLogger("session_idle_timeout_seconds"), 1800), t.register({ $configured_session_timeout_ms: this._sessionTimeoutMs }), this.pi(), this.gi = "ph_" + s + "_window_id", this.mi = "ph_" + s + "_primary_window_exists", this.yi()) { var n = fr.Z(this.gi), o = fr.Z(this.mi); n && !o ? this.ci = n : fr.F(this.gi), fr.M(this.mi, !0); } if (null != (r = this.Bt.bootstrap) && r.sessionID) try { var a = ((t) => { var e = this.Bt.bootstrap.sessionID.replace(/-/g, ""); if (32 !== e.length) throw new Error("Not a valid UUID"); if ("7" !== e[12]) throw new Error("Not a UUIDv7"); return parseInt(e.substring(0, 12), 16); })(); this.bi(this.Bt.bootstrap.sessionID, (/* @__PURE__ */ new Date()).getTime(), a); } catch (t) { dn.error("Invalid sessionID in bootstrap", t); } this.wi(); } get sessionTimeoutMs() { return this._sessionTimeoutMs; } onSessionId(t) { return C$2(this.li) && (this.li = []), this.li.push(t), this.di && t(this.di, this.ci), () => { this.li = this.li.filter(((e) => e !== t)); }; } yi() { return "memory" !== this.Bt.persistence && !this.ni._r && fr.R(); } Ii(t) { t !== this.ci && (this.ci = t, this.yi() && fr.M(this.gi, t)); } Ci() { return this.ci ? this.ci : this.yi() ? fr.Z(this.gi) : null; } bi(t, e, i) { t === this.di && e === this._sessionActivityTimestamp && i === this._sessionStartTimestamp || (this._sessionStartTimestamp = i, this._sessionActivityTimestamp = e, this.di = t, this.ni.register({ [Ze$1]: [ e, t, i ] })); } Si() { var t = this.ni.props[Ze$1]; return R$1(t) && 2 === t.length && t.push(t[0]), t || [ 0, null, 0 ]; } resetSessionId() { this.bi(null, null, null); } destroy() { clearTimeout(this.xi), this.xi = void 0, this.ui && t && (t.removeEventListener(Li, this.ui, { capture: !1 }), this.ui = void 0), this.li = []; } wi() { this.ui = () => { this.yi() && fr.F(this.mi); }, Xi(t, Li, this.ui, { capture: !1 }); } checkAndGetSessionAndWindowId(t, e) { if (void 0 === t && (t = !1), void 0 === e && (e = null), this.Bt.cookieless_mode === Ci) throw new Error("checkAndGetSessionAndWindowId should not be called with cookieless_mode=\"always\""); var i = e || (/* @__PURE__ */ new Date()).getTime(), [r, s, n] = this.Si(), o = this.Ci(), a = U(n) && Math.abs(i - n) > 864e5, l = !1, u = !s, h = !u && !t && this.hi(i, r); u || h || a ? (s = this.vi(), o = this.fi(), dn.info("new session ID generated", { sessionId: s, windowId: o, changeReason: { noSessionId: u, activityTimeout: h, sessionPastMaximumLength: a } }), n = i, l = !0) : o || (o = this.fi(), l = !0); var d = U(r) && t && !a ? r : i, v = U(n) ? n : (/* @__PURE__ */ new Date()).getTime(); return this.Ii(o), this.bi(s, d, v), t || this.pi(), l && this.li.forEach(((t) => t(s, o, l ? { noSessionId: u, activityTimeout: h, sessionPastMaximumLength: a } : void 0))), { sessionId: s, windowId: o, sessionStartTimestamp: v, changeReason: l ? { noSessionId: u, activityTimeout: h, sessionPastMaximumLength: a } : void 0, lastActivityTimestamp: r }; } pi() { clearTimeout(this.xi), this.xi = setTimeout((() => { var [t] = this.Si(); if (this.hi((/* @__PURE__ */ new Date()).getTime(), t)) { var e = this.di; this.resetSessionId(), this.ai.emit("forcedIdleReset", { idleSessionId: e }); } }), 1.1 * this.sessionTimeoutMs); } }; var cn = function(t, e) { if (!t) return !1; var i = t.userAgent; if (i && b$2(i, e)) return !0; try { var r = null == t ? void 0 : t.userAgentData; if (null != r && r.brands && r.brands.some(((t) => b$2(null == t ? void 0 : t.brand, e)))) return !0; } catch (t) {} return !!t.webdriver; }, pn = function(t, e) { if (!function(t) { try { new RegExp(t); } catch (t) { return !1; } return !0; }(e)) return !1; try { return new RegExp(e).test(t); } catch (t) { return !1; } }; function fn(t, e, i) { return Xs({ distinct_id: t, userPropertiesToSet: e, userPropertiesToSetOnce: i }); } var _n = { exact: (t, e) => e.some(((e) => t.some(((t) => e === t)))), is_not: (t, e) => e.every(((e) => t.every(((t) => e !== t)))), regex: (t, e) => e.some(((e) => t.some(((t) => pn(e, t))))), not_regex: (t, e) => e.every(((e) => t.every(((t) => !pn(e, t))))), icontains: (t, e) => e.map(gn).some(((e) => t.map(gn).some(((t) => e.includes(t))))), not_icontains: (t, e) => e.map(gn).every(((e) => t.map(gn).every(((t) => !e.includes(t))))), gt: (t, e) => e.some(((e) => { var i = parseFloat(e); return !isNaN(i) && t.some(((t) => i > parseFloat(t))); })), lt: (t, e) => e.some(((e) => { var i = parseFloat(e); return !isNaN(i) && t.some(((t) => i < parseFloat(t))); })) }, gn = (t) => t.toLowerCase(); function mn(t, e) { return !t || Object.entries(t).every(((t) => { var [i, r] = t, s = null == e ? void 0 : e[i]; if (C$2(s) || M(s)) return !1; var n = [String(s)], o = _n[r.operator]; return !!o && o(r.values, n); })); } var bn = "custom", yn = "i.posthog.com", wn = /^\/static\//; var xn = class { constructor(t) { this.ki = {}, this.instance = t; } get apiHost() { var t = this.instance.config.api_host.trim().replace(/\/$/, ""); return "https://app.posthog.com" === t ? "https://us.i.posthog.com" : t; } get flagsApiHost() { var t = this.instance.config.flags_api_host; return t ? t.trim().replace(/\/$/, "") : this.apiHost; } get uiHost() { var t, e = null == (t = this.instance.config.ui_host) ? void 0 : t.replace(/\/$/, ""); return e || (e = this.apiHost.replace("." + yn, ".posthog.com")), "https://app.posthog.com" === e ? "https://us.posthog.com" : e; } get region() { return this.ki[this.apiHost] || (this.ki[this.apiHost] = /https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost) ? "us" : /https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost) ? "eu" : bn), this.ki[this.apiHost]; } Ti(t) { var e = this.instance.config.__preview_external_dependency_versioned_paths; if ("string" == typeof e && wn.test(t)) return e.trim().replace(/\/$/, "") || void 0; } endpointFor(t, e) { if (void 0 === e && (e = ""), e && (e = "/" === e[0] ? e : "/" + e), "ui" === t) return this.uiHost + e; if ("flags" === t) return this.flagsApiHost + e; if ("assets" === t) { var i = this.Ti(e); if (i) return "" + i + e; } if (this.region === bn) return this.apiHost + e; var r = yn + e; switch (t) { case "assets": return "https://" + this.region + "-assets." + r; case "api": return "https://" + this.region + "." + r; } } }; var En = Ce$1("[Surveys]"), Sn = "seenSurvey_", $n = [ Zr.Popover, Zr.Widget, Zr.API ], Tn = { ignoreConditions: !1, ignoreDelay: !1, displayType: ns.Popover }, kn = Ce$1("[PostHog ExternalIntegrations]"), Rn = { intercom: "intercom-integration", crispChat: "crisp-chat-integration" }; var Pn = class { constructor(t) { this._instance = t; } ur(t, e) { var i; null == (i = h$2.__PosthogExtensions__) || null == i.loadExternalDependency || i.loadExternalDependency(this._instance, t, ((t) => { if (t) return kn.error("failed to load script", t); e(); })); } startIfEnabledOrStop() { var t = this, e = function(e) { var i, s, n; !r || null != (i = h$2.__PosthogExtensions__) && null != (i = i.integrations) && i[e] || t.ur(Rn[e], (() => { var i; null == (i = h$2.__PosthogExtensions__) || null == (i = i.integrations) || null == (i = i[e]) || i.start(t._instance); })), !r && null != (s = h$2.__PosthogExtensions__) && null != (s = s.integrations) && s[e] && (null == (n = h$2.__PosthogExtensions__) || null == (n = n.integrations) || null == (n = n[e]) || n.stop()); }; for (var [i, r] of Object.entries(null !== (s = this._instance.config.integrations) && void 0 !== s ? s : {})) { var s; e(i); } } }; var On, In = {}, Cn = 0, Fn = () => {}, An = "Consent opt in/out is not valid with cookieless_mode=\"always\" and will be ignored", Mn = "Surveys module not available", Dn = "sanitize_properties is deprecated. Use before_send instead", Ln = "Invalid value for property_denylist config: ", Un = "posthog", Nn = !Gs && -1 === (null == u$1 ? void 0 : u$1.indexOf("MSIE")) && -1 === (null == u$1 ? void 0 : u$1.indexOf("Mozilla")), jn = (e) => { var i; return f$1({ api_host: "https://us.i.posthog.com", flags_api_host: null, ui_host: null, token: "", autocapture: !0, cross_subdomain_cookie: Ki(null == r$1 ? void 0 : r$1.location), persistence: "localStorage+cookie", persistence_name: "", cookie_persisted_properties: [], loaded: Fn, save_campaign_params: !0, custom_campaign_params: [], custom_blocked_useragents: [], save_referrer: !0, capture_pageleave: "if_capture_pageview", defaults: null != e ? e : "unset", __preview_deferred_init_extensions: !1, __preview_external_dependency_versioned_paths: !1, debug: s$1 && F$1(null == s$1 ? void 0 : s$1.search) && -1 !== s$1.search.indexOf("__posthog_debug=true") || !1, cookie_expiration: 365, upgrade: !1, disable_session_recording: !1, disable_persistence: !1, disable_web_experiments: !0, disable_surveys: !1, disable_surveys_automatic_display: !1, disable_conversations: !1, disable_product_tours: !1, disable_external_dependency_loading: !1, enable_recording_console_log: void 0, secure_cookie: "https:" === (null == t || null == (i = t.location) ? void 0 : i.protocol), ip: !1, opt_out_capturing_by_default: !1, opt_out_persistence_by_default: !1, opt_out_useragent_filter: !1, opt_out_capturing_persistence_type: "localStorage", consent_persistence_name: null, opt_out_capturing_cookie_prefix: null, opt_in_site_apps: !1, property_denylist: [], respect_dnt: !1, sanitize_properties: null, request_headers: {}, request_batching: !0, properties_string_max_length: 65535, mask_all_element_attributes: !1, mask_all_text: !1, mask_personal_data_properties: !1, custom_personal_data_properties: [], advanced_disable_flags: !1, advanced_disable_decide: !1, advanced_disable_feature_flags: !1, advanced_disable_feature_flags_on_first_load: !1, advanced_only_evaluate_survey_feature_flags: !1, advanced_feature_flags_dedup_per_session: !1, advanced_enable_surveys: !1, advanced_disable_toolbar_metrics: !1, feature_flag_request_timeout_ms: 3e3, surveys_request_timeout_ms: 1e4, on_request_error(t) { Ie.error("Bad HTTP status: " + t.statusCode + " " + t.text); }, get_device_id: (t) => t, capture_performance: void 0, name: "posthog", bootstrap: {}, disable_compression: !1, session_idle_timeout_seconds: 1800, person_profiles: Mi, before_send: void 0, request_queue_config: { flush_interval_ms: rn }, error_tracking: {}, _onCapture: Fn, __preview_eager_load_replay: !1 }, ((t) => ({ rageclick: !t || "2025-11-30" > t || { content_ignorelist: !0 }, capture_pageview: !t || "2025-05-24" > t || "history_change", session_recording: t && t >= "2025-11-30" ? { strictMinimumDuration: !0 } : {}, external_scripts_inject_target: t && t >= "2026-01-30" ? "head" : "body", internal_or_test_user_hostname: t && t >= "2026-01-30" ? /^(localhost|127\.0\.0\.1)$/ : void 0 }))(e)); }, zn = [ ["process_person", "person_profiles"], ["xhr_headers", "request_headers"], ["cookie_name", "persistence_name"], ["disable_cookie", "disable_persistence"], ["store_google", "save_campaign_params"], ["verbose", "debug"] ], Bn = (t) => { var e = {}; for (var [i, r] of zn) C$2(t[i]) || (e[r] = t[i]); var s = qi({}, e, t); return R$1(t.property_blacklist) && (C$2(t.property_denylist) ? s.property_denylist = t.property_blacklist : R$1(t.property_denylist) ? s.property_denylist = [...t.property_blacklist, ...t.property_denylist] : Ie.error(Ln + t.property_denylist)), s; }; var Hn = class { constructor() { this.__forceAllowLocalhost = !1; } get Ai() { return this.__forceAllowLocalhost; } set Ai(t) { Ie.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"), this.__forceAllowLocalhost = t; } }; var qn = class qn { Ei(t, e) { if (t) { var i = this.Ri.indexOf(t); -1 !== i && this.Ri.splice(i, 1); } return this.Ri.push(e), null == e.initialize || e.initialize(), e; } Ni() { return this.config.cookieless_mode === Ci || this.config.cookieless_mode === Ii && this.consent.isRejected(); } get decideEndpointWasHit() { var t, e; return null !== (t = null == (e = this.featureFlags) ? void 0 : e.hasLoadedFlags) && void 0 !== t && t; } get flagsEndpointWasHit() { var t, e; return null !== (t = null == (e = this.featureFlags) ? void 0 : e.hasLoadedFlags) && void 0 !== t && t; } constructor() { var t; this.webPerformance = new Hn(), this.Mi = !1, this.version = v$1.LIB_VERSION, this.Fi = new hn(), this.Ri = [], this._calculate_event_properties = this.calculateEventProperties.bind(this), this.config = jn(), this.SentryIntegration = Sr, this.sentryIntegration = (t) => function(t, e) { var i = Er(t, e); return { name: xr, processEvent: (t) => i(t) }; }(this, t), this.__request_queue = [], this.__loaded = !1, this.analyticsDefaultEndpoint = "/e/", this.Oi = !1, this.Pi = null, this.Li = null, this.Di = null, this.scrollManager = new an(this), this.pageViewManager = new $r(this), this.rateLimiter = new hs(this), this.requestRouter = new xn(this), this.consent = new _r(this), this.externalIntegrations = new Pn(this); var e = null !== (t = qn.__defaultExtensionClasses) && void 0 !== t ? t : {}; this.featureFlags = e.featureFlags && new e.featureFlags(this), this.toolbar = e.toolbar && new e.toolbar(this), this.surveys = e.surveys && new e.surveys(this), this.conversations = e.conversations && new e.conversations(this), this.logs = e.logs && new e.logs(this), this.experiments = e.experiments && new e.experiments(this), this.exceptions = e.exceptions && new e.exceptions(this), this.people = { set: (t, e, i) => { var r = F$1(t) ? { [t]: e } : t; this.setPersonProperties(r), i?.({}); }, set_once: (t, e, i) => { var r = F$1(t) ? { [t]: e } : t; this.setPersonProperties(void 0, r), i?.({}); } }, this.on("eventCaptured", ((t) => Ie.info("send \"" + (null == t ? void 0 : t.event) + "\"", t))); } init(t, e, i) { if (i && i !== Un) { var r, s = null !== (r = In[i]) && void 0 !== r ? r : new qn(); return s._init(t, e, i), In[i] = s, In[Un][i] = s, s; } return this._init(t, e, i); } _init(e, i, r) { var s, n; if (void 0 === i && (i = {}), C$2(e) || A$1(e)) return Ie.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"), this; if (this.__loaded) return console.warn("[PostHog.js]", "You have already initialized PostHog! Re-initializing is a no-op"), this; this.__loaded = !0, this.config = {}, i.debug = this.Bi(i.debug), this.ji = i, this.$i = [], i.person_profiles ? this.Li = i.person_profiles : i.process_person && (this.Li = i.process_person), this.set_config(qi({}, jn(i.defaults), Bn(i), { name: r, token: e })), this.config.on_xhr_error && Ie.error("on_xhr_error is deprecated. Use on_request_error instead"), this.compression = i.disable_compression ? void 0 : ps.GZipJS; var o = this.qi(); this.persistence = new Yr(this.config, o), this.sessionPersistence = "sessionStorage" === this.config.persistence || "memory" === this.config.persistence ? this.persistence : new Yr(f$1({}, this.config, { persistence: "sessionStorage" }), o); var a = f$1({}, this.persistence.props), l = f$1({}, this.sessionPersistence.props); this.register({ $initialization_time: (/* @__PURE__ */ new Date()).toISOString() }), this.Zi = new sn(((t) => this.Vi(t)), this.config.request_queue_config), this.Hi = new on(this), this.__request_queue = []; var u = this.Ni(); if (u || (this.sessionManager = new vn(this), this.sessionPropsManager = new un(this, this.sessionManager, this.persistence)), this.config.__preview_deferred_init_extensions ? (Ie.info("Deferring extension initialization to improve startup performance"), setTimeout((() => { this.zi(u); }), 0)) : (Ie.info("Initializing extensions synchronously"), this.zi(u)), v$1.DEBUG = v$1.DEBUG || this.config.debug, v$1.DEBUG && Ie.info("Starting in debug mode", { this: this, config: i, thisC: f$1({}, this.config), p: a, s: l }), !this.config.identity_distinct_id || null != (s = i.bootstrap) && s.distinctID || (i.bootstrap = f$1({}, i.bootstrap, { distinctID: this.config.identity_distinct_id, isIdentifiedID: !0 })), void 0 !== (null == (n = i.bootstrap) ? void 0 : n.distinctID)) { var h = i.bootstrap.distinctID, d = this.get_distinct_id(), c = this.persistence.get_property(mi); if (i.bootstrap.isIdentifiedID && null != d && d !== h && c === Fi) this.identify(h); else if (i.bootstrap.isIdentifiedID && null != d && d !== h && c === Ai) Ie.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users."); else { var p = this.config.get_device_id(sr()), _ = i.bootstrap.isIdentifiedID ? p : h; this.persistence.set_property(mi, i.bootstrap.isIdentifiedID ? Ai : Fi), this.register({ distinct_id: h, $device_id: _ }); } } if (u) this.register_once({ distinct_id: Ti, $device_id: null }, ""); else if (!this.get_distinct_id()) { var g = this.config.get_device_id(sr()); this.register_once({ distinct_id: g, $device_id: g }, ""), this.persistence.set_property(mi, Fi); } return Xi(t, "onpagehide" in self ? "pagehide" : "unload", this._handle_unload.bind(this), { passive: !1 }), i.segment ? function(t, e) { var i = t.config.segment; if (!i) return e(); (function(t, e) { var i = t.config.segment; if (!i) return e(); var r = (i) => { var r = () => i.anonymousId() || sr(); t.config.get_device_id = r, i.id() && (t.register({ distinct_id: i.id(), $device_id: r() }), t.persistence.set_property(mi, Ai)), e(); }, s = i.user(); "then" in s && P$1(s.then) ? s.then(r) : r(s); })(t, (() => { i.register(((t) => { Promise && Promise.resolve || wr.warn("This browser does not have Promise support, and can not use the segment integration"); var e = (e, i) => { if (!i) return e; e.event.userId || e.event.anonymousId === t.get_distinct_id() || (wr.info("No userId set, resetting PostHog"), t.reset()), e.event.userId && e.event.userId !== t.get_distinct_id() && (wr.info("UserId set, identifying with PostHog"), t.identify(e.event.userId)); var r = t.calculateEventProperties(i, e.event.properties); return e.event.properties = Object.assign({}, r, e.event.properties), e; }; return { name: "PostHog JS", type: "enrichment", version: "1.0.0", isLoaded: () => !0, load: () => Promise.resolve(), track: (t) => e(t, t.event.event), page: (t) => e(t, Ui), identify: (t) => e(t, ji), screen: (t) => e(t, "$screen") }; })(t)).then((() => { e(); })); })); }(this, (() => this.Ui())) : this.Ui(), P$1(this.config._onCapture) && this.config._onCapture !== Fn && (Ie.warn("onCapture is deprecated. Please use `before_send` instead"), this.on("eventCaptured", ((t) => this.config._onCapture(t.event, t)))), this.config.ip && Ie.warn("The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or \"Discard IP data\" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information."), this; } zi(t) { var e, i, r, s, n, o, a, l = performance.now(), u = f$1({}, qn.__defaultExtensionClasses, this.config.__extensionClasses), h = []; u.featureFlags && this.Ri.push(this.featureFlags = null !== (e = this.featureFlags) && void 0 !== e ? e : new u.featureFlags(this)), u.exceptions && this.Ri.push(this.exceptions = null !== (i = this.exceptions) && void 0 !== i ? i : new u.exceptions(this)), u.historyAutocapture && this.Ri.push(this.historyAutocapture = new u.historyAutocapture(this)), u.tracingHeaders && this.Ri.push(new u.tracingHeaders(this)), u.siteApps && this.Ri.push(this.siteApps = new u.siteApps(this)), u.sessionRecording && !t && this.Ri.push(this.sessionRecording = new u.sessionRecording(this)), this.config.disable_scroll_properties || h.push((() => { this.scrollManager.startMeasuringScrollPosition(); })), u.autocapture && this.Ri.push(this.autocapture = new u.autocapture(this)), u.surveys && this.Ri.push(this.surveys = null !== (r = this.surveys) && void 0 !== r ? r : new u.surveys(this)), u.logs && this.Ri.push(this.logs = null !== (s = this.logs) && void 0 !== s ? s : new u.logs(this)), u.conversations && this.Ri.push(this.conversations = null !== (n = this.conversations) && void 0 !== n ? n : new u.conversations(this)), u.productTours && this.Ri.push(this.productTours = new u.productTours(this)), u.heatmaps && this.Ri.push(this.heatmaps = new u.heatmaps(this)), u.webVitalsAutocapture && this.Ri.push(this.webVitalsAutocapture = new u.webVitalsAutocapture(this)), u.exceptionObserver && this.Ri.push(this.exceptionObserver = new u.exceptionObserver(this)), u.deadClicksAutocapture && this.Ri.push(this.deadClicksAutocapture = new u.deadClicksAutocapture(this, br)), u.toolbar && this.Ri.push(this.toolbar = null !== (o = this.toolbar) && void 0 !== o ? o : new u.toolbar(this)), u.experiments && this.Ri.push(this.experiments = null !== (a = this.experiments) && void 0 !== a ? a : new u.experiments(this)), this.Ri.forEach(((t) => { t.initialize && h.push((() => { null == t.initialize || t.initialize(); })); })), h.push((() => { if (this.Yi) { var t = this.Yi; this.Yi = void 0, this.Nr(t); } })), this.Gi(h, l); } Gi(t, e) { for (; t.length > 0;) { if (this.config.__preview_deferred_init_extensions && performance.now() - e >= 30 && t.length > 0) return void setTimeout((() => { this.Gi(t, e); }), 0); var i = t.shift(); if (i) try { i(); } catch (t) { Ie.error("Error initializing extension:", t); } } var r = Math.round(performance.now() - e); this.register_for_session({ [ki]: this.config.__preview_deferred_init_extensions ? "deferred" : "synchronous", [Ri]: r }), this.config.__preview_deferred_init_extensions && Ie.info("PostHog extensions initialized (" + r + "ms)"); } Nr(t) { var e; if (!r$1 || !r$1.body) return Ie.info("document not ready yet, trying again in 500 milliseconds..."), void setTimeout((() => { this.Nr(t); }), 500); this.config.__preview_deferred_init_extensions && (this.Yi = t), this.Wi = t, this.compression = void 0, t.supportedCompression && !this.config.disable_compression && (this.compression = w$1(t.supportedCompression, ps.GZipJS) ? ps.GZipJS : w$1(t.supportedCompression, ps.Base64) ? ps.Base64 : void 0), null != (e = t.analytics) && e.endpoint && (this.analyticsDefaultEndpoint = t.analytics.endpoint), this.set_config({ person_profiles: this.Li ? this.Li : Mi }), this.Ri.forEach(((e) => null == e.onRemoteConfig ? void 0 : e.onRemoteConfig(t))); } Ui() { try { this.config.loaded(this); } catch (t) { Ie.critical("`loaded` function failed", t); } if (this.Xi(), this.config.internal_or_test_user_hostname && null != s$1 && s$1.hostname) { var t = s$1.hostname, e = this.config.internal_or_test_user_hostname; ("string" == typeof e ? t === e : e.test(t)) && this.setInternalOrTestUser(); } this.config.capture_pageview && setTimeout((() => { (this.consent.isOptedIn() || this.Ni()) && this.Ji(); }), 1), this.Ki = new vs(this), this.Ki.load(); } Xi() { var t; this.is_capturing() && this.config.request_batching && (null == (t = this.Zi) || t.enable()); } _dom_loaded() { this.is_capturing() && Bi(this.__request_queue, ((t) => this.Vi(t))), this.__request_queue = [], this.Xi(); } _handle_unload() { var t, e, i, r; null == (t = this.surveys) || t.handlePageUnload(), this.config.request_batching ? (this.Qi() && this.capture(Ni), null == (e = this.logs) || e.flushLogs("sendBeacon"), null == (i = this.Zi) || i.unload(), null == (r = this.Hi) || r.unload()) : this.Qi() && this.capture(Ni, null, { transport: "sendBeacon" }); } _send_request(t) { this.__loaded && (Nn ? this.__request_queue.push(t) : this.rateLimiter.isServerRateLimited(t.batchKey) || (t.transport = t.transport || this.config.api_transport, t.url = Ks(t.url, { ip: this.config.ip ? 1 : 0 }), t.headers = f$1({}, this.config.request_headers, t.headers), t.compression = "best-available" === t.compression ? this.compression : t.compression, t.disableXHRCredentials = this.config.__preview_disable_xhr_credentials, this.config.__preview_disable_beacon && (t.disableTransport = ["sendBeacon"]), t.fetchOptions = t.fetchOptions || this.config.fetch_options, ((t) => { var e, i, r, s = f$1({}, t); s.timeout = s.timeout || 6e4, s.url = tn(s.url, s.compression); var n = null !== (e = s.transport) && void 0 !== e ? e : "fetch", o = en.filter(((t) => !s.disableTransport || !t.transport || !s.disableTransport.includes(t.transport))), a = null !== (i = null == (r = function(t, e) { for (var i = 0; t.length > i; i++) if (t[i].transport === n) return t[i]; }(o)) ? void 0 : r.method) && void 0 !== i ? i : o[0].method; if (!a) throw new Error("No available transport method"); "sendBeacon" !== n && s.data && s.compression === ps.GZipJS && l$1 && !Js ? Zs(s).then(((t) => { a(t); })).catch(((e) => { if (((t) => !(!t || "object" != typeof t) && "NotReadableError" === ("name" in t ? String(t.name) : ""))(e)) return Js = !0, void a(f$1({}, s, { compression: void 0, url: tn(t.url, void 0) })); a(s); })) : a(s); })(f$1({}, t, { callback: (e) => { var i, r; this.rateLimiter.checkForLimiting(e), 400 > e.statusCode || null == (i = (r = this.config).on_request_error) || i.call(r, e), null == t.callback || t.callback(e); } })))); } Vi(t) { this.Hi ? this.Hi.retriableRequest(t) : this._send_request(t); } _execute_array(t) { Cn++; try { var e, i = [], r = [], s = []; Bi(t, ((t) => { t && (R$1(e = t[0]) ? s.push(t) : P$1(t) ? t.call(this) : R$1(t) && "alias" === e ? i.push(t) : R$1(t) && -1 !== e.indexOf("capture") && P$1(this[e]) ? s.push(t) : r.push(t)); })); var n = function(t, e) { Bi(t, (function(t) { if (R$1(t[0])) { var i = e; Hi(t, (function(t) { i = i[t[0]].apply(i, t.slice(1)); })); } else e[t[0]].apply(e, t.slice(1)); })); }; n(i, this), n(r, this), n(s, this); } finally { Cn--; } } push(t) { if (Cn > 0 && R$1(t) && F$1(t[0])) { var e = qn.prototype[t[0]]; P$1(e) && e.apply(this, t.slice(1)); } else this._execute_array([t]); } capture(t, e, i) { var r, s, n, o, a; if (this.__loaded && this.persistence && this.sessionPersistence && this.Zi) { if (this.is_capturing()) if (!C$2(t) && F$1(t)) { var l = !this.config.opt_out_useragent_filter && this._is_bot(); if (!l || this.config.__preview_capture_bot_pageviews) { var u = null != i && i.skip_client_rate_limiting ? void 0 : this.rateLimiter.clientRateLimitContext(); if (null == u || !u.isRateLimited) { null != e && e.$current_url && !F$1(null == e ? void 0 : e.$current_url) && (Ie.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."), null == e || delete e.$current_url), "$exception" !== t || null != i && i.en || Ie.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."), this.sessionPersistence.update_search_keyword(), this.config.save_campaign_params && this.sessionPersistence.update_campaign_params(), this.config.save_referrer && this.sessionPersistence.update_referrer_info(), (this.config.save_campaign_params || this.config.save_referrer) && this.persistence.set_initial_person_info(); var h = /* @__PURE__ */ new Date(), d = (null == i ? void 0 : i.timestamp) || h, v = sr(), c = { uuid: v, event: t, properties: this.calculateEventProperties(t, e || {}, d, v) }; t === Ui && this.config.__preview_capture_bot_pageviews && l && (c.event = "$bot_pageview", c.properties.$browser_type = "bot"), u && (c.properties.$lib_rate_limit_remaining_tokens = u.remainingTokens), null != i && i.$set && (c.$set = null == i ? void 0 : i.$set); var p, _, g, m = this.tn(null == i ? void 0 : i.$set_once, t !== zi, t === ji); if (m && (c.$set_once = m), null != i && i._noTruncate || (s = this.config.properties_string_max_length, n = c, o = (t) => F$1(t) ? t.slice(0, s) : t, a = /* @__PURE__ */ new Set(), c = function t(e, i) { return e !== Object(e) ? o ? o(e) : e : a.has(e) ? void 0 : (a.add(e), R$1(e) ? (r = [], Bi(e, ((e) => { r.push(t(e)); }))) : (r = {}, Hi(e, ((e, i) => { a.has(e) || (r[i] = t(e, i)); }))), r); var r; }(n)), c.timestamp = d, C$2(null == i ? void 0 : i.timestamp) || (c.properties.$event_time_override_provided = !0, c.properties.$event_time_override_system_time = h), t === rs.DISMISSED || t === rs.SENT) { var b = null == e ? void 0 : e[ss.SURVEY_ID], y = null == e ? void 0 : e[ss.SURVEY_ITERATION]; ((t) => { try { var e = ((t) => ((t, e) => { var i = "" + Sn + e.id; return e.current_iteration && e.current_iteration > 0 && (i = "" + Sn + e.id + "_" + e.current_iteration), i; })(0, t))(t); if (localStorage.getItem(e)) return; localStorage.setItem(e, "true"); } catch (t) { En.error("Failed to persist survey seen state", t); } })({ id: b, current_iteration: y }), c.$set = f$1({}, c.$set, { [(p = { id: b, current_iteration: y }, _ = t === rs.SENT ? "responded" : "dismissed", g = "$survey_" + _ + "/" + p.id, p.current_iteration && p.current_iteration > 0 && (g = "$survey_" + _ + "/" + p.id + "/" + p.current_iteration), g)]: !0 }); } else t === rs.SHOWN && (c.$set = f$1({}, c.$set, { [ss.SURVEY_LAST_SEEN_DATE]: (/* @__PURE__ */ new Date()).toISOString() })); if (t === as.SHOWN) { var w = null == e ? void 0 : e[ls.TOUR_TYPE]; w && (c.$set = f$1({}, c.$set, { [ls.TOUR_LAST_SEEN_DATE + "/" + w]: (/* @__PURE__ */ new Date()).toISOString() })); } var x = f$1({}, c.properties.$set, c.$set); if (I(x) || this.setPersonPropertiesForFlags(x), !D$1(this.config.before_send)) { var E = this.rn(c); if (!E) return; c = E; } this.Fi.emit("eventCaptured", c); var S = { method: "POST", url: null !== (r = null == i ? void 0 : i._url) && void 0 !== r ? r : this.requestRouter.endpointFor("api", this.analyticsDefaultEndpoint), data: c, compression: "best-available", batchKey: null == i ? void 0 : i._batchKey }; return !this.config.request_batching || i && (null == i || !i._batchKey) || null != i && i.send_instantly ? this.Vi(S) : this.Zi.enqueue(S), c; } Ie.critical("This capture call is ignored due to client rate limiting."); } } else Ie.error("No event name provided to posthog.capture"); } else Ie.uninitializedWarning("posthog.capture"); } _addCaptureHook(t) { return this.on("eventCaptured", ((e) => t(e.event, e))); } calculateEventProperties(e, i, n, o, a) { if (n = n || /* @__PURE__ */ new Date(), !this.persistence || !this.sessionPersistence) return i; var l = a ? void 0 : this.persistence.remove_event_timer(e), h = f$1({}, i); if (h.token = this.config.token, h.$config_defaults = this.config.defaults, this.Ni() && (h.$cookieless_mode = !0), "$snapshot" === e) { var d = f$1({}, this.persistence.properties(), this.sessionPersistence.properties()); return h.distinct_id = d.distinct_id, (!F$1(h.distinct_id) && !L$1(h.distinct_id) || A$1(h.distinct_id)) && Ie.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"), h; } var c, p = function(e, i) { var r, n, o, a; if (!u$1) return {}; var l, h, d, c, p, f, _, g, m = e ? [...Fr, ...i || []] : [], [b, y] = function(t) { for (var e = 0; Wt$1.length > e; e++) { var [i, r] = Wt$1[e], s = i.exec(t), n = s && (P$1(r) ? r(s, t) : r); if (n) return n; } return ["", ""]; }(u$1); return qi(Yi({ $os: b, $os_version: y, $browser: Ht$1(u$1, navigator.vendor), $device: Gt$1(u$1), $device_type: (h = u$1, d = { userAgentDataPlatform: null == (r = navigator) || null == (r = r.userAgentData) ? void 0 : r.platform, maxTouchPoints: null == (n = navigator) ? void 0 : n.maxTouchPoints, screenWidth: null == t || null == (o = t.screen) ? void 0 : o.width, screenHeight: null == t || null == (a = t.screen) ? void 0 : a.height, devicePixelRatio: null == t ? void 0 : t.devicePixelRatio }, g = Gt$1(h), g === st$1 || g === rt$1 || "Kobo" === g || "Kindle Fire" === g || g === At ? it$1 : g === Et$1 || g === $t$1 || g === St$1 || g === It$1 ? "Console" : g === ot$1 ? "Wearable" : g ? Z$2 : "Android" === (null == d ? void 0 : d.userAgentDataPlatform) && (null !== (c = null == d ? void 0 : d.maxTouchPoints) && void 0 !== c ? c : 0) > 0 ? 600 > Math.min(null !== (p = null == d ? void 0 : d.screenWidth) && void 0 !== p ? p : 0, null !== (f = null == d ? void 0 : d.screenHeight) && void 0 !== f ? f : 0) / (null !== (_ = null == d ? void 0 : d.devicePixelRatio) && void 0 !== _ ? _ : 1) ? Z$2 : it$1 : "Desktop"), $timezone: Vr(), $timezone_offset: Wr() }), { $current_url: Or(null == s$1 ? void 0 : s$1.href, m, Mr), $host: null == s$1 ? void 0 : s$1.host, $pathname: null == s$1 ? void 0 : s$1.pathname, $raw_user_agent: u$1.length > 1e3 ? u$1.substring(0, 997) + "..." : u$1, $browser_version: Vt$1(u$1, navigator.vendor), $browser_language: jr(), $browser_language_prefix: (l = jr(), "string" == typeof l ? l.split("-")[0] : void 0), $screen_height: null == t ? void 0 : t.screen.height, $screen_width: null == t ? void 0 : t.screen.width, $viewport_height: null == t ? void 0 : t.innerHeight, $viewport_width: null == t ? void 0 : t.innerWidth, $lib: v$1.LIB_NAME, $lib_version: v$1.LIB_VERSION, $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10), $time: Date.now() / 1e3 }); }(this.config.mask_personal_data_properties, this.config.custom_personal_data_properties); if (this.sessionManager) { var { sessionId: _, windowId: g } = this.sessionManager.checkAndGetSessionAndWindowId(a, n.getTime()); h.$session_id = _, h.$window_id = g; } this.sessionPropsManager && qi(h, this.sessionPropsManager.getSessionProps()); try { var m; this.sessionRecording && qi(h, this.sessionRecording.sdkDebugProperties), h.$sdk_debug_retry_queue_size = null == (m = this.Hi) ? void 0 : m.length; } catch (t) { h.$sdk_debug_error_capturing_properties = String(t); } if (this.requestRouter.region === bn && (h.$lib_custom_api_host = this.config.api_host), c = e !== Ui || a ? e !== Ni || a ? this.pageViewManager.doEvent() : this.pageViewManager.doPageLeave(n) : this.pageViewManager.doPageView(n, o), h = qi(h, c), e === Ui && r$1 && (h.title = r$1.title), !C$2(l)) { var b = n.getTime() - l; h.$duration = parseFloat((b / 1e3).toFixed(3)); } u$1 && this.config.opt_out_useragent_filter && (h.$browser_type = this._is_bot() ? "bot" : "browser"), (h = qi({}, p, this.persistence.properties(), this.sessionPersistence.properties(), h)).$is_identified = this._isIdentified(), R$1(this.config.property_denylist) ? Hi(this.config.property_denylist, (function(t) { delete h[t]; })) : Ie.error(Ln + this.config.property_denylist + " or property_blacklist config: " + this.config.property_blacklist); var y = this.config.sanitize_properties; y && (Ie.error(Dn), h = y(h, e)); var w = this.nn(); return h.$process_person_profile = w, w && !a && this.sn("_calculate_event_properties"), h; } tn(t, e, i) { var r; if (void 0 === e && (e = !0), void 0 === i && (i = !1), !this.persistence || !this.nn()) return t; if (this.Mi && !i) return t; var o = qi({}, this.persistence.get_initial_props(), (null == (r = this.sessionPropsManager) ? void 0 : r.getSetOnceProps()) || {}, t || {}), a = this.config.sanitize_properties; return a && (Ie.error(Dn), o = a(o, "$set_once")), e && (this.Mi = !0), I(o) ? void 0 : o; } register(t, e) { var i; null == (i = this.persistence) || i.register(t, e); } register_once(t, e, i) { var r; null == (r = this.persistence) || r.register_once(t, e, i); } register_for_session(t) { var e; null == (e = this.sessionPersistence) || e.register(t); } unregister(t) { var e; null == (e = this.persistence) || e.unregister(t); } unregister_for_session(t) { var e; null == (e = this.sessionPersistence) || e.unregister(t); } an(t, e) { this.register({ [t]: e }); } getFeatureFlag(t, e) { var i; return null == (i = this.featureFlags) ? void 0 : i.getFeatureFlag(t, e); } getFeatureFlagPayload(t) { var e; return null == (e = this.featureFlags) ? void 0 : e.getFeatureFlagPayload(t); } getFeatureFlagResult(t, e) { var i; return null == (i = this.featureFlags) ? void 0 : i.getFeatureFlagResult(t, e); } isFeatureEnabled(t, e) { var i; return null == (i = this.featureFlags) ? void 0 : i.isFeatureEnabled(t, e); } reloadFeatureFlags() { var t; null == (t = this.featureFlags) || t.reloadFeatureFlags(); } updateFlags(t, e, i) { var r; null == (r = this.featureFlags) || r.updateFlags(t, e, i); } updateEarlyAccessFeatureEnrollment(t, e, i) { var r; null == (r = this.featureFlags) || r.updateEarlyAccessFeatureEnrollment(t, e, i); } getEarlyAccessFeatures(t, e, i) { var r; return void 0 === e && (e = !1), null == (r = this.featureFlags) ? void 0 : r.getEarlyAccessFeatures(t, e, i); } on(t, e) { return this.Fi.on(t, e); } onFeatureFlags(t) { return this.featureFlags ? this.featureFlags.onFeatureFlags(t) : (t([], {}, { errorsLoading: !0 }), () => {}); } onSurveysLoaded(t) { return this.surveys ? this.surveys.onSurveysLoaded(t) : (t([], { isLoaded: !1, error: Mn }), () => {}); } onSessionId(t) { var e, i; return null !== (e = null == (i = this.sessionManager) ? void 0 : i.onSessionId(t)) && void 0 !== e ? e : () => {}; } getSurveys(t, e) { void 0 === e && (e = !1), this.surveys ? this.surveys.getSurveys(t, e) : t([], { isLoaded: !1, error: Mn }); } getActiveMatchingSurveys(t, e) { void 0 === e && (e = !1), this.surveys ? this.surveys.getActiveMatchingSurveys(t, e) : t([], { isLoaded: !1, error: Mn }); } renderSurvey(t, e) { var i; null == (i = this.surveys) || i.renderSurvey(t, e); } displaySurvey(t, e) { var i; void 0 === e && (e = Tn), null == (i = this.surveys) || i.displaySurvey(t, e); } cancelPendingSurvey(t) { var e; null == (e = this.surveys) || e.cancelPendingSurvey(t); } canRenderSurvey(t) { var e, i; return null !== (e = null == (i = this.surveys) ? void 0 : i.canRenderSurvey(t)) && void 0 !== e ? e : { visible: !1, disabledReason: Mn }; } canRenderSurveyAsync(t, e) { var i, r; return void 0 === e && (e = !1), null !== (i = null == (r = this.surveys) ? void 0 : r.canRenderSurveyAsync(t, e)) && void 0 !== i ? i : Promise.resolve({ visible: !1, disabledReason: Mn }); } ln(t) { return !t || A$1(t) ? (Ie.critical("Unique user id has not been set in posthog.identify"), !1) : t === Ti ? (Ie.critical("The string \"" + t + "\" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value."), !1) : !["distinct_id", "distinctid"].includes(t.toLowerCase()) && !["undefined", "null"].includes(t.toLowerCase()) || (Ie.critical("The string \"" + t + "\" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string."), !1); } identify(t, e, i) { if (!this.__loaded || !this.persistence) return Ie.uninitializedWarning("posthog.identify"); if (L$1(t) && (t = t.toString(), Ie.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")), this.ln(t) && this.sn("posthog.identify")) { var r = this.get_distinct_id(); this.register({ $user_id: t }), this.get_property(De$1) || this.register_once({ $had_persisted_distinct_id: !0, $device_id: r }, ""), t !== r && t !== this.get_property(Le) && (this.unregister(Le), this.register({ distinct_id: t })); var s, n = (this.persistence.get_property(mi) || Fi) === Fi; t !== r && n ? (this.persistence.set_property(mi, Ai), this.setPersonPropertiesForFlags({ $set: e || {}, $set_once: i || {} }, !1), this.capture(ji, { distinct_id: t, $anon_distinct_id: r }, { $set: e || {}, $set_once: i || {} }), this.Di = fn(t, e, i), null == (s = this.featureFlags) || s.setAnonymousDistinctId(r)) : (e || i) && this.setPersonProperties(e, i), t !== r && (this.reloadFeatureFlags(), this.unregister(pi)); } } setPersonProperties(t, e) { if ((t || e) && this.sn("posthog.setPersonProperties")) { var i = fn(this.get_distinct_id(), t, e); this.Di !== i ? (this.setPersonPropertiesForFlags({ $set: t || {}, $set_once: e || {} }, !0), this.capture("$set", { $set: t || {}, $set_once: e || {} }), this.Di = i) : Ie.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored."); } } group(t, e, i) { if (t && e) { var r = this.getGroups(), s = r[t] !== e; if (s && this.resetGroupPropertiesForFlags(t), this.register({ $groups: f$1({}, r, { [t]: e }) }), s || i) { var n = { $group_type: t, $group_key: e }; i && (n.$group_set = i), this.capture(zi, n); } i && this.setGroupPropertiesForFlags({ [t]: i }), s && !i && this.reloadFeatureFlags(); } else Ie.error("posthog.group requires a group type and group key"); } resetGroups() { this.register({ $groups: {} }), this.resetGroupPropertiesForFlags(), this.reloadFeatureFlags(); } setPersonPropertiesForFlags(t, e) { var i; void 0 === e && (e = !0), null == (i = this.featureFlags) || i.setPersonPropertiesForFlags(t, e); } resetPersonPropertiesForFlags() { var t; null == (t = this.featureFlags) || t.resetPersonPropertiesForFlags(); } setGroupPropertiesForFlags(t, e) { var i; void 0 === e && (e = !0), this.sn("posthog.setGroupPropertiesForFlags") && (null == (i = this.featureFlags) || i.setGroupPropertiesForFlags(t, e)); } resetGroupPropertiesForFlags(t) { var e; null == (e = this.featureFlags) || e.resetGroupPropertiesForFlags(t); } reset(t) { var e, i, r, s, n, o, a, l; if (Ie.info("reset"), !this.__loaded) return Ie.uninitializedWarning("posthog.reset"); var u = this.get_property(De$1); if (this.consent.reset(), null == (e = this.persistence) || e.clear(), null == (i = this.sessionPersistence) || i.clear(), null == (r = this.surveys) || r.reset(), null == (s = this.Ki) || s.stop(), null == (n = this.featureFlags) || n.reset(), null == (o = this.conversations) || o.reset(), null == (a = this.persistence) || a.set_property(mi, Fi), null == (l = this.sessionManager) || l.resetSessionId(), this.Di = null, this.config.cookieless_mode === Ci) this.register_once({ distinct_id: Ti, $device_id: null }, ""); else { var h = this.config.get_device_id(sr()); this.register_once({ distinct_id: h, $device_id: t ? h : u }, ""); } this.register({ $last_posthog_reset: (/* @__PURE__ */ new Date()).toISOString() }, 1), delete this.config.identity_distinct_id, delete this.config.identity_hash, this.reloadFeatureFlags(); } setIdentity(t, e) { var i; this.config.identity_distinct_id = t, this.config.identity_hash = e, this.alias(t), null == (i = this.conversations) || i.un(); } clearIdentity() { var t; delete this.config.identity_distinct_id, delete this.config.identity_hash, null == (t = this.conversations) || t.hn(); } get_distinct_id() { return this.get_property("distinct_id"); } getGroups() { return this.get_property("$groups") || {}; } get_session_id() { var t, e; return null !== (t = null == (e = this.sessionManager) ? void 0 : e.checkAndGetSessionAndWindowId(!0).sessionId) && void 0 !== t ? t : ""; } get_session_replay_url(t) { if (!this.sessionManager) return ""; var { sessionId: e, sessionStartTimestamp: i } = this.sessionManager.checkAndGetSessionAndWindowId(!0), r = this.requestRouter.endpointFor("ui", "/project/" + this.config.token + "/replay/" + e); if (null != t && t.withTimestamp && i) { var s, n = null !== (s = t.timestampLookBack) && void 0 !== s ? s : 10; if (!i) return r; r += "?t=" + Math.max(Math.floor(((/* @__PURE__ */ new Date()).getTime() - i) / 1e3) - n, 0); } return r; } alias(t, e) { return t === this.get_property(Me$1) ? (Ie.critical("Attempting to create alias for existing People user - aborting."), -2) : this.sn("posthog.alias") ? (C$2(e) && (e = this.get_distinct_id()), t !== e ? (this.an(Le, t), this.capture("$create_alias", { alias: t, distinct_id: e })) : (Ie.warn("alias matches current distinct_id - skipping api call."), this.identify(t), -1)) : void 0; } set_config(t) { var e = f$1({}, this.config); if (O$1(t)) { var i, r, s, n, o, a, l, u, h, d; qi(this.config, Bn(t)); var c = this.qi(); null == (i = this.persistence) || i.update_config(this.config, e, c), this.sessionPersistence = "sessionStorage" === this.config.persistence || "memory" === this.config.persistence ? this.persistence : new Yr(f$1({}, this.config, { persistence: "sessionStorage" }), c); var p = this.Bi(this.config.debug); N(p) && (this.config.debug = p), N(this.config.debug) && (this.config.debug ? (v$1.DEBUG = !0, hr.R() && hr.M("ph_debug", !0), Ie.info("set_config", { config: t, oldConfig: e, newConfig: f$1({}, this.config) })) : (v$1.DEBUG = !1, hr.R() && hr.F("ph_debug"))), null == (r = this.exceptionObserver) || r.onConfigChange(), null == (s = this.exceptions) || s.onConfigChange(), null == (n = this.sessionRecording) || n.startIfEnabledOrStop(), null == (o = this.autocapture) || o.startIfEnabled(), null == (a = this.heatmaps) || a.startIfEnabled(), null == (l = this.exceptionObserver) || l.startIfEnabledOrStop(), null == (u = this.deadClicksAutocapture) || u.startIfEnabledOrStop(), null == (h = this.surveys) || h.loadIfEnabled(), this.cn(), null == (d = this.externalIntegrations) || d.startIfEnabledOrStop(); } } _overrideSDKInfo(t, e) { v$1.LIB_NAME = t, v$1.LIB_VERSION = e; } startSessionRecording(t) { var e, i, r, s, n, o = !0 === t, a = { sampling: o || !(null == t || !t.sampling), linked_flag: o || !(null == t || !t.linked_flag), url_trigger: o || !(null == t || !t.url_trigger), event_trigger: o || !(null == t || !t.event_trigger) }; Object.values(a).some(Boolean) && (null == (e = this.sessionManager) || e.checkAndGetSessionAndWindowId(), a.sampling && (null == (i = this.sessionRecording) || i.overrideSampling()), a.linked_flag && (null == (r = this.sessionRecording) || r.overrideLinkedFlag()), a.url_trigger && (null == (s = this.sessionRecording) || s.overrideTrigger("url")), a.event_trigger && (null == (n = this.sessionRecording) || n.overrideTrigger("event"))); this.set_config({ disable_session_recording: !1 }); } stopSessionRecording() { this.set_config({ disable_session_recording: !0 }); } sessionRecordingStarted() { var t; return !(null == (t = this.sessionRecording) || !t.started); } captureException(t, e) { if (this.exceptions) { var i = /* @__PURE__ */ new Error("PostHog syntheticException"), r = this.exceptions.buildProperties(t, { handled: !0, syntheticException: i }); return this.exceptions.sendExceptionEvent(f$1({}, r, e)); } } addExceptionStep(t, e) { var i; null == (i = this.exceptions) || i.addExceptionStep(t, e); } captureLog(t) { var e; null == (e = this.logs) || e.captureLog(t); } get logger() { var t, e; return null !== (t = null == (e = this.logs) ? void 0 : e.logger) && void 0 !== t ? t : qn.dn; } startExceptionAutocapture(t) { this.set_config({ capture_exceptions: null == t || t }); } stopExceptionAutocapture() { this.set_config({ capture_exceptions: !1 }); } loadToolbar(t) { var e, i; return null !== (e = null == (i = this.toolbar) ? void 0 : i.loadToolbar(t)) && void 0 !== e && e; } get_property(t) { var e; return null == (e = this.persistence) ? void 0 : e.props[t]; } getSessionProperty(t) { var e; return null == (e = this.sessionPersistence) ? void 0 : e.props[t]; } toString() { var t, e = null !== (t = this.config.name) && void 0 !== t ? t : Un; return e !== Un && (e = Un + "." + e), e; } _isIdentified() { var t, e; return (null == (t = this.persistence) ? void 0 : t.get_property(mi)) === Ai || (null == (e = this.sessionPersistence) ? void 0 : e.get_property(mi)) === Ai; } nn() { var t, e; return !("never" === this.config.person_profiles || this.config.person_profiles === Mi && !this._isIdentified() && I(this.getGroups()) && (null == (t = this.persistence) || null == (t = t.props) || !t[Le]) && (null == (e = this.persistence) || null == (e = e.props) || !e[Si])); } Qi() { return !0 === this.config.capture_pageleave || "if_capture_pageview" === this.config.capture_pageleave && (!0 === this.config.capture_pageview || "history_change" === this.config.capture_pageview); } createPersonProfile() { this.nn() || this.sn("posthog.createPersonProfile") && this.setPersonProperties({}, {}); } setInternalOrTestUser() { this.sn("posthog.setInternalOrTestUser") && this.setPersonProperties({ $internal_or_test_user: !0 }); } sn(t) { return "never" === this.config.person_profiles ? (Ie.error(t + " was called, but process_person is set to \"never\". This call will be ignored."), !1) : (this.an(Si, !0), !0); } qi() { if ("always" === this.config.cookieless_mode) return !0; var t = this.consent.isOptedOut(); return this.config.disable_persistence || t && !(!this.config.opt_out_persistence_by_default && this.config.cookieless_mode !== Ii); } cn() { var t, e, i, r, s = this.qi(); return (null == (t = this.persistence) ? void 0 : t._r) !== s && (null == (i = this.persistence) || i.set_disabled(s)), (null == (e = this.sessionPersistence) ? void 0 : e._r) !== s && (null == (r = this.sessionPersistence) || r.set_disabled(s)), s; } opt_in_capturing(t) { var e; if (this.config.cookieless_mode !== Ci) { if (this.Ni()) { var i, r, s, n, o; this.reset(!0), null == (i = this.sessionManager) || i.destroy(), null == (r = this.pageViewManager) || r.destroy(), this.sessionManager = new vn(this), this.pageViewManager = new $r(this), this.persistence && (this.sessionPropsManager = new un(this, this.sessionManager, this.persistence)); var a, l = null !== (s = null == (n = this.config.__extensionClasses) ? void 0 : n.sessionRecording) && void 0 !== s ? s : null == (o = qn.__defaultExtensionClasses) ? void 0 : o.sessionRecording; l && (this.sessionRecording = this.Ei(this.sessionRecording, new l(this)), this.Wi && (null == (a = this.sessionRecording) || null == a.onRemoteConfig || a.onRemoteConfig(this.Wi))); } var u, h; this.consent.optInOut(!0), this.cn(), this.Xi(), null == (e = this.sessionRecording) || e.startIfEnabledOrStop(), this.config.cookieless_mode == Ii && (null == (u = this.surveys) || u.loadIfEnabled()), (C$2(null == t ? void 0 : t.captureEventName) || null != t && t.captureEventName) && this.capture(null !== (h = null == t ? void 0 : t.captureEventName) && void 0 !== h ? h : "$opt_in", null == t ? void 0 : t.captureProperties, { send_instantly: !0 }), this.config.capture_pageview && this.Ji(); } else Ie.warn(An); } opt_out_capturing() { var t, e, i; this.config.cookieless_mode !== Ci ? (this.config.cookieless_mode === Ii && this.consent.isOptedIn() && this.reset(!0), this.consent.optInOut(!1), this.cn(), this.config.cookieless_mode === Ii && (this.register({ distinct_id: Ti, $device_id: null }), null == (t = this.sessionManager) || t.destroy(), null == (e = this.pageViewManager) || e.destroy(), this.sessionManager = void 0, this.sessionPropsManager = void 0, null == (i = this.sessionRecording) || i.stopRecording(), this.sessionRecording = void 0, this.Ji())) : Ie.warn(An); } has_opted_in_capturing() { return this.consent.isOptedIn(); } has_opted_out_capturing() { return this.consent.isOptedOut(); } get_explicit_consent_status() { var t = this.consent.consent; return 1 === t ? "granted" : 0 === t ? "denied" : "pending"; } is_capturing() { return this.config.cookieless_mode === Ci || (this.config.cookieless_mode === Ii ? this.consent.isRejected() || this.consent.isOptedIn() : !this.has_opted_out_capturing()); } clear_opt_in_out_capturing() { this.consent.reset(), this.cn(); } _is_bot() { return i$1 ? cn(i$1, this.config.custom_blocked_useragents) : void 0; } Ji() { r$1 && ("visible" === r$1.visibilityState ? this.Oi || (this.Oi = !0, this.capture(Ui, { title: r$1.title }, { send_instantly: !0 }), this.Pi && (r$1.removeEventListener(Di, this.Pi), this.Pi = null)) : this.Pi || (this.Pi = this.Ji.bind(this), Xi(r$1, Di, this.Pi))); } debug(e) { !1 === e ? (t?.console.log("You've disabled debug mode."), this.set_config({ debug: !1 })) : (t?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."), this.set_config({ debug: !0 })); } Fr() { var t, e, i, r, s, n, o = this.ji || {}; return "advanced_disable_flags" in o ? !!o.advanced_disable_flags : !1 !== this.config.advanced_disable_flags ? !!this.config.advanced_disable_flags : !0 === this.config.advanced_disable_decide ? (Ie.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."), !0) : (i = "advanced_disable_decide", r = Ie, s = (e = "advanced_disable_flags") in (t = o) && !D$1(t[e]), n = i in t && !D$1(t[i]), s ? t[e] : !!n && (r && r.warn("Config field '" + i + "' is deprecated. Please use '" + e + "' instead. The old field will be removed in a future major version."), t[i])); } rn(t) { if (D$1(this.config.before_send)) return t; var e = R$1(this.config.before_send) ? this.config.before_send : [this.config.before_send], i = t; for (var r of e) { if (i = r(i), D$1(i)) { var s = "Event '" + t.event + "' was rejected in beforeSend function"; return z$1(t.event) ? Ie.warn(s + ". This can cause unexpected behavior.") : Ie.info(s), null; } i.properties && !I(i.properties) || Ie.warn("Event '" + t.event + "' has no properties after beforeSend function, this is likely an error."); } return i; } getPageViewId() { var t; return null == (t = this.pageViewManager.dr) ? void 0 : t.pageViewId; } captureTraceFeedback(t, e) { this.capture("$ai_feedback", { $ai_trace_id: String(t), $ai_feedback_text: e }); } captureTraceMetric(t, e, i) { this.capture("$ai_metric", { $ai_trace_id: String(t), $ai_metric_name: e, $ai_metric_value: String(i) }); } Bi(t) { var e = N(t) && !t, i = hr.R() && "true" === hr.O("ph_debug"); return !e && (!!i || t); } }; qn.__defaultExtensionClasses = {}, qn.dn = { trace: On = () => {}, debug: On, info: On, warn: On, error: On, fatal: On }, function(t, e) { for (var i = 0; e.length > i; i++) t.prototype[e[i]] = Gi(t.prototype[e[i]]); }(qn, ["identify"]); var Vn = 1, Wn = 3, Gn = 11; function Yn(t) { return t instanceof Element && (t.id === $i || !(null == t.closest || !t.closest(".toolbar-global-fade-container"))); } function Jn(t) { return !!t && t.nodeType === Vn; } function Kn(t, e) { return !!t && !!t.tagName && t.tagName.toLowerCase() === e.toLowerCase(); } function Xn(t) { return !!t && t.nodeType === Wn; } function Qn(t) { return !!t && t.nodeType === Gn && Jn(t.host); } function Zn(t) { return t ? x$2(t).split(/\s+/) : []; } function to(e) { var i = null == t ? void 0 : t.location.href; return !!(i && e && e.some(((t) => i.match(t)))); } function eo(t) { var e = ""; switch (typeof t.className) { case "string": e = t.className; break; case "object": e = (t.className && "baseVal" in t.className ? t.className.baseVal : null) || t.getAttribute("class") || ""; break; default: e = ""; } return Zn(e); } function io(t) { return D$1(t) ? null : x$2(t).split(/(\s+)/).filter(((t) => wo$1(t))).join("").replace(/[\r\n]/g, " ").replace(/[ ]+/g, " ").substring(0, 255); } function ro(t) { var e = ""; return co$1(t) && !po$1(t) && t.childNodes && t.childNodes.length && Hi(t.childNodes, (function(t) { var i; Xn(t) && t.textContent && (e += null !== (i = io(t.textContent)) && void 0 !== i ? i : ""); })), x$2(e); } function so(t) { return C$2(t.target) ? t.srcElement || null : null != (e = t.target) && e.shadowRoot ? t.composedPath()[0] || null : t.target || null; var e; } var no = [ "a", "button", "form", "input", "select", "textarea", "label" ]; function oo(t, e) { if (C$2(e)) return !0; var i, r = function(t) { if (e.some(((e) => t.matches(e)))) return { v: !0 }; }; for (var s of t) if (i = r(s)) return i.v; return !1; } function ao(t) { var e = t.parentNode; return !(!e || !Jn(e)) && e; } var lo = [ "next", "previous", "prev", ">", "<" ], uo$1 = [".ph-no-rageclick", ".ph-no-capture"]; var ho$1 = (t) => !t || Kn(t, "html") || !Jn(t), vo$1 = (e, i) => { if (!t || ho$1(e)) return { parentIsUsefulElement: !1, targetElementList: [] }; for (var r = !1, s = [e], n = e; n.parentNode && !Kn(n, "body");) if (Qn(n.parentNode)) s.push(n.parentNode.host), n = n.parentNode.host; else { var o = ao(n); if (!o) break; if (i || no.indexOf(o.tagName.toLowerCase()) > -1) r = !0; else { var a = t.getComputedStyle(o); a && "pointer" === a.getPropertyValue("cursor") && (r = !0); } s.push(o), n = o; } return { parentIsUsefulElement: r, targetElementList: s }; }; function co$1(t) { for (var e = t; e.parentNode && !Kn(e, "body"); e = e.parentNode) { var i = eo(e); if (w$1(i, "ph-sensitive") || w$1(i, "ph-no-capture")) return !1; } if (w$1(eo(t), "ph-include")) return !0; var r = t.type || ""; if (F$1(r)) switch (r.toLowerCase()) { case "hidden": case "password": return !1; } var s = t.name || t.id || ""; return !F$1(s) || !/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g, "")); } function po$1(t) { return !!(Kn(t, "input") && ![ "button", "checkbox", "submit", "reset" ].includes(t.type) || Kn(t, "select") || Kn(t, "textarea") || "true" === t.getAttribute("contenteditable")); } var fo$1 = "(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})", _o = new RegExp("^(?:" + fo$1 + ")$"), go$1 = new RegExp(fo$1), mo$1 = "\\d{3}-?\\d{2}-?\\d{4}", bo$1 = new RegExp("^(" + mo$1 + ")$"), yo$1 = new RegExp("(" + mo$1 + ")"); function wo$1(t, e) { if (void 0 === e && (e = !0), D$1(t)) return !1; if (F$1(t)) { if (t = x$2(t), (e ? _o : go$1).test((t || "").replace(/[- ]/g, ""))) return !1; if ((e ? bo$1 : yo$1).test(t)) return !1; } return !0; } function xo(t) { var e = ro(t); return wo$1(e = (e + " " + Eo$1(t)).trim()) ? e : ""; } function Eo$1(t) { var e = ""; return t && t.childNodes && t.childNodes.length && Hi(t.childNodes, (function(t) { var i; if (t && "span" === (null == (i = t.tagName) ? void 0 : i.toLowerCase())) try { var r = ro(t); e = (e + " " + r).trim(), t.childNodes && t.childNodes.length && (e = (e + " " + Eo$1(t)).trim()); } catch (t) { Ie.error("[AutoCapture]", t); } })), e; } function So$1(t) { return t.replace(/"|\\"/g, "\\\""); } function $o(t) { var e = t.attr__class; return e ? R$1(e) ? e : Zn(e) : void 0; } var To$1 = class { constructor(t) { this.disabled = !1 === t; var e = O$1(t) ? t : {}; this.thresholdPx = e.threshold_px || 30, this.timeoutMs = e.timeout_ms || 1e3, this.clickCount = e.click_count || 3, this.clicks = []; } isRageClick(t, e, i) { if (this.disabled) return !1; var r = this.clicks[this.clicks.length - 1]; if (r && Math.abs(t - r.x) + Math.abs(e - r.y) < this.thresholdPx && this.timeoutMs > i - r.timestamp) { if (this.clicks.push({ x: t, y: e, timestamp: i }), this.clicks.length === this.clickCount) return !0; } else this.clicks = [{ x: t, y: e, timestamp: i }]; return !1; } }; var ko$1 = "$copy_autocapture", Ro$1 = Ce$1("[AutoCapture]"); function Po$1(t, e) { return e.length > t ? e.slice(0, t) + "..." : e; } function Oo$1(t) { if (t.previousElementSibling) return t.previousElementSibling; var e = t; do e = e.previousSibling; while (e && !Jn(e)); return e; } function Io(e, i) { var r, s, { e: n, maskAllElementAttributes: o, maskAllText: a, elementAttributeIgnoreList: l, elementsChainAsString: u } = i; if (!Jn(e)) return { props: {} }; for (var h = [e], d = e; d.parentNode && !Kn(d, "body");) if (Qn(d.parentNode)) h.push(d.parentNode.host), d = d.parentNode.host; else { if (!Jn(d.parentNode)) break; h.push(d.parentNode), d = d.parentNode; } var v, c, p = [], _ = {}, g = !1, m = !1; if (Hi(h, ((t) => { var e = co$1(t); if (Kn(t, "a")) { var i = t.getAttribute("href"); g = e && !!i && wo$1(i) && i; } w$1(eo(t), "ph-no-capture") && (m = !0), p.push(function(t, e, i, r) { var s = t.tagName.toLowerCase(), n = { tag_name: s }; no.indexOf(s) > -1 && !i && (n.$el_text = "a" === s.toLowerCase() || "button" === s.toLowerCase() ? Po$1(1024, xo(t)) : Po$1(1024, ro(t))); var o = eo(t); o.length > 0 && (n.classes = o.filter((function(t) { return "" !== t; }))), Hi(t.attributes, (function(i) { var s; if ((!po$1(t) || -1 !== [ "name", "id", "class", "aria-label" ].indexOf(i.name)) && (null == r || !r.includes(i.name)) && !e && wo$1(i.value) && (!F$1(s = i.name) || "_ngcontent" !== s.substring(0, 10) && "_nghost" !== s.substring(0, 7))) { var o = i.value; "class" === i.name && (o = Zn(o).join(" ")), n["attr__" + i.name] = Po$1(1024, o); } })); for (var a = 1, l = 1, u = t; u = Oo$1(u);) a++, u.tagName === t.tagName && l++; return n.nth_child = a, n.nth_of_type = l, n; }(t, o, a, l)); qi(_, function(t) { if (!co$1(t)) return {}; var e = {}; return Hi(t.attributes, (function(t) { if (t.name && 0 === t.name.indexOf("data-ph-capture-attribute")) { var i = t.name.replace("data-ph-capture-attribute-", ""), r = t.value; i && r && wo$1(r) && (e[i] = r); } })), e; }(t)); })), m) return { props: {}, explicitNoCapture: m }; if (a || (p[0].$el_text = Kn(e, "a") || Kn(e, "button") ? xo(e) : ro(e)), g) { var b, y; p[0].attr__href = g; var x = null == (b = Rr(g)) ? void 0 : b.host, E = null == t || null == (y = t.location) ? void 0 : y.host; x && E && x !== E && (v = g); } return { props: qi({ $event_type: n.type, $ce_version: 1 }, u ? {} : { $elements: p }, { $elements_chain: (c = p, function(t) { return t.map(((t) => { var e, i, r = ""; if (t.tag_name && (r += t.tag_name), t.attr_class) for (var s of (t.attr_class.sort(), t.attr_class)) r += "." + s.replace(/"/g, ""); var n = f$1({}, t.text ? { text: t.text } : {}, { "nth-child": null !== (e = t.nth_child) && void 0 !== e ? e : 0, "nth-of-type": null !== (i = t.nth_of_type) && void 0 !== i ? i : 0 }, t.href ? { href: t.href } : {}, t.attr_id ? { attr_id: t.attr_id } : {}, t.attributes), o = {}; return Vi(n).sort(((t, e) => { var [i] = t, [r] = e; return i.localeCompare(r); })).forEach(((t) => { var [e, i] = t; return o[So$1(e.toString())] = So$1(i.toString()); })), (r += ":") + Vi(o).map(((t) => { var [e, i] = t; return e + "=\"" + i + "\""; })).join(""); })).join(";"); }(function(t) { return t.map(((t) => { var e, i, r = { text: null == (e = t.$el_text) ? void 0 : e.slice(0, 400), tag_name: t.tag_name, href: null == (i = t.attr__href) ? void 0 : i.slice(0, 2048), attr_class: $o(t), attr_id: t.attr__id, nth_child: t.nth_child, nth_of_type: t.nth_of_type, attributes: {} }; return Vi(t).filter(((t) => { var [e] = t; return 0 === e.indexOf("attr__"); })).forEach(((t) => { var [e, i] = t; return r.attributes[e] = i; })), r; })); }(c))) }, null != (r = p[0]) && r.$el_text ? { $el_text: null == (s = p[0]) ? void 0 : s.$el_text } : {}, v && "click" === n.type ? { $external_click_url: v } : {}, _) }; } var Co$1 = Ce$1("[ExceptionAutocapture]"); function Fo(t, e, i) { try { if (!(e in t)) return () => {}; var r = t[e], s = i(r); return P$1(s) && (s.prototype = s.prototype || {}, Object.defineProperties(s, { __posthog_wrapped__: { enumerable: !1, value: !0 } })), t[e] = s, () => { t[e] = r; }; } catch (t) { return () => {}; } } var Ao$1 = Ce$1("[TracingHeaders]"), Mo$1 = Ce$1("[Web Vitals]"), Do$1 = 9e5, Lo$1 = "disabled", Uo = "lazy_loading", No = "awaiting_config", jo = "missing_config"; Ce$1("[SessionRecording]"), Ce$1("[SessionRecording]"); var zo$1 = "[SessionRecording]", Bo$1 = Ce$1(zo$1), Ho = Ce$1("[Heatmaps]"); function qo(t) { return O$1(t) && "clientX" in t && "clientY" in t && L$1(t.clientX) && L$1(t.clientY); } var Vo$1 = Ce$1("[Product Tours]"), Wo = ["$set_once", "$set"], Go = Ce$1("[SiteApps]"), Yo = "Error while initializing PostHog app with config id "; function Jo(t, e, i) { if (D$1(t)) return !1; switch (i) { case "exact": return t === e; case "contains": var r = e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/_/g, ".").replace(/%/g, ".*"); return new RegExp(r, "i").test(t); case "regex": try { return new RegExp(e).test(t); } catch (t) { return !1; } default: return !1; } } var Ko = class { constructor(t) { this.vn = new hn(), this.fn = (t, e) => this.pn(t, e) && this.gn(t, e) && this.mn(t, e) && this.yn(t, e), this.pn = (t, e) => null == e || !e.event || (null == t ? void 0 : t.event) === (null == e ? void 0 : e.event), this._instance = t, this.bn = /* @__PURE__ */ new Set(), this._n = /* @__PURE__ */ new Set(); } init() { var t, e; C$2(null == (t = this._instance) ? void 0 : t._addCaptureHook) || null == (e = this._instance) || e._addCaptureHook(((t, e) => { this.on(t, e); })); } register(t) { var e, i; if (!C$2(null == (e = this._instance) ? void 0 : e._addCaptureHook) && (t.forEach(((t) => { var e, i; null == (e = this._n) || e.add(t), null == (i = t.steps) || i.forEach(((t) => { var e; null == (e = this.bn) || e.add((null == t ? void 0 : t.event) || ""); })); })), null != (i = this._instance) && i.autocapture)) { var r, s = /* @__PURE__ */ new Set(); t.forEach(((t) => { var e; null == (e = t.steps) || e.forEach(((t) => { null != t && t.selector && s.add(null == t ? void 0 : t.selector); })); })), null == (r = this._instance) || r.autocapture.setElementSelectors(s); } } on(t, e) { var i; null != e && 0 != t.length && (this.bn.has(t) || this.bn.has(null == e ? void 0 : e.event)) && this._n && (null == (i = this._n) ? void 0 : i.size) > 0 && this._n.forEach(((t) => { this.wn(e, t) && this.vn.emit("actionCaptured", t.name); })); } In(t) { this.onAction("actionCaptured", ((e) => t(e))); } wn(t, e) { if (null == (null == e ? void 0 : e.steps)) return !1; for (var i of e.steps) if (this.fn(t, i)) return !0; return !1; } onAction(t, e) { return this.vn.on(t, e); } gn(t, e) { if (null != e && e.url) { var i, r = null == t || null == (i = t.properties) ? void 0 : i.$current_url; if (!r || "string" != typeof r) return !1; if (!Jo(r, e.url, e.url_matching || "contains")) return !1; } return !0; } mn(t, e) { return !!this.Cn(t, e) && !!this.Sn(t, e) && !!this.xn(t, e); } Cn(t, e) { var i; if (null == e || !e.href) return !0; var r = this.kn(t); if (r.length > 0) return r.some(((t) => Jo(t.href, e.href, e.href_matching || "exact"))); var s, n = (null == t || null == (i = t.properties) ? void 0 : i.$elements_chain) || ""; return !!n && Jo((s = n.match(/(?::|")href="(.*?)"/)) ? s[1] : "", e.href, e.href_matching || "exact"); } Sn(t, e) { var i; if (null == e || !e.text) return !0; var r = this.kn(t); if (r.length > 0) return r.some(((t) => Jo(t.text, e.text, e.text_matching || "exact") || Jo(t.$el_text, e.text, e.text_matching || "exact"))); var s, n, o, a = (null == t || null == (i = t.properties) ? void 0 : i.$elements_chain) || ""; return !!a && (s = function(t) { for (var e, i = [], r = /(?::|")text="(.*?)"/g; !D$1(e = r.exec(t));) i.includes(e[1]) || i.push(e[1]); return i; }(a), n = e.text, o = e.text_matching || "exact", s.some(((t) => Jo(t, n, o)))); } xn(t, e) { var i, r; if (null == e || !e.selector) return !0; var s = null == t || null == (i = t.properties) ? void 0 : i.$element_selectors; if (null != s && s.includes(e.selector)) return !0; var n = (null == t || null == (r = t.properties) ? void 0 : r.$elements_chain) || ""; if (e.selector_regex && n) try { return new RegExp(e.selector_regex).test(n); } catch (t) { return !1; } return !1; } kn(t) { var e; return null == (null == t || null == (e = t.properties) ? void 0 : e.$elements) ? [] : null == t ? void 0 : t.properties.$elements; } yn(t, e) { return null == e || !e.properties || 0 === e.properties.length || mn(e.properties.reduce(((t, e) => { var i = R$1(e.value) ? e.value.map(String) : null != e.value ? [String(e.value)] : []; return t[e.key] = { values: i, operator: e.operator || "exact" }, t; }), {}), null == t ? void 0 : t.properties); } }; var Xo = class { constructor(t) { this._instance = t, this.Tn = /* @__PURE__ */ new Map(), this.An = /* @__PURE__ */ new Map(), this.En = /* @__PURE__ */ new Map(); } Rn(t, e) { return !!t && mn(t.propertyFilters, null == e ? void 0 : e.properties); } Nn(t, e) { var i = /* @__PURE__ */ new Map(); return t.forEach(((t) => { var r; null == (r = t.conditions) || null == (r = r[e]) || null == (r = r.values) || r.forEach(((e) => { if (null != e && e.name) { var r = i.get(e.name) || []; r.push(t.id), i.set(e.name, r); } })); })), i; } Mn(t, e, i) { var r = (i === Jr.Activation ? this.Tn : this.An).get(t), s = []; return this.Fn(((t) => { s = t.filter(((t) => null == r ? void 0 : r.includes(t.id))); })), s.filter(((r) => { var s, n = null == (s = r.conditions) || null == (s = s[i]) || null == (s = s.values) ? void 0 : s.find(((e) => e.name === t)); return this.Rn(n, e); })); } register(t) { var e; C$2(null == (e = this._instance) ? void 0 : e._addCaptureHook) || (this.On(t), this.Pn(t)); } Pn(t) { var e = t.filter(((t) => { var e, i; return (null == (e = t.conditions) ? void 0 : e.actions) && (null == (i = t.conditions) || null == (i = i.actions) || null == (i = i.values) ? void 0 : i.length) > 0; })); 0 !== e.length && (this.Ln ?? (this.Ln = new Ko(this._instance), this.Ln.init(), this.Ln.In(((t) => { this.onAction(t); }))), e.forEach(((t) => { var e, i, r, s, n; t.conditions && null != (e = t.conditions) && e.actions && null != (i = t.conditions) && null != (i = i.actions) && i.values && (null == (r = t.conditions) || null == (r = r.actions) || null == (r = r.values) ? void 0 : r.length) > 0 && (null == (s = this.Ln) || s.register(t.conditions.actions.values), null == (n = t.conditions) || null == (n = n.actions) || null == (n = n.values) || n.forEach(((e) => { if (e && e.name) { var i = this.En.get(e.name); i && i.push(t.id), this.En.set(e.name, i || [t.id]); } }))); }))); } On(t) { var e, i = t.filter(((t) => { var e, i; return (null == (e = t.conditions) ? void 0 : e.events) && (null == (i = t.conditions) || null == (i = i.events) || null == (i = i.values) ? void 0 : i.length) > 0; })), r = t.filter(((t) => { var e, i; return (null == (e = t.conditions) ? void 0 : e.cancelEvents) && (null == (i = t.conditions) || null == (i = i.cancelEvents) || null == (i = i.values) ? void 0 : i.length) > 0; })); 0 === i.length && 0 === r.length || (null == (e = this._instance) || e._addCaptureHook(((t, e) => { this.onEvent(t, e); })), this.Tn = this.Nn(t, Jr.Activation), this.An = this.Nn(t, Jr.Cancellation)); } onEvent(t, e) { var i, r = this.le(), s = this.Dn(), n = this.Bn(), o = (null == (i = this._instance) || null == (i = i.persistence) ? void 0 : i.props[s]) || []; if (n === t && e && o.length > 0) { var a, l; r.info("event matched, removing item from activated items", { event: t, eventPayload: e, existingActivatedItems: o }); var u = (null == e || null == (a = e.properties) ? void 0 : a.$survey_id) || (null == e || null == (l = e.properties) ? void 0 : l.$product_tour_id); if (u) { var h = o.indexOf(u); 0 > h || (o.splice(h, 1), this.jn(o)); } } else { if (this.An.has(t)) { var d = this.Mn(t, e, Jr.Cancellation); d.length > 0 && (r.info("cancel event matched, cancelling items", { event: t, itemsToCancel: d.map(((t) => t.id)) }), d.forEach(((t) => { var e = o.indexOf(t.id); 0 > e || o.splice(e, 1), this.$n(t.id); })), this.jn(o)); } if (this.Tn.has(t)) { r.info("event name matched", { event: t, eventPayload: e, items: this.Tn.get(t) }); var v = this.Mn(t, e, Jr.Activation); this.jn(o.concat(v.map(((t) => t.id)) || [])); } } } onAction(t) { var e, i = this.Dn(), r = (null == (e = this._instance) || null == (e = e.persistence) ? void 0 : e.props[i]) || []; this.En.has(t) && this.jn(r.concat(this.En.get(t) || [])); } jn(t) { var e = this.le(), i = [...new Set(t)].filter(((t) => !this.qn(t))); e.info("updating activated items", { activatedItems: i }), this.Zn(i); } getActivatedIds() { var t, e = this.Dn(); return (null == (t = this._instance) || null == (t = t.persistence) ? void 0 : t.props[e]) || []; } getEventToItemsMap() { return this.Tn; } Vn() { return this.Ln; } }; var Qo = class extends Xo { constructor(t) { super(t); } Dn() { return vi; } Bn() { return rs.SHOWN; } Fn(t) { var e; null == (e = this._instance) || e.getSurveys(t); } $n(t) { var e; null == (e = this._instance) || e.cancelPendingSurvey(t); } le() { return En; } Zn(t) { var e; null == (e = this._instance) || null == (e = e.persistence) || e.register({ [vi]: t }); } qn() { return !1; } getSurveys() { return this.getActivatedIds(); } getEventToSurveys() { return this.getEventToItemsMap(); } }; var Zo = "SDK is not enabled or survey functionality is not yet loaded", ta = "Disabled. Not loading surveys.", ea = null != t && t.location ? Ir(t.location.hash, "__posthog") || Ir(location.hash, "state") : null, ia = "_postHogToolbarParams", ra = Ce$1("[Toolbar]"), sa = Ce$1("[FeatureFlags]"), na = Ce$1("[FeatureFlags]", { debugEnabled: !0 }), oa = "\" failed. Feature flags didn't load in time.", aa = (t) => { for (var e = {}, i = 0; t.length > i; i++) e[t[i]] = !0; return e; }, la = (t) => { var e = {}; for (var [i, r] of Vi(t || {})) r && (e[i] = r); return e; }, ua = Ce$1("[Error tracking]"), ha = "Refusing to render web experiment since the viewer is a likely bot", da = { icontains: (e, i) => !!t && i.href.toLowerCase().indexOf(e.toLowerCase()) > -1, not_icontains: (e, i) => !!t && -1 === i.href.toLowerCase().indexOf(e.toLowerCase()), regex: (e, i) => !!t && pn(i.href, e), not_regex: (e, i) => !!t && !pn(i.href, e), exact: (t, e) => e.href === t, is_not: (t, e) => e.href !== t }; var va = class va { get Bt() { return this._instance.config; } constructor(t) { var e = this; this.getWebExperimentsAndEvaluateDisplayLogic = function(t) { void 0 === t && (t = !1), e.getWebExperiments(((t) => { va.Hn("retrieved web experiments from the server"), e.zn = /* @__PURE__ */ new Map(), t.forEach(((t) => { if (t.feature_flag_key) { var i; e.zn && (va.Hn("setting flag key ", t.feature_flag_key, " to web experiment ", t), null == (i = e.zn) || i.set(t.feature_flag_key, t)); var r = e._instance.getFeatureFlag(t.feature_flag_key); F$1(r) && t.variants[r] && e.Un(t.name, r, t.variants[r].transforms); } else if (t.variants) for (var s in t.variants) { var n = t.variants[s]; va.Yn(n) && e.Un(t.name, s, n.transforms); } })); }), t); }, this._instance = t, this._instance.onFeatureFlags(((t) => { this.onFeatureFlags(t); })); } initialize() {} onFeatureFlags(t) { if (this._is_bot()) va.Hn(ha); else if (!this.Bt.disable_web_experiments) { if (D$1(this.zn)) return this.zn = /* @__PURE__ */ new Map(), this.loadIfEnabled(), void this.previewWebExperiment(); va.Hn("applying feature flags", t), t.forEach(((t) => { var e; if (this.zn && null != (e = this.zn) && e.has(t)) { var i, r = this._instance.getFeatureFlag(t), s = null == (i = this.zn) ? void 0 : i.get(t); r && null != s && s.variants[r] && this.Un(s.name, r, s.variants[r].transforms); } })); } } previewWebExperiment() { var t = va.getWindowLocation(); if (null != t && t.search) { var e = Pr(null == t ? void 0 : t.search, "__experiment_id"), i = Pr(null == t ? void 0 : t.search, "__experiment_variant"); e && i && (va.Hn("previewing web experiments " + e + " && " + i), this.getWebExperiments(((t) => { this.Gn(parseInt(e), i, t); }), !1, !0)); } } loadIfEnabled() { this.Bt.disable_web_experiments || this.getWebExperimentsAndEvaluateDisplayLogic(); } getWebExperiments(t, e, i) { if (this.Bt.disable_web_experiments && !i) return t([]); var r = this._instance.get_property("$web_experiments"); if (r && !e) return t(r); this._instance._send_request({ url: this._instance.requestRouter.endpointFor("api", "/api/web_experiments/?token=" + this.Bt.token), method: "GET", callback: (e) => t(200 === e.statusCode && e.json && e.json.experiments || []) }); } Gn(t, e, i) { var r = i.filter(((e) => e.id === t)); r && r.length > 0 && (va.Hn("Previewing web experiment [" + r[0].name + "] with variant [" + e + "]"), this.Un(r[0].name, e, r[0].variants[e].transforms)); } static Yn(t) { return !D$1(t.conditions) && va.Wn(t) && va.Xn(t); } static Wn(t) { var e; if (D$1(t.conditions) || D$1(null == (e = t.conditions) ? void 0 : e.url)) return !0; var i, r, s, n = va.getWindowLocation(); return !!n && (null == (i = t.conditions) || !i.url || da[null !== (r = null == (s = t.conditions) ? void 0 : s.urlMatchType) && void 0 !== r ? r : "icontains"](t.conditions.url, n)); } static getWindowLocation() { return null == t ? void 0 : t.location; } static Xn(t) { var e; if (D$1(t.conditions) || D$1(null == (e = t.conditions) ? void 0 : e.utm)) return !0; var i = Lr(); if (i.utm_source) { var r, s, n, o, a, l, u, h, d = null == (r = t.conditions) || null == (r = r.utm) || !r.utm_campaign || (null == (s = t.conditions) || null == (s = s.utm) ? void 0 : s.utm_campaign) == i.utm_campaign, v = null == (n = t.conditions) || null == (n = n.utm) || !n.utm_source || (null == (o = t.conditions) || null == (o = o.utm) ? void 0 : o.utm_source) == i.utm_source, c = null == (a = t.conditions) || null == (a = a.utm) || !a.utm_medium || (null == (l = t.conditions) || null == (l = l.utm) ? void 0 : l.utm_medium) == i.utm_medium, p = null == (u = t.conditions) || null == (u = u.utm) || !u.utm_term || (null == (h = t.conditions) || null == (h = h.utm) ? void 0 : h.utm_term) == i.utm_term; return d && c && p && v; } return !1; } static Hn(t) { for (var e = arguments.length, i = new Array(e > 1 ? e - 1 : 0), r = 1; e > r; r++) i[r - 1] = arguments[r]; Ie.info("[WebExperiments] " + t, i); } Un(t, e, i) { this._is_bot() ? va.Hn(ha) : "control" !== e ? i.forEach(((i) => { if (i.selector) { var r; va.Hn("applying transform of variant " + e + " for experiment " + t + " ", i); (null == (r = document) ? void 0 : r.querySelectorAll(i.selector))?.forEach(((t) => { var e = t; i.html && (e.innerHTML = i.html), i.css && e.setAttribute("style", i.css); })); } })) : va.Hn("Control variants leave the page unmodified."); } _is_bot() { return i$1 && this._instance ? cn(i$1, this.Bt.custom_blocked_useragents) : void 0; } }; var ca = Ce$1("[Conversations]"), pa = "Conversations not available yet.", fa = { featureFlags: class { constructor(t) { this.Jn = !1, this.Kn = !1, this.Qn = !1, this.es = !1, this.ts = !1, this.rs = !1, this.ns = !1, this.ss = !1, this._instance = t, this.featureFlagEventHandlers = []; } get Bt() { return this._instance.config; } get ni() { return this._instance.persistence; } os(t) { return this._instance.get_property(t); } ls() { var t, e; return null !== (t = null == (e = this.ni) ? void 0 : e.wr(this.Bt.feature_flag_cache_ttl_ms)) && void 0 !== t && t; } us() { return !!this.ls() && (this.ss || this.Qn || (this.ss = !0, sa.warn("Feature flag cache is stale, triggering refresh..."), this.reloadFeatureFlags()), !0); } hs() { var t, e = null !== (t = this.Bt.evaluation_contexts) && void 0 !== t ? t : this.Bt.evaluation_environments; return !this.Bt.evaluation_environments || this.Bt.evaluation_contexts || this.ns || (sa.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."), this.ns = !0), null != e && e.length ? e.filter(((t) => { var e = t && "string" == typeof t && t.trim().length > 0; return e || sa.error("Invalid evaluation context found:", t, "Expected non-empty string"), e; })) : []; } cs() { return this.hs().length > 0; } initialize() { var t, e, { config: i } = this._instance, r = null !== (t = null == (e = i.bootstrap) ? void 0 : e.featureFlags) && void 0 !== t ? t : {}; if (Object.keys(r).length) { var s, n, o = null !== (s = null == (n = i.bootstrap) ? void 0 : n.featureFlagPayloads) && void 0 !== s ? s : {}, a = Object.keys(r).filter(((t) => !!r[t])).reduce(((t, e) => (t[e] = r[e] || !1, t)), {}), l = Object.keys(o).filter(((t) => a[t])).reduce(((t, e) => (o[e] && (t[e] = o[e]), t)), {}); this.receivedFeatureFlags({ featureFlags: a, featureFlagPayloads: l }); } } updateFlags(t, e, i) { var r = null != i && i.merge ? this.getFlagVariants() : {}, s = null != i && i.merge ? this.getFlagPayloads() : {}, n = f$1({}, r, t), o = f$1({}, s, e), a = {}; for (var [l, u] of Object.entries(n)) { var h = "string" == typeof u; a[l] = { key: l, enabled: !!h || Boolean(u), variant: h ? u : void 0, reason: void 0, metadata: C$2(null == o ? void 0 : o[l]) ? void 0 : { id: 0, version: void 0, description: void 0, payload: o[l] } }; } this.receivedFeatureFlags({ flags: a }); } get hasLoadedFlags() { return this.Kn; } getFlags() { return Object.keys(this.getFlagVariants()); } getFlagsWithDetails() { var t = this.os(si), e = this.os(ai), i = this.os(li); if (!i && !e) return t || {}; var r = qi({}, t || {}); for (var n of [...new Set([...Object.keys(i || {}), ...Object.keys(e || {})])]) { var o, a, l = r[n], u = null == e ? void 0 : e[n], h = C$2(u) ? null !== (o = null == l ? void 0 : l.enabled) && void 0 !== o && o : !!u, d = C$2(u) ? l.variant : "string" == typeof u ? u : void 0, v = null == i ? void 0 : i[n], c = f$1({}, l, { enabled: h, variant: h ? null != d ? d : null == l ? void 0 : l.variant : void 0 }); h !== (null == l ? void 0 : l.enabled) && (c.original_enabled = null == l ? void 0 : l.enabled), d !== (null == l ? void 0 : l.variant) && (c.original_variant = null == l ? void 0 : l.variant), v && (c.metadata = f$1({}, null == l ? void 0 : l.metadata, { payload: v, original_payload: null == l || null == (a = l.metadata) ? void 0 : a.payload })), r[n] = c; } return this.Jn || (sa.warn(" Overriding feature flag details!", { flagDetails: t, overriddenPayloads: i, finalDetails: r }), this.Jn = !0), r; } getFlagVariants() { var t = this.os(ei), e = this.os(ai); if (!e) return t || {}; for (var i = qi({}, t), r = Object.keys(e), s = 0; r.length > s; s++) i[r[s]] = e[r[s]]; return this.Jn || (sa.warn(" Overriding feature flags!", { enabledFlags: t, overriddenFlags: e, finalFlags: i }), this.Jn = !0), i; } getFlagPayloads() { var t = this.os(ni), e = this.os(li); if (!e) return t || {}; for (var i = qi({}, t || {}), r = Object.keys(e), s = 0; r.length > s; s++) i[r[s]] = e[r[s]]; return this.Jn || (sa.warn(" Overriding feature flag payloads!", { flagPayloads: t, overriddenPayloads: e, finalPayloads: i }), this.Jn = !0), i; } reloadFeatureFlags() { this.es || this.Bt.advanced_disable_feature_flags || this.ds || (this._instance.Fi.emit("featureFlagsReloading", !0), this.ds = setTimeout((() => { this.vs(); }), 5)); } fs() { clearTimeout(this.ds), this.ds = void 0; } ensureFlagsLoaded() { this.Kn || this.Qn || this.ds || this.reloadFeatureFlags(); } setAnonymousDistinctId(t) { this.$anon_distinct_id = t; } setReloadingPaused(t) { this.es = t; } vs(t) { var e; if (this.fs(), !this._instance.Fr()) if (this.Qn) this.ts = !0; else { var i = this.Bt.token, r = this.os(De$1), s = { token: i, distinct_id: this._instance.get_distinct_id(), groups: this._instance.getGroups(), $anon_distinct_id: this.$anon_distinct_id, person_properties: f$1({}, (null == (e = this.ni) ? void 0 : e.get_initial_props()) || {}, this.os(ui) || {}), group_properties: this.os(hi), timezone: Vr() }; M(r) || C$2(r) || (s.$device_id = r), (null != t && t.disableFlags || this.Bt.advanced_disable_feature_flags) && (s.disable_flags = !0), this.cs() && (s.evaluation_contexts = this.hs()); var n = this._instance.requestRouter.endpointFor("flags", "/flags/?v=2" + (this.Bt.advanced_only_evaluate_survey_feature_flags ? "&only_evaluate_survey_feature_flags=true" : "")); this.Qn = !0, this._instance._send_request({ method: "POST", url: n, data: s, compression: this.Bt.disable_compression ? void 0 : ps.Base64, timeout: this.Bt.feature_flag_request_timeout_ms, callback: (t) => { var e, i, r, n = !0; if (200 === t.statusCode && (this.ts || (this.$anon_distinct_id = void 0), n = !1), this.Qn = !1, !s.disable_flags || this.ts) { this.rs = !n; var o = []; t.error ? t.error instanceof Error ? o.push("AbortError" === t.error.name ? "timeout" : "connection_error") : o.push("unknown_error") : 200 !== t.statusCode && o.push("api_error_" + t.statusCode), null != (e = t.json) && e.errorsWhileComputingFlags && o.push("errors_while_computing_flags"); var a, l = !(null == (i = t.json) || null == (i = i.quotaLimited) || !i.includes("feature_flags")); if (l && o.push("quota_limited"), null == (r = this.ni) || r.register({ [_i]: o }), l) sa.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."); else s.disable_flags || this.receivedFeatureFlags(null !== (a = t.json) && void 0 !== a ? a : {}, n, { partialResponse: !!this.Bt.advanced_only_evaluate_survey_feature_flags }), this.ts && (this.ts = !1, this.vs()); } } }); } } getFeatureFlag(t, e) { var i; if (void 0 === e && (e = {}), !e.fresh || this.rs) if (this.Kn || this.getFlags() && this.getFlags().length > 0) { if (!this.us()) { var r = this.getFeatureFlagResult(t, e); return null !== (i = null == r ? void 0 : r.variant) && void 0 !== i ? i : null == r ? void 0 : r.enabled; } } else sa.warn("getFeatureFlag for key \"" + t + oa); } getFeatureFlagDetails(t) { return this.getFlagsWithDetails()[t]; } getFeatureFlagPayload(t) { var e = this.getFeatureFlagResult(t, { send_event: !1 }); return null == e ? void 0 : e.payload; } getFeatureFlagResult(t, e) { if (void 0 === e && (e = {}), !e.fresh || this.rs) if (this.Kn || this.getFlags() && this.getFlags().length > 0) { if (!this.us()) { var i = this.getFlagVariants(), r = t in i, s = i[t], n = this.getFlagPayloads()[t], o = String(s), a = this.os(oi) || void 0, l = this.os(gi) || void 0, u = this.os(pi) || {}; if (this.Bt.advanced_feature_flags_dedup_per_session) { var h, d = this._instance.get_session_id(), v = this.os(fi); d && d !== v && (u = {}, null == (h = this.ni) || h.register({ [pi]: u, [fi]: d })); } if ((e.send_event || !("send_event" in e)) && (!(t in u) || !u[t].includes(o))) { var c, p, f, _, g, m, b, y, w, x; R$1(u[t]) ? u[t].push(o) : u[t] = [o], null == (c = this.ni) || c.register({ [pi]: u }); var E = this.getFeatureFlagDetails(t), S = [...null !== (p = this.os(_i)) && void 0 !== p ? p : []]; C$2(s) && S.push("flag_missing"); var T = { $feature_flag: t, $feature_flag_response: s, $feature_flag_payload: n || null, $feature_flag_request_id: a, $feature_flag_evaluated_at: l, $feature_flag_bootstrapped_response: (null == (f = this.Bt.bootstrap) || null == (f = f.featureFlags) ? void 0 : f[t]) || null, $feature_flag_bootstrapped_payload: (null == (_ = this.Bt.bootstrap) || null == (_ = _.featureFlagPayloads) ? void 0 : _[t]) || null, $used_bootstrap_value: !this.rs }; C$2(null == E || null == (g = E.metadata) ? void 0 : g.version) || (T.$feature_flag_version = E.metadata.version); var k, P = null !== (m = null == E || null == (b = E.reason) ? void 0 : b.description) && void 0 !== m ? m : null == E || null == (y = E.reason) ? void 0 : y.code; P && (T.$feature_flag_reason = P), null != E && null != (w = E.metadata) && w.id && (T.$feature_flag_id = E.metadata.id), C$2(null == E ? void 0 : E.original_variant) && C$2(null == E ? void 0 : E.original_enabled) || (T.$feature_flag_original_response = C$2(E.original_variant) ? E.original_enabled : E.original_variant), null != E && null != (x = E.metadata) && x.original_payload && (T.$feature_flag_original_payload = null == E || null == (k = E.metadata) ? void 0 : k.original_payload), S.length && (T.$feature_flag_error = S.join(",")), this._instance.capture("$feature_flag_called", T); } if (r) { var O = n; if (!C$2(n)) try { O = JSON.parse(n); } catch (t) {} return { key: t, enabled: !!s, variant: "string" == typeof s ? s : void 0, payload: O }; } } } else sa.warn("getFeatureFlagResult for key \"" + t + oa); } getRemoteConfigPayload(t, e) { var i = this.Bt.token, r = { distinct_id: this._instance.get_distinct_id(), token: i }; this.cs() && (r.evaluation_contexts = this.hs()), this._instance._send_request({ method: "POST", url: this._instance.requestRouter.endpointFor("flags", "/flags/?v=2"), data: r, compression: this.Bt.disable_compression ? void 0 : ps.Base64, timeout: this.Bt.feature_flag_request_timeout_ms, callback(i) { var r, s = null == (r = i.json) ? void 0 : r.featureFlagPayloads; e((null == s ? void 0 : s[t]) || void 0); } }); } isFeatureEnabled(t, e) { if (void 0 === e && (e = {}), !e.fresh || this.rs) { if (this.Kn || this.getFlags() && this.getFlags().length > 0) { var i = this.getFeatureFlag(t, e); return C$2(i) ? void 0 : !!i; } sa.warn("isFeatureEnabled for key \"" + t + oa); } } addFeatureFlagsHandler(t) { this.featureFlagEventHandlers.push(t); } removeFeatureFlagsHandler(t) { this.featureFlagEventHandlers = this.featureFlagEventHandlers.filter(((e) => e !== t)); } receivedFeatureFlags(t, e, i) { if (this.ni) { this.Kn = !0; var r = this.getFlagVariants(), s = this.getFlagPayloads(), n = this.getFlagsWithDetails(); (function(t, e, i, r, s, n) { void 0 === i && (i = {}), void 0 === r && (r = {}), void 0 === s && (s = {}); var o = ((t) => { var e = t.flags; return e ? (t.featureFlags = Object.fromEntries(Object.keys(e).map(((t) => { var i; return [t, null !== (i = e[t].variant) && void 0 !== i ? i : e[t].enabled]; }))), t.featureFlagPayloads = Object.fromEntries(Object.keys(e).filter(((t) => e[t].enabled)).filter(((t) => { var i; return null == (i = e[t].metadata) ? void 0 : i.payload; })).map(((t) => { var i; return [t, null == (i = e[t].metadata) ? void 0 : i.payload]; })))) : sa.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"), t; })(t), a = o.flags, l = o.featureFlags, u = o.featureFlagPayloads; if (l) { var h = t.requestId, d = t.evaluatedAt; if (R$1(l)) { sa.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version."); var v = {}; if (l) for (var c = 0; l.length > c; c++) v[l[c]] = !0; e && e.register({ [ii]: l, [ei]: v }); } else { var p = l, _ = u, g = a; if (null != n && n.partialResponse) p = f$1({}, i, p), _ = f$1({}, r, _), g = f$1({}, s, g); else if (t.errorsWhileComputingFlags) if (a) { var m = new Set(Object.keys(a).filter(((t) => { var e; return !(null != (e = a[t]) && e.failed); }))); p = f$1({}, i, Object.fromEntries(Object.entries(p).filter(((t) => { var [e] = t; return m.has(e); })))), _ = f$1({}, r, Object.fromEntries(Object.entries(_ || {}).filter(((t) => { var [e] = t; return m.has(e); })))), g = f$1({}, s, Object.fromEntries(Object.entries(g || {}).filter(((t) => { var [e] = t; return m.has(e); })))); } else p = f$1({}, i, p), _ = f$1({}, r, _), g = f$1({}, s, g); e && e.register(f$1({ [ii]: Object.keys(la(p)), [ei]: p || {}, [ni]: _ || {}, [si]: g || {} }, h ? { [oi]: h } : {}, d ? { [gi]: d } : {})); } } })(t, this.ni, r, s, n, i), e || (this.ss = !1), this.ps(e); } } override(t, e) { void 0 === e && (e = !1), sa.warn("override is deprecated. Please use overrideFeatureFlags instead."), this.overrideFeatureFlags({ flags: t, suppressWarning: e }); } overrideFeatureFlags(t) { if (!this._instance.__loaded || !this.ni) return sa.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags"); if (!1 === t) return this.ni.unregister(ai), this.ni.unregister(li), this.ps(), na.info("All overrides cleared"); if (R$1(t)) { var e = aa(t); return this.ni.register({ [ai]: e }), this.ps(), na.info("Flag overrides set", { flags: t }); } if (t && "object" == typeof t && ("flags" in t || "payloads" in t)) { var i, r = t; if (this.Jn = Boolean(null !== (i = r.suppressWarning) && void 0 !== i && i), "flags" in r) { if (!1 === r.flags) this.ni.unregister(ai), na.info("Flag overrides cleared"); else if (r.flags) { if (R$1(r.flags)) { var s = aa(r.flags); this.ni.register({ [ai]: s }); } else this.ni.register({ [ai]: r.flags }); na.info("Flag overrides set", { flags: r.flags }); } } "payloads" in r && (!1 === r.payloads ? (this.ni.unregister(li), na.info("Payload overrides cleared")) : r.payloads && (this.ni.register({ [li]: r.payloads }), na.info("Payload overrides set", { payloads: r.payloads }))), this.ps(); return; } if (t && "object" == typeof t) return this.ni.register({ [ai]: t }), this.ps(), na.info("Flag overrides set", { flags: t }); sa.warn("Invalid overrideOptions provided to overrideFeatureFlags", { overrideOptions: t }); } onFeatureFlags(t) { if (this.addFeatureFlagsHandler(t), this.Kn) { var { flags: e, flagVariants: i } = this.gs(); t(e, i); } return () => this.removeFeatureFlagsHandler(t); } updateEarlyAccessFeatureEnrollment(t, e, i) { var r, s = (this.os(ri) || []).find(((e) => e.flagKey === t)), n = { ["$feature_enrollment/" + t]: e }, o = { $feature_flag: t, $feature_enrollment: e, $set: n }; s && (o.$early_access_feature_name = s.name), i && (o.$feature_enrollment_stage = i), this._instance.capture("$feature_enrollment_update", o), this.setPersonPropertiesForFlags(n, !1); var a = f$1({}, this.getFlagVariants(), { [t]: e }); null == (r = this.ni) || r.register({ [ii]: Object.keys(la(a)), [ei]: a }), this.ps(); } getEarlyAccessFeatures(t, e, i) { void 0 === e && (e = !1); var r = this.os(ri), s = i ? "&" + i.map(((t) => "stage=" + t)).join("&") : ""; if (r && !e) return t(r); this._instance._send_request({ url: this._instance.requestRouter.endpointFor("api", "/api/early_access_features/?token=" + this.Bt.token + s), method: "GET", callback: (e) => { var i, r; if (e.json) { var s = e.json.earlyAccessFeatures; return null == (i = this.ni) || i.unregister(ri), null == (r = this.ni) || r.register({ [ri]: s }), t(s); } } }); } gs() { var t = this.getFlags(), e = this.getFlagVariants(); return { flags: t.filter(((t) => e[t])), flagVariants: Object.keys(e).filter(((t) => e[t])).reduce(((t, i) => (t[i] = e[i], t)), {}) }; } ps(t) { var { flags: e, flagVariants: i } = this.gs(); this.featureFlagEventHandlers.forEach(((r) => r(e, i, { errorsLoading: t }))); } setPersonPropertiesForFlags(t, e) { void 0 === e && (e = !0); var i = this.os(ui) || {}, r = (null == t ? void 0 : t.$set) || (null != t && t.$set_once ? {} : t), s = null == t ? void 0 : t.$set_once, n = {}; if (s) for (var o in s) ({}).hasOwnProperty.call(s, o) && (o in i || (n[o] = s[o])); this._instance.register({ [ui]: f$1({}, i, n, r) }), e && this._instance.reloadFeatureFlags(); } resetPersonPropertiesForFlags() { this._instance.unregister(ui); } setGroupPropertiesForFlags(t, e) { void 0 === e && (e = !0); var i = this.os(hi) || {}; 0 !== Object.keys(i).length && Object.keys(i).forEach(((e) => { i[e] = f$1({}, i[e], t[e]), delete t[e]; })), this._instance.register({ [hi]: f$1({}, i, t) }), e && this._instance.reloadFeatureFlags(); } resetGroupPropertiesForFlags(t) { if (t) { var e = this.os(hi) || {}; this._instance.register({ [hi]: f$1({}, e, { [t]: {} }) }); } else this._instance.unregister(hi); } reset() { this.Kn = !1, this.Qn = !1, this.es = !1, this.ts = !1, this.rs = !1, this.$anon_distinct_id = void 0, this.fs(), this.Jn = !1; } } }, _a = { sessionRecording: class { get Bt() { return this._instance.config; } get ni() { return this._instance.persistence; } get started() { var t; return !(null == (t = this.ys) || !t.isStarted); } get status() { var t, e; return this.bs === No || this.bs === jo ? this.bs : null !== (t = null == (e = this.ys) ? void 0 : e.status) && void 0 !== t ? t : this.bs; } constructor(t) { if (this._forceAllowLocalhostNetworkCapture = !1, this.bs = Lo$1, this._s = void 0, this._instance = t, !this._instance.sessionManager) throw Bo$1.error("started without valid sessionManager"), /* @__PURE__ */ new Error(zo$1 + " started without valid sessionManager. This is a bug."); if (this.Bt.cookieless_mode === Ci) throw new Error(zo$1 + " cannot be used with cookieless_mode=\"always\""); } initialize() { this.startIfEnabledOrStop(); } get ws() { var e, i = !(null == (e = this._instance.get_property(Ye$1)) || !e.enabled), r = !this.Bt.disable_session_recording, s = this.Bt.disable_session_recording || this._instance.consent.isOptedOut(); return t && i && r && !s; } startIfEnabledOrStop(t) { var e; if (!this.ws || null == (e = this.ys) || !e.isStarted) { var i = !C$2(Object.assign) && !C$2(Array.from); this.ws && i ? (this.Is(t), Bo$1.info("starting")) : (this.bs = Lo$1, this.stopRecording()); } } Is(t) { var e, i, r; this.ws && (this.bs !== No && this.bs !== jo && (this.bs = Uo), null != h$2 && null != (e = h$2.__PosthogExtensions__) && null != (e = e.rrweb) && e.record && null != (i = h$2.__PosthogExtensions__) && i.initSessionRecording ? this.Cs(t) : null == (r = h$2.__PosthogExtensions__) || null == r.loadExternalDependency || r.loadExternalDependency(this._instance, this.Ss, ((e) => { if (e) return Bo$1.error("could not load recorder", e); this.Cs(t); }))); } stopRecording() { var t, e; null == (t = this._s) || t.call(this), this._s = void 0, null == (e = this.ys) || e.stop(); } xs() { var t, e; null == (t = this._s) || t.call(this), this._s = void 0, null == (e = this.ys) || e.discard(); } ks() { var t; null == (t = this.ni) || t.unregister(ti); } Ts(t, e) { if (D$1(t)) return null; var i, r = L$1(t) ? t : parseFloat(t); return "number" != typeof (i = r) || !Number.isFinite(i) || 0 > i || i > 1 ? (Bo$1.warn(e + " must be between 0 and 1. Ignoring invalid value:", t), null) : r; } As(t) { if (this.ni) { var e, i, r = this.ni, s = () => { var e, i = !1 === t.sessionRecording ? void 0 : t.sessionRecording, s = this.Ts(null == (e = this.Bt.session_recording) ? void 0 : e.sampleRate, "session_recording.sampleRate"), n = this.Ts(null == i ? void 0 : i.sampleRate, "remote config sampleRate"), o = null != s ? s : n; D$1(o) && this.ks(); var a = null == i ? void 0 : i.minimumDurationMilliseconds; r.register({ [Ye$1]: f$1({ cache_timestamp: Date.now(), enabled: !!i }, i, { networkPayloadCapture: f$1({ capturePerformance: t.capturePerformance }, null == i ? void 0 : i.networkPayloadCapture), canvasRecording: { enabled: null == i ? void 0 : i.recordCanvas, fps: null == i ? void 0 : i.canvasFps, quality: null == i ? void 0 : i.canvasQuality }, sampleRate: o, minimumDurationMilliseconds: C$2(a) ? null : a, endpoint: null == i ? void 0 : i.endpoint, triggerMatchType: null == i ? void 0 : i.triggerMatchType, masking: null == i ? void 0 : i.masking, urlTriggers: null == i ? void 0 : i.urlTriggers, version: null == i ? void 0 : i.version, triggerGroups: null == i ? void 0 : i.triggerGroups }) }); }; s(), null == (e = this._s) || e.call(this), this._s = null == (i = this._instance.sessionManager) ? void 0 : i.onSessionId(s); } } onRemoteConfig(t) { "sessionRecording" in t ? !1 === t.sessionRecording ? (this.As(t), this.xs()) : (this.As(t), this.startIfEnabledOrStop()) : (this.bs === No && (this.bs = jo, Bo$1.warn("config refresh failed, recording will not start until page reload")), this.startIfEnabledOrStop()); } log(t, e) { var i; void 0 === e && (e = "log"), null != (i = this.ys) && i.log ? this.ys.log(t, e) : Bo$1.warn("log called before recorder was ready"); } get Ss() { var t, e, i = null == (t = this._instance) || null == (t = t.persistence) ? void 0 : t.get_property(Ye$1); return (null == i || null == (e = i.scriptConfig) ? void 0 : e.script) || "lazy-recorder"; } Es() { var t, e = this._instance.get_property(Ye$1); if (!e) return !1; var i = null !== (t = ("object" == typeof e ? e : JSON.parse(e)).cache_timestamp) && void 0 !== t ? t : Date.now(); return 36e5 >= Date.now() - i; } Cs(t) { var e, i; if (null == (e = h$2.__PosthogExtensions__) || !e.initSessionRecording) return Bo$1.warn("Called on script loaded before session recording is available. This can be caused by adblockers."), void this._instance.register_for_session({ [Pi]: !0 }); if (this.ys || (this.ys = null == (i = h$2.__PosthogExtensions__) ? void 0 : i.initSessionRecording(this._instance), this.ys._forceAllowLocalhostNetworkCapture = this._forceAllowLocalhostNetworkCapture), !this.Es()) { if (this.bs === jo || this.bs === No) return; this.bs = No, Bo$1.info("persisted remote config is stale, requesting fresh config before starting"), new vs(this._instance).load(); return; } this.bs = Uo, this.ys.start(t); } onRRwebEmit(t) { var e; null == (e = this.ys) || null == e.onRRwebEmit || e.onRRwebEmit(t); } overrideLinkedFlag() { var t, e; this.ys || null == (e = this.ni) || e.register({ [Ke]: !0 }), null == (t = this.ys) || t.overrideLinkedFlag(); } overrideSampling() { var t, e; this.ys || null == (e = this.ni) || e.register({ [Je]: !0 }), null == (t = this.ys) || t.overrideSampling(); } overrideTrigger(t) { var e, i; this.ys || null == (i = this.ni) || i.register({ ["url" === t ? Xe : Qe]: !0 }), null == (e = this.ys) || e.overrideTrigger(t); } get sdkDebugProperties() { var t; return (null == (t = this.ys) ? void 0 : t.sdkDebugProperties) || { $recording_status: this.status }; } tryAddCustomEvent(t, e) { var i; return !(null == (i = this.ys) || !i.tryAddCustomEvent(t, e)); } } }, ga = { autocapture: class { constructor(t) { this.Rs = !1, this.Ns = null, this.Ms = !1, this.instance = t, this.rageclicks = new To$1(t.config.rageclick), this.Fs = null; } initialize() { this.startIfEnabled(); } get Bt() { var t, e, i = O$1(this.instance.config.autocapture) ? this.instance.config.autocapture : {}; return i.url_allowlist = null == (t = i.url_allowlist) ? void 0 : t.map(((t) => new RegExp(t))), i.url_ignorelist = null == (e = i.url_ignorelist) ? void 0 : e.map(((t) => new RegExp(t))), i; } Os() { if (this.isBrowserSupported()) { if (t && r$1) { var e = (e) => { e = e || (null == t ? void 0 : t.event); try { this.Ps(e); } catch (t) { Ro$1.error("Failed to capture event", t); } }; if (Xi(r$1, "submit", e, { capture: !0 }), Xi(r$1, "change", e, { capture: !0 }), Xi(r$1, "click", e, { capture: !0 }), this.Bt.capture_copied_text) { var i = (e) => { e = e || (null == t ? void 0 : t.event); try { this.Ps(e, ko$1); } catch (t) { Ro$1.error("Failed to capture copy/cut event", t); } }; Xi(r$1, "copy", i, { capture: !0 }), Xi(r$1, "cut", i, { capture: !0 }); } } } else Ro$1.info("Disabling Automatic Event Collection because this browser is not supported"); } startIfEnabled() { this.isEnabled && !this.Rs && (this.Os(), this.Rs = !0); } onRemoteConfig(t) { t.elementsChainAsString && (this.Ms = t.elementsChainAsString), this.instance.persistence && this.instance.persistence.register({ [Ne$2]: !!t.autocapture_opt_out }), this.Ns = !!t.autocapture_opt_out, this.startIfEnabled(); } setElementSelectors(t) { this.Fs = t; } getElementSelectors(t) { var e, i = []; return null == (e = this.Fs) || e.forEach(((e) => { (null == r$1 ? void 0 : r$1.querySelectorAll(e))?.forEach(((r) => { t === r && i.push(e); })); })), i; } get isEnabled() { var t, e, i = null == (t = this.instance.persistence) ? void 0 : t.props[Ne$2]; if (M(this.Ns) && !N(i) && !this.instance.Fr()) return !1; var r = null !== (e = this.Ns) && void 0 !== e ? e : !!i; return !!this.instance.config.autocapture && !r; } Ps(e, i) { if (void 0 === i && (i = "$autocapture"), this.isEnabled) { var r, s = so(e); Xn(s) && (s = s.parentNode || null), "$autocapture" === i && "click" === e.type && e instanceof MouseEvent && this.instance.config.rageclick && null != (r = this.rageclicks) && r.isRageClick(e.clientX, e.clientY, e.timeStamp || (/* @__PURE__ */ new Date()).getTime()) && function(e, i) { if (!t || ho$1(e)) return !1; var r, s, n; if (N(i) ? (r = !!i && uo$1, s = void 0) : (r = null !== (n = null == i ? void 0 : i.css_selector_ignorelist) && void 0 !== n ? n : uo$1, s = null == i ? void 0 : i.content_ignorelist), !1 === r) return !1; var { targetElementList: o } = vo$1(e, !1); return !function(t, e) { if (!1 === t || C$2(t)) return !1; var i; if (!0 === t) i = lo; else { if (!R$1(t)) return !1; if (t.length > 10) return Ie.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."), !1; i = t.map(((t) => t.toLowerCase())); } return e.some(((t) => { var { safeText: e, ariaLabel: r } = t; return i.some(((t) => e.includes(t) || r.includes(t))); })); }(s, o.map(((t) => { var e; return { safeText: ro(t).toLowerCase(), ariaLabel: (null == (e = t.getAttribute("aria-label")) ? void 0 : e.toLowerCase().trim()) || "" }; }))) && !oo(o, r); }(s, this.instance.config.rageclick) && this.Ps(e, "$rageclick"); var n = i === ko$1; if (s && function(e, i, r, s, n) { var o, a, l, u; if (void 0 === r && (r = void 0), !t || ho$1(e)) return !1; if (null != (o = r) && o.url_allowlist && !to(r.url_allowlist)) return !1; if (null != (a = r) && a.url_ignorelist && to(r.url_ignorelist)) return !1; if (null != (l = r) && l.dom_event_allowlist) { var h = r.dom_event_allowlist; if (h && !h.some(((t) => i.type === t))) return !1; } var { parentIsUsefulElement: d, targetElementList: v } = vo$1(e, s); if (!function(t, e) { var i = null == e ? void 0 : e.element_allowlist; if (C$2(i)) return !0; var r, s = function(t) { if (i.some(((e) => t.tagName.toLowerCase() === e))) return { v: !0 }; }; for (var n of t) if (r = s(n)) return r.v; return !1; }(v, r)) return !1; if (!oo(v, null == (u = r) ? void 0 : u.css_selector_allowlist)) return !1; var c = t.getComputedStyle(e); if (c && "pointer" === c.getPropertyValue("cursor") && "click" === i.type) return !0; var p = e.tagName.toLowerCase(); switch (p) { case "html": return !1; case "form": return (n || ["submit"]).indexOf(i.type) >= 0; case "input": case "select": case "textarea": return (n || ["change", "click"]).indexOf(i.type) >= 0; default: return d ? (n || ["click"]).indexOf(i.type) >= 0 : (n || ["click"]).indexOf(i.type) >= 0 && (no.indexOf(p) > -1 || "true" === e.getAttribute("contenteditable")); } }(s, e, this.Bt, n, n ? ["copy", "cut"] : void 0)) { var { props: o, explicitNoCapture: a } = Io(s, { e, maskAllElementAttributes: this.instance.config.mask_all_element_attributes, maskAllText: this.instance.config.mask_all_text, elementAttributeIgnoreList: this.Bt.element_attribute_ignorelist, elementsChainAsString: this.Ms }); if (a) return !1; var l = this.getElementSelectors(s); if (l && l.length > 0 && (o.$element_selectors = l), i === ko$1) { var u, h = io(null == t || null == (u = t.getSelection()) ? void 0 : u.toString()), d = e.type || "clipboard"; if (!h) return !1; o.$selected_content = h, o.$copy_type = d; } return this.instance.capture(i, o), !0; } } } isBrowserSupported() { return P$1(null == r$1 ? void 0 : r$1.querySelectorAll); } }, historyAutocapture: class { constructor(e) { var i; this._instance = e, this.Ls = (null == t || null == (i = t.location) ? void 0 : i.pathname) || ""; } initialize() { this.startIfEnabled(); } get isEnabled() { return "history_change" === this._instance.config.capture_pageview; } startIfEnabled() { this.isEnabled && (Ie.info("History API monitoring enabled, starting..."), this.monitorHistoryChanges()); } stop() { this.Ds && this.Ds(), this.Ds = void 0, Ie.info("History API monitoring stopped"); } monitorHistoryChanges() { var e, i; if (t && t.history) { var r = this; null != (e = t.history.pushState) && e.__posthog_wrapped__ || Fo(t.history, "pushState", ((t) => function(e, i, s) { t.call(this, e, i, s), r.Bs("pushState"); })), null != (i = t.history.replaceState) && i.__posthog_wrapped__ || Fo(t.history, "replaceState", ((t) => function(e, i, s) { t.call(this, e, i, s), r.Bs("replaceState"); })), this.js(); } } Bs(e) { try { var i, r = null == t || null == (i = t.location) ? void 0 : i.pathname; if (!r) return; r !== this.Ls && this.isEnabled && this._instance.capture(Ui, { navigation_type: e }), this.Ls = r; } catch (t) { Ie.error("Error capturing " + e + " pageview", t); } } js() { if (!this.Ds) { var e = () => { this.Bs("popstate"); }; Xi(t, "popstate", e), this.Ds = () => { t && t.removeEventListener("popstate", e); }; } } }, heatmaps: class { get Bt() { return this.instance.config; } constructor(t) { var e; this.$s = !1, this.Rs = !1, this.qs = null, this.instance = t, this.$s = !(null == (e = this.instance.persistence) || !e.props[je$1]), this.rageclicks = new To$1(t.config.rageclick); } initialize() { this.startIfEnabled(); } get flushIntervalMilliseconds() { var t = 5e3; return O$1(this.Bt.capture_heatmaps) && this.Bt.capture_heatmaps.flush_interval_milliseconds && (t = this.Bt.capture_heatmaps.flush_interval_milliseconds), t; } get isEnabled() { return D$1(this.Bt.capture_heatmaps) ? D$1(this.Bt.enable_heatmaps) ? this.$s : this.Bt.enable_heatmaps : !1 !== this.Bt.capture_heatmaps; } startIfEnabled() { if (this.isEnabled) { if (this.Rs) return; Ho.info("starting..."), this.Zs(), this.Ft(); } else { var t; clearInterval(null !== (t = this.qs) && void 0 !== t ? t : void 0), this.Vs(), this.getAndClearBuffer(); } } onRemoteConfig(t) { if ("heatmaps" in t) { var e = !!t.heatmaps; this.instance.persistence && this.instance.persistence.register({ [je$1]: e }), this.$s = e, this.startIfEnabled(); } } getAndClearBuffer() { var t = this.T; return this.T = void 0, t; } Hs(t) { this.Tt(t.originalEvent, "deadclick"); } Ft() { this.qs && clearInterval(this.qs), this.qs = "visible" === (null == r$1 ? void 0 : r$1.visibilityState) ? setInterval(this.Yr.bind(this), this.flushIntervalMilliseconds) : null; } Zs() { t && r$1 && (this.zs = this.Yr.bind(this), Xi(t, Li, this.zs), this.Us = (e) => this.Tt(e || (null == t ? void 0 : t.event)), Xi(r$1, "click", this.Us, { capture: !0 }), this.Ys = (e) => this.Gs(e || (null == t ? void 0 : t.event)), Xi(r$1, "mousemove", this.Ys, { capture: !0 }), this.Ws = new yr(this.instance, mr, this.Hs.bind(this)), this.Ws.startIfEnabledOrStop(), this.Xs = this.Ft.bind(this), Xi(r$1, Di, this.Xs), this.Rs = !0); } Vs() { var e; t && r$1 && (this.zs && t.removeEventListener(Li, this.zs), this.Us && r$1.removeEventListener("click", this.Us, { capture: !0 }), this.Ys && r$1.removeEventListener("mousemove", this.Ys, { capture: !0 }), this.Xs && r$1.removeEventListener(Di, this.Xs), clearTimeout(this.Js), null == (e = this.Ws) || e.stop(), this.Rs = !1); } Ks(e, i) { var r = this.instance.scrollManager.scrollY(), s = this.instance.scrollManager.scrollX(), n = this.instance.scrollManager.scrollElement(), o = function(e, i, r) { for (var s = e; s && Jn(s) && !Kn(s, "body");) { if (s === r) return !1; if (w$1(i, null == t ? void 0 : t.getComputedStyle(s).position)) return !0; s = ao(s); } return !1; }(so(e), ["fixed", "sticky"], n); return { x: e.clientX + (o ? 0 : s), y: e.clientY + (o ? 0 : r), target_fixed: o, type: i }; } Tt(t, e) { var i; if (void 0 === e && (e = "click"), !Yn(t.target) && qo(t)) { var r = this.Ks(t, e); null != (i = this.rageclicks) && i.isRageClick(t.clientX, t.clientY, (/* @__PURE__ */ new Date()).getTime()) && this.Qs(f$1({}, r, { type: "rageclick" })), this.Qs(r); } } Gs(t) { !Yn(t.target) && qo(t) && (clearTimeout(this.Js), this.Js = setTimeout((() => { this.Qs(this.Ks(t, "mousemove")); }), 500)); } Qs(e) { if (t) { var i = t.location.href, r = this.Bt.custom_personal_data_properties, n = Or(i, this.Bt.mask_personal_data_properties ? [...Fr, ...r || []] : [], Mr); this.T = this.T || {}, this.T[n] || (this.T[n] = []), this.T[n].push(e); } } Yr() { this.T && !I(this.T) && this.instance.capture("$$heatmap", { $heatmap_data: this.getAndClearBuffer() }); } }, deadClicksAutocapture: yr, webVitalsAutocapture: class { constructor(t) { var e; this.$s = !1, this.Rs = !1, this.T = { url: void 0, metrics: [], firstMetricTimestamp: void 0 }, this.eo = () => { clearTimeout(this.ro), 0 !== this.T.metrics.length && (this._instance.capture("$web_vitals", this.T.metrics.reduce(((t, e) => f$1({}, t, { ["$web_vitals_" + e.name + "_event"]: f$1({}, e), ["$web_vitals_" + e.name + "_value"]: e.value })), {})), this.T = { url: void 0, metrics: [], firstMetricTimestamp: void 0 }); }, this.ht = (t) => { var e, i = null == (e = this._instance.sessionManager) ? void 0 : e.checkAndGetSessionAndWindowId(!0); if (C$2(i)) Mo$1.error("Could not read session ID. Dropping metrics!"); else { this.T = this.T || { url: void 0, metrics: [], firstMetricTimestamp: void 0 }; var r = this.io(); C$2(r) || (D$1(null == t ? void 0 : t.name) || D$1(null == t ? void 0 : t.value) ? Mo$1.error("Invalid metric received", t) : !this.no || this.no > t.value ? (this.T.url !== r && (this.eo(), this.ro = setTimeout(this.eo, this.flushToCaptureTimeoutMs)), C$2(this.T.url) && (this.T.url = r), this.T.firstMetricTimestamp = C$2(this.T.firstMetricTimestamp) ? Date.now() : this.T.firstMetricTimestamp, t.attribution && t.attribution.interactionTargetElement && (t.attribution.interactionTargetElement = void 0), this.T.metrics.push(f$1({}, t, { $current_url: r, $session_id: i.sessionId, $window_id: i.windowId, timestamp: Date.now() })), this.T.metrics.length === this.allowedMetrics.length && this.eo()) : Mo$1.error("Ignoring metric with value >= " + this.no, t)); } }, this.so = () => { if (!this.Rs) { var t, e, i, r, s = h$2.__PosthogExtensions__; C$2(s) || C$2(s.postHogWebVitalsCallbacks) || ({onLCP: t, onCLS: e, onFCP: i, onINP: r} = s.postHogWebVitalsCallbacks), t && e && i && r ? (this.allowedMetrics.indexOf("LCP") > -1 && t(this.ht.bind(this)), this.allowedMetrics.indexOf("CLS") > -1 && e(this.ht.bind(this)), this.allowedMetrics.indexOf("FCP") > -1 && i(this.ht.bind(this)), this.allowedMetrics.indexOf("INP") > -1 && r(this.ht.bind(this)), this.Rs = !0) : Mo$1.error("web vitals callbacks not loaded - not starting"); } }, this._instance = t, this.$s = !(null == (e = this._instance.persistence) || !e.props[qe]), this.startIfEnabled(); } get oo() { return this._instance.config.capture_performance; } get allowedMetrics() { var t, e, i = O$1(this.oo) ? null == (t = this.oo) ? void 0 : t.web_vitals_allowed_metrics : void 0; return D$1(i) ? (null == (e = this._instance.persistence) ? void 0 : e.props[Ge]) || [ "CLS", "FCP", "INP", "LCP" ] : i; } get flushToCaptureTimeoutMs() { return (O$1(this.oo) ? this.oo.web_vitals_delayed_flush_ms : void 0) || 5e3; } get useAttribution() { var t = O$1(this.oo) ? this.oo.web_vitals_attribution : void 0; return null != t && t; } get no() { var t = O$1(this.oo) && L$1(this.oo.__web_vitals_max_value) ? this.oo.__web_vitals_max_value : Do$1; return t > 0 && 6e4 >= t ? Do$1 : t; } get isEnabled() { var t = null == s$1 ? void 0 : s$1.protocol; if ("http:" !== t && "https:" !== t) return Mo$1.info("Web Vitals are disabled on non-http/https protocols"), !1; var e = O$1(this.oo) ? this.oo.web_vitals : N(this.oo) ? this.oo : void 0; return N(e) ? e : this.$s; } startIfEnabled() { this.isEnabled && !this.Rs && (Mo$1.info("enabled, starting..."), this.ur(this.so)); } onRemoteConfig(t) { if ("capturePerformance" in t) { var e = O$1(t.capturePerformance) && !!t.capturePerformance.web_vitals, i = O$1(t.capturePerformance) ? t.capturePerformance.web_vitals_allowed_metrics : void 0; this._instance.persistence && (this._instance.persistence.register({ [qe]: e }), this._instance.persistence.register({ [Ge]: i })), this.$s = e, this.startIfEnabled(); } } ur(t) { var e, i; null != (e = h$2.__PosthogExtensions__) && e.postHogWebVitalsCallbacks ? t() : null == (i = h$2.__PosthogExtensions__) || null == i.loadExternalDependency || i.loadExternalDependency(this._instance, this.useAttribution ? "web-vitals-with-attribution" : "web-vitals", ((e) => { e ? Mo$1.error("failed to load script", e) : t(); })); } io() { var e = t ? t.location.href : void 0; if (e) { var i = this._instance.config.custom_personal_data_properties; return Or(e, this._instance.config.mask_personal_data_properties ? [...Fr, ...i || []] : [], Mr); } Mo$1.error("Could not determine current URL"); } } }, ma = { exceptionObserver: class { constructor(e) { var i, r, s; this.so = () => { var e; if (t && this.isEnabled && null != (e = h$2.__PosthogExtensions__) && e.errorWrappingFunctions) { var i = h$2.__PosthogExtensions__.errorWrappingFunctions.wrapOnError, r = h$2.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection, s = h$2.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError; try { !this.ao && this.Bt.capture_unhandled_errors && (this.ao = i(this.captureException.bind(this))), !this.lo && this.Bt.capture_unhandled_rejections && (this.lo = r(this.captureException.bind(this))), !this.uo && this.Bt.capture_console_errors && (this.uo = s(this.captureException.bind(this))); } catch (t) { Co$1.error("failed to start", t), this.ho(); } } }, this._instance = e, this.co = !(null == (i = this._instance.persistence) || !i.props[ze$1]), this.do = new J({ refillRate: null !== (r = this._instance.config.error_tracking.__exceptionRateLimiterRefillRate) && void 0 !== r ? r : 1, bucketSize: null !== (s = this._instance.config.error_tracking.__exceptionRateLimiterBucketSize) && void 0 !== s ? s : 10, refillInterval: 1e4, Gt: Co$1 }), this.Bt = this.vo(), this.startIfEnabledOrStop(); } vo() { var t = this._instance.config.capture_exceptions, e = { capture_unhandled_errors: !1, capture_unhandled_rejections: !1, capture_console_errors: !1 }; return O$1(t) ? e = f$1({}, e, t) : (C$2(t) ? this.co : t) && (e = f$1({}, e, { capture_unhandled_errors: !0, capture_unhandled_rejections: !0 })), e; } get isEnabled() { return this.Bt.capture_console_errors || this.Bt.capture_unhandled_errors || this.Bt.capture_unhandled_rejections; } startIfEnabledOrStop() { this.isEnabled ? (Co$1.info("enabled"), this.ho(), this.ur(this.so)) : this.ho(); } ur(t) { var e, i; null != (e = h$2.__PosthogExtensions__) && e.errorWrappingFunctions && t(), null == (i = h$2.__PosthogExtensions__) || null == i.loadExternalDependency || i.loadExternalDependency(this._instance, "exception-autocapture", ((e) => { if (e) return Co$1.error("failed to load script", e); t(); })); } ho() { var t, e, i; null == (t = this.ao) || t.call(this), this.ao = void 0, null == (e = this.lo) || e.call(this), this.lo = void 0, null == (i = this.uo) || i.call(this), this.uo = void 0; } onRemoteConfig(t) { "autocaptureExceptions" in t && (this.co = !!t.autocaptureExceptions || !1, this._instance.persistence && this._instance.persistence.register({ [ze$1]: this.co }), this.Bt = this.vo(), this.startIfEnabledOrStop()); } onConfigChange() { this.Bt = this.vo(); } captureException(t) { var e, i, r, s = null !== (e = null == t || null == (i = t.$exception_list) || null == (i = i[0]) ? void 0 : i.type) && void 0 !== e ? e : "Exception"; this.do.consumeRateLimit(s) ? Co$1.info("Skipping exception capture because of client rate limiting.", { exception: s }) : null == (r = this._instance.exceptions) || r.sendExceptionEvent(t); } }, exceptions: class { constructor(t) { var e, i; this.fo = [], this.po = new te$1([ new ve$1(), new xe(), new pe$1(), new ce$1(), new ye$1(), new be$2(), new _e$1(), new we$1() ], function(t) { for (var e = arguments.length, i = new Array(e > 1 ? e - 1 : 0), r = 1; e > r; r++) i[r - 1] = arguments[r]; return function(e, r) { void 0 === r && (r = 0); for (var s = [], n = e.split("\n"), o = r; n.length > o; o++) { var a = n[o]; if (1024 >= a.length) { var l = de$1.test(a) ? a.replace(de$1, "$1") : a; if (!l.match(/\S*Error: /)) { for (var u of i) { var h = u(l, t); if (h) { s.push(h); break; } } if (s.length >= 50) break; } } } return function(t) { if (!t.length) return []; var e = Array.from(t); return e.reverse(), e.slice(0, 50).map(((t) => { return f$1({}, t, { filename: t.filename || (i = e, i[i.length - 1] || {}).filename, function: t.function || ee$1 }); var i; })); }(s); }; }("web:javascript", ae$1, he$1)), this._instance = t, this.fo = null !== (e = null == (i = this._instance.persistence) ? void 0 : i.get_property(Be$1)) && void 0 !== e ? e : [], this.mo = ke(this.yo()), this.bo = new Re(this.mo); } onConfigChange() { this.mo = ke(this.yo()), this.bo.setConfig(this.mo); } onRemoteConfig(t) { var e, i, r; if ("errorTracking" in t) { var s = null !== (e = null == (i = t.errorTracking) ? void 0 : i.suppressionRules) && void 0 !== e ? e : [], n = null == (r = t.errorTracking) ? void 0 : r.captureExtensionExceptions; this.fo = s, this._instance.persistence && this._instance.persistence.register({ [Be$1]: this.fo, [He$2]: n }); } } get _o() { var t, e = !!this._instance.get_property(He$2), i = this._instance.config.error_tracking.captureExtensionExceptions; return null !== (t = null != i ? i : e) && void 0 !== t && t; } buildProperties(t, e) { return this.po.buildFromUnknown(t, { syntheticException: null == e ? void 0 : e.syntheticException, mechanism: { handled: null == e ? void 0 : e.handled } }); } addExceptionStep(t, e) { if (this.mo.enabled) try { if (!F$1(t) || 0 === t.trim().length) return void ua.warn("Ignoring exception step because message must be a non-empty string"); var { sanitizedProperties: r, droppedKeys: s } = function(t) { if (!t) return { sanitizedProperties: {}, droppedKeys: [] }; var e = []; return { sanitizedProperties: Object.keys(t).reduce(((i, r) => $e.has(r) ? (e.push(r), i) : (i[r] = t[r], i)), {}), droppedKeys: e }; }(this.wo(e)); s.length > 0 && ua.warn("Ignoring reserved exception step fields", { droppedKeys: s }), this.bo.add(f$1({ [Ee]: t, [Se$1]: (/* @__PURE__ */ new Date()).toISOString() }, r)); } catch (t) { ua.error("Failed to add exception step. Ignoring breadcrumb.", t); } } sendExceptionEvent(t) { try { var e = t.$exception_list; if (this.Io(e)) { if (this.Co(e)) return this.So("Exception dropped: matched a suppression rule"), void ua.info("Skipping exception capture because a suppression rule matched"); if (!this._o && this.xo(e)) return this.So("Exception dropped: thrown by a browser extension"), void ua.info("Skipping exception capture because it was thrown by an extension"); if (!this._instance.config.error_tracking.__capturePostHogExceptions && this.ko(e)) return this.So("Exception dropped: thrown by the PostHog SDK"), void ua.info("Skipping exception capture because it was thrown by the PostHog SDK"); } var i = this.mo.enabled && D$1(t.$exception_steps) ? this.To(t) : t; try { var r = this._instance.capture("$exception", i, { _noTruncate: !0, _batchKey: "exceptionEvent", en: !0 }); return r && this.bo.clear(), r; } catch (t) { ua.error("Failed to capture exception event. Dropping this exception.", t), this.bo.clear(); return; } } catch (t) { ua.error("Failed to process exception event. Ignoring this exception.", t); return; } } To(t) { try { var e = this.bo.getAttachable(); return 0 === e.length ? t : f$1({}, t, { $exception_steps: e }); } catch (e) { return ua.error("Failed to read buffered exception steps. Capturing exception without steps.", e), t; } } So(t) { this.mo.enabled && this.bo.add({ [Ee]: t, [Se$1]: (/* @__PURE__ */ new Date()).toISOString() }); } wo(t) { return O$1(t) ? f$1({}, t) : {}; } yo() { var t, e; return null !== (t = null == (e = this._instance.config.error_tracking) ? void 0 : e.exception_steps) && void 0 !== t ? t : {}; } Co(t) { if (0 === t.length) return !1; var e = t.reduce(((t, e) => { var { type: i, value: r } = e; return F$1(i) && i.length > 0 && t.$exception_types.push(i), F$1(r) && r.length > 0 && t.$exception_values.push(r), t; }), { $exception_types: [], $exception_values: [] }); return this.fo.some(((t) => { var i = t.values.map(((t) => { var i, r = _n[t.operator], s = R$1(t.value) ? t.value : [t.value], n = null !== (i = e[t.key]) && void 0 !== i ? i : []; return s.length > 0 && r(s, n); })); return "OR" === t.type ? i.some(Boolean) : i.every(Boolean); })); } xo(t) { return t.flatMap(((t) => { var e, i; return null !== (e = null == (i = t.stacktrace) ? void 0 : i.frames) && void 0 !== e ? e : []; })).some(((t) => t.filename && t.filename.startsWith("chrome-extension://"))); } ko(t) { if (t.length > 0) { var e, i, r, s, n = null !== (e = null == (i = t[0].stacktrace) ? void 0 : i.frames) && void 0 !== e ? e : [], o = n[n.length - 1]; return null !== (r = null == o || null == (s = o.filename) ? void 0 : s.includes("posthog.com/static")) && void 0 !== r && r; } return !1; } Io(t) { return !D$1(t) && R$1(t); } } }, ba = f$1({ productTours: class { get ni() { return this._instance.persistence; } constructor(t) { this.Ao = null, this.Eo = null, this._instance = t; } initialize() { this.loadIfEnabled(); } onRemoteConfig(t) { "productTours" in t && (this.ni && this.ni.register({ [We]: !!t.productTours }), this.loadIfEnabled()); } loadIfEnabled() { var t, e; this.Ao || (t = this._instance).config.disable_product_tours || null == (e = t.persistence) || !e.get_property(We) || this.ur((() => this.Ro())); } ur(t) { var e, i; null != (e = h$2.__PosthogExtensions__) && e.generateProductTours ? t() : null == (i = h$2.__PosthogExtensions__) || null == i.loadExternalDependency || i.loadExternalDependency(this._instance, "product-tours", ((e) => { e ? Vo$1.error("Could not load product tours script", e) : t(); })); } Ro() { var t; !this.Ao && null != (t = h$2.__PosthogExtensions__) && t.generateProductTours && (this.Ao = h$2.__PosthogExtensions__.generateProductTours(this._instance, !0)); } getProductTours(t, e) { if (void 0 === e && (e = !1), !R$1(this.Eo) || e) { var i = this.ni; if (i) { var r = i.props[ci]; if (R$1(r) && !e) return this.Eo = r, void t(r, { isLoaded: !0 }); } this._instance._send_request({ url: this._instance.requestRouter.endpointFor("api", "/api/product_tours/?token=" + this._instance.config.token), method: "GET", callback: (e) => { var r = e.statusCode; if (200 !== r || !e.json) { var s = "Product Tours API could not be loaded, status: " + r; Vo$1.error(s), t([], { isLoaded: !1, error: s }); return; } var n = R$1(e.json.product_tours) ? e.json.product_tours : []; this.Eo = n, i && i.register({ [ci]: n }), t(n, { isLoaded: !0 }); } }); } else t(this.Eo, { isLoaded: !0 }); } getActiveProductTours(t) { D$1(this.Ao) ? t([], { isLoaded: !1, error: "Product tours not loaded" }) : this.Ao.getActiveProductTours(t); } showProductTour(t) { var e; null == (e = this.Ao) || e.showTourById(t); } previewTour(t) { this.Ao ? this.Ao.previewTour(t) : this.ur((() => { var e; this.Ro(), null == (e = this.Ao) || e.previewTour(t); })); } dismissProductTour() { var t; null == (t = this.Ao) || t.dismissTour("user_clicked_skip"); } nextStep() { var t; null == (t = this.Ao) || t.nextStep(); } previousStep() { var t; null == (t = this.Ao) || t.previousStep(); } clearCache() { var t; this.Eo = null, null == (t = this.ni) || t.unregister(ci); } resetTour(t) { var e; null == (e = this.Ao) || e.resetTour(t); } resetAllTours() { var t; null == (t = this.Ao) || t.resetAllTours(); } cancelPendingTour(t) { var e; null == (e = this.Ao) || e.cancelPendingTour(t); } } }, fa), ya = { siteApps: class { constructor(t) { this._instance = t, this.No = [], this.apps = {}; } get isEnabled() { return !!this._instance.config.opt_in_site_apps; } Mo(t, e) { if (e) { var i = this.globalsForEvent(e); this.No.push(i), this.No.length > 1e3 && (this.No = this.No.slice(10)); } } get siteAppLoaders() { var t; return null == (t = h$2._POSTHOG_REMOTE_CONFIG) || null == (t = t[this._instance.config.token]) ? void 0 : t.siteApps; } initialize() { if (this.isEnabled) { var t = this._instance._addCaptureHook(this.Mo.bind(this)); this.Fo = () => { t(), this.No = [], this.Fo = void 0; }; } } globalsForEvent(t) { var e, i, r, s, n, o, a; if (!t) throw new Error("Event payload is required"); var l = {}, u = this._instance.get_property("$groups") || [], h = this._instance.get_property("$stored_group_properties") || {}; for (var [d, v] of Object.entries(h)) l[d] = { id: u[d], type: d, properties: v }; var { $set_once: c, $set: p } = t; return { event: f$1({}, _$1(t, Wo), { properties: f$1({}, t.properties, p ? { $set: f$1({}, null !== (e = null == (i = t.properties) ? void 0 : i.$set) && void 0 !== e ? e : {}, p) } : {}, c ? { $set_once: f$1({}, null !== (r = null == (s = t.properties) ? void 0 : s.$set_once) && void 0 !== r ? r : {}, c) } : {}), elements_chain: null !== (n = null == (o = t.properties) ? void 0 : o.$elements_chain) && void 0 !== n ? n : "", distinct_id: null == (a = t.properties) ? void 0 : a.distinct_id }), person: { properties: this._instance.get_property("$stored_person_properties") }, groups: l }; } setupSiteApp(t) { var e = this.apps[t.id], i = () => { var i; !e.errored && this.No.length && (Go.info("Processing " + this.No.length + " events for site app with id " + t.id), this.No.forEach(((t) => null == e.processEvent ? void 0 : e.processEvent(t))), e.processedBuffer = !0), Object.values(this.apps).every(((t) => t.processedBuffer || t.errored)) && (null == (i = this.Fo) || i.call(this)); }, r = !1, s = (s) => { e.errored = !s, e.loaded = !0, Go.info("Site app with id " + t.id + " " + (s ? "loaded" : "errored")), r && i(); }; try { var { processEvent: n } = t.init({ posthog: this._instance, callback(t) { s(t); } }); n && (e.processEvent = n), r = !0; } catch (e) { Go.error(Yo + t.id, e), s(!1); } if (r && e.loaded) try { i(); } catch (i) { Go.error("Error while processing buffered events PostHog app with config id " + t.id, i), e.errored = !0; } } Oo() { var t = this.siteAppLoaders || []; for (var e of t) this.apps[e.id] = { id: e.id, loaded: !1, errored: !1, processedBuffer: !1 }; for (var i of t) this.setupSiteApp(i); } Po(t) { if (0 !== Object.keys(this.apps).length) { var e = this.globalsForEvent(t); for (var i of Object.values(this.apps)) try { null == i.processEvent || i.processEvent(e); } catch (e) { Go.error("Error while processing event " + t.event + " for site app " + i.id, e); } } } onRemoteConfig(t) { var e, i, r, s = this; if (null != (e = this.siteAppLoaders) && e.length) return this.isEnabled ? (this.Oo(), void this._instance.on("eventCaptured", ((t) => this.Po(t)))) : void Go.error("PostHog site apps are disabled. Enable the \"opt_in_site_apps\" config to proceed."); if (null == (i = this.Fo) || i.call(this), null != (r = t.siteApps) && r.length) if (this.isEnabled) { var n = function(t) { var e; h$2["__$$ph_site_app_" + t] = s._instance, null == (e = h$2.__PosthogExtensions__) || null == e.loadSiteApp || e.loadSiteApp(s._instance, a, ((e) => { if (e) return Go.error(Yo + t, e); })); }; for (var { id: o, url: a } of t.siteApps) n(o); } else Go.error("PostHog site apps are disabled. Enable the \"opt_in_site_apps\" config to proceed."); } } }, wa = { tracingHeaders: class { constructor(t) { this.Lo = void 0, this.Do = void 0, this.so = () => { var t, e, i = this.Bo() || []; C$2(this.Lo) && (null == (t = h$2.__PosthogExtensions__) || null == (t = t.tracingHeadersPatchFns) || t._patchXHR(i, this._instance.get_distinct_id(), this._instance.sessionManager)), C$2(this.Do) && (null == (e = h$2.__PosthogExtensions__) || null == (e = e.tracingHeadersPatchFns) || e._patchFetch(i, this._instance.get_distinct_id(), this._instance.sessionManager)); }, this._instance = t; } initialize() { this.startIfEnabledOrStop(); } ur(t) { var e, i; null != (e = h$2.__PosthogExtensions__) && e.tracingHeadersPatchFns && t(), null == (i = h$2.__PosthogExtensions__) || null == i.loadExternalDependency || i.loadExternalDependency(this._instance, "tracing-headers", ((e) => { if (e) return Ao$1.error("failed to load script", e); t(); })); } Bo() { var t; return null !== (t = this._instance.config.addTracingHeaders) && void 0 !== t ? t : this._instance.config.__add_tracing_headers; } startIfEnabledOrStop() { var t, e; this.Bo() ? this.ur(this.so) : (null == (t = this.Lo) || t.call(this), null == (e = this.Do) || e.call(this), this.Lo = void 0, this.Do = void 0); } } }, xa = f$1({ surveys: class { get Bt() { return this._instance.config; } constructor(t) { this.jo = void 0, this._surveyManager = null, this.$o = !1, this.qo = [], this.Zo = null, this._instance = t, this._surveyEventReceiver = null; } initialize() { this.loadIfEnabled(); } onRemoteConfig(t) { if (!this.Bt.disable_surveys) { var e = t.surveys; if (D$1(e)) return En.warn("Flags not loaded yet. Not loading surveys."); var i = R$1(e); this.jo = i ? e.length > 0 : e, En.info("flags response received, isSurveysEnabled: " + this.jo), this.loadIfEnabled(); } } reset() { localStorage.removeItem("lastSeenSurveyDate"); for (var t = [], e = 0; e < localStorage.length; e++) { var i = localStorage.key(e); (null != i && i.startsWith(Sn) || null != i && i.startsWith("inProgressSurvey_")) && t.push(i); } t.forEach(((t) => localStorage.removeItem(t))); } loadIfEnabled() { if (!this._surveyManager) if (this.$o) En.info("Already initializing surveys, skipping..."); else if (this.Bt.disable_surveys) En.info(ta); else if (this.Bt.cookieless_mode && this._instance.consent.isOptedOut()) En.info("Not loading surveys in cookieless mode without consent."); else { var t = null == h$2 ? void 0 : h$2.__PosthogExtensions__; if (t) { if (!C$2(this.jo) || this.Bt.advanced_enable_surveys) { var e = this.jo || this.Bt.advanced_enable_surveys; this.$o = !0; try { var i = t.generateSurveys; if (i) return void this.Vo(i, e); var r = t.loadExternalDependency; if (!r) return void this.Ho(Oi); r(this._instance, "surveys", ((i) => { i || !t.generateSurveys ? this.Ho("Could not load surveys script", i) : this.Vo(t.generateSurveys, e); })); } catch (t) { throw this.Ho("Error initializing surveys", t), t; } finally { this.$o = !1; } } } else En.error("PostHog Extensions not found."); } } Vo(t, e) { this._surveyManager = t(this._instance, e), this._surveyEventReceiver = new Qo(this._instance), En.info("Surveys loaded successfully"), this.zo({ isLoaded: !0 }); } Ho(t, e) { En.error(t, e), this.zo({ isLoaded: !1, error: t }); } onSurveysLoaded(t) { return this.qo.push(t), this._surveyManager && this.zo({ isLoaded: !0 }), () => { this.qo = this.qo.filter(((e) => e !== t)); }; } getSurveys(t, e) { if (void 0 === e && (e = !1), this.Bt.disable_surveys) return En.info(ta), t([]); var i, r = this._instance.get_property(di); if (r && !e) return t(r, { isLoaded: !0 }); "undefined" != typeof Promise && this.Zo ? this.Zo.then(((e) => { var { surveys: i, context: r } = e; return t(i, r); })) : ("undefined" != typeof Promise && (this.Zo = new Promise(((t) => { i = t; }))), this._instance._send_request({ url: this._instance.requestRouter.endpointFor("api", "/api/surveys/?token=" + this.Bt.token), method: "GET", timeout: this.Bt.surveys_request_timeout_ms, callback: (e) => { var r; this.Zo = null; var s = e.statusCode; if (200 !== s || !e.json) { var n = "Surveys API could not be loaded, status: " + s; En.error(n); var o = { isLoaded: !1, error: n }; t([], o), i?.({ surveys: [], context: o }); return; } var a, l = e.json.surveys || [], u = l.filter(((t) => function(t) { return !(!t.start_date || t.end_date); }(t) && (function(t) { var e; return !(null == (e = t.conditions) || null == (e = e.events) || null == (e = e.values) || !e.length); }(t) || function(t) { var e; return !(null == (e = t.conditions) || null == (e = e.actions) || null == (e = e.values) || !e.length); }(t)))); u.length > 0 && (null == (a = this._surveyEventReceiver) || a.register(u)), null == (r = this._instance.persistence) || r.register({ [di]: l }); var h = { isLoaded: !0 }; t(l, h), i?.({ surveys: l, context: h }); } })); } zo(t) { for (var e of this.qo) try { if (!t.isLoaded) return e([], t); this.getSurveys(e); } catch (t) { En.error("Error in survey callback", t); } } getActiveMatchingSurveys(t, e) { if (void 0 === e && (e = !1), !D$1(this._surveyManager)) return this._surveyManager.getActiveMatchingSurveys(t, e); En.warn("init was not called"); } Uo(t) { var e = null; return this.getSurveys(((i) => { var r; e = null !== (r = i.find(((e) => e.id === t))) && void 0 !== r ? r : null; })), e; } Yo(t) { if (D$1(this._surveyManager)) return { eligible: !1, reason: Zo }; var e = "string" == typeof t ? this.Uo(t) : t; return e ? this._surveyManager.checkSurveyEligibility(e) : { eligible: !1, reason: "Survey not found" }; } canRenderSurvey(t) { if (D$1(this._surveyManager)) return En.warn("init was not called"), { visible: !1, disabledReason: Zo }; var e = this.Yo(t); return { visible: e.eligible, disabledReason: e.reason }; } canRenderSurveyAsync(t, e) { return D$1(this._surveyManager) ? (En.warn("init was not called"), Promise.resolve({ visible: !1, disabledReason: Zo })) : new Promise(((i) => { this.getSurveys(((e) => { var r, s = null !== (r = e.find(((e) => e.id === t))) && void 0 !== r ? r : null; if (s) { var n = this.Yo(s); i({ visible: n.eligible, disabledReason: n.reason }); } else i({ visible: !1, disabledReason: "Survey not found" }); }), e); })); } renderSurvey(t, e, i) { var s; if (D$1(this._surveyManager)) En.warn("init was not called"); else { var n = "string" == typeof t ? this.Uo(t) : t; if (null != n && n.id) if ($n.includes(n.type)) { var o = null == r$1 ? void 0 : r$1.querySelector(e); if (o) return null != (s = n.appearance) && s.surveyPopupDelaySeconds ? (En.info("Rendering survey " + n.id + " with delay of " + n.appearance.surveyPopupDelaySeconds + " seconds"), void setTimeout((() => { var t, e; En.info("Rendering survey " + n.id + " with delay of " + (null == (t = n.appearance) ? void 0 : t.surveyPopupDelaySeconds) + " seconds"), null == (e = this._surveyManager) || e.renderSurvey(n, o, i), En.info("Survey " + n.id + " rendered"); }), 1e3 * n.appearance.surveyPopupDelaySeconds)) : void this._surveyManager.renderSurvey(n, o, i); En.warn("Survey element not found"); } else En.warn("Surveys of type " + n.type + " cannot be rendered in the app"); else En.warn("Survey not found"); } } displaySurvey(t, e) { var i; if (D$1(this._surveyManager)) En.warn("init was not called"); else { var r = this.Uo(t); if (r) { var s = r; if (null != (i = r.appearance) && i.surveyPopupDelaySeconds && e.ignoreDelay && (s = f$1({}, r, { appearance: f$1({}, r.appearance, { surveyPopupDelaySeconds: 0 }) })), e.displayType !== ns.Popover && e.initialResponses && En.warn("initialResponses is only supported for popover surveys. prefill will not be applied."), !1 === e.ignoreConditions) { var n = this.canRenderSurvey(r); if (!n.visible) return void En.warn("Survey is not eligible to be displayed: ", n.disabledReason); } e.displayType !== ns.Inline ? this._surveyManager.handlePopoverSurvey(s, e) : this.renderSurvey(s, e.selector, e.properties); } else En.warn("Survey not found"); } } cancelPendingSurvey(t) { D$1(this._surveyManager) ? En.warn("init was not called") : this._surveyManager.cancelSurvey(t); } handlePageUnload() { var t; null == (t = this._surveyManager) || t.handlePageUnload(); } } }, fa), Ea = { toolbar: class { constructor(t) { this.instance = t; } Go(t) { h$2.ph_toolbar_state = t; } Wo() { var t; return null !== (t = h$2.ph_toolbar_state) && void 0 !== t ? t : 0; } initialize() { return this.maybeLoadToolbar(); } maybeLoadToolbar(e, i, s) { if (void 0 === e && (e = void 0), void 0 === i && (i = void 0), void 0 === s && (s = void 0), Qi(this.instance.config)) return !1; if (!t || !r$1) return !1; e = null != e ? e : t.location, s = null != s ? s : t.history; try { if (!i) { try { t.localStorage.setItem("test", "test"), t.localStorage.removeItem("test"); } catch (t) { return !1; } i = null == t ? void 0 : t.localStorage; } var n, o = ea || Ir(e.hash, "__posthog") || Ir(e.hash, "state"), a = o ? Wi((() => JSON.parse(atob(decodeURIComponent(o))))) || Wi((() => JSON.parse(decodeURIComponent(o)))) : null; return a && "ph_authorize" === a.action ? ((n = a).source = "url", n && Object.keys(n).length > 0 && (a.desiredHash ? e.hash = a.desiredHash : s ? s.replaceState(s.state, "", e.pathname + e.search) : e.hash = "")) : ((n = JSON.parse(i.getItem(ia) || "{}")).source = "localstorage", delete n.userIntent), !(!n.token || this.instance.config.token !== n.token || (this.loadToolbar(n), 0)); } catch (t) { return !1; } } Xo(t) { var e = h$2.ph_load_toolbar || h$2.ph_load_editor; !D$1(e) && P$1(e) ? e(t, this.instance) : ra.warn("No toolbar load function found"); } loadToolbar(e) { var i = !(null == r$1 || !r$1.getElementById($i)); if (!t || i) return !1; var s = "custom" === this.instance.requestRouter.region && this.instance.config.advanced_disable_toolbar_metrics, n = f$1({ token: this.instance.config.token }, e, { apiURL: this.instance.requestRouter.endpointFor("ui") }, s ? { instrument: !1 } : {}); if (t.localStorage.setItem(ia, JSON.stringify(f$1({}, n, { source: void 0 }))), 2 === this.Wo()) this.Xo(n); else if (0 === this.Wo()) { var o; this.Go(1), null == (o = h$2.__PosthogExtensions__) || null == o.loadExternalDependency || o.loadExternalDependency(this.instance, "toolbar", ((t) => { if (t) return ra.error("[Toolbar] Failed to load", t), void this.Go(0); this.Go(2), this.Xo(n); })), Xi(t, "turbolinks:load", (() => { this.Go(0), this.loadToolbar(n); })); } return !0; } Jo(t) { return this.loadToolbar(t); } maybeLoadEditor(t, e, i) { return void 0 === t && (t = void 0), void 0 === e && (e = void 0), void 0 === i && (i = void 0), this.maybeLoadToolbar(t, e, i); } } }, Sa = f$1({ experiments: va }, fa), ka = f$1({}, fa, _a, ga, ma, ba, ya, xa, wa, Ea, Sa, { conversations: class { constructor(t) { this.Ko = void 0, this._conversationsManager = null, this.Qo = !1, this.ea = null, this._instance = t; } initialize() { this.loadIfEnabled(); } onRemoteConfig(t) { if (!this._instance.config.disable_conversations) { var e = t.conversations; D$1(e) || (N(e) ? this.Ko = e : (this.Ko = e.enabled, this.ea = e), this.loadIfEnabled()); } } reset() { var t; null == (t = this._conversationsManager) || t.reset(), this._conversationsManager = null, this.Ko = void 0, this.ea = null; } loadIfEnabled() { if (!(this._conversationsManager || this.Qo || this._instance.config.disable_conversations || Qi(this._instance.config) || this._instance.config.cookieless_mode && this._instance.consent.isOptedOut())) { var t = null == h$2 ? void 0 : h$2.__PosthogExtensions__; if (t && !C$2(this.Ko) && this.Ko) if (this.ea && this.ea.token) { this.Qo = !0; try { var e = t.initConversations; if (e) return this.ta(e), void (this.Qo = !1); var i = t.loadExternalDependency; if (!i) return void this.ra(Oi); i(this._instance, "conversations", ((e) => { e || !t.initConversations ? this.ra("Could not load conversations script", e) : this.ta(t.initConversations), this.Qo = !1; })); } catch (t) { this.ra("Error initializing conversations", t), this.Qo = !1; } } else ca.error("Conversations enabled but missing token in remote config."); } } ta(t) { if (this.ea) try { this._conversationsManager = t(this.ea, this._instance), ca.info("Conversations loaded successfully"); } catch (t) { this.ra("Error completing conversations initialization", t); } else ca.error("Cannot complete initialization: remote config is null"); } ra(t, e) { ca.error(t, e), this._conversationsManager = null, this.Qo = !1; } show() { this._conversationsManager ? this._conversationsManager.show() : ca.warn("Conversations not loaded yet."); } hide() { this._conversationsManager && this._conversationsManager.hide(); } isAvailable() { return !0 === this.Ko && !M(this._conversationsManager); } isVisible() { var t, e; return null !== (t = null == (e = this._conversationsManager) ? void 0 : e.isVisible()) && void 0 !== t && t; } sendMessage(t, e, i) { var r = this; return p$1((function* () { return r._conversationsManager ? r._conversationsManager.sendMessage(t, e, i) : (ca.warn(pa), null); }))(); } getMessages(t, e) { var i = this; return p$1((function* () { return i._conversationsManager ? i._conversationsManager.getMessages(t, e) : (ca.warn(pa), null); }))(); } markAsRead(t) { var e = this; return p$1((function* () { return e._conversationsManager ? e._conversationsManager.markAsRead(t) : (ca.warn(pa), null); }))(); } getTickets(t) { var e = this; return p$1((function* () { return e._conversationsManager ? e._conversationsManager.getTickets(t) : (ca.warn(pa), null); }))(); } requestRestoreLink(t) { var e = this; return p$1((function* () { return e._conversationsManager ? e._conversationsManager.requestRestoreLink(t) : (ca.warn(pa), null); }))(); } restoreFromToken(t) { var e = this; return p$1((function* () { return e._conversationsManager ? e._conversationsManager.restoreFromToken(t) : (ca.warn(pa), null); }))(); } restoreFromUrlToken() { var t = this; return p$1((function* () { return t._conversationsManager ? t._conversationsManager.restoreFromUrlToken() : (ca.warn(pa), null); }))(); } getCurrentTicketId() { var t, e; return null !== (t = null == (e = this._conversationsManager) ? void 0 : e.getCurrentTicketId()) && void 0 !== t ? t : null; } getWidgetSessionId() { var t, e; return null !== (t = null == (e = this._conversationsManager) ? void 0 : e.getWidgetSessionId()) && void 0 !== t ? t : null; } un() { var t; null == (t = this._conversationsManager) || t.setIdentity(); } hn() { var t; null == (t = this._conversationsManager) || t.clearIdentity(); } } }, { logs: class { constructor(t) { var e; this.ia = !1, this.na = !1, this.Gt = Ce$1("[logs]"), this.sa = [], this.oa = 0, this.aa = 0, this.la = !1, this._instance = t, this._instance && null != (e = this._instance.config.logs) && e.captureConsoleLogs && (this.ia = !0); } initialize() { this.loadIfEnabled(); } onRemoteConfig(t) { var e, i = null == (e = t.logs) ? void 0 : e.captureConsoleLogs; !D$1(i) && i && (this.ia = !0, this.loadIfEnabled()); } reset() { this.sa = [], this.jr && (clearTimeout(this.jr), this.jr = void 0), this.oa = 0, this.aa = 0, this.la = !1; } loadIfEnabled() { if (this.ia && !this.na) { var t = null == h$2 ? void 0 : h$2.__PosthogExtensions__; if (t) { var e = t.loadExternalDependency; e ? e(this._instance, "logs", ((e) => { var i; e || null == (i = t.logs) || !i.initializeLogs ? this.Gt.error("Could not load logs script", e) : (t.logs.initializeLogs(this._instance), this.na = !0); })) : this.Gt.error(Oi); } else this.Gt.error("PostHog Extensions not found."); } } captureLog(t) { var e, i, r, s, n, o; if (this._instance.is_capturing()) if (t && t.body) { var a = null !== (e = null == (i = this._instance.config.logs) ? void 0 : i.flushIntervalMs) && void 0 !== e ? e : 3e3, l = null !== (r = null == (s = this._instance.config.logs) ? void 0 : s.maxLogsPerInterval) && void 0 !== r ? r : 1e3, u = Date.now(); if (a > u - this.aa || (this.aa = u, this.oa = 0, this.la = !1), l > this.oa) { this.oa++; var h = function(t, e) { var { text: r, number: s } = Jt[t.level || "info"] || Kt, n = String(Date.now()) + "000000", o = {}; e.distinctId && (o.posthogDistinctId = e.distinctId), e.sessionId && (o.sessionId = e.sessionId), e.currentUrl && (o["url.full"] = e.currentUrl), e.screenName && (o["screen.name"] = e.screenName), e.appState && (o["app.state"] = e.appState), e.activeFeatureFlags && e.activeFeatureFlags.length > 0 && (o.feature_flags = e.activeFeatureFlags); var a = f$1({}, o, t.attributes || {}), l = { timeUnixNano: n, observedTimeUnixNano: n, severityNumber: s, severityText: r, body: { stringValue: t.body }, attributes: Qt(a) }; return t.trace_id && (l.traceId = t.trace_id), t.span_id && (l.spanId = t.span_id), C$2(t.trace_flags) || (l.flags = t.trace_flags), l; }(t, this.ua()); this.sa.push({ record: h }), (null !== (n = null == (o = this._instance.config.logs) ? void 0 : o.maxBufferSize) && void 0 !== n ? n : 100) > this.sa.length ? this.ha() : this.flushLogs(); } else this.la || (this.Gt.warn("captureLog dropping logs: exceeded " + l + " logs per " + a + "ms"), this.la = !0); } else this.Gt.warn("captureLog requires a body"); } get logger() { return this.ca || (this.ca = { trace: (t, e) => this.captureLog({ body: t, level: "trace", attributes: e }), debug: (t, e) => this.captureLog({ body: t, level: "debug", attributes: e }), info: (t, e) => this.captureLog({ body: t, level: "info", attributes: e }), warn: (t, e) => this.captureLog({ body: t, level: "warn", attributes: e }), error: (t, e) => this.captureLog({ body: t, level: "error", attributes: e }), fatal: (t, e) => this.captureLog({ body: t, level: "fatal", attributes: e }) }), this.ca; } flushLogs(t) { if (this.jr && (clearTimeout(this.jr), this.jr = void 0), 0 !== this.sa.length) { var e = this.sa; this.sa = []; var i = this._instance.config.logs, r = f$1({ "service.name": (null == i ? void 0 : i.serviceName) || "unknown_service" }, (null == i ? void 0 : i.environment) && { "deployment.environment": i.environment }, (null == i ? void 0 : i.serviceVersion) && { "service.version": i.serviceVersion }, null == i ? void 0 : i.resourceAttributes), s = function(t, e, i, r) { return { resourceLogs: [{ resource: { attributes: Qt(e) }, scopeLogs: [{ scope: { name: i, version: r }, logRecords: t }] }] }; }(e.map(((t) => t.record)), r, v$1.LIB_NAME, v$1.LIB_VERSION), n = this._instance.requestRouter.endpointFor("api", "/i/v1/logs") + "?token=" + encodeURIComponent(this._instance.config.token); this._instance.Vi({ method: "POST", url: n, data: s, compression: "best-available", batchKey: "logs", transport: t }); } } ha() { var t, e; this.jr || (this.jr = setTimeout((() => { this.jr = void 0, this.flushLogs(); }), null !== (t = null == (e = this._instance.config.logs) ? void 0 : e.flushIntervalMs) && void 0 !== t ? t : 3e3)); } ua() { var t, e = {}; if (e.distinctId = this._instance.get_distinct_id(), this._instance.sessionManager) { var { sessionId: i } = this._instance.sessionManager.checkAndGetSessionAndWindowId(!0); e.sessionId = i; } if (null != h$2 && null != (t = h$2.location) && t.href && (e.currentUrl = h$2.location.href), this._instance.featureFlags) { var r = this._instance.featureFlags.getFlags(); r && r.length > 0 && (e.activeFeatureFlags = r); } return e; } } }); qn.__defaultExtensionClasses = f$1({}, ka); var Ra, Pa = (Ra = In[Un] = new qn(), function() { function e() { e.done || (e.done = !0, Nn = !1, Hi(In, (function(t) { t._dom_loaded(); }))); } null != r$1 && r$1.addEventListener ? "complete" === r$1.readyState ? e() : Xi(r$1, "DOMContentLoaded", e, { capture: !1 }) : t && Ie.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized"); }(), Ra); //#endregion //#region ../send/frontend/src/plugins/posthog.js var initialized$1 = false; function initPosthog() { if (initialized$1) return; Pa.init("phc_61NZH7teRtwmtZQHpKRltXUEEO7acpEAjpjdSiE5tdu", { api_host: "https://us.i.posthog.com", persistence: "memory" }); Pa.register({ service: "send" }); initialized$1 = true; } /** * Enables or disables PostHog capture at runtime in response to the Thunderbird * telemetry opt-out preference (see issue #892). * * When enabled, PostHog is initialized lazily on first opt-in — so while opted * out it is never initialized and makes zero network requests. When disabled, * capture is opted out and the stored distinct id is reset. * * `capture()` / `identify()` calls on the shared instance before init are * no-ops, so callers throughout the app remain safe regardless of consent. */ function setPosthogConsent(enabled) { if (enabled) { initPosthog(); Pa.opt_in_capturing(); } else if (initialized$1) { Pa.opt_out_capturing(); Pa.reset(); } } var posthog_default = { install(app) { app.config.globalProperties.$posthog = Pa; }, rest: Pa }; //#endregion //#region ../send/frontend/src/stores/metrics.ts var initializeClientMetrics = (uid) => { if (!uid) return; posthog_default.rest.identify(uid); }; var useMetricsStore = defineStore("metrics", () => { return { metrics: posthog_default.rest, initializeClientMetrics }; }); //#endregion //#region ../send/frontend/src/lib/validations.ts var validateToken = async (api) => { try { try { const authStore = await __vitePreload(() => Promise.resolve().then(() => auth_store_exports).then((m) => m.useAuthStore()), void 0); const isExtension = await __vitePreload(() => Promise.resolve().then(() => stores_exports).then((m) => m.useConfigStore().isExtension), void 0); const accessToken = await authStore.getAccessToken(); if (isExtension) await authStore.loadUser(); if (accessToken) { if ((await api.call("auth/oidc/me", {}, "GET", { Authorization: `Bearer ${accessToken}` }, { fullResponse: true }))?.ok) return true; console.log("OIDC token appears invalid, attempting refresh..."); const newToken = await authStore.refreshToken(); if (newToken) return !!(await api.call("auth/oidc/me", {}, "GET", { Authorization: `Bearer ${newToken}` }, { fullResponse: true }))?.ok; } } catch (error) { console.debug("OIDC validation failed, falling back to JWT:", error); } return !!await api.call("auth/me", {}, "GET", {}, { fullResponse: true }); } catch (err) { console.error("Error validating session", err); return false; } }; var validateUser = async (api) => { try { const userResponse = await api.call(`users/me`); if (userResponse?.user) return userResponse; } catch (error) { console.error("Error validating user", error); return null; } }; var validateBackedUpKeys = async (getBackup, keychain) => { const keybackup = await getBackup(); const hasBackedUpKeys = keychain.getPassphraseValue(); if (!keybackup || !hasBackedUpKeys) return false; return true; }; /** * Checks local storage for a user object */ var validateLocalStorageSession = ({ user }) => { if (user?.id != void 0) return true; else return false; }; var validator = async ({ api, keychain, userStore }) => { const validations = { hasBackedUpKeys: false, hasLocalStorageSession: false, isTokenValid: false, hasCorrectKeys: false, hasForcedLogin: false }; let shouldClearSessionAndStorage = false; const userIDFromBackend = (await validateUser(api))?.user?.id; const userIDFromStore = userStore?.user?.id; try { await restoreKeysUsingLocalStorage(keychain, api); validations.hasCorrectKeys = true; } catch { validations.hasCorrectKeys = false; shouldClearSessionAndStorage = true; console.error("Incorrect passphrase. Removing local storage data."); } if (userIDFromStore && userIDFromBackend && userIDFromBackend !== userIDFromStore) { console.error("User ID mismatch. Removing local storage data."); shouldClearSessionAndStorage = true; } else { validations.hasLocalStorageSession = validateLocalStorageSession(userStore); validations.isTokenValid = await validateToken(api); validations.hasBackedUpKeys = await validateBackedUpKeys(userStore.getBackup, keychain); } if (shouldClearSessionAndStorage) { await userStore.clearUserFromStorage(); validations.hasForcedLogin = true; try { location.reload(); } catch { console.warn("Failed to reload page"); } } return validations; }; function toValue(r) { return typeof r === "function" ? r() : unref(r); } var isClient$1 = typeof window !== "undefined" && typeof document !== "undefined"; typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope; var noop$1 = () => {}; function createFilterWrapper(filter, fn) { function wrapper(...args) { return new Promise((resolve, reject) => { Promise.resolve(filter(() => fn.apply(this, args), { fn, thisArg: this, args })).then(resolve).catch(reject); }); } return wrapper; } function debounceFilter(ms, options = {}) { let timer; let maxTimer; let lastRejector = noop$1; const _clearTimeout = (timer2) => { clearTimeout(timer2); lastRejector(); lastRejector = noop$1; }; const filter = (invoke) => { const duration = toValue(ms); const maxDuration = toValue(options.maxWait); if (timer) _clearTimeout(timer); if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) { if (maxTimer) { _clearTimeout(maxTimer); maxTimer = null; } return Promise.resolve(invoke()); } return new Promise((resolve, reject) => { lastRejector = options.rejectOnCancel ? reject : resolve; if (maxDuration && !maxTimer) maxTimer = setTimeout(() => { if (timer) _clearTimeout(timer); maxTimer = null; resolve(invoke()); }, maxDuration); timer = setTimeout(() => { if (maxTimer) _clearTimeout(maxTimer); maxTimer = null; resolve(invoke()); }, duration); }); }; return filter; } function useDebounceFn(fn, ms = 200, options = {}) { return createFilterWrapper(debounceFilter(ms, options), fn); } isClient$1 && window.document; isClient$1 && window.navigator; isClient$1 && window.location; Number.POSITIVE_INFINITY; //#endregion //#region ../send/frontend/src/apps/send/stores/status-store.ts var useStatusStore = defineStore("status", () => { const { api } = useApiStore(); const userStore = useUserStore(); const { keychain } = useKeychainStore(); const total = /* @__PURE__ */ ref(0); const progressed = /* @__PURE__ */ ref(0); const error = /* @__PURE__ */ ref(""); const text = /* @__PURE__ */ ref(""); const fileName = /* @__PURE__ */ ref(""); const processStage = /* @__PURE__ */ ref("idle"); const isRouterLoading = /* @__PURE__ */ ref(false); const debouncedUpdate = useDebounceFn((updatedValue) => { progressed.value = updatedValue; }, 1); function setText(message) { text.value = message; } function setUploadSize(size) { total.value = size; } function setProgress(number) { console.info("setting progress", number); debouncedUpdate(number); } function setFileName(name) { fileName.value = name; } function setProcessStage(stage) { processStage.value = stage; } function initialize() { total.value = 0; progressed.value = 0; error.value = ""; text.value = ""; fileName.value = ""; processStage.value = "idle"; } function setRouterLoading(loading) { isRouterLoading.value = loading; } const percentage = computed(() => { const result = progressed.value * 100 / total.value; if (Number.isNaN(result)) return 0; if (result > 100) return 100; return Math.round(result); }); const validators = () => validator({ api, keychain, userStore }); return { validators, setProgress, setUploadSize, setText, setFileName, setProcessStage, setRouterLoading, isRouterLoading, progress: { total, progressed, percentage, error, text, fileName, processStage, initialize, setProgress, setUploadSize, setText, setFileName, setProcessStage } }; }); //#endregion //#region ../send/frontend/src/apps/send/stores/folder-store.ts var useFolderStore = defineStore("folderManager", () => { const { api } = useApiStore(); const { user, populateFromBackend } = useUserStore(); const { progress } = useStatusStore(); const { metrics } = useMetricsStore(); const { keychain } = useKeychainStore(); const uploader = new Uploader(user, keychain, api); const downloader = new Downloader(keychain, api); const folders = /* @__PURE__ */ ref([]); const rootFolder = /* @__PURE__ */ ref(null); const msg = /* @__PURE__ */ ref(""); const selectedFolderId = /* @__PURE__ */ ref(null); const selectedFileId = /* @__PURE__ */ ref(null); const rootFolderId = /* @__PURE__ */ ref(null); onMounted(async () => { await getDefaultFolderId(); }); async function getDefaultFolderId() { try { const result = (await trpc.getDefaultFolder.query()).id || null; rootFolderId.value = result; return result; } catch { console.info("No default folder set for user"); return null; } } const defaultFolder = computed(() => { if (!folders?.value) return null; const total = folders.value.length; return total === 0 ? null : folders.value[total - 1]; }); const visibleFolders = computed(() => { if (folders.value.length === 0) return []; return calculateFolderSizes(folders.value); }); const selectedFolder = computed(() => { if (!selectedFolderId.value) return null; return findContainer(selectedFolderId.value, folders.value); }); const selectedFile = computed(() => { if (!selectedFileId.value || !rootFolder.value?.items) return null; return findItem(selectedFileId.value, rootFolder.value.items); }); function init() { console.log(`initializing the folderStore`); folders.value = []; rootFolder.value = null; selectedFolderId.value = null; selectedFileId.value = null; } async function fetchSubtree(rootFolderId) { const tree = await api.call(`containers/${rootFolderId}/`); folders.value = tree.children; rootFolder.value = tree; } async function fetchUserFolders() { folders.value = await api.call(`users/folders`); rootFolder.value = null; } async function goToRootFolder(folderId) { if (folderId) await fetchSubtree(folderId); else { await fetchUserFolders(); selectedFolderId.value = null; selectedFileId.value = null; } } function setSelectedFolder(folderId) { selectedFolderId.value = folderId; selectedFileId.value = null; } async function setSelectedFile(itemId) { selectedFolderId.value = null; selectedFileId.value = itemId; } async function createFolder(name = "Default", parentId, shareOnly = false) { if (rootFolder.value) parentId = rootFolder.value.id; const containerResponse = await api.call(`containers`, { name, type: CONTAINER_TYPE.FOLDER, parentId, shareOnly }, "POST"); if (containerResponse?.container) { const { container } = containerResponse; try { await keychain.newKeyForContainer(container.id); await backupKeys(keychain, api, msg); await keychain.store(); folders.value = [...folders.value, container]; return container; } catch (error) { console.error(`Failed to set up key for container ${container.id}, rolling back`, error); try { await api.call(`containers/${container.id}`, {}, "DELETE"); } catch (deleteError) { console.error("Failed to roll back container creation", deleteError); } return null; } } return null; } async function renameFolder(folderId, name) { const result = await api.call(`containers/${folderId}/rename`, { name }, "POST"); if (result) { const node = findContainer(folderId, folders.value); if (node) node.name = result.name; } return result; } async function renameItem(folderId, itemId, name) { const result = await api.call(`containers/${folderId}/item/${itemId}/rename`, { name }, "POST"); if (result && rootFolder.value?.items) { const node = findItem(itemId, rootFolder.value.items); if (node) node.name = result.name; } return result; } async function uploadItem(fileBlob, folderId, api) { progress.error = ""; if (!user.id) { console.warn("uploadItem: user.id missing; re-populating from backend"); await populateFromBackend(); } if (!user.id) { progress.error = "You are not fully signed in. Please sign in again."; throw new Error("Cannot upload: user session is missing a user id (ownerId would be empty)."); } const canUpload = await checkBlobSize(fileBlob); if (await canUserUpload(fileBlob.size)) { progress.error = CLIENT_MESSAGES.STORAGE_LIMIT_EXCEEDED; alert(`Error uploading ${fileBlob.name}; ${CLIENT_MESSAGES.STORAGE_LIMIT_EXCEEDED}`); throw new Error("Uploading this file would exceed your storage limit."); } if (!canUpload) { progress.error = CLIENT_MESSAGES.FILE_TOO_BIG; throw new Error("Too big"); } const formattedBlob = await formatBlob(fileBlob); progress.setFileName(formattedBlob.name); try { const newItems = await uploader.doUpload(formattedBlob, folderId, api, progress); if (!newItems || newItems.length === 0) throw new Error(`Upload failed for ${formattedBlob.name}`); if (rootFolder.value) rootFolder.value.items = [...rootFolder.value.items, ...newItems]; return newItems; } catch (error) { console.error("Upload failed in uploadItem:", error); const message = error instanceof Error ? error.message : "Unknown error"; progress.error = message; progress.setProcessStage("error"); throw new Error(`Upload failed: ${message}`); } } async function deleteFolder(folderId) { if ((await api.call(`containers/${folderId}`, {}, "DELETE"))?.result.length > 0) folders.value = [...folders.value.filter((f) => f.id !== folderId)]; } async function deleteItem(itemId, folderId) { const result = await api.call(`containers/${folderId}/item/${itemId}`, { shouldDeleteContent: true }, "DELETE"); if (result) { if (selectedFileId.value === itemId) setSelectedFile(null); if (rootFolder.value?.items) { const deletedKey = result.wrappedKey; rootFolder.value.items = [...rootFolder.value.items.filter((i) => i.wrappedKey !== deletedKey)]; } } } /** * Memory-Optimized Multipart Download Implementation * * This implementation replaces the previous memory-intensive approach that loaded all file pieces * into ArrayBuffer objects simultaneously. The key improvements include: * * 1. **Streaming Processing**: Each piece is processed as a stream, reducing peak memory usage * 2. **Sequential Download**: Pieces are downloaded and processed one at a time rather than all at once * 3. **Chunked Output**: Large pieces are streamed in 64KB chunks to prevent memory spikes * 4. **Progressive Enhancement**: Uses File System Access API when available for true streaming saves * 5. **Efficient Concatenation**: Combines pieces using ReadableStream without intermediate buffers * * For a 2GB file split into 10 pieces: * - Old approach: ~4GB+ peak memory usage (original + combined + intermediate buffers) * - New approach: ~200MB peak memory usage (single piece + processing overhead) */ async function downloadMultipart(upload, containerId, wrappedKeyStr, name, api, keychain, progressTracker) { const isBucketStorage = api.isBucketStorage; let combinedType = ""; const _uploads = await api.call(`uploads/${upload.at(0).id}/parts`); const wrappingKey = await keychain.get(containerId); if (!wrappingKey) throw new Error("Wrapping key not found"); const contentKey = await keychain.container.unwrapContentKey(wrappedKeyStr, wrappingKey); const validMetadata = (await Promise.all(_uploads.map(async ({ id, part }) => { if (!id) return null; const { size, type } = await api.call(`uploads/${id}/metadata`); if (!size) return null; if (!combinedType && type) combinedType = type; return { id, part, size, type }; }))).filter((meta) => meta !== null); if (validMetadata.length === 0) throw new Error("No valid pieces found"); const sortedMetadata = validMetadata.sort((a, b) => a.part - b.part); const totalSize = sortedMetadata.reduce((sum, meta) => sum + meta.size, 0); progressTracker.setUploadSize(totalSize); progressTracker.setProcessStage("downloading"); progressTracker.setText("Downloading file"); const multipartTracker = createMultipartDownloadProgressTracker(progressTracker, sortedMetadata, sortedMetadata.length > 1); const createPieceStream = async (metadata, partTracker) => { let downloadedBlob; if (!isBucketStorage) { downloadedBlob = await _download({ id: metadata.id, progressTracker: partTracker }); if (!downloadedBlob) throw new Error("DOWNLOAD_FAILED"); } else { const bucketResponse = await api.call(`download/${metadata.id}/signed`); if (!bucketResponse?.url) throw new Error("BUCKET_URL_NOT_FOUND"); downloadedBlob = await _download({ url: bucketResponse.url, progressTracker: partTracker }); } let pieceStream; if (contentKey) pieceStream = decryptStream(blobStream(downloadedBlob), contentKey); else pieceStream = blobStream(downloadedBlob); return new ReadableStream({ async start(controller) { const reader = pieceStream.getReader(); const chunks = []; let totalSize = 0; try { while (true) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); totalSize += value.length; } const pieceBuffer = new Uint8Array(totalSize); let offset = 0; for (const chunk of chunks) { pieceBuffer.set(chunk, offset); offset += chunk.length; } const { content: unzippedContent } = await unzipMultipartPiece(pieceBuffer.buffer); const chunkSize = 64 * 1024; const unzippedView = new Uint8Array(unzippedContent); for (let i = 0; i < unzippedView.length; i += chunkSize) { const chunk = unzippedView.slice(i, i + chunkSize); controller.enqueue(chunk); } controller.close(); } catch (error) { controller.error(error); } } }); }; return await _saveFileStream({ stream: new ReadableStream({ async start(controller) { try { for (let index = 0; index < sortedMetadata.length; index++) { const metadata = sortedMetadata[index]; const reader = (await createPieceStream(metadata, multipartTracker.getPartTracker(index))).getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; controller.enqueue(value); } multipartTracker.markPartComplete(index); } controller.close(); } catch (error) { controller.error(error); } } }), name: decodeURIComponent(name), type: combinedType }); } async function downloadContent(uploadId, containerId, wrappedKeyStr, name) { return await downloader.doDownload(uploadId, containerId, wrappedKeyStr, name, metrics, progress); } function print() { console.log(`rootFolder: ${rootFolder.value}`); console.log(`defaultFolder: ${defaultFolder.value}`); console.log(`visibleFolders: ${visibleFolders.value}`); console.log(`selectedFolder: ${selectedFolder.value}`); console.log(`selectedFile: ${selectedFile.value}`); } /** * Creates a multipart download progress tracker that manages overall progress across all parts */ function createMultipartDownloadProgressTracker(mainTracker, metadata, isMultipart) { const partSizes = metadata.map((meta) => meta.size); const totalSize = partSizes.reduce((sum, size) => sum + size, 0); let completedParts = 0; return { getPartTracker: (partIndex) => { const partSize = partSizes[partIndex]; return { total: mainTracker.total, progressed: mainTracker.progressed, percentage: mainTracker.percentage, error: mainTracker.error, text: mainTracker.text, fileName: mainTracker.fileName, processStage: mainTracker.processStage, initialize: () => {}, setUploadSize: () => {}, setFileName: (name) => { mainTracker.setFileName(name); }, setProcessStage: (stage) => { mainTracker.setProcessStage(stage); }, setText: (message) => { if (isMultipart) if (message.includes("Downloading")) mainTracker.setText("Downloading file"); else if (message.includes("Decrypting")) mainTracker.setText("Decrypting file"); else mainTracker.setText(message); else mainTracker.setText(message); }, setProgress: (partProgress) => { const overallProgress = completedParts / metadata.length * totalSize + Math.min(partProgress / partSize, 1) * (totalSize / metadata.length); mainTracker.setProgress(Math.min(overallProgress, totalSize)); } }; }, markPartComplete: (partIndex) => { completedParts = partIndex + 1; const progress = completedParts / metadata.length * totalSize; mainTracker.setProgress(progress); } }; } return { rootFolder: computed(() => { const rootFolderValue = rootFolder.value; if (!rootFolderValue) return null; return { ...rootFolderValue, items: organizeFiles(rootFolderValue?.items || []) }; }), defaultFolder: computed(() => { const defaultFolderValue = defaultFolder.value; if (!defaultFolderValue) return null; return defaultFolderValue ? { ...defaultFolderValue, items: organizeFiles(defaultFolderValue.items || []) } : null; }), visibleFolders: computed(() => visibleFolders.value), selectedFolder: computed(() => selectedFolder.value), selectedFile: computed(() => { if (!selectedFileId.value || !rootFolder.value?.items) return null; return organizeFiles([selectedFile.value])[0] || null; }), rootFolderId: computed(() => rootFolderId.value), getDefaultFolderId, print, init, fetchSubtree, fetchUserFolders, goToRootFolder, sync: async () => await goToRootFolder(null), setSelectedFolder, setSelectedFile, createFolder, renameFolder, deleteFolder, renameItem, uploadItem, deleteItem, downloadContent, downloadMultipart }; }); function calculateFolderSizes(folders) { return folders.map((folder) => { folder.size = folder.items?.reduce((total, { upload }) => total + upload?.size || 0, 0) || 0; return folder; }); } function findContainer(id, containers) { if (!containers) return null; return containers.find((container) => container.id === id) || null; } function findItem(id, items) { if (!items) return null; return items.find((item) => item.id === id) || null; } //#endregion //#region ../send/frontend/src/apps/common/mixins/metrics.ts function useMetricsUpdate() { const userStore = useUserStore(); const { initializeClientMetrics } = useMetricsStore(); const updateMetricsIdentity = async () => { await userStore.loadFromLocalStorage(); const uid = userStore.user.uniqueHash; initializeClientMetrics(uid); }; onMounted(() => { window.addEventListener("focus", updateMetricsIdentity); }); onBeforeUnmount(() => { window.removeEventListener("focus", updateMetricsIdentity); }); return { updateMetricsIdentity }; } //#endregion //#region ../send/frontend/src/apps/common/VersionTag.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$13 = { class: "addon-version-tag", "data-testid": "addon-version" }; var VersionTag_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({ __name: "VersionTag", setup(__props) { const version = "2.0.5"; return (_ctx, _cache) => { return openBlock(), createElementBlock("span", _hoisted_1$13, " v" + toDisplayString(unref(version)), 1); }; } }); //#endregion //#region \0plugin-vue:export-helper var _plugin_vue_export_helper_default = (sfc, props) => { const target = sfc.__vccOpts || sfc; for (const [key, val] of props) target[key] = val; return target; }; //#endregion //#region ../send/frontend/src/apps/common/VersionTag.vue var VersionTag_default = /*#__PURE__*/ _plugin_vue_export_helper_default(VersionTag_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-46c038cc"]]); //#endregion //#region ../send/frontend/src/apps/send/components/ErrorUploading.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$12 = { class: "flex flex-col gap-2 items-center justify-center p-4 rounded-lg transition duration-500 ease-in-out text-white bg-red-400 hover:bg-red-300", role: "status" }; //#endregion //#region ../send/frontend/src/apps/send/components/ErrorUploading.vue var ErrorUploading_default = /* @__PURE__ */ defineComponent({ __name: "ErrorUploading", setup(__props) { const { progress } = useStatusStore(); return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1$12, [createBaseVNode("p", null, toDisplayString(unref(progress).error || `There was an error uploading your file, please try again or raise an issue`), 1)]); }; } }); //#endregion //#region ../send/frontend/src/lib/challenge.ts async function getContainerKeyFromChallenge(hash, password, api, keychain) { const resp = await api.call(`sharing/${hash}/challenge`); if (!resp) return null; const { challengeKey: challengeKeyStr, challengeSalt: challengeSaltStr, challengeCiphertext } = resp; let challengeSalt; try { challengeSalt = Util.base64ToArrayBuffer(challengeSaltStr); } catch (e) { return null; } try { const unwrappedChallengeKey = await keychain.password.unwrapContentKey(challengeKeyStr, password, challengeSalt); const challengePlaintext = await keychain.challenge.decryptChallenge(challengeCiphertext, unwrappedChallengeKey, challengeSalt); const challengeResp = await api.call(`sharing/${hash}/challenge`, { challengePlaintext }, "POST"); if (!challengeResp.containerId) throw Error("Challenge unsuccessful"); const { containerId, wrappedKey: wrappedKeyStr, salt: saltStr } = challengeResp; return { unwrappedKey: await keychain.password.unwrapContainerKey(wrappedKeyStr, password, Util.base64ToArrayBuffer(saltStr)), containerId }; } catch (e) { console.log(e); return null; } } //#endregion //#region ../send/frontend/src/lib/share.ts var Sharer = class { constructor(user, keychain, api) { this.user = user; this.keychain = keychain; this.api = api; } async handleMultipartItems(item) { const ids = (await this.api.call(`uploads/parts`, { wrappedKey: item.wrappedKey }, "POST")).map((u) => u.id); console.log(`ids:`, ids); const _items = await this.api.call(`uploads/items`, { ids, wrappedKey: item.wrappedKey }, "POST"); console.log(`_items:`, _items); return _items; } async shareItemsWithPassword(items, password, expiration) { const __items = []; for (const item of items) if (item.multipart) { const _items = await this.handleMultipartItems(item); __items.push(..._items); } else __items.push(item); const containerId = await this.createShareOnlyContainer(__items, null); return await this.requestAccessLink(containerId, password, expiration); } async shareContainerWithInvitation(containerId, email) { const user = await this.api.call(`users/lookup/${email}/`); if (user) { let publicKey = user.publicKey; const recipientId = user.id; if (!publicKey) console.log(`Could not find public key for user ${email}`); console.warn("SOMETHING WEIRD IS HAPPENING WITH PUBLIC KEYS ON SERVER"); while (typeof publicKey !== "object") publicKey = JSON.parse(publicKey); const importedPublicKey = await crypto.subtle.importKey("jwk", publicKey, { name: "RSA-OAEP", hash: { name: "SHA-256" } }, true, ["wrapKey"]); const key = await this.keychain.get(containerId); const wrappedKey = await this.keychain.rsa.wrapContainerKey(key, importedPublicKey); if (!wrappedKey) { console.log(`no wrapped key for the invitation`); return null; } const resp = await this.api.call(`containers/${containerId}/member/invite`, { wrappedKey, recipientId, senderId: this.user.id }, "POST"); console.log(`Invitation creation response:`); console.log(resp); return resp; } } async createShareOnlyContainer(items = [], containerId = null) { if (items.length === 0 && !containerId) return null; if (!this.api?.call || !this.keychain?.store) return null; const itemsToShare = [...items]; let currentContainer = { name: "default" }; if (containerId) currentContainer = await this.api.call(`containers/${containerId}/info`); const response = await this.api.call(`containers`, { name: currentContainer.name, type: CONTAINER_TYPE.FOLDER, parentId: 0, shareOnly: true }, "POST"); if (!response.container?.id) return null; const { id: newContainerId } = response.container; await this.keychain.newKeyForContainer(newContainerId); await this.keychain.store(); await Promise.all(itemsToShare.map(async (item) => { const containerId = item.containerId ?? item.folderId; const filename = item.name ?? item.filename; const currentWrappingKey = await this.keychain.get(containerId); const { uploadId, wrappedKey, type } = item; const contentKey = await this.keychain.container.unwrapContentKey(wrappedKey, currentWrappingKey); const newWrappingKey = await this.keychain.get(newContainerId); const wrappedKeyStr = await this.keychain.container.wrapContentKey(contentKey, newWrappingKey); return await this.api.call(`containers/${newContainerId}/item`, { uploadId, name: filename, type, wrappedKey: wrappedKeyStr, multipart: item.multipart ?? false, totalSize: item.totalSize ?? void 0 }, "POST"); })); return newContainerId; } async requestAccessLink(containerId, password, expiration) { if (!(await this.api.call(`sharing/${containerId}/canCreateAccessLink`))?.canCreateLink) throw new Error("Cannot create access link for this container because it contains files that have been reported for abuse."); const unwrappedKey = await this.keychain.get(containerId); const salt = Util.generateSalt(); const passwordWrappedKeyStr = await this.keychain.password.wrapContainerKey(unwrappedKey, password, salt); const challengeKey = await this.keychain.challenge.generateKey(); const challengeSalt = Util.generateSalt(); const passwordWrappedChallengeKeyStr = await this.keychain.password.wrapContentKey(challengeKey, password, challengeSalt); const challengePlaintext = this.keychain.challenge.createChallenge(); const challengeCiphertext = await this.keychain.challenge.encryptChallenge(challengePlaintext, challengeKey, challengeSalt); const saltStr = Util.arrayBufferToBase64(salt); const challengeSaltStr = Util.arrayBufferToBase64(challengeSalt); const resp = await this.api.call(`sharing`, { containerId, wrappedKey: passwordWrappedKeyStr, salt: saltStr, challengeKey: passwordWrappedChallengeKeyStr, challengeSalt: challengeSaltStr, senderId: this.user.id, challengePlaintext, challengeCiphertext, expiration }, "POST"); if (!resp?.id) return null; return `https://send.tb.pro/share/${resp.id}`; } }; //#endregion //#region ../send/frontend/src/apps/send/stores/sharing-store.ts var useSharingStore = defineStore("sharingManager", () => { const { api } = useApiStore(); const { user } = useUserStore(); const { keychain } = useKeychainStore(); const sharer = new Sharer(user, keychain, api); const _links = /* @__PURE__ */ ref([]); const links = computed(() => { return [..._links.value]; }); async function createAccessLink(folderId, password, expiration) { let shouldAddPasswordAsHash = false; if (password.length === 0) { password = Util.generateRandomPassword(); shouldAddPasswordAsHash = true; } let url = await sharer.requestAccessLink(folderId, password, expiration); if (!url) return null; if (shouldAddPasswordAsHash) url = `${url}#${password}`; return url; } async function acceptAccessLink(linkId, password) { const containerKey = await getContainerKeyFromChallenge(linkId, password, api, keychain); if (!containerKey?.unwrappedKey) { await trpc.incrementPasswordRetryCount.mutate({ linkId }); return false; } const { unwrappedKey, containerId } = containerKey; await keychain.rsa.generateKeyPair(); await keychain.add(containerId, unwrappedKey); await keychain.store(); return true; } async function isAccessLinkValid(linkId) { return await api.call(`sharing/exists/${linkId}`); } async function fetchFolderAccessLinks(folderId) { _links.value = await api.call(`containers/${folderId}/links`); } async function fetchFileAccessLinks(uploadId) { _links.value = await api.call(`sharing/${uploadId}/links?type=file`); } async function shareItems(itemsArray, password, expiration) { let shouldAddPasswordAsHash = false; if (password.length === 0) { password = Util.generateRandomPassword(); shouldAddPasswordAsHash = true; } let url = await sharer.shareItemsWithPassword(itemsArray, password, expiration); if (!url) return null; if (shouldAddPasswordAsHash) url = `${url}#${password}`; return url; } async function getSharedFolder(hash) { return await api.call(`sharing/${hash}/`); } async function getInvitations(userId) { return await api.call(`users/${userId}/invitations/`); } async function getFoldersSharedWithUser(userId) { return await api.call(`users/${userId}/folders/sharedWithUser`); } async function getFoldersSharedByUser(userId) { return await api.call(`users/${userId}/folders/sharedByUser`); } async function getSharesForFolder(containerId, userId) { return await api.call(`containers/${containerId}/shares`, { userId }); } async function acceptInvitation(invitationId, containerId) { return await api.call(`containers/${containerId}/member/accept/${invitationId}`, {}, "POST"); } async function updateInvitationPermissions(containerId, userId, invitationId, permission) { return await api.call(`containers/${containerId}/shares/invitation/update`, { userId, invitationId, permission }, "POST"); } async function updateAccessLinkPermissions(containerId, userId, accessLinkId, permission) { return await api.call(`containers/${containerId}/shares/accessLink/update`, { userId, accessLinkId, permission }, "POST"); } return { links, createAccessLink, isAccessLinkValid, acceptAccessLink, fetchFolderAccessLinks, fetchFileAccessLinks, shareItems, getSharedFolder, getInvitations, getFoldersSharedWithUser, getFoldersSharedByUser, getSharesForFolder, acceptInvitation, updateInvitationPermissions, updateAccessLinkPermissions }; }); //#endregion //#region ../send/frontend/src/apps/send/composables/useUploadAndShare.ts function useUploadAndShare() { const folderStore = useFolderStore(); const sharingStore = useSharingStore(); const { api } = useApiStore(); const isUploading = /* @__PURE__ */ ref(false); const isError = /* @__PURE__ */ ref(false); const uploadMap = /* @__PURE__ */ ref(/* @__PURE__ */ new Map()); async function uploadAndShare(files, password, expiration, onStatusUpdate) { isUploading.value = true; isError.value = false; const uploadedItems = []; const rootFolderId = await folderStore.getDefaultFolderId(); for (let i = 0; i < files.length; i++) { const file = files[i]; try { if (onStatusUpdate) onStatusUpdate(i, "uploading"); const itemObjArray = await folderStore.uploadItem(file.data, rootFolderId, api); if (!itemObjArray || itemObjArray?.length === 0) throw new Error(`Could not upload file ${file.name}`); console.log(`[uploadAndShare] Successfully uploaded ${file.name}`); for (const itemObj of itemObjArray) { uploadedItems.push({ originalId: file.id, ...itemObj }); uploadMap.value.set(file.id, true); } if (onStatusUpdate) onStatusUpdate(i, "completed"); } catch (err) { console.log(err); if (onStatusUpdate) onStatusUpdate(i, "error"); uploadAborted(); isError.value = true; isUploading.value = false; throw err; } } try { const organizedFiles = organizeFiles(uploadedItems); const url = await sharingStore.shareItems(organizedFiles, password, expiration); if (!url) throw new Error(`Did not get URL back from sharingStore`); console.log(`I got a sharing url and it is`); console.log(url); shareComplete(url, [...uploadedItems]); } catch (err) { console.log(err.message); shareAborted(); isError.value = true; isUploading.value = false; throw err; } } function shareComplete(url, results) { browser.runtime.sendMessage({ type: ALL_UPLOADS_COMPLETE, url, results, aborted: false }); window.close(); } function uploadAborted() { browser.runtime.sendMessage({ type: ALL_UPLOADS_ABORTED, aborted: true }); } function shareAborted() { browser.runtime.sendMessage({ type: ALL_UPLOADS_ABORTED, aborted: true }); window.close(); } return { isUploading, isError, uploadMap, uploadAndShare }; } //#endregion //#region ../send/frontend/src/apps/common/ProButton.vue var ProButton_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "ProButton", props: { type: { default: "primary" } }, emits: ["click"], setup(__props) { return (_ctx, _cache) => { return openBlock(), createElementBlock("button", { class: normalizeClass(["pro-button", { "pro-button--primary": __props.type === "primary", "pro-button--secondary": __props.type === "secondary" }]), onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("click")) }, [renderSlot(_ctx.$slots, "default", {}, void 0, true)], 2); }; } }), [["__scopeId", "data-v-eb342a1c"]]); //#endregion //#region ../send/frontend/src/apps/send/components/SpinnerAnimated.vue var _sfc_main = {}; var _hoisted_1$11 = { class: "flex flex-col items-center justify-center p-4 rounded-lg transition duration-500 ease-in-out text-white", role: "status" }; function _sfc_render(_ctx, _cache) { return openBlock(), createElementBlock("div", _hoisted_1$11, [..._cache[0] || (_cache[0] = [createBaseVNode("div", null, [createBaseVNode("svg", { class: "animate-spin h-5 w-5 text-white", xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24" }, [createBaseVNode("circle", { class: "opacity-25 fill", cx: "12", cy: "12", r: "10", "stroke-width": "4" }), createBaseVNode("path", { class: "opacity-75 fill", d: "M4 12a8 8 0 018-8V2.5" })])], -1)])]); } var SpinnerAnimated_default = /*#__PURE__*/ _plugin_vue_export_helper_default(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-611f9e03"]]); //#endregion //#region ../send/frontend/src/apps/common/LoadingComponent.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$10 = { class: "loading", "data-tesid": "loading" }; //#endregion //#region ../send/frontend/src/apps/common/LoadingComponent.vue var LoadingComponent_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "LoadingComponent", setup(__props) { return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1$10, [createVNode(SpinnerAnimated_default)]); }; } }), [["__scopeId", "data-v-4be0547e"]]); //#endregion //#region ../send/frontend/src/apps/common/WithLoader.vue var WithLoader_default = /* @__PURE__ */ defineComponent({ __name: "WithLoader", props: { isLoading: { type: Boolean } }, setup(__props) { return (_ctx, _cache) => { return __props.isLoading ? (openBlock(), createBlock(LoadingComponent_default, { key: 0 })) : renderSlot(_ctx.$slots, "default", { key: 1 }); }; } }); "https://send.tb.pro".includes("send.tb.pro"); //#endregion //#region ../send/frontend/src/apps/send/views/PromptLogin.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$9 = { class: "prompt-login" }; //#endregion //#region ../send/frontend/src/apps/send/views/PromptLogin.vue var PromptLogin_default = /* @__PURE__ */ defineComponent({ __name: "PromptLogin", setup(__props) { onMounted(async () => { await browser.runtime.sendMessage({ type: SIGN_IN }); }); return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1$9, [..._cache[0] || (_cache[0] = [createBaseVNode("h1", null, "Please log in to continue", -1), createBaseVNode("p", null, "A new window has been opened for you to log in.", -1)])]); }; } }); //#endregion //#region ../send/frontend/src/composables/useIsExtension.ts function useIsExtension() { const { isThunderbirdHost } = useConfigStore(); const isExtension = computed(() => { if (window.location.href.includes("https://send.tb.pro") && !isThunderbirdHost) return false; return true; }); const isRunningInsideThunderbird = computed(() => { return isThunderbirdHost; }); const isUrlMozExtension = computed(() => { return location.href.includes("moz-extension:"); }); const isAppNameAddon = computed(() => { return true; }); return { isExtension, isRunningInsideThunderbird, isAppNameAddon, isUrlMozExtension, environmentType: computed(() => { if (!isUrlMozExtension.value && isRunningInsideThunderbird.value) return "WEB APP INSIDE THUNDERBIRD"; if (isUrlMozExtension.value && isRunningInsideThunderbird.value) return "EXTENSION INSIDE THUNDERBIRD"; if (!isAppNameAddon.value && !isRunningInsideThunderbird.value) return "WEB APP OUTSIDE THUNDERBIRD"; return "UNKNOWN ENVIRONMENT"; }) }; } //#endregion //#region ../send/frontend/src/apps/send/stores/extension-store.ts var SERVER = `server`; defineStore("extension", () => { const { serverUrl, setServerUrl, getAddonId } = useConfigStore(); const { isRunningInsideThunderbird } = useIsExtension(); const accountId = new URL(location.href).searchParams.get("accountId"); function setAccountConfigured(accountId) { try { browser.cloudFile.updateAccount(accountId, { configured: true }); } catch { console.log(`setAccountConfigured: You're probably running this outside of Thundebird`); } } async function configureExtension(id = accountId) { if (!isRunningInsideThunderbird.value) return; try { const result = await browser.CloudFileAccounts.createAccount(getAddonId(), true); if (!result.success) console.warn(`[extension-store] Failed to create cloud file account: ${result.error}`); else if (result.alreadyExists) console.log(`[extension-store] Cloud file account already exists: ${result.accountId}`); else console.log(`[extension-store] Cloud file account created: ${result.accountId}`); } catch (error) { console.warn(`[extension-store] Error creating cloud file account:`, error); } if (!id) { console.log(`[extension-store] No id provided to configureExtension()`); return; } return browser.storage.local.set({ [id]: { [SERVER]: serverUrl.value } }).catch((error) => { console.log(error); }).then(() => { setAccountConfigured(id); setServerUrl(serverUrl.value); browser.storage.local.get(id).then((accountInfo) => { if (accountInfo[id] && SERVER in accountInfo[id]) { setServerUrl(accountInfo[id][SERVER]); setAccountConfigured(id); } else console.log(`You probably need to wait longer`); }); }); } const sendMessageToBridge = (message) => { window.postMessage({ type: SEND_MESSAGE_TO_BRIDGE, value: message }, window.location.origin); }; return { configureExtension, sendMessageToBridge, serverUrl, setServerUrl }; }); //#endregion //#region ../../node_modules/.pnpm/jwt-decode@4.0.0/node_modules/jwt-decode/build/esm/index.js var InvalidTokenError = class extends Error {}; InvalidTokenError.prototype.name = "InvalidTokenError"; function b64DecodeUnicode(str) { return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => { let code = p.charCodeAt(0).toString(16).toUpperCase(); if (code.length < 2) code = "0" + code; return "%" + code; })); } function base64UrlDecode(str) { let output = str.replace(/-/g, "+").replace(/_/g, "/"); switch (output.length % 4) { case 0: break; case 2: output += "=="; break; case 3: output += "="; break; default: throw new Error("base64 string is not of the correct length"); } try { return b64DecodeUnicode(output); } catch (err) { return atob(output); } } function jwtDecode(token, options) { if (typeof token !== "string") throw new InvalidTokenError("Invalid token specified: must be a string"); options || (options = {}); const pos = options.header === true ? 0 : 1; const part = token.split(".")[pos]; if (typeof part !== "string") throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`); let decoded; try { decoded = base64UrlDecode(part); } catch (e) { throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`); } try { return JSON.parse(decoded); } catch (e) { throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`); } } //#endregion //#region ../../node_modules/.pnpm/oidc-client-ts@3.5.0/node_modules/oidc-client-ts/dist/esm/oidc-client-ts.js var nopLogger = { debug: () => void 0, info: () => void 0, warn: () => void 0, error: () => void 0 }; var level; var logger; var Log = /* @__PURE__ */ ((Log2) => { Log2[Log2["NONE"] = 0] = "NONE"; Log2[Log2["ERROR"] = 1] = "ERROR"; Log2[Log2["WARN"] = 2] = "WARN"; Log2[Log2["INFO"] = 3] = "INFO"; Log2[Log2["DEBUG"] = 4] = "DEBUG"; return Log2; })(Log || {}); ((Log2) => { function reset() { level = 3; logger = nopLogger; } Log2.reset = reset; function setLevel(value) { if (!(0 <= value && value <= 4)) throw new Error("Invalid log level"); level = value; } Log2.setLevel = setLevel; function setLogger(value) { logger = value; } Log2.setLogger = setLogger; })(Log || (Log = {})); var Logger = class _Logger { constructor(_name) { this._name = _name; } debug(...args) { if (level >= 4) logger.debug(_Logger._format(this._name, this._method), ...args); } info(...args) { if (level >= 3) logger.info(_Logger._format(this._name, this._method), ...args); } warn(...args) { if (level >= 2) logger.warn(_Logger._format(this._name, this._method), ...args); } error(...args) { if (level >= 1) logger.error(_Logger._format(this._name, this._method), ...args); } throw(err) { this.error(err); throw err; } create(method) { const methodLogger = Object.create(this); methodLogger._method = method; methodLogger.debug("begin"); return methodLogger; } static createStatic(name, staticMethod) { const staticLogger = new _Logger(`${name}.${staticMethod}`); staticLogger.debug("begin"); return staticLogger; } static _format(name, method) { const prefix = `[${name}]`; return method ? `${prefix} ${method}:` : prefix; } static debug(name, ...args) { if (level >= 4) logger.debug(_Logger._format(name), ...args); } static info(name, ...args) { if (level >= 3) logger.info(_Logger._format(name), ...args); } static warn(name, ...args) { if (level >= 2) logger.warn(_Logger._format(name), ...args); } static error(name, ...args) { if (level >= 1) logger.error(_Logger._format(name), ...args); } }; Log.reset(); var JwtUtils = class { static decode(token) { try { return jwtDecode(token); } catch (err) { Logger.error("JwtUtils.decode", err); throw err; } } static async generateSignedJwt(header, payload, privateKey) { const encodedToken = `${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(header)))}.${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(payload)))}`; const signature = await window.crypto.subtle.sign({ name: "ECDSA", hash: { name: "SHA-256" } }, privateKey, new TextEncoder().encode(encodedToken)); return `${encodedToken}.${CryptoUtils.encodeBase64Url(new Uint8Array(signature))}`; } static async generateSignedJwtWithHmac(header, payload, secretKey) { const encodedToken = `${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(header)))}.${CryptoUtils.encodeBase64Url(new TextEncoder().encode(JSON.stringify(payload)))}`; const signature = await window.crypto.subtle.sign("HMAC", secretKey, new TextEncoder().encode(encodedToken)); return `${encodedToken}.${CryptoUtils.encodeBase64Url(new Uint8Array(signature))}`; } }; var UUID_V4_TEMPLATE = "10000000-1000-4000-8000-100000000000"; var toBase64 = (val) => btoa([...new Uint8Array(val)].map((chr) => String.fromCharCode(chr)).join("")); var _CryptoUtils = class _CryptoUtils { static _randomWord() { const arr = new Uint32Array(1); crypto.getRandomValues(arr); return arr[0]; } /** * Generates RFC4122 version 4 guid */ static generateUUIDv4() { return UUID_V4_TEMPLATE.replace(/[018]/g, (c) => (+c ^ _CryptoUtils._randomWord() & 15 >> +c / 4).toString(16)).replace(/-/g, ""); } /** * PKCE: Generate a code verifier */ static generateCodeVerifier() { return _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4(); } /** * PKCE: Generate a code challenge */ static async generateCodeChallenge(code_verifier) { if (!crypto.subtle) throw new Error("Crypto.subtle is available only in secure contexts (HTTPS)."); try { const data = new TextEncoder().encode(code_verifier); return toBase64(await crypto.subtle.digest("SHA-256", data)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } catch (err) { Logger.error("CryptoUtils.generateCodeChallenge", err); throw err; } } /** * Generates a base64-encoded string for a basic auth header */ static generateBasicAuth(client_id, client_secret) { return toBase64(new TextEncoder().encode([client_id, client_secret].join(":"))); } /** * Generates a hash of a string using a given algorithm * @param alg * @param message */ static async hash(alg, message) { const msgUint8 = new TextEncoder().encode(message); const hashBuffer = await crypto.subtle.digest(alg, msgUint8); return new Uint8Array(hashBuffer); } /** * Generates a rfc7638 compliant jwk thumbprint * @param jwk */ static async customCalculateJwkThumbprint(jwk) { let jsonObject; switch (jwk.kty) { case "RSA": jsonObject = { "e": jwk.e, "kty": jwk.kty, "n": jwk.n }; break; case "EC": jsonObject = { "crv": jwk.crv, "kty": jwk.kty, "x": jwk.x, "y": jwk.y }; break; case "OKP": jsonObject = { "crv": jwk.crv, "kty": jwk.kty, "x": jwk.x }; break; case "oct": jsonObject = { "crv": jwk.k, "kty": jwk.kty }; break; default: throw new Error("Unknown jwk type"); } const utf8encodedAndHashed = await _CryptoUtils.hash("SHA-256", JSON.stringify(jsonObject)); return _CryptoUtils.encodeBase64Url(utf8encodedAndHashed); } static async generateDPoPProof({ url, accessToken, httpMethod, keyPair, nonce }) { let hashedToken; let encodedHash; const payload = { "jti": window.crypto.randomUUID(), "htm": httpMethod != null ? httpMethod : "GET", "htu": url, "iat": Math.floor(Date.now() / 1e3) }; if (accessToken) { hashedToken = await _CryptoUtils.hash("SHA-256", accessToken); encodedHash = _CryptoUtils.encodeBase64Url(hashedToken); payload.ath = encodedHash; } if (nonce) payload.nonce = nonce; try { const publicJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey); const header = { "alg": "ES256", "typ": "dpop+jwt", "jwk": { "crv": publicJwk.crv, "kty": publicJwk.kty, "x": publicJwk.x, "y": publicJwk.y } }; return await JwtUtils.generateSignedJwt(header, payload, keyPair.privateKey); } catch (err) { if (err instanceof TypeError) throw new Error(`Error exporting dpop public key: ${err.message}`); else throw err; } } static async generateDPoPJkt(keyPair) { try { const publicJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey); return await _CryptoUtils.customCalculateJwkThumbprint(publicJwk); } catch (err) { if (err instanceof TypeError) throw new Error(`Could not retrieve dpop keys from storage: ${err.message}`); else throw err; } } static async generateDPoPKeys() { return await window.crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]); } /** * Generates a client assertion JWT for client_secret_jwt authentication * @param client_id The client identifier * @param client_secret The client secret * @param audience The token endpoint URL (audience) * @param algorithm The HMAC algorithm to use (HS256, HS384, HS512). Defaults to HS256 */ static async generateClientAssertionJwt(client_id, client_secret, audience, algorithm = "HS256") { const now = Math.floor(Date.now() / 1e3); const header = { "alg": algorithm, "typ": "JWT" }; const payload = { "iss": client_id, "sub": client_id, "aud": audience, "jti": _CryptoUtils.generateUUIDv4(), "exp": now + 300, "iat": now }; const hashFunction = { "HS256": "SHA-256", "HS384": "SHA-384", "HS512": "SHA-512" }[algorithm]; if (!hashFunction) throw new Error(`Unsupported algorithm: ${algorithm}. Supported algorithms are: HS256, HS384, HS512`); const encoder = new TextEncoder(); const secretKey = await crypto.subtle.importKey("raw", encoder.encode(client_secret), { name: "HMAC", hash: hashFunction }, false, ["sign"]); return await JwtUtils.generateSignedJwtWithHmac(header, payload, secretKey); } }; /** * Generates a base64url encoded string */ _CryptoUtils.encodeBase64Url = (input) => { return toBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); }; var CryptoUtils = _CryptoUtils; var Event$1 = class { constructor(_name) { this._name = _name; this._callbacks = []; this._logger = new Logger(`Event('${this._name}')`); } addHandler(cb) { this._callbacks.push(cb); return () => this.removeHandler(cb); } removeHandler(cb) { const idx = this._callbacks.lastIndexOf(cb); if (idx >= 0) this._callbacks.splice(idx, 1); } async raise(...ev) { this._logger.debug("raise:", ...ev); for (const cb of this._callbacks) await cb(...ev); } }; var PopupUtils = class { /** * Populates a map of window features with a placement centered in front of * the current window. If no explicit width is given, a default value is * binned into [800, 720, 600, 480, 360] based on the current window's width. */ static center({ ...features }) { var _a; if (features.width == null) features.width = (_a = [ 800, 720, 600, 480 ].find((width) => width <= window.outerWidth / 1.618)) != null ? _a : 360; features.left ??= Math.max(0, Math.round(window.screenX + (window.outerWidth - features.width) / 2)); if (features.height != null) features.top ??= Math.max(0, Math.round(window.screenY + (window.outerHeight - features.height) / 2)); return features; } static serialize(features) { return Object.entries(features).filter(([, value]) => value != null).map(([key, value]) => `${key}=${typeof value !== "boolean" ? value : value ? "yes" : "no"}`).join(","); } }; var Timer = class _Timer extends Event$1 { constructor() { super(...arguments); this._logger = new Logger(`Timer('${this._name}')`); this._timerHandle = null; this._expiration = 0; this._callback = () => { const diff = this._expiration - _Timer.getEpochTime(); this._logger.debug("timer completes in", diff); if (this._expiration <= _Timer.getEpochTime()) { this.cancel(); super.raise(); } }; } static getEpochTime() { return Math.floor(Date.now() / 1e3); } init(durationInSeconds) { const logger2 = this._logger.create("init"); durationInSeconds = Math.max(Math.floor(durationInSeconds), 1); const expiration = _Timer.getEpochTime() + durationInSeconds; if (this.expiration === expiration && this._timerHandle) { logger2.debug("skipping since already initialized for expiration at", this.expiration); return; } this.cancel(); logger2.debug("using duration", durationInSeconds); this._expiration = expiration; const timerDurationInSeconds = Math.min(durationInSeconds, 5); this._timerHandle = setInterval(this._callback, timerDurationInSeconds * 1e3); } get expiration() { return this._expiration; } cancel() { this._logger.create("cancel"); if (this._timerHandle) { clearInterval(this._timerHandle); this._timerHandle = null; } } }; var UrlUtils = class { static readParams(url, responseMode = "query") { if (!url) throw new TypeError("Invalid URL"); const params = new URL(url, "http://127.0.0.1")[responseMode === "fragment" ? "hash" : "search"]; return new URLSearchParams(params.slice(1)); } }; var URL_STATE_DELIMITER = ";"; var ErrorResponse = class extends Error { constructor(args, form) { var _a, _b, _c; super(args.error_description || args.error || ""); this.form = form; /** Marker to detect class: "ErrorResponse" */ this.name = "ErrorResponse"; if (!args.error) { Logger.error("ErrorResponse", "No error passed"); throw new Error("No error passed"); } this.error = args.error; this.error_description = (_a = args.error_description) != null ? _a : null; this.error_uri = (_b = args.error_uri) != null ? _b : null; this.state = args.userState; this.session_state = (_c = args.session_state) != null ? _c : null; this.url_state = args.url_state; } }; var ErrorTimeout = class extends Error { constructor(message) { super(message); /** Marker to detect class: "ErrorTimeout" */ this.name = "ErrorTimeout"; } }; var AccessTokenEvents = class { constructor(args) { this._logger = new Logger("AccessTokenEvents"); this._expiringTimer = new Timer("Access token expiring"); this._expiredTimer = new Timer("Access token expired"); this._expiringNotificationTimeInSeconds = args.expiringNotificationTimeInSeconds; } async load(container) { const logger2 = this._logger.create("load"); if (container.access_token && container.expires_in !== void 0) { const duration = container.expires_in; logger2.debug("access token present, remaining duration:", duration); if (duration > 0) { let expiring = duration - this._expiringNotificationTimeInSeconds; if (expiring <= 0) expiring = 1; logger2.debug("registering expiring timer, raising in", expiring, "seconds"); this._expiringTimer.init(expiring); } else { logger2.debug("canceling existing expiring timer because we're past expiration."); this._expiringTimer.cancel(); } const expired = duration + 1; logger2.debug("registering expired timer, raising in", expired, "seconds"); this._expiredTimer.init(expired); } else { this._expiringTimer.cancel(); this._expiredTimer.cancel(); } } async unload() { this._logger.debug("unload: canceling existing access token timers"); this._expiringTimer.cancel(); this._expiredTimer.cancel(); } /** * Add callback: Raised prior to the access token expiring. */ addAccessTokenExpiring(cb) { return this._expiringTimer.addHandler(cb); } /** * Remove callback: Raised prior to the access token expiring. */ removeAccessTokenExpiring(cb) { this._expiringTimer.removeHandler(cb); } /** * Add callback: Raised after the access token has expired. */ addAccessTokenExpired(cb) { return this._expiredTimer.addHandler(cb); } /** * Remove callback: Raised after the access token has expired. */ removeAccessTokenExpired(cb) { this._expiredTimer.removeHandler(cb); } }; var CheckSessionIFrame = class { constructor(_callback, _client_id, url, _intervalInSeconds, _stopOnError) { this._callback = _callback; this._client_id = _client_id; this._intervalInSeconds = _intervalInSeconds; this._stopOnError = _stopOnError; this._logger = new Logger("CheckSessionIFrame"); this._timer = null; this._session_state = null; this._message = (e) => { if (e.origin === this._frame_origin && e.source === this._frame.contentWindow) if (e.data === "error") { this._logger.error("error message from check session op iframe"); if (this._stopOnError) this.stop(); } else if (e.data === "changed") { this._logger.debug("changed message from check session op iframe"); this.stop(); this._callback(); } else this._logger.debug(e.data + " message from check session op iframe"); }; const parsedUrl = new URL(url); this._frame_origin = parsedUrl.origin; this._frame = window.document.createElement("iframe"); this._frame.style.visibility = "hidden"; this._frame.style.position = "fixed"; this._frame.style.left = "-1000px"; this._frame.style.top = "0"; this._frame.width = "0"; this._frame.height = "0"; this._frame.src = parsedUrl.href; } load() { return new Promise((resolve) => { this._frame.onload = () => { resolve(); }; window.document.body.appendChild(this._frame); window.addEventListener("message", this._message, false); }); } start(session_state) { if (this._session_state === session_state) return; this._logger.create("start"); this.stop(); this._session_state = session_state; const send = () => { if (!this._frame.contentWindow || !this._session_state) return; this._frame.contentWindow.postMessage(this._client_id + " " + this._session_state, this._frame_origin); }; send(); this._timer = setInterval(send, this._intervalInSeconds * 1e3); } stop() { this._logger.create("stop"); this._session_state = null; if (this._timer) { clearInterval(this._timer); this._timer = null; } } }; var InMemoryWebStorage = class { constructor() { this._logger = new Logger("InMemoryWebStorage"); this._data = {}; } clear() { this._logger.create("clear"); this._data = {}; } getItem(key) { this._logger.create(`getItem('${key}')`); return this._data[key]; } setItem(key, value) { this._logger.create(`setItem('${key}')`); this._data[key] = value; } removeItem(key) { this._logger.create(`removeItem('${key}')`); delete this._data[key]; } get length() { return Object.getOwnPropertyNames(this._data).length; } key(index) { return Object.getOwnPropertyNames(this._data)[index]; } }; var ErrorDPoPNonce = class extends Error { constructor(nonce, message) { super(message); /** Marker to detect class: "ErrorDPoPNonce" */ this.name = "ErrorDPoPNonce"; this.nonce = nonce; } }; var JsonService = class { constructor(additionalContentTypes = [], _jwtHandler = null, _extraHeaders = {}) { this._jwtHandler = _jwtHandler; this._extraHeaders = _extraHeaders; this._logger = new Logger("JsonService"); this._contentTypes = []; this._contentTypes.push(...additionalContentTypes, "application/json"); if (_jwtHandler) this._contentTypes.push("application/jwt"); } async fetchWithTimeout(input, init = {}) { const { timeoutInSeconds, ...initFetch } = init; if (!timeoutInSeconds) return await fetch(input, initFetch); const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeoutInSeconds * 1e3); try { return await fetch(input, { ...init, signal: controller.signal }); } catch (err) { if (err instanceof DOMException && err.name === "AbortError") throw new ErrorTimeout("Network timed out"); throw err; } finally { clearTimeout(timeoutId); } } async getJson(url, { token, credentials, timeoutInSeconds } = {}) { const logger2 = this._logger.create("getJson"); const headers = { "Accept": this._contentTypes.join(", ") }; if (token) { logger2.debug("token passed, setting Authorization header"); headers["Authorization"] = "Bearer " + token; } this._appendExtraHeaders(headers); let response; try { logger2.debug("url:", url); response = await this.fetchWithTimeout(url, { method: "GET", headers, timeoutInSeconds, credentials }); } catch (err) { logger2.error("Network Error"); throw err; } logger2.debug("HTTP response received, status", response.status); const contentType = response.headers.get("Content-Type"); if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) logger2.throw(/* @__PURE__ */ new Error(`Invalid response Content-Type: ${contentType != null ? contentType : "undefined"}, from URL: ${url}`)); if (response.ok && this._jwtHandler && (contentType == null ? void 0 : contentType.startsWith("application/jwt"))) return await this._jwtHandler(await response.text()); let json; try { json = await response.json(); } catch (err) { logger2.error("Error parsing JSON response", err); if (response.ok) throw err; throw new Error(`${response.statusText} (${response.status})`); } if (!response.ok) { logger2.error("Error from server:", json); if (json.error) throw new ErrorResponse(json); throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`); } return json; } async postForm(url, { body, basicAuth, timeoutInSeconds, initCredentials, extraHeaders }) { const logger2 = this._logger.create("postForm"); const headers = { "Accept": this._contentTypes.join(", "), "Content-Type": "application/x-www-form-urlencoded", ...extraHeaders }; if (basicAuth !== void 0) headers["Authorization"] = "Basic " + basicAuth; this._appendExtraHeaders(headers); let response; try { logger2.debug("url:", url); response = await this.fetchWithTimeout(url, { method: "POST", headers, body, timeoutInSeconds, credentials: initCredentials }); } catch (err) { logger2.error("Network error"); throw err; } logger2.debug("HTTP response received, status", response.status); const contentType = response.headers.get("Content-Type"); if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) throw new Error(`Invalid response Content-Type: ${contentType != null ? contentType : "undefined"}, from URL: ${url}`); const responseText = await response.text(); let json = {}; if (responseText) try { json = JSON.parse(responseText); } catch (err) { logger2.error("Error parsing JSON response", err); if (response.ok) throw err; throw new Error(`${response.statusText} (${response.status})`); } if (!response.ok) { logger2.error("Error from server:", json); if (response.headers.has("dpop-nonce")) throw new ErrorDPoPNonce(response.headers.get("dpop-nonce"), `${JSON.stringify(json)}`); if (json.error) throw new ErrorResponse(json, body); throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`); } return json; } _appendExtraHeaders(headers) { const logger2 = this._logger.create("appendExtraHeaders"); const customKeys = Object.keys(this._extraHeaders); const protectedHeaders = ["accept", "content-type"]; const preventOverride = ["authorization"]; if (customKeys.length === 0) return; customKeys.forEach((headerName) => { if (protectedHeaders.includes(headerName.toLocaleLowerCase())) { logger2.warn("Protected header could not be set", headerName, protectedHeaders); return; } if (preventOverride.includes(headerName.toLocaleLowerCase()) && Object.keys(headers).includes(headerName)) { logger2.warn("Header could not be overridden", headerName, preventOverride); return; } const content = typeof this._extraHeaders[headerName] === "function" ? this._extraHeaders[headerName]() : this._extraHeaders[headerName]; if (content && content !== "") headers[headerName] = content; }); } }; var MetadataService = class { constructor(_settings) { this._settings = _settings; this._logger = new Logger("MetadataService"); this._signingKeys = null; this._metadata = null; this._metadataUrl = this._settings.metadataUrl; this._jsonService = new JsonService(["application/jwk-set+json"], null, this._settings.extraHeaders); if (this._settings.signingKeys) { this._logger.debug("using signingKeys from settings"); this._signingKeys = this._settings.signingKeys; } if (this._settings.metadata) { this._logger.debug("using metadata from settings"); this._metadata = this._settings.metadata; } if (this._settings.fetchRequestCredentials) { this._logger.debug("using fetchRequestCredentials from settings"); this._fetchRequestCredentials = this._settings.fetchRequestCredentials; } } resetSigningKeys() { this._signingKeys = null; } async getMetadata() { const logger2 = this._logger.create("getMetadata"); if (this._metadata) { logger2.debug("using cached values"); return this._metadata; } if (!this._metadataUrl) { logger2.throw(/* @__PURE__ */ new Error("No authority or metadataUrl configured on settings")); throw null; } logger2.debug("getting metadata from", this._metadataUrl); const metadata = await this._jsonService.getJson(this._metadataUrl, { credentials: this._fetchRequestCredentials, timeoutInSeconds: this._settings.requestTimeoutInSeconds }); logger2.debug("merging remote JSON with seed metadata"); this._metadata = Object.assign({}, metadata, this._settings.metadataSeed); return this._metadata; } getIssuer() { return this._getMetadataProperty("issuer"); } getAuthorizationEndpoint() { return this._getMetadataProperty("authorization_endpoint"); } getUserInfoEndpoint() { return this._getMetadataProperty("userinfo_endpoint"); } getTokenEndpoint(optional = true) { return this._getMetadataProperty("token_endpoint", optional); } getCheckSessionIframe() { return this._getMetadataProperty("check_session_iframe", true); } getEndSessionEndpoint() { return this._getMetadataProperty("end_session_endpoint", true); } getRevocationEndpoint(optional = true) { return this._getMetadataProperty("revocation_endpoint", optional); } getKeysEndpoint(optional = true) { return this._getMetadataProperty("jwks_uri", optional); } async _getMetadataProperty(name, optional = false) { const logger2 = this._logger.create(`_getMetadataProperty('${name}')`); const metadata = await this.getMetadata(); logger2.debug("resolved"); if (metadata[name] === void 0) { if (optional === true) { logger2.warn("Metadata does not contain optional property"); return; } logger2.throw(/* @__PURE__ */ new Error("Metadata does not contain property " + name)); } return metadata[name]; } async getSigningKeys() { const logger2 = this._logger.create("getSigningKeys"); if (this._signingKeys) { logger2.debug("returning signingKeys from cache"); return this._signingKeys; } const jwks_uri = await this.getKeysEndpoint(false); logger2.debug("got jwks_uri", jwks_uri); const keySet = await this._jsonService.getJson(jwks_uri, { timeoutInSeconds: this._settings.requestTimeoutInSeconds }); logger2.debug("got key set", keySet); if (!Array.isArray(keySet.keys)) { logger2.throw(/* @__PURE__ */ new Error("Missing keys on keyset")); throw null; } this._signingKeys = keySet.keys; return this._signingKeys; } }; var WebStorageStateStore = class { constructor({ prefix = "oidc.", store = localStorage } = {}) { this._logger = new Logger("WebStorageStateStore"); this._store = store; this._prefix = prefix; } async set(key, value) { this._logger.create(`set('${key}')`); key = this._prefix + key; await this._store.setItem(key, value); } async get(key) { this._logger.create(`get('${key}')`); key = this._prefix + key; return await this._store.getItem(key); } async remove(key) { this._logger.create(`remove('${key}')`); key = this._prefix + key; const item = await this._store.getItem(key); await this._store.removeItem(key); return item; } async getAllKeys() { this._logger.create("getAllKeys"); const len = await this._store.length; const keys = []; for (let index = 0; index < len; index++) { const key = await this._store.key(index); if (key && key.indexOf(this._prefix) === 0) keys.push(key.substr(this._prefix.length)); } return keys; } }; var DefaultResponseType = "code"; var DefaultScope = "openid"; var DefaultClientAuthentication = "client_secret_post"; var DefaultStaleStateAgeInSeconds = 900; var OidcClientSettingsStore = class { constructor({ authority, metadataUrl, metadata, signingKeys, metadataSeed, client_id, client_secret, response_type = DefaultResponseType, scope = DefaultScope, redirect_uri, post_logout_redirect_uri, client_authentication = DefaultClientAuthentication, token_endpoint_auth_signing_alg = "HS256", prompt, display, max_age, ui_locales, acr_values, resource, response_mode, filterProtocolClaims = true, loadUserInfo = false, requestTimeoutInSeconds, staleStateAgeInSeconds = DefaultStaleStateAgeInSeconds, mergeClaimsStrategy = { array: "replace" }, disablePKCE = false, stateStore, revokeTokenAdditionalContentTypes, fetchRequestCredentials, refreshTokenAllowedScope, extraQueryParams = {}, extraTokenParams = {}, extraHeaders = {}, dpop, omitScopeWhenRequesting = false }) { var _a; this.authority = authority; if (metadataUrl) this.metadataUrl = metadataUrl; else { this.metadataUrl = authority; if (authority) { if (!this.metadataUrl.endsWith("/")) this.metadataUrl += "/"; this.metadataUrl += ".well-known/openid-configuration"; } } this.metadata = metadata; this.metadataSeed = metadataSeed; this.signingKeys = signingKeys; this.client_id = client_id; this.client_secret = client_secret; this.response_type = response_type; this.scope = scope; this.redirect_uri = redirect_uri; this.post_logout_redirect_uri = post_logout_redirect_uri; this.client_authentication = client_authentication; this.token_endpoint_auth_signing_alg = token_endpoint_auth_signing_alg; this.prompt = prompt; this.display = display; this.max_age = max_age; this.ui_locales = ui_locales; this.acr_values = acr_values; this.resource = resource; this.response_mode = response_mode; this.filterProtocolClaims = filterProtocolClaims != null ? filterProtocolClaims : true; this.loadUserInfo = !!loadUserInfo; this.staleStateAgeInSeconds = staleStateAgeInSeconds; this.mergeClaimsStrategy = mergeClaimsStrategy; this.omitScopeWhenRequesting = omitScopeWhenRequesting; this.disablePKCE = !!disablePKCE; this.revokeTokenAdditionalContentTypes = revokeTokenAdditionalContentTypes; this.fetchRequestCredentials = fetchRequestCredentials ? fetchRequestCredentials : "same-origin"; this.requestTimeoutInSeconds = requestTimeoutInSeconds; if (stateStore) this.stateStore = stateStore; else { const store = typeof window !== "undefined" ? window.localStorage : new InMemoryWebStorage(); this.stateStore = new WebStorageStateStore({ store }); } this.refreshTokenAllowedScope = refreshTokenAllowedScope; this.extraQueryParams = extraQueryParams; this.extraTokenParams = extraTokenParams; this.extraHeaders = extraHeaders; this.dpop = dpop; if (this.dpop && !((_a = this.dpop) == null ? void 0 : _a.store)) throw new Error("A DPoPStore is required when dpop is enabled"); } }; var UserInfoService = class { constructor(_settings, _metadataService) { this._settings = _settings; this._metadataService = _metadataService; this._logger = new Logger("UserInfoService"); this._getClaimsFromJwt = async (responseText) => { const logger2 = this._logger.create("_getClaimsFromJwt"); try { const payload = JwtUtils.decode(responseText); logger2.debug("JWT decoding successful"); return payload; } catch (err) { logger2.error("Error parsing JWT response"); throw err; } }; this._jsonService = new JsonService(void 0, this._getClaimsFromJwt, this._settings.extraHeaders); } async getClaims(token) { const logger2 = this._logger.create("getClaims"); if (!token) this._logger.throw(/* @__PURE__ */ new Error("No token passed")); const url = await this._metadataService.getUserInfoEndpoint(); logger2.debug("got userinfo url", url); const claims = await this._jsonService.getJson(url, { token, credentials: this._settings.fetchRequestCredentials, timeoutInSeconds: this._settings.requestTimeoutInSeconds }); logger2.debug("got claims", claims); return claims; } }; var TokenClient = class { constructor(_settings, _metadataService) { this._settings = _settings; this._metadataService = _metadataService; this._logger = new Logger("TokenClient"); this._jsonService = new JsonService(this._settings.revokeTokenAdditionalContentTypes, null, this._settings.extraHeaders); } /** * Exchange code. * * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3 */ async exchangeCode({ grant_type = "authorization_code", redirect_uri = this._settings.redirect_uri, client_id = this._settings.client_id, client_secret = this._settings.client_secret, extraHeaders, ...args }) { const logger2 = this._logger.create("exchangeCode"); if (!client_id) logger2.throw(/* @__PURE__ */ new Error("A client_id is required")); if (!redirect_uri) logger2.throw(/* @__PURE__ */ new Error("A redirect_uri is required")); if (!args.code) logger2.throw(/* @__PURE__ */ new Error("A code is required")); const params = new URLSearchParams({ grant_type, redirect_uri }); for (const [key, value] of Object.entries(args)) if (value != null) params.set(key, value); if ((this._settings.client_authentication === "client_secret_basic" || this._settings.client_authentication === "client_secret_jwt") && (client_secret === void 0 || client_secret === null)) { logger2.throw(/* @__PURE__ */ new Error("A client_secret is required")); throw null; } let basicAuth; const url = await this._metadataService.getTokenEndpoint(false); switch (this._settings.client_authentication) { case "client_secret_basic": basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret); break; case "client_secret_post": params.append("client_id", client_id); if (client_secret) params.append("client_secret", client_secret); break; case "client_secret_jwt": { const clientAssertion = await CryptoUtils.generateClientAssertionJwt(client_id, client_secret, url, this._settings.token_endpoint_auth_signing_alg); params.append("client_id", client_id); params.append("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); params.append("client_assertion", clientAssertion); break; } } logger2.debug("got token endpoint"); const response = await this._jsonService.postForm(url, { body: params, basicAuth, timeoutInSeconds: this._settings.requestTimeoutInSeconds, initCredentials: this._settings.fetchRequestCredentials, extraHeaders }); logger2.debug("got response"); return response; } /** * Exchange credentials. * * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2 */ async exchangeCredentials({ grant_type = "password", client_id = this._settings.client_id, client_secret = this._settings.client_secret, scope = this._settings.scope, ...args }) { const logger2 = this._logger.create("exchangeCredentials"); if (!client_id) logger2.throw(/* @__PURE__ */ new Error("A client_id is required")); const params = new URLSearchParams({ grant_type }); if (!this._settings.omitScopeWhenRequesting) params.set("scope", scope); for (const [key, value] of Object.entries(args)) if (value != null) params.set(key, value); if ((this._settings.client_authentication === "client_secret_basic" || this._settings.client_authentication === "client_secret_jwt") && (client_secret === void 0 || client_secret === null)) { logger2.throw(/* @__PURE__ */ new Error("A client_secret is required")); throw null; } let basicAuth; const url = await this._metadataService.getTokenEndpoint(false); switch (this._settings.client_authentication) { case "client_secret_basic": basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret); break; case "client_secret_post": params.append("client_id", client_id); if (client_secret) params.append("client_secret", client_secret); break; case "client_secret_jwt": { const clientAssertion = await CryptoUtils.generateClientAssertionJwt(client_id, client_secret, url, this._settings.token_endpoint_auth_signing_alg); params.append("client_id", client_id); params.append("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); params.append("client_assertion", clientAssertion); break; } } logger2.debug("got token endpoint"); const response = await this._jsonService.postForm(url, { body: params, basicAuth, timeoutInSeconds: this._settings.requestTimeoutInSeconds, initCredentials: this._settings.fetchRequestCredentials }); logger2.debug("got response"); return response; } /** * Exchange a refresh token. * * @see https://www.rfc-editor.org/rfc/rfc6749#section-6 */ async exchangeRefreshToken({ grant_type = "refresh_token", client_id = this._settings.client_id, client_secret = this._settings.client_secret, timeoutInSeconds, extraHeaders, ...args }) { const logger2 = this._logger.create("exchangeRefreshToken"); if (!client_id) logger2.throw(/* @__PURE__ */ new Error("A client_id is required")); if (!args.refresh_token) logger2.throw(/* @__PURE__ */ new Error("A refresh_token is required")); const params = new URLSearchParams({ grant_type }); for (const [key, value] of Object.entries(args)) if (Array.isArray(value)) value.forEach((param) => params.append(key, param)); else if (value != null) params.set(key, value); if ((this._settings.client_authentication === "client_secret_basic" || this._settings.client_authentication === "client_secret_jwt") && (client_secret === void 0 || client_secret === null)) { logger2.throw(/* @__PURE__ */ new Error("A client_secret is required")); throw null; } let basicAuth; const url = await this._metadataService.getTokenEndpoint(false); switch (this._settings.client_authentication) { case "client_secret_basic": basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret); break; case "client_secret_post": params.append("client_id", client_id); if (client_secret) params.append("client_secret", client_secret); break; case "client_secret_jwt": { const clientAssertion = await CryptoUtils.generateClientAssertionJwt(client_id, client_secret, url, this._settings.token_endpoint_auth_signing_alg); params.append("client_id", client_id); params.append("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); params.append("client_assertion", clientAssertion); break; } } logger2.debug("got token endpoint"); const response = await this._jsonService.postForm(url, { body: params, basicAuth, timeoutInSeconds, initCredentials: this._settings.fetchRequestCredentials, extraHeaders }); logger2.debug("got response"); return response; } /** * Revoke an access or refresh token. * * @see https://datatracker.ietf.org/doc/html/rfc7009#section-2.1 */ async revoke(args) { var _a; const logger2 = this._logger.create("revoke"); if (!args.token) logger2.throw(/* @__PURE__ */ new Error("A token is required")); const url = await this._metadataService.getRevocationEndpoint(false); logger2.debug(`got revocation endpoint, revoking ${(_a = args.token_type_hint) != null ? _a : "default token type"}`); const params = new URLSearchParams(); for (const [key, value] of Object.entries(args)) if (value != null) params.set(key, value); params.set("client_id", this._settings.client_id); if (this._settings.client_secret) params.set("client_secret", this._settings.client_secret); await this._jsonService.postForm(url, { body: params, timeoutInSeconds: this._settings.requestTimeoutInSeconds }); logger2.debug("got response"); } }; var ResponseValidator = class { constructor(_settings, _metadataService, _claimsService) { this._settings = _settings; this._metadataService = _metadataService; this._claimsService = _claimsService; this._logger = new Logger("ResponseValidator"); this._userInfoService = new UserInfoService(this._settings, this._metadataService); this._tokenClient = new TokenClient(this._settings, this._metadataService); } async validateSigninResponse(response, state, extraHeaders) { const logger2 = this._logger.create("validateSigninResponse"); this._processSigninState(response, state); logger2.debug("state processed"); await this._processCode(response, state, extraHeaders); logger2.debug("code processed"); if (response.isOpenId) this._validateIdTokenAttributes(response, "", state.nonce); logger2.debug("tokens validated"); await this._processClaims(response, state == null ? void 0 : state.skipUserInfo, response.isOpenId); logger2.debug("claims processed"); } async validateCredentialsResponse(response, skipUserInfo) { const logger2 = this._logger.create("validateCredentialsResponse"); const shouldValidateSubClaim = response.isOpenId && !!response.id_token; if (shouldValidateSubClaim) this._validateIdTokenAttributes(response); logger2.debug("tokens validated"); await this._processClaims(response, skipUserInfo, shouldValidateSubClaim); logger2.debug("claims processed"); } async validateRefreshResponse(response, state) { const logger2 = this._logger.create("validateRefreshResponse"); response.userState = state.data; response.session_state ??= state.session_state; response.scope ??= state.scope; if (response.isOpenId && !!response.id_token) { this._validateIdTokenAttributes(response, state.id_token); logger2.debug("ID Token validated"); } if (!response.id_token) { response.id_token = state.id_token; response.profile = state.profile; } const hasIdToken = response.isOpenId && !!response.id_token; await this._processClaims(response, false, hasIdToken); logger2.debug("claims processed"); } validateSignoutResponse(response, state) { const logger2 = this._logger.create("validateSignoutResponse"); if (state.id !== response.state) logger2.throw(/* @__PURE__ */ new Error("State does not match")); logger2.debug("state validated"); response.userState = state.data; if (response.error) { logger2.warn("Response was error", response.error); throw new ErrorResponse(response); } } _processSigninState(response, state) { const logger2 = this._logger.create("_processSigninState"); if (state.id !== response.state) logger2.throw(/* @__PURE__ */ new Error("State does not match")); if (!state.client_id) logger2.throw(/* @__PURE__ */ new Error("No client_id on state")); if (!state.authority) logger2.throw(/* @__PURE__ */ new Error("No authority on state")); if (this._settings.authority !== state.authority) logger2.throw(/* @__PURE__ */ new Error("authority mismatch on settings vs. signin state")); if (this._settings.client_id && this._settings.client_id !== state.client_id) logger2.throw(/* @__PURE__ */ new Error("client_id mismatch on settings vs. signin state")); logger2.debug("state validated"); response.userState = state.data; response.url_state = state.url_state; response.scope ??= state.scope; if (response.error) { logger2.warn("Response was error", response.error); throw new ErrorResponse(response); } if (state.code_verifier && !response.code) logger2.throw(/* @__PURE__ */ new Error("Expected code in response")); } async _processClaims(response, skipUserInfo = false, validateSub = true) { const logger2 = this._logger.create("_processClaims"); response.profile = this._claimsService.filterProtocolClaims(response.profile); if (skipUserInfo || !this._settings.loadUserInfo || !response.access_token) { logger2.debug("not loading user info"); return; } logger2.debug("loading user info"); const claims = await this._userInfoService.getClaims(response.access_token); logger2.debug("user info claims received from user info endpoint"); if (validateSub && claims.sub !== response.profile.sub) logger2.throw(/* @__PURE__ */ new Error("subject from UserInfo response does not match subject in ID Token")); response.profile = this._claimsService.mergeClaims(response.profile, this._claimsService.filterProtocolClaims(claims)); logger2.debug("user info claims received, updated profile:", response.profile); } async _processCode(response, state, extraHeaders) { const logger2 = this._logger.create("_processCode"); if (response.code) { logger2.debug("Validating code"); const tokenResponse = await this._tokenClient.exchangeCode({ client_id: state.client_id, client_secret: state.client_secret, code: response.code, redirect_uri: state.redirect_uri, code_verifier: state.code_verifier, extraHeaders, ...state.extraTokenParams }); Object.assign(response, tokenResponse); } else logger2.debug("No code to process"); } _validateIdTokenAttributes(response, existingToken, nonce) { var _a; const logger2 = this._logger.create("_validateIdTokenAttributes"); logger2.debug("decoding ID Token JWT"); const incoming = JwtUtils.decode((_a = response.id_token) != null ? _a : ""); if (!incoming.sub) logger2.throw(/* @__PURE__ */ new Error("ID Token is missing a subject claim")); if (nonce && incoming.nonce !== nonce) logger2.throw(/* @__PURE__ */ new Error("nonce in id_token does not match nonce in client storage")); if (existingToken) { const existing = JwtUtils.decode(existingToken); if (incoming.sub !== existing.sub) logger2.throw(/* @__PURE__ */ new Error("sub in id_token does not match current sub")); if (incoming.auth_time && incoming.auth_time !== existing.auth_time) logger2.throw(/* @__PURE__ */ new Error("auth_time in id_token does not match original auth_time")); if (incoming.azp && incoming.azp !== existing.azp) logger2.throw(/* @__PURE__ */ new Error("azp in id_token does not match original azp")); if (!incoming.azp && existing.azp) logger2.throw(/* @__PURE__ */ new Error("azp not in id_token, but present in original id_token")); } response.profile = incoming; } }; var State = class _State { constructor(args) { this.id = args.id || CryptoUtils.generateUUIDv4(); this.data = args.data; if (args.created && args.created > 0) this.created = args.created; else this.created = Timer.getEpochTime(); this.request_type = args.request_type; this.url_state = args.url_state; } toStorageString() { new Logger("State").create("toStorageString"); return JSON.stringify({ id: this.id, data: this.data, created: this.created, request_type: this.request_type, url_state: this.url_state }); } static fromStorageString(storageString) { Logger.createStatic("State", "fromStorageString"); return Promise.resolve(new _State(JSON.parse(storageString))); } static async clearStaleState(storage, age) { const logger2 = Logger.createStatic("State", "clearStaleState"); const cutoff = Timer.getEpochTime() - age; const keys = await storage.getAllKeys(); logger2.debug("got keys", keys); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const item = await storage.get(key); let remove = false; if (item) try { const state = await _State.fromStorageString(item); logger2.debug("got item from key:", key, state.created); if (state.created <= cutoff) remove = true; } catch (err) { logger2.error("Error parsing state for key:", key, err); remove = true; } else { logger2.debug("no item in storage for key:", key); remove = true; } if (remove) { logger2.debug("removed item for key:", key); storage.remove(key); } } } }; var SigninState = class _SigninState extends State { constructor(args) { super(args); this.code_verifier = args.code_verifier; this.code_challenge = args.code_challenge; this.authority = args.authority; this.client_id = args.client_id; this.redirect_uri = args.redirect_uri; this.scope = args.scope; this.client_secret = args.client_secret; this.extraTokenParams = args.extraTokenParams; this.response_mode = args.response_mode; this.skipUserInfo = args.skipUserInfo; this.nonce = args.nonce; } static async create(args) { const code_verifier = args.code_verifier === true ? CryptoUtils.generateCodeVerifier() : args.code_verifier || void 0; const code_challenge = code_verifier ? await CryptoUtils.generateCodeChallenge(code_verifier) : void 0; return new _SigninState({ ...args, code_verifier, code_challenge }); } toStorageString() { new Logger("SigninState").create("toStorageString"); return JSON.stringify({ id: this.id, data: this.data, created: this.created, request_type: this.request_type, url_state: this.url_state, code_verifier: this.code_verifier, authority: this.authority, client_id: this.client_id, redirect_uri: this.redirect_uri, scope: this.scope, client_secret: this.client_secret, extraTokenParams: this.extraTokenParams, response_mode: this.response_mode, skipUserInfo: this.skipUserInfo, nonce: this.nonce }); } static fromStorageString(storageString) { Logger.createStatic("SigninState", "fromStorageString"); const data = JSON.parse(storageString); return _SigninState.create(data); } }; var _SigninRequest = class _SigninRequest { constructor(args) { this.url = args.url; this.state = args.state; } static async create({ url, authority, client_id, redirect_uri, response_type, scope, state_data, response_mode, request_type, client_secret, nonce, url_state, resource, skipUserInfo, extraQueryParams, extraTokenParams, disablePKCE, dpopJkt, omitScopeWhenRequesting, ...optionalParams }) { if (!url) { this._logger.error("create: No url passed"); throw new Error("url"); } if (!client_id) { this._logger.error("create: No client_id passed"); throw new Error("client_id"); } if (!redirect_uri) { this._logger.error("create: No redirect_uri passed"); throw new Error("redirect_uri"); } if (!response_type) { this._logger.error("create: No response_type passed"); throw new Error("response_type"); } if (!scope) { this._logger.error("create: No scope passed"); throw new Error("scope"); } if (!authority) { this._logger.error("create: No authority passed"); throw new Error("authority"); } const state = await SigninState.create({ data: state_data, request_type, url_state, code_verifier: !disablePKCE, client_id, authority, redirect_uri, response_mode, client_secret, scope, extraTokenParams, skipUserInfo, nonce }); const parsedUrl = new URL(url); parsedUrl.searchParams.append("client_id", client_id); parsedUrl.searchParams.append("redirect_uri", redirect_uri); parsedUrl.searchParams.append("response_type", response_type); if (!omitScopeWhenRequesting) parsedUrl.searchParams.append("scope", scope); if (nonce) parsedUrl.searchParams.append("nonce", nonce); if (dpopJkt) parsedUrl.searchParams.append("dpop_jkt", dpopJkt); let stateParam = state.id; if (url_state) stateParam = `${stateParam}${URL_STATE_DELIMITER}${url_state}`; parsedUrl.searchParams.append("state", stateParam); if (state.code_challenge) { parsedUrl.searchParams.append("code_challenge", state.code_challenge); parsedUrl.searchParams.append("code_challenge_method", "S256"); } if (resource) (Array.isArray(resource) ? resource : [resource]).forEach((r) => parsedUrl.searchParams.append("resource", r)); for (const [key, value] of Object.entries({ response_mode, ...optionalParams, ...extraQueryParams })) if (value != null) parsedUrl.searchParams.append(key, value.toString()); return new _SigninRequest({ url: parsedUrl.href, state }); } }; _SigninRequest._logger = new Logger("SigninRequest"); var SigninRequest = _SigninRequest; var OidcScope = "openid"; var SigninResponse = class { constructor(params) { /** @see {@link User.access_token} */ this.access_token = ""; /** @see {@link User.token_type} */ this.token_type = ""; /** @see {@link User.profile} */ this.profile = {}; this.state = params.get("state"); this.session_state = params.get("session_state"); if (this.state) { const splitState = decodeURIComponent(this.state).split(URL_STATE_DELIMITER); this.state = splitState[0]; if (splitState.length > 1) this.url_state = splitState.slice(1).join(URL_STATE_DELIMITER); } this.error = params.get("error"); this.error_description = params.get("error_description"); this.error_uri = params.get("error_uri"); this.code = params.get("code"); } get expires_in() { if (this.expires_at === void 0) return; return this.expires_at - Timer.getEpochTime(); } set expires_in(value) { if (typeof value === "string") value = Number(value); if (value !== void 0 && value >= 0) this.expires_at = Math.floor(value) + Timer.getEpochTime(); } get isOpenId() { var _a; return ((_a = this.scope) == null ? void 0 : _a.split(" ").includes(OidcScope)) || !!this.id_token; } }; var SignoutRequest = class { constructor({ url, state_data, id_token_hint, post_logout_redirect_uri, extraQueryParams, request_type, client_id, url_state }) { this._logger = new Logger("SignoutRequest"); if (!url) { this._logger.error("ctor: No url passed"); throw new Error("url"); } const parsedUrl = new URL(url); if (id_token_hint) parsedUrl.searchParams.append("id_token_hint", id_token_hint); if (client_id) parsedUrl.searchParams.append("client_id", client_id); if (post_logout_redirect_uri) { parsedUrl.searchParams.append("post_logout_redirect_uri", post_logout_redirect_uri); if (state_data || url_state) { this.state = new State({ data: state_data, request_type, url_state }); let stateParam = this.state.id; if (url_state) stateParam = `${stateParam}${URL_STATE_DELIMITER}${url_state}`; parsedUrl.searchParams.append("state", stateParam); } } for (const [key, value] of Object.entries({ ...extraQueryParams })) if (value != null) parsedUrl.searchParams.append(key, value.toString()); this.url = parsedUrl.href; } }; var SignoutResponse = class { constructor(params) { this.state = params.get("state"); if (this.state) { const splitState = decodeURIComponent(this.state).split(URL_STATE_DELIMITER); this.state = splitState[0]; if (splitState.length > 1) this.url_state = splitState.slice(1).join(URL_STATE_DELIMITER); } this.error = params.get("error"); this.error_description = params.get("error_description"); this.error_uri = params.get("error_uri"); } }; var DefaultProtocolClaims = [ "nbf", "jti", "auth_time", "nonce", "acr", "amr", "azp", "at_hash" ]; var InternalRequiredProtocolClaims = [ "sub", "iss", "aud", "exp", "iat" ]; var ClaimsService = class { constructor(_settings) { this._settings = _settings; this._logger = new Logger("ClaimsService"); } filterProtocolClaims(claims) { const result = { ...claims }; if (this._settings.filterProtocolClaims) { let protocolClaims; if (Array.isArray(this._settings.filterProtocolClaims)) protocolClaims = this._settings.filterProtocolClaims; else protocolClaims = DefaultProtocolClaims; for (const claim of protocolClaims) if (!InternalRequiredProtocolClaims.includes(claim)) delete result[claim]; } return result; } mergeClaims(claims1, claims2) { const result = { ...claims1 }; for (const [claim, values] of Object.entries(claims2)) if (result[claim] !== values) if (Array.isArray(result[claim]) || Array.isArray(values)) if (this._settings.mergeClaimsStrategy.array == "replace") result[claim] = values; else { const mergedValues = Array.isArray(result[claim]) ? result[claim] : [result[claim]]; for (const value of Array.isArray(values) ? values : [values]) if (!mergedValues.includes(value)) mergedValues.push(value); result[claim] = mergedValues; } else if (typeof result[claim] === "object" && typeof values === "object") result[claim] = this.mergeClaims(result[claim], values); else result[claim] = values; return result; } }; var DPoPState = class { constructor(keys, nonce) { this.keys = keys; this.nonce = nonce; } }; var OidcClient = class { constructor(settings, metadataService) { this._logger = new Logger("OidcClient"); this.settings = settings instanceof OidcClientSettingsStore ? settings : new OidcClientSettingsStore(settings); this.metadataService = metadataService != null ? metadataService : new MetadataService(this.settings); this._claimsService = new ClaimsService(this.settings); this._validator = new ResponseValidator(this.settings, this.metadataService, this._claimsService); this._tokenClient = new TokenClient(this.settings, this.metadataService); } async createSigninRequest({ state, request, request_uri, request_type, id_token_hint, login_hint, skipUserInfo, nonce, url_state, response_type = this.settings.response_type, scope = this.settings.scope, redirect_uri = this.settings.redirect_uri, prompt = this.settings.prompt, display = this.settings.display, max_age = this.settings.max_age, ui_locales = this.settings.ui_locales, acr_values = this.settings.acr_values, resource = this.settings.resource, response_mode = this.settings.response_mode, extraQueryParams = this.settings.extraQueryParams, extraTokenParams = this.settings.extraTokenParams, dpopJkt, omitScopeWhenRequesting = this.settings.omitScopeWhenRequesting }) { const logger2 = this._logger.create("createSigninRequest"); if (response_type !== "code") throw new Error("Only the Authorization Code flow (with PKCE) is supported"); const url = await this.metadataService.getAuthorizationEndpoint(); logger2.debug("Received authorization endpoint", url); const signinRequest = await SigninRequest.create({ url, authority: this.settings.authority, client_id: this.settings.client_id, redirect_uri, response_type, scope, state_data: state, url_state, prompt, display, max_age, ui_locales, id_token_hint, login_hint, acr_values, dpopJkt, resource, request, request_uri, extraQueryParams, extraTokenParams, request_type, response_mode, client_secret: this.settings.client_secret, skipUserInfo, nonce, disablePKCE: this.settings.disablePKCE, omitScopeWhenRequesting }); await this.clearStaleState(); const signinState = signinRequest.state; await this.settings.stateStore.set(signinState.id, signinState.toStorageString()); return signinRequest; } async readSigninResponseState(url, removeState = false) { const logger2 = this._logger.create("readSigninResponseState"); const response = new SigninResponse(UrlUtils.readParams(url, this.settings.response_mode)); if (!response.state) { logger2.throw(/* @__PURE__ */ new Error("No state in response")); throw null; } const storedStateString = await this.settings.stateStore[removeState ? "remove" : "get"](response.state); if (!storedStateString) { logger2.throw(/* @__PURE__ */ new Error("No matching state found in storage")); throw null; } return { state: await SigninState.fromStorageString(storedStateString), response }; } async processSigninResponse(url, extraHeaders, removeState = true) { const logger2 = this._logger.create("processSigninResponse"); const { state, response } = await this.readSigninResponseState(url, removeState); logger2.debug("received state from storage; validating response"); if (this.settings.dpop && this.settings.dpop.store) { const dpopProof = await this.getDpopProof(this.settings.dpop.store); extraHeaders = { ...extraHeaders, "DPoP": dpopProof }; } try { await this._validator.validateSigninResponse(response, state, extraHeaders); } catch (err) { if (err instanceof ErrorDPoPNonce && this.settings.dpop) { const dpopProof = await this.getDpopProof(this.settings.dpop.store, err.nonce); extraHeaders["DPoP"] = dpopProof; await this._validator.validateSigninResponse(response, state, extraHeaders); } else throw err; } return response; } async getDpopProof(dpopStore, nonce) { let keyPair; let dpopState; if (!(await dpopStore.getAllKeys()).includes(this.settings.client_id)) { keyPair = await CryptoUtils.generateDPoPKeys(); dpopState = new DPoPState(keyPair, nonce); await dpopStore.set(this.settings.client_id, dpopState); } else { dpopState = await dpopStore.get(this.settings.client_id); if (dpopState.nonce !== nonce && nonce) { dpopState.nonce = nonce; await dpopStore.set(this.settings.client_id, dpopState); } } return await CryptoUtils.generateDPoPProof({ url: await this.metadataService.getTokenEndpoint(false), httpMethod: "POST", keyPair: dpopState.keys, nonce: dpopState.nonce }); } async processResourceOwnerPasswordCredentials({ username, password, skipUserInfo = false, extraTokenParams = {} }) { const tokenResponse = await this._tokenClient.exchangeCredentials({ username, password, ...extraTokenParams }); const signinResponse = new SigninResponse(new URLSearchParams()); Object.assign(signinResponse, tokenResponse); await this._validator.validateCredentialsResponse(signinResponse, skipUserInfo); return signinResponse; } async useRefreshToken({ state, redirect_uri, resource, timeoutInSeconds, extraHeaders, extraTokenParams }) { var _a; const logger2 = this._logger.create("useRefreshToken"); let scope; if (this.settings.refreshTokenAllowedScope === void 0) scope = state.scope; else { const allowableScopes = this.settings.refreshTokenAllowedScope.split(" "); scope = (((_a = state.scope) == null ? void 0 : _a.split(" ")) || []).filter((s) => allowableScopes.includes(s)).join(" "); } if (this.settings.dpop && this.settings.dpop.store) { const dpopProof = await this.getDpopProof(this.settings.dpop.store); extraHeaders = { ...extraHeaders, "DPoP": dpopProof }; } let result; try { result = await this._tokenClient.exchangeRefreshToken({ refresh_token: state.refresh_token, scope, redirect_uri, resource, timeoutInSeconds, extraHeaders, ...extraTokenParams }); } catch (err) { if (err instanceof ErrorDPoPNonce && this.settings.dpop) { extraHeaders["DPoP"] = await this.getDpopProof(this.settings.dpop.store, err.nonce); result = await this._tokenClient.exchangeRefreshToken({ refresh_token: state.refresh_token, scope, redirect_uri, resource, timeoutInSeconds, extraHeaders, ...extraTokenParams }); } else throw err; } const response = new SigninResponse(new URLSearchParams()); Object.assign(response, result); logger2.debug("validating response", response); await this._validator.validateRefreshResponse(response, { ...state, scope }); return response; } async createSignoutRequest({ state, id_token_hint, client_id, request_type, url_state, post_logout_redirect_uri = this.settings.post_logout_redirect_uri, extraQueryParams = this.settings.extraQueryParams } = {}) { const logger2 = this._logger.create("createSignoutRequest"); const url = await this.metadataService.getEndSessionEndpoint(); if (!url) { logger2.throw(/* @__PURE__ */ new Error("No end session endpoint")); throw null; } logger2.debug("Received end session endpoint", url); if (!client_id && post_logout_redirect_uri && !id_token_hint) client_id = this.settings.client_id; const request = new SignoutRequest({ url, id_token_hint, client_id, post_logout_redirect_uri, state_data: state, extraQueryParams, request_type, url_state }); await this.clearStaleState(); const signoutState = request.state; if (signoutState) { logger2.debug("Signout request has state to persist"); await this.settings.stateStore.set(signoutState.id, signoutState.toStorageString()); } return request; } async readSignoutResponseState(url, removeState = false) { const logger2 = this._logger.create("readSignoutResponseState"); const response = new SignoutResponse(UrlUtils.readParams(url, this.settings.response_mode)); if (!response.state) { logger2.debug("No state in response"); if (response.error) { logger2.warn("Response was error:", response.error); throw new ErrorResponse(response); } return { state: void 0, response }; } const storedStateString = await this.settings.stateStore[removeState ? "remove" : "get"](response.state); if (!storedStateString) { logger2.throw(/* @__PURE__ */ new Error("No matching state found in storage")); throw null; } return { state: await State.fromStorageString(storedStateString), response }; } async processSignoutResponse(url) { const logger2 = this._logger.create("processSignoutResponse"); const { state, response } = await this.readSignoutResponseState(url, true); if (state) { logger2.debug("Received state from storage; validating response"); this._validator.validateSignoutResponse(response, state); } else logger2.debug("No state from storage; skipping response validation"); return response; } clearStaleState() { this._logger.create("clearStaleState"); return State.clearStaleState(this.settings.stateStore, this.settings.staleStateAgeInSeconds); } async revokeToken(token, type) { this._logger.create("revokeToken"); return await this._tokenClient.revoke({ token, token_type_hint: type }); } }; var SessionMonitor = class { constructor(_userManager) { this._userManager = _userManager; this._logger = new Logger("SessionMonitor"); this._start = async (user) => { const session_state = user.session_state; if (!session_state) return; const logger2 = this._logger.create("_start"); if (user.profile) { this._sub = user.profile.sub; logger2.debug("session_state", session_state, ", sub", this._sub); } else { this._sub = void 0; logger2.debug("session_state", session_state, ", anonymous user"); } if (this._checkSessionIFrame) { this._checkSessionIFrame.start(session_state); return; } try { const url = await this._userManager.metadataService.getCheckSessionIframe(); if (url) { logger2.debug("initializing check session iframe"); const client_id = this._userManager.settings.client_id; const intervalInSeconds = this._userManager.settings.checkSessionIntervalInSeconds; const stopOnError = this._userManager.settings.stopCheckSessionOnError; const checkSessionIFrame = new CheckSessionIFrame(this._callback, client_id, url, intervalInSeconds, stopOnError); await checkSessionIFrame.load(); this._checkSessionIFrame = checkSessionIFrame; checkSessionIFrame.start(session_state); } else logger2.warn("no check session iframe found in the metadata"); } catch (err) { logger2.error("Error from getCheckSessionIframe:", err instanceof Error ? err.message : err); } }; this._stop = () => { const logger2 = this._logger.create("_stop"); this._sub = void 0; if (this._checkSessionIFrame) this._checkSessionIFrame.stop(); if (this._userManager.settings.monitorAnonymousSession) { const timerHandle = setInterval(async () => { clearInterval(timerHandle); try { const session = await this._userManager.querySessionStatus(); if (session) { const tmpUser = { session_state: session.session_state, profile: session.sub ? { sub: session.sub } : null }; this._start(tmpUser); } } catch (err) { logger2.error("error from querySessionStatus", err instanceof Error ? err.message : err); } }, 1e3); } }; this._callback = async () => { const logger2 = this._logger.create("_callback"); try { const session = await this._userManager.querySessionStatus(); let raiseEvent = true; if (session && this._checkSessionIFrame) if (session.sub === this._sub) { raiseEvent = false; this._checkSessionIFrame.start(session.session_state); logger2.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state", session.session_state); await this._userManager.events._raiseUserSessionChanged(); } else logger2.debug("different subject signed into OP", session.sub); else logger2.debug("subject no longer signed into OP"); if (raiseEvent) if (this._sub) await this._userManager.events._raiseUserSignedOut(); else await this._userManager.events._raiseUserSignedIn(); else logger2.debug("no change in session detected, no event to raise"); } catch (err) { if (this._sub) { logger2.debug("Error calling queryCurrentSigninSession; raising signed out event", err); await this._userManager.events._raiseUserSignedOut(); } } }; if (!_userManager) this._logger.throw(/* @__PURE__ */ new Error("No user manager passed")); this._userManager.events.addUserLoaded(this._start); this._userManager.events.addUserUnloaded(this._stop); this._init().catch((err) => { this._logger.error(err); }); } async _init() { this._logger.create("_init"); const user = await this._userManager.getUser(); if (user) this._start(user); else if (this._userManager.settings.monitorAnonymousSession) { const session = await this._userManager.querySessionStatus(); if (session) { const tmpUser = { session_state: session.session_state, profile: session.sub ? { sub: session.sub } : null }; this._start(tmpUser); } } } }; var User = class _User { constructor(args) { var _a; this.id_token = args.id_token; this.session_state = (_a = args.session_state) != null ? _a : null; this.access_token = args.access_token; this.refresh_token = args.refresh_token; this.token_type = args.token_type; this.scope = args.scope; this.profile = args.profile; this.expires_at = args.expires_at; this.state = args.userState; this.url_state = args.url_state; } /** Computed number of seconds the access token has remaining. */ get expires_in() { if (this.expires_at === void 0) return; return this.expires_at - Timer.getEpochTime(); } set expires_in(value) { if (value !== void 0) this.expires_at = Math.floor(value) + Timer.getEpochTime(); } /** Computed value indicating if the access token is expired. */ get expired() { const expires_in = this.expires_in; if (expires_in === void 0) return; return expires_in <= 0; } /** Array representing the parsed values from the `scope`. */ get scopes() { var _a, _b; return (_b = (_a = this.scope) == null ? void 0 : _a.split(" ")) != null ? _b : []; } toStorageString() { new Logger("User").create("toStorageString"); return JSON.stringify({ id_token: this.id_token, session_state: this.session_state, access_token: this.access_token, refresh_token: this.refresh_token, token_type: this.token_type, scope: this.scope, profile: this.profile, expires_at: this.expires_at }); } static fromStorageString(storageString) { Logger.createStatic("User", "fromStorageString"); return new _User(JSON.parse(storageString)); } }; var messageSource = "oidc-client"; var AbstractChildWindow = class { constructor() { this._abort = new Event$1("Window navigation aborted"); this._disposeHandlers = /* @__PURE__ */ new Set(); this._window = null; } async navigate(params) { const logger2 = this._logger.create("navigate"); if (!this._window) throw new Error("Attempted to navigate on a disposed window"); logger2.debug("setting URL in window"); this._window.location.replace(params.url); const { url, keepOpen } = await new Promise((resolve, reject) => { const listener = (e) => { var _a; const data = e.data; const origin = (_a = params.scriptOrigin) != null ? _a : window.location.origin; if (e.origin !== origin || (data == null ? void 0 : data.source) !== messageSource) return; try { const state = UrlUtils.readParams(data.url, params.response_mode).get("state"); if (!state) logger2.warn("no state found in response url"); if (e.source !== this._window && state !== params.state) return; } catch { this._dispose(); reject(/* @__PURE__ */ new Error("Invalid response from window")); } resolve(data); }; window.addEventListener("message", listener, false); this._disposeHandlers.add(() => window.removeEventListener("message", listener, false)); const channel = new BroadcastChannel(`oidc-client-popup-${params.state}`); channel.addEventListener("message", listener, false); this._disposeHandlers.add(() => channel.close()); this._disposeHandlers.add(this._abort.addHandler((reason) => { this._dispose(); reject(reason); })); }); logger2.debug("got response from window"); this._dispose(); if (!keepOpen) this.close(); return { url }; } _dispose() { this._logger.create("_dispose"); for (const dispose of this._disposeHandlers) dispose(); this._disposeHandlers.clear(); } static _notifyParent(parent, url, keepOpen = false, targetOrigin = window.location.origin) { const msgData = { source: messageSource, url, keepOpen }; const logger2 = new Logger("_notifyParent"); if (parent) { logger2.debug("With parent. Using parent.postMessage."); parent.postMessage(msgData, targetOrigin); } else { logger2.debug("No parent. Using BroadcastChannel."); const state = new URL(url).searchParams.get("state"); if (!state) throw new Error("No parent and no state in URL. Can't complete notification."); const channel = new BroadcastChannel(`oidc-client-popup-${state}`); channel.postMessage(msgData); channel.close(); } } }; var DefaultPopupWindowFeatures = { location: false, toolbar: false, height: 640, closePopupWindowAfterInSeconds: -1 }; var DefaultPopupTarget = "_blank"; var DefaultAccessTokenExpiringNotificationTimeInSeconds = 60; var DefaultCheckSessionIntervalInSeconds = 2; var DefaultSilentRequestTimeoutInSeconds = 10; var UserManagerSettingsStore = class extends OidcClientSettingsStore { constructor(args) { const { popup_redirect_uri = args.redirect_uri, popup_post_logout_redirect_uri = args.post_logout_redirect_uri, popupWindowFeatures = DefaultPopupWindowFeatures, popupWindowTarget = DefaultPopupTarget, redirectMethod = "assign", redirectTarget = "self", iframeNotifyParentOrigin = args.iframeNotifyParentOrigin, iframeScriptOrigin = args.iframeScriptOrigin, requestTimeoutInSeconds, silent_redirect_uri = args.redirect_uri, silentRequestTimeoutInSeconds, automaticSilentRenew = true, validateSubOnSilentRenew = true, includeIdTokenInSilentRenew = false, monitorSession = false, monitorAnonymousSession = false, checkSessionIntervalInSeconds = DefaultCheckSessionIntervalInSeconds, query_status_response_type = "code", stopCheckSessionOnError = true, revokeTokenTypes = ["access_token", "refresh_token"], revokeTokensOnSignout = false, includeIdTokenInSilentSignout = false, accessTokenExpiringNotificationTimeInSeconds = DefaultAccessTokenExpiringNotificationTimeInSeconds, maxSilentRenewTimeoutRetries, userStore } = args; super(args); this.popup_redirect_uri = popup_redirect_uri; this.popup_post_logout_redirect_uri = popup_post_logout_redirect_uri; this.popupWindowFeatures = popupWindowFeatures; this.popupWindowTarget = popupWindowTarget; this.redirectMethod = redirectMethod; this.redirectTarget = redirectTarget; this.iframeNotifyParentOrigin = iframeNotifyParentOrigin; this.iframeScriptOrigin = iframeScriptOrigin; this.silent_redirect_uri = silent_redirect_uri; this.silentRequestTimeoutInSeconds = silentRequestTimeoutInSeconds || requestTimeoutInSeconds || DefaultSilentRequestTimeoutInSeconds; this.automaticSilentRenew = automaticSilentRenew; this.validateSubOnSilentRenew = validateSubOnSilentRenew; this.includeIdTokenInSilentRenew = includeIdTokenInSilentRenew; this.monitorSession = monitorSession; this.monitorAnonymousSession = monitorAnonymousSession; this.checkSessionIntervalInSeconds = checkSessionIntervalInSeconds; this.stopCheckSessionOnError = stopCheckSessionOnError; this.query_status_response_type = query_status_response_type; this.revokeTokenTypes = revokeTokenTypes; this.revokeTokensOnSignout = revokeTokensOnSignout; this.includeIdTokenInSilentSignout = includeIdTokenInSilentSignout; this.accessTokenExpiringNotificationTimeInSeconds = accessTokenExpiringNotificationTimeInSeconds; this.maxSilentRenewTimeoutRetries = maxSilentRenewTimeoutRetries; if (userStore) this.userStore = userStore; else { const store = typeof window !== "undefined" ? window.sessionStorage : new InMemoryWebStorage(); this.userStore = new WebStorageStateStore({ store }); } } }; var IFrameWindow = class _IFrameWindow extends AbstractChildWindow { constructor({ silentRequestTimeoutInSeconds = DefaultSilentRequestTimeoutInSeconds }) { super(); this._logger = new Logger("IFrameWindow"); this._timeoutInSeconds = silentRequestTimeoutInSeconds; this._frame = _IFrameWindow.createHiddenIframe(); this._window = this._frame.contentWindow; } static createHiddenIframe() { const iframe = window.document.createElement("iframe"); iframe.style.visibility = "hidden"; iframe.style.position = "fixed"; iframe.style.left = "-1000px"; iframe.style.top = "0"; iframe.width = "0"; iframe.height = "0"; window.document.body.appendChild(iframe); return iframe; } async navigate(params) { this._logger.debug("navigate: Using timeout of:", this._timeoutInSeconds); const timer = setTimeout(() => void this._abort.raise(new ErrorTimeout("IFrame timed out without a response")), this._timeoutInSeconds * 1e3); this._disposeHandlers.add(() => clearTimeout(timer)); return await super.navigate(params); } close() { var _a; if (this._frame) { if (this._frame.parentNode) { this._frame.addEventListener("load", (ev) => { var _a2; const frame = ev.target; (_a2 = frame.parentNode) == null || _a2.removeChild(frame); this._abort.raise(/* @__PURE__ */ new Error("IFrame removed from DOM")); }, true); (_a = this._frame.contentWindow) == null || _a.location.replace("about:blank"); } this._frame = null; } this._window = null; } static notifyParent(url, targetOrigin) { return super._notifyParent(window.parent, url, false, targetOrigin); } }; var IFrameNavigator = class { constructor(_settings) { this._settings = _settings; this._logger = new Logger("IFrameNavigator"); } async prepare({ silentRequestTimeoutInSeconds = this._settings.silentRequestTimeoutInSeconds }) { return new IFrameWindow({ silentRequestTimeoutInSeconds }); } async callback(url) { this._logger.create("callback"); IFrameWindow.notifyParent(url, this._settings.iframeNotifyParentOrigin); } }; var checkForPopupClosedInterval = 500; var second = 1e3; var PopupWindow = class extends AbstractChildWindow { constructor({ popupWindowTarget = DefaultPopupTarget, popupWindowFeatures = {}, popupSignal, popupAbortOnClose }) { super(); this._logger = new Logger("PopupWindow"); const centeredPopup = PopupUtils.center({ ...DefaultPopupWindowFeatures, ...popupWindowFeatures }); this._window = window.open(void 0, popupWindowTarget, PopupUtils.serialize(centeredPopup)); this.abortOnClose = Boolean(popupAbortOnClose); if (popupSignal) popupSignal.addEventListener("abort", () => { var _a; this._abort.raise(new Error((_a = popupSignal.reason) != null ? _a : "Popup aborted")); }); if (popupWindowFeatures.closePopupWindowAfterInSeconds && popupWindowFeatures.closePopupWindowAfterInSeconds > 0) setTimeout(() => { if (!this._window || typeof this._window.closed !== "boolean" || this._window.closed) { this._abort.raise(/* @__PURE__ */ new Error("Popup blocked by user")); return; } this.close(); }, popupWindowFeatures.closePopupWindowAfterInSeconds * second); } async navigate(params) { var _a; (_a = this._window) == null || _a.focus(); const popupClosedInterval = setInterval(() => { if (!this._window || this._window.closed) { this._logger.debug("Popup closed by user or isolated by redirect"); clearPopupClosedInterval(); this._disposeHandlers.delete(clearPopupClosedInterval); if (this.abortOnClose) this._abort.raise(/* @__PURE__ */ new Error("Popup closed by user")); } }, checkForPopupClosedInterval); const clearPopupClosedInterval = () => clearInterval(popupClosedInterval); this._disposeHandlers.add(clearPopupClosedInterval); return await super.navigate(params); } close() { if (this._window) { if (!this._window.closed) { this._window.close(); this._abort.raise(/* @__PURE__ */ new Error("Popup closed")); } } this._window = null; } static notifyOpener(url, keepOpen) { super._notifyParent(window.opener, url, keepOpen); if (!keepOpen && !window.opener) window.close(); } }; var PopupNavigator = class { constructor(_settings) { this._settings = _settings; this._logger = new Logger("PopupNavigator"); } async prepare({ popupWindowFeatures = this._settings.popupWindowFeatures, popupWindowTarget = this._settings.popupWindowTarget, popupSignal, popupAbortOnClose }) { return new PopupWindow({ popupWindowFeatures, popupWindowTarget, popupSignal, popupAbortOnClose }); } async callback(url, { keepOpen = false }) { this._logger.create("callback"); PopupWindow.notifyOpener(url, keepOpen); } }; var RedirectNavigator = class { constructor(_settings) { this._settings = _settings; this._logger = new Logger("RedirectNavigator"); } async prepare({ redirectMethod = this._settings.redirectMethod, redirectTarget = this._settings.redirectTarget }) { var _a; this._logger.create("prepare"); let targetWindow = window.self; if (redirectTarget === "top") targetWindow = (_a = window.top) != null ? _a : window.self; const redirect = targetWindow.location[redirectMethod].bind(targetWindow.location); let abort; return { navigate: async (params) => { this._logger.create("navigate"); return await new Promise((resolve, reject) => { abort = reject; window.addEventListener("pageshow", () => resolve(window.location.href)); redirect(params.url); }); }, close: () => { this._logger.create("close"); abort?.(/* @__PURE__ */ new Error("Redirect aborted")); targetWindow.stop(); } }; } async callback() {} }; var UserManagerEvents = class extends AccessTokenEvents { constructor(settings) { super({ expiringNotificationTimeInSeconds: settings.accessTokenExpiringNotificationTimeInSeconds }); this._logger = new Logger("UserManagerEvents"); this._userLoaded = new Event$1("User loaded"); this._userUnloaded = new Event$1("User unloaded"); this._silentRenewError = new Event$1("Silent renew error"); this._userSignedIn = new Event$1("User signed in"); this._userSignedOut = new Event$1("User signed out"); this._userSessionChanged = new Event$1("User session changed"); } async load(user, raiseEvent = true) { await super.load(user); if (raiseEvent) await this._userLoaded.raise(user); } async unload() { await super.unload(); await this._userUnloaded.raise(); } /** * Add callback: Raised when a user session has been established (or re-established). */ addUserLoaded(cb) { return this._userLoaded.addHandler(cb); } /** * Remove callback: Raised when a user session has been established (or re-established). */ removeUserLoaded(cb) { return this._userLoaded.removeHandler(cb); } /** * Add callback: Raised when a user session has been terminated. */ addUserUnloaded(cb) { return this._userUnloaded.addHandler(cb); } /** * Remove callback: Raised when a user session has been terminated. */ removeUserUnloaded(cb) { return this._userUnloaded.removeHandler(cb); } /** * Add callback: Raised when the automatic silent renew has failed. */ addSilentRenewError(cb) { return this._silentRenewError.addHandler(cb); } /** * Remove callback: Raised when the automatic silent renew has failed. */ removeSilentRenewError(cb) { return this._silentRenewError.removeHandler(cb); } /** * @internal */ async _raiseSilentRenewError(e) { await this._silentRenewError.raise(e); } /** * Add callback: Raised when the user is signed in (when `monitorSession` is set). * @see {@link UserManagerSettings.monitorSession} */ addUserSignedIn(cb) { return this._userSignedIn.addHandler(cb); } /** * Remove callback: Raised when the user is signed in (when `monitorSession` is set). */ removeUserSignedIn(cb) { this._userSignedIn.removeHandler(cb); } /** * @internal */ async _raiseUserSignedIn() { await this._userSignedIn.raise(); } /** * Add callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set). * @see {@link UserManagerSettings.monitorSession} */ addUserSignedOut(cb) { return this._userSignedOut.addHandler(cb); } /** * Remove callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set). */ removeUserSignedOut(cb) { this._userSignedOut.removeHandler(cb); } /** * @internal */ async _raiseUserSignedOut() { await this._userSignedOut.raise(); } /** * Add callback: Raised when the user session changed (when `monitorSession` is set). * @see {@link UserManagerSettings.monitorSession} */ addUserSessionChanged(cb) { return this._userSessionChanged.addHandler(cb); } /** * Remove callback: Raised when the user session changed (when `monitorSession` is set). */ removeUserSessionChanged(cb) { this._userSessionChanged.removeHandler(cb); } /** * @internal */ async _raiseUserSessionChanged() { await this._userSessionChanged.raise(); } }; var SilentRenewService = class { constructor(_userManager) { this._userManager = _userManager; this._logger = new Logger("SilentRenewService"); this._isStarted = false; this._retryTimer = new Timer("Retry Silent Renew"); this._timeoutRetryCount = 0; this._tokenExpiring = async () => { const logger2 = this._logger.create("_tokenExpiring"); try { await this._userManager.signinSilent(); this._timeoutRetryCount = 0; logger2.debug("silent token renewal successful"); } catch (err) { if (err instanceof ErrorTimeout) { this._timeoutRetryCount++; const maxRetries = this._userManager.settings.maxSilentRenewTimeoutRetries; if (maxRetries !== void 0 && this._timeoutRetryCount > maxRetries) { logger2.error(`Timeout retry limit reached (${this._timeoutRetryCount} > ${maxRetries}), raising silentRenewError:`, err); this._timeoutRetryCount = 0; await this._userManager.events._raiseSilentRenewError(err); return; } logger2.warn(`ErrorTimeout from signinSilent (attempt ${this._timeoutRetryCount}), retry in 5s:`, err); this._retryTimer.init(5); return; } logger2.error("Error from signinSilent:", err); this._timeoutRetryCount = 0; await this._userManager.events._raiseSilentRenewError(err); } }; } async start() { const logger2 = this._logger.create("start"); if (!this._isStarted) { this._isStarted = true; this._userManager.events.addAccessTokenExpiring(this._tokenExpiring); this._retryTimer.addHandler(this._tokenExpiring); try { await this._userManager.getUser(); } catch (err) { logger2.error("getUser error", err); } } } stop() { if (this._isStarted) { this._retryTimer.cancel(); this._retryTimer.removeHandler(this._tokenExpiring); this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring); this._isStarted = false; } } }; var RefreshState = class { constructor(args) { this.refresh_token = args.refresh_token; this.id_token = args.id_token; this.session_state = args.session_state; this.scope = args.scope; this.profile = args.profile; this.data = args.state; } }; var UserManager = class { constructor(settings, redirectNavigator, popupNavigator, iframeNavigator) { this._logger = new Logger("UserManager"); this.settings = new UserManagerSettingsStore(settings); this._client = new OidcClient(settings); this._redirectNavigator = redirectNavigator != null ? redirectNavigator : new RedirectNavigator(this.settings); this._popupNavigator = popupNavigator != null ? popupNavigator : new PopupNavigator(this.settings); this._iframeNavigator = iframeNavigator != null ? iframeNavigator : new IFrameNavigator(this.settings); this._events = new UserManagerEvents(this.settings); this._silentRenewService = new SilentRenewService(this); if (this.settings.automaticSilentRenew) this.startSilentRenew(); this._sessionMonitor = null; if (this.settings.monitorSession) this._sessionMonitor = new SessionMonitor(this); } /** * Get object used to register for events raised by the `UserManager`. */ get events() { return this._events; } /** * Get object used to access the metadata configuration of the identity provider. */ get metadataService() { return this._client.metadataService; } /** * Load the `User` object for the currently authenticated user. * * @param raiseEvent - If `true`, the `UserLoaded` event will be raised. Defaults to false. * @returns A promise */ async getUser(raiseEvent = false) { const logger2 = this._logger.create("getUser"); const user = await this._loadUser(); if (user) { logger2.info("user loaded"); await this._events.load(user, raiseEvent); return user; } logger2.info("user not found in storage"); return null; } /** * Remove from any storage the currently authenticated user. * * @returns A promise */ async removeUser() { const logger2 = this._logger.create("removeUser"); await this.storeUser(null); logger2.info("user removed from storage"); await this._events.unload(); } /** * Trigger a redirect of the current window to the authorization endpoint. * * @returns A promise * * @throws `Error` In cases of wrong authentication. */ async signinRedirect(args = {}) { var _a; this._logger.create("signinRedirect"); const { redirectMethod, ...requestArgs } = args; let dpopJkt; if ((_a = this.settings.dpop) == null ? void 0 : _a.bind_authorization_code) dpopJkt = await this.generateDPoPJkt(this.settings.dpop); const handle = await this._redirectNavigator.prepare({ redirectMethod }); await this._signinStart({ request_type: "si:r", dpopJkt, ...requestArgs }, handle); } /** * Process the response (callback) from the authorization endpoint. * It is recommended to use {@link UserManager.signinCallback} instead. * * @returns A promise containing the authenticated `User`. * * @see {@link UserManager.signinCallback} */ async signinRedirectCallback(url = window.location.href) { const logger2 = this._logger.create("signinRedirectCallback"); const user = await this._signinEnd(url); if (user.profile && user.profile.sub) logger2.info("success, signed in subject", user.profile.sub); else logger2.info("no subject"); return user; } /** * Trigger the signin with user/password. * * @returns A promise containing the authenticated `User`. * @throws {@link ErrorResponse} In cases of wrong authentication. */ async signinResourceOwnerCredentials({ username, password, skipUserInfo = false }) { const logger2 = this._logger.create("signinResourceOwnerCredential"); const signinResponse = await this._client.processResourceOwnerPasswordCredentials({ username, password, skipUserInfo, extraTokenParams: this.settings.extraTokenParams }); logger2.debug("got signin response"); const user = await this._buildUser(signinResponse); if (user.profile && user.profile.sub) logger2.info("success, signed in subject", user.profile.sub); else logger2.info("no subject"); return user; } /** * Trigger a request (via a popup window) to the authorization endpoint. * * @returns A promise containing the authenticated `User`. * @throws `Error` In cases of wrong authentication. */ async signinPopup(args = {}) { var _a; const logger2 = this._logger.create("signinPopup"); let dpopJkt; if ((_a = this.settings.dpop) == null ? void 0 : _a.bind_authorization_code) dpopJkt = await this.generateDPoPJkt(this.settings.dpop); const { popupWindowFeatures, popupWindowTarget, popupSignal, popupAbortOnClose, ...requestArgs } = args; const url = this.settings.popup_redirect_uri; if (!url) logger2.throw(/* @__PURE__ */ new Error("No popup_redirect_uri configured")); const handle = await this._popupNavigator.prepare({ popupWindowFeatures, popupWindowTarget, popupSignal, popupAbortOnClose }); const user = await this._signin({ request_type: "si:p", redirect_uri: url, display: "popup", dpopJkt, ...requestArgs }, handle); if (user) if (user.profile && user.profile.sub) logger2.info("success, signed in subject", user.profile.sub); else logger2.info("no subject"); return user; } /** * Notify the opening window of response (callback) from the authorization endpoint. * It is recommended to use {@link UserManager.signinCallback} instead. * * @returns A promise * * @see {@link UserManager.signinCallback} */ async signinPopupCallback(url = window.location.href, keepOpen = false) { const logger2 = this._logger.create("signinPopupCallback"); await this._popupNavigator.callback(url, { keepOpen }); logger2.info("success"); } /** * Trigger a silent request (via refresh token or an iframe) to the authorization endpoint. * * @returns A promise that contains the authenticated `User`. */ async signinSilent(args = {}) { var _a, _b; const logger2 = this._logger.create("signinSilent"); const { silentRequestTimeoutInSeconds, ...requestArgs } = args; let user = await this._loadUser(); if (!args.forceIframeAuth && (user == null ? void 0 : user.refresh_token)) { logger2.debug("using refresh token"); const state = new RefreshState(user); return await this._useRefreshToken({ state, redirect_uri: requestArgs.redirect_uri, resource: requestArgs.resource, extraTokenParams: requestArgs.extraTokenParams, timeoutInSeconds: silentRequestTimeoutInSeconds }); } let dpopJkt; if ((_a = this.settings.dpop) == null ? void 0 : _a.bind_authorization_code) dpopJkt = await this.generateDPoPJkt(this.settings.dpop); const url = this.settings.silent_redirect_uri; if (!url) logger2.throw(/* @__PURE__ */ new Error("No silent_redirect_uri configured")); let verifySub; if (user && this.settings.validateSubOnSilentRenew) { logger2.debug("subject prior to silent renew:", user.profile.sub); verifySub = user.profile.sub; } const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds }); user = await this._signin({ request_type: "si:s", redirect_uri: url, prompt: "none", id_token_hint: this.settings.includeIdTokenInSilentRenew ? user == null ? void 0 : user.id_token : void 0, dpopJkt, ...requestArgs }, handle, verifySub); if (user) if ((_b = user.profile) == null ? void 0 : _b.sub) logger2.info("success, signed in subject", user.profile.sub); else logger2.info("no subject"); return user; } async _useRefreshToken(args) { const response = await this._client.useRefreshToken({ timeoutInSeconds: this.settings.silentRequestTimeoutInSeconds, ...args }); const user = new User({ ...args.state, ...response }); await this.storeUser(user); await this._events.load(user); return user; } /** * * Notify the parent window of response (callback) from the authorization endpoint. * It is recommended to use {@link UserManager.signinCallback} instead. * * @returns A promise * * @see {@link UserManager.signinCallback} */ async signinSilentCallback(url = window.location.href) { const logger2 = this._logger.create("signinSilentCallback"); await this._iframeNavigator.callback(url); logger2.info("success"); } /** * Process any response (callback) from the authorization endpoint, by dispatching the request_type * and executing one of the following functions: * - {@link UserManager.signinRedirectCallback} * - {@link UserManager.signinPopupCallback} * - {@link UserManager.signinSilentCallback} * * @throws `Error` If request_type is unknown or signin cannot be processed. */ async signinCallback(url = window.location.href) { const { state } = await this._client.readSigninResponseState(url); switch (state.request_type) { case "si:r": return await this.signinRedirectCallback(url); case "si:p": await this.signinPopupCallback(url); break; case "si:s": await this.signinSilentCallback(url); break; default: throw new Error("invalid request_type in state"); } } /** * Process any response (callback) from the end session endpoint, by dispatching the request_type * and executing one of the following functions: * - {@link UserManager.signoutRedirectCallback} * - {@link UserManager.signoutPopupCallback} * - {@link UserManager.signoutSilentCallback} * * @throws `Error` If request_type is unknown or signout cannot be processed. */ async signoutCallback(url = window.location.href, keepOpen = false) { const { state } = await this._client.readSignoutResponseState(url); if (!state) return; switch (state.request_type) { case "so:r": return await this.signoutRedirectCallback(url); case "so:p": await this.signoutPopupCallback(url, keepOpen); break; case "so:s": await this.signoutSilentCallback(url); break; default: throw new Error("invalid request_type in state"); } } /** * Query OP for user's current signin status. * * @returns A promise object with session_state and subject identifier. */ async querySessionStatus(args = {}) { const logger2 = this._logger.create("querySessionStatus"); const { silentRequestTimeoutInSeconds, ...requestArgs } = args; const url = this.settings.silent_redirect_uri; if (!url) logger2.throw(/* @__PURE__ */ new Error("No silent_redirect_uri configured")); const user = await this._loadUser(); const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds }); const navResponse = await this._signinStart({ request_type: "si:s", redirect_uri: url, prompt: "none", id_token_hint: this.settings.includeIdTokenInSilentRenew ? user == null ? void 0 : user.id_token : void 0, response_type: this.settings.query_status_response_type, scope: "openid", skipUserInfo: true, ...requestArgs }, handle); try { const signinResponse = await this._client.processSigninResponse(navResponse.url, {}); logger2.debug("got signin response"); if (signinResponse.session_state && signinResponse.profile.sub) { logger2.info("success for subject", signinResponse.profile.sub); return { session_state: signinResponse.session_state, sub: signinResponse.profile.sub }; } logger2.info("success, user not authenticated"); return null; } catch (err) { if (this.settings.monitorAnonymousSession && err instanceof ErrorResponse) switch (err.error) { case "login_required": case "consent_required": case "interaction_required": case "account_selection_required": logger2.info("success for anonymous user"); return { session_state: err.session_state }; } throw err; } } async _signin(args, handle, verifySub) { const navResponse = await this._signinStart(args, handle); return await this._signinEnd(navResponse.url, verifySub); } async _signinStart(args, handle) { const logger2 = this._logger.create("_signinStart"); try { const signinRequest = await this._client.createSigninRequest(args); logger2.debug("got signin request"); return await handle.navigate({ url: signinRequest.url, state: signinRequest.state.id, response_mode: signinRequest.state.response_mode, scriptOrigin: this.settings.iframeScriptOrigin }); } catch (err) { logger2.debug("error after preparing navigator, closing navigator window"); handle.close(); throw err; } } async _signinEnd(url, verifySub) { const logger2 = this._logger.create("_signinEnd"); const signinResponse = await this._client.processSigninResponse(url, {}); logger2.debug("got signin response"); return await this._buildUser(signinResponse, verifySub); } async _buildUser(signinResponse, verifySub) { const logger2 = this._logger.create("_buildUser"); const user = new User(signinResponse); if (verifySub) { if (verifySub !== user.profile.sub) { logger2.debug("current user does not match user returned from signin. sub from signin:", user.profile.sub); throw new ErrorResponse({ ...signinResponse, error: "login_required" }); } logger2.debug("current user matches user returned from signin"); } await this.storeUser(user); logger2.debug("user stored"); await this._events.load(user); return user; } /** * Trigger a redirect of the current window to the end session endpoint. * * @returns A promise */ async signoutRedirect(args = {}) { const logger2 = this._logger.create("signoutRedirect"); const { redirectMethod, ...requestArgs } = args; const handle = await this._redirectNavigator.prepare({ redirectMethod }); await this._signoutStart({ request_type: "so:r", post_logout_redirect_uri: this.settings.post_logout_redirect_uri, ...requestArgs }, handle); logger2.info("success"); } /** * Process response (callback) from the end session endpoint. * It is recommended to use {@link UserManager.signoutCallback} instead. * * @returns A promise containing signout response * * @see {@link UserManager.signoutCallback} */ async signoutRedirectCallback(url = window.location.href) { const logger2 = this._logger.create("signoutRedirectCallback"); const response = await this._signoutEnd(url); logger2.info("success"); return response; } /** * Trigger a redirect of a popup window to the end session endpoint. * * @returns A promise */ async signoutPopup(args = {}) { const logger2 = this._logger.create("signoutPopup"); const { popupWindowFeatures, popupWindowTarget, popupSignal, ...requestArgs } = args; const url = this.settings.popup_post_logout_redirect_uri; const handle = await this._popupNavigator.prepare({ popupWindowFeatures, popupWindowTarget, popupSignal }); await this._signout({ request_type: "so:p", post_logout_redirect_uri: url, state: url == null ? void 0 : {}, ...requestArgs }, handle); logger2.info("success"); } /** * Process response (callback) from the end session endpoint from a popup window. * It is recommended to use {@link UserManager.signoutCallback} instead. * * @returns A promise * * @see {@link UserManager.signoutCallback} */ async signoutPopupCallback(url = window.location.href, keepOpen = false) { const logger2 = this._logger.create("signoutPopupCallback"); await this._popupNavigator.callback(url, { keepOpen }); logger2.info("success"); } async _signout(args, handle) { const navResponse = await this._signoutStart(args, handle); return await this._signoutEnd(navResponse.url); } async _signoutStart(args = {}, handle) { var _a; const logger2 = this._logger.create("_signoutStart"); try { const user = await this._loadUser(); logger2.debug("loaded current user from storage"); if (this.settings.revokeTokensOnSignout) await this._revokeInternal(user); const id_token = args.id_token_hint || user && user.id_token; if (id_token) { logger2.debug("setting id_token_hint in signout request"); args.id_token_hint = id_token; } await this.removeUser(); logger2.debug("user removed, creating signout request"); const signoutRequest = await this._client.createSignoutRequest(args); logger2.debug("got signout request"); return await handle.navigate({ url: signoutRequest.url, state: (_a = signoutRequest.state) == null ? void 0 : _a.id, scriptOrigin: this.settings.iframeScriptOrigin }); } catch (err) { logger2.debug("error after preparing navigator, closing navigator window"); handle.close(); throw err; } } async _signoutEnd(url) { const logger2 = this._logger.create("_signoutEnd"); const signoutResponse = await this._client.processSignoutResponse(url); logger2.debug("got signout response"); return signoutResponse; } /** * Trigger a silent request (via an iframe) to the end session endpoint. * * @returns A promise */ async signoutSilent(args = {}) { var _a; const logger2 = this._logger.create("signoutSilent"); const { silentRequestTimeoutInSeconds, ...requestArgs } = args; const id_token_hint = this.settings.includeIdTokenInSilentSignout ? (_a = await this._loadUser()) == null ? void 0 : _a.id_token : void 0; const url = this.settings.popup_post_logout_redirect_uri; const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds }); await this._signout({ request_type: "so:s", post_logout_redirect_uri: url, id_token_hint, ...requestArgs }, handle); logger2.info("success"); } /** * Notify the parent window of response (callback) from the end session endpoint. * It is recommended to use {@link UserManager.signoutCallback} instead. * * @returns A promise * * @see {@link UserManager.signoutCallback} */ async signoutSilentCallback(url = window.location.href) { const logger2 = this._logger.create("signoutSilentCallback"); await this._iframeNavigator.callback(url); logger2.info("success"); } async revokeTokens(types) { const user = await this._loadUser(); await this._revokeInternal(user, types); } async _revokeInternal(user, types = this.settings.revokeTokenTypes) { const logger2 = this._logger.create("_revokeInternal"); if (!user) return; const typesPresent = types.filter((type) => typeof user[type] === "string"); if (!typesPresent.length) { logger2.debug("no need to revoke due to no token(s)"); return; } for (const type of typesPresent) { await this._client.revokeToken(user[type], type); logger2.info(`${type} revoked successfully`); if (type !== "access_token") user[type] = null; } await this.storeUser(user); logger2.debug("user stored"); await this._events.load(user); } /** * Enables silent renew for the `UserManager`. */ startSilentRenew() { this._logger.create("startSilentRenew"); this._silentRenewService.start(); } /** * Disables silent renew for the `UserManager`. */ stopSilentRenew() { this._silentRenewService.stop(); } get _userStoreKey() { return `user:${this.settings.authority}:${this.settings.client_id}`; } async _loadUser() { const logger2 = this._logger.create("_loadUser"); const storageString = await this.settings.userStore.get(this._userStoreKey); if (storageString) { logger2.debug("user storageString loaded"); return User.fromStorageString(storageString); } logger2.debug("no user storageString"); return null; } async storeUser(user) { const logger2 = this._logger.create("storeUser"); if (user) { logger2.debug("storing user"); const storageString = user.toStorageString(); await this.settings.userStore.set(this._userStoreKey, storageString); } else { this._logger.debug("removing user"); await this.settings.userStore.remove(this._userStoreKey); if (this.settings.dpop) await this.settings.dpop.store.remove(this.settings.client_id); } } /** * Removes stale state entries in storage for incomplete authorize requests. */ async clearStaleState() { await this._client.clearStaleState(); } /** * Dynamically generates a DPoP proof for a given user, URL and optional Http method. * This method is useful when you need to make a request to a resource server * with fetch or similar, and you need to include a DPoP proof in a DPoP header. * @param url - The URL to generate the DPoP proof for * @param user - The user to generate the DPoP proof for * @param httpMethod - Optional, defaults to "GET" * @param nonce - Optional nonce provided by the resource server * * @returns A promise containing the DPoP proof or undefined if DPoP is not enabled/no user is found. */ async dpopProof(url, user, httpMethod, nonce) { var _a, _b; const dpopState = await ((_b = (_a = this.settings.dpop) == null ? void 0 : _a.store) == null ? void 0 : _b.get(this.settings.client_id)); if (dpopState) return await CryptoUtils.generateDPoPProof({ url, accessToken: user == null ? void 0 : user.access_token, httpMethod, keyPair: dpopState.keys, nonce }); } async generateDPoPJkt(dpopSettings) { let dpopState = await dpopSettings.store.get(this.settings.client_id); if (!dpopState) { dpopState = new DPoPState(await CryptoUtils.generateDPoPKeys()); await dpopSettings.store.set(this.settings.client_id, dpopState); } return await CryptoUtils.generateDPoPJkt(dpopState.keys); } }; //#endregion //#region ../send/frontend/src/stores/auth-store.ts var auth_store_exports = /* @__PURE__ */ __exportAll({ useAuthStore: () => useAuthStore }); var settings = { authority: "https://auth.tb.pro/realms/tbpro/", client_id: "desktop", redirect_uri: `${window.location.origin}/post-login`, post_logout_redirect_uri: `https://send.tb.pro/logout`, response_type: "code", scope: "openid profile email offline_access", automaticSilentRenew: false, filterProtocolClaims: true, loadUserInfo: false }; var userManager = new UserManager(settings); /** * OIDC error codes that mean the session is genuinely over — the refresh token * was revoked or has expired. Any other failure (network, timeout, userinfo) * is transient and must NOT drop the user out of a still-valid session. */ var GENUINE_AUTH_FAILURE_CODES = [ "invalid_grant", "login_required", "session_expired" ]; function isGenuineAuthFailure(error) { const code = error?.error; return typeof code === "string" && GENUINE_AUTH_FAILURE_CODES.includes(code); } var forcedLogoutInProgress = false; var useAuthStore = defineStore("auth", () => { const { api } = useApiStore(); const { isExtension, isThunderbirdHost } = useConfigStore(); const isLoggedIn = /* @__PURE__ */ ref(false); const currentUser = /* @__PURE__ */ ref(null); watch(isLoggedIn, (newValue) => { console.info("isLoggedIn changed", newValue); }); let inFlightRefresh = null; let lastRefreshFailedGenuinely = false; /** * Notify the add-on background that the session is over so its menu reverts * to logged-out. Only meaningful inside Thunderbird, where the token-bridge * content script forwards window messages to background.ts — the same path * UserMenu.vue uses on explicit logout. */ function notifyAddonSignedOut() { if (!isThunderbirdHost) return; try { window.postMessage({ type: SIGN_OUT }, window.location.origin); } catch (error) { console.error("Failed to notify add-on of sign-out:", error); } } /** * Refresh the access token via the refresh_token, deduping concurrent callers. * * Returns the refreshed User on success. On a genuine auth failure (refresh * token revoked/expired) it clears local login state, notifies the add-on, * and returns null. On a transient failure (network/timeout) it leaves the * session intact and returns null so a later call can retry — we do not log * the user out over a blip. */ async function refreshAccessToken() { if (inFlightRefresh) return inFlightRefresh; inFlightRefresh = (async () => { lastRefreshFailedGenuinely = false; try { const user = await userManager.signinSilent(); currentUser.value = user; if (isExtension && user) await browser.storage.local.set({ [STORAGE_KEY_AUTH]: user }); return user; } catch (error) { if (isGenuineAuthFailure(error)) { lastRefreshFailedGenuinely = true; console.warn(`Silent token refresh failed — session ended (${error.error}). Signing out.`); isLoggedIn.value = false; currentUser.value = null; notifyAddonSignedOut(); } else console.warn("Silent token refresh hit a transient error; keeping session:", error); return null; } finally { inFlightRefresh = null; } })(); return inFlightRefresh; } async function getOIDCUser() { try { return await userManager.getUser(); } catch (error) { console.error("Failed to get OIDC user:", error); return null; } } /** * Web to add-on — Step 2: Start the OIDC login process. * * Redirects the browser (or extension popup) to accounts.tb.pro. * The OIDC provider authenticates the user and redirects back to * /post-login (or /post-login?isExtension=true) with an authorization code. * * Web flow : redirect_uri = /post-login * Extension : redirect_uri = /post-login?isExtension=true * The isExtension flag is read by PostLoginPage / the router * guard after login to skip the key-backup prompt. */ async function loginToOIDC({ onSuccess, isExtension }) { try { if (isExtension) await userManager.signinRedirect({ redirect_uri: `${window.location.origin}/post-login?isExtension=${isExtension}` }); else await userManager.signinRedirect(); if (onSuccess) onSuccess(); } catch (error) { console.error("OIDC login failed:", error); throw error; } } /** * Web to add-on — Steps 5–8: Handle the OIDC redirect callback. * * Called by PostLoginPage.vue after accounts.tb.pro redirects back to * /post-login with an authorization code in the URL. * * Step 5 — Token exchange: * signinCallback() reads the code from the URL and exchanges it with * the OIDC token endpoint for access_token, refresh_token, and id_token. * * Step 6 — Notify the background script via the token-bridge: * Because this page runs as a normal web tab, we cannot call * browser.runtime.sendMessage() directly. Instead we use window.postMessage * and rely on token-bridge.js (a content script injected into every tab) * to forward the messages to background.ts. * • OIDC_TOKEN → background creates/updates the Thundermail mail account * using the refresh token as the OAuth2 credential. * • OIDC_USER → background stores the full User object in * browser.storage.local[STORAGE_KEY_AUTH] so the add-on * popup/menu can read it back via loadUser(). * * Step 7 — Update background state (handled by background.ts, see there). * * Step 8 — Authenticate with the backend: * POSTs the access_token as a Bearer token to auth/oidc/authenticate. * The backend introspects it against the OIDC provider, finds or creates * the user record, and responds with httpOnly JWT session cookies that * all subsequent API calls use. */ async function handleOIDCCallback() { try { const user = await userManager.signinCallback(); currentUser.value = user; window.addEventListener("message", (e) => { if (e.origin === window.location.origin && e.data?.type === "TB/BRIDGE_READY") console.log("[web app] bridge says: ready"); }); window.postMessage({ type: BRIDGE_PING, text: "hello from auth store 👋" }, window.location.origin); window.postMessage({ type: OIDC_TOKEN, token: user.refresh_token, email: user.profile.preferred_username, name: user.profile.name || user.profile.given_name }, window.location.origin); window.postMessage({ type: OIDC_USER, user }, window.location.origin); const response = await api.call("auth/oidc/authenticate", { method: "POST", headers: { Authorization: `Bearer ${user.access_token}`, "Content-Type": "application/json" } }); if (response?.user) { isLoggedIn.value = true; return response.user; } else throw new Error("Backend authentication failed"); } catch (error) { console.error("OIDC callback handling failed:", error); throw error; } } /** * Check if user is currently authenticated and get user info */ async function checkAuthStatus() { try { if (isExtension) await loadUser(); let user = await userManager.getUser(); if (user?.expired) { user = await refreshAccessToken(); if (!user) return null; } if (user && !user.expired) { currentUser.value = user; const response = await api.call("auth/oidc/me", { headers: { Authorization: `Bearer ${user.access_token}` } }); if (response?.user) { isLoggedIn.value = true; return response.user; } } isLoggedIn.value = false; currentUser.value = null; return null; } catch (error) { console.error("Auth status check failed:", error); isLoggedIn.value = false; currentUser.value = null; return null; } } /** * Get the current access token for API requests. * Transparently refreshes the token if it has expired. */ async function getAccessToken() { try { let user = await userManager.getUser(); if (!user) return null; if (user.expired) user = await refreshAccessToken(); return user?.access_token || null; } catch (error) { console.error("Failed to get access token:", error); return null; } } /** * Forced logout in response to the backend's x-logout header (#960): the * session was ended server-side (logout elsewhere, password change, admin * revoke). Clear local auth and return to a clean state. Deliberately does * NOT call the API (that path is what surfaced x-logout, so calling it again * would loop); it only clears client state and redirects. */ async function handleForcedLogout() { if (forcedLogoutInProgress) return; forcedLogoutInProgress = true; try { isLoggedIn.value = false; currentUser.value = null; try { await userManager.removeUser(); } catch {} try { if (typeof browser !== "undefined") { await browser.storage.local.remove(STORAGE_KEY_AUTH); browser.runtime.sendMessage({ type: SIGN_OUT }); } } catch {} if (typeof window !== "undefined") window.dispatchEvent(new CustomEvent("tbpro:force-logout")); } finally { forcedLogoutInProgress = false; } } /** * Logout from OIDC and clear local state */ async function logoutFromOIDC() { try { await api.call("auth/oidc/logout", {}, "POST"); await userManager.signoutRedirect(); } catch (error) { console.error("OIDC logout failed:", error); isLoggedIn.value = false; currentUser.value = null; } finally { await browser.storage.local.remove(STORAGE_KEY_AUTH); browser.runtime.sendMessage({ type: SIGN_OUT }); } } /** * Silent refresh of the access token. Delegates to the deduped * refreshAccessToken(), which owns state/notification on genuine failure and * preserves the session on transient errors. */ async function refreshToken() { return (await refreshAccessToken())?.access_token ?? null; } /** * The backend reported the current access token revoked (x-logout, #960). * Before tearing the session down, try a silent refresh: a revoked/expired * *access* token can often be replaced using a still-valid *refresh* token, * so the session keeps rolling instead of bouncing the user to login (PR #974 * review). Only force logout when the refresh token is also gone; on a * transient refresh error keep the session (fail open). * * Goes through refreshAccessToken() — an unconditional signinSilent — rather * than getAccessToken(), because the token behind x-logout is still within * its lifetime (the backend exp-gates the signal), so getAccessToken() would * hand back the same stale, revoked token without refreshing. * * @returns `true` if the session was recovered — the caller should retry the * request with the fresh token — and `false` otherwise (forced logout on a * genuine failure, or session kept on a transient error). */ async function recoverOrForceLogout() { const user = await refreshAccessToken(); if (user && !user.expired) return true; if (lastRefreshFailedGenuinely) await handleForcedLogout(); return false; } async function loadUser() { try { const result = await browser.storage.local.get(STORAGE_KEY_AUTH); if (result["STORAGE_KEY_AUTH"]) { const userInstance = new User(result[STORAGE_KEY_AUTH]); await userManager.storeUser(userInstance); } else { await userManager.removeUser(); isLoggedIn.value = false; currentUser.value = null; } } catch (e) { console.log(`No error. Only works if running in add-on.`); console.log(e); } } /** * Add-On to Web — Steps 3–8: Authenticate using a token set provided by the add-on. * * Called by AddonAuthPage.vue when the /addon-auth route loads. The add-on * already obtained an OIDC token set from accounts.tb.pro and staged it in * browser.storage.local via triggerAddonLogin(). Because this page runs as a * normal web tab, it cannot access browser.storage.local directly — instead * it requests the token via message-passing through the token-bridge content * script, then uses it to authenticate with the backend. * * Full flow (Add-On to Web): * 1. background.ts – triggerAddonLogin() stores token, opens /addon-auth * 2. AddonAuthPage.vue loads, calls this function * 3. POST GET_PENDING_ADDON_TOKEN → token-bridge → background * 4. background reads storage, responds with PENDING_ADDON_TOKEN_RESPONSE, * then deletes the staging key * 5. token-bridge forwards response → window.postMessage → Promise resolves * 6. User object is reconstructed (or obtained via signinSilent) * 7. OIDC_TOKEN + OIDC_USER are posted so the background keeps its own * state in sync (Thundermail account setup, STORAGE_KEY_AUTH) * 8. POST auth/oidc/authenticate — backend issues session cookies * 9. AddonAuthPage posts SIGN_IN_COMPLETE → background closes tab */ async function authenticateWithAddonToken() { const tokenSet = await new Promise((resolve, reject) => { const timeout = setTimeout(() => { window.removeEventListener("message", handler); reject(/* @__PURE__ */ new Error("Timed out waiting for pending addon token")); }, 5e3); function handler(e) { if (e.origin === window.location.origin && e.data?.type === "TB/PENDING_ADDON_TOKEN_RESPONSE") { clearTimeout(timeout); window.removeEventListener("message", handler); resolve(e.data.tokenSet ?? null); } } window.addEventListener("message", handler); window.postMessage({ type: GET_PENDING_ADDON_TOKEN }, window.location.origin); }); if (!tokenSet?.refresh_token) throw new Error("No pending addon token found in storage"); let user; if (tokenSet.access_token && tokenSet.id_token) { const idTokenPayload = JSON.parse(atob(tokenSet.id_token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))); user = new User({ access_token: tokenSet.access_token, refresh_token: tokenSet.refresh_token, id_token: tokenSet.id_token, token_type: "Bearer", scope: tokenSet.scope ?? "openid profile email offline_access", expires_at: tokenSet.expires_at ?? idTokenPayload.exp, profile: idTokenPayload }); await userManager.storeUser(user); if (user.expired) user = await userManager.signinSilent(); } else { await userManager.storeUser(new User({ access_token: "", token_type: "Bearer", refresh_token: tokenSet.refresh_token, scope: tokenSet.scope ?? "openid profile email offline_access", expires_at: 0, profile: { sub: "", iss: settings.authority ?? "", aud: settings.client_id ?? "", exp: 0, iat: 0 } })); user = await userManager.signinSilent(); } currentUser.value = user; window.postMessage({ type: OIDC_TOKEN, token: user.refresh_token, email: user.profile.preferred_username ?? user.profile.email, name: user.profile.name ?? user.profile.given_name }, window.location.origin); window.postMessage({ type: OIDC_USER, user }, window.location.origin); const response = await api.call("auth/oidc/authenticate", { method: "POST", headers: { Authorization: `Bearer ${user.access_token}`, "Content-Type": "application/json" } }); if (response?.user) { isLoggedIn.value = true; return response.user; } else throw new Error("Backend authentication failed"); } return { isLoggedIn, currentUser, loginToOIDC, handleOIDCCallback, checkAuthStatus, getAccessToken, logoutFromOIDC, handleForcedLogout, recoverOrForceLogout, refreshToken, loginToKeyCloak: loginToOIDC, loadUser, getOIDCUser, authenticateWithAddonToken }; }); //#endregion //#region ../send/frontend/src/stores/index.ts var stores_exports = /* @__PURE__ */ __exportAll({ useConfigStore: () => useConfigStore }); //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/subscribable.js var Subscribable = class { constructor() { this.listeners = /* @__PURE__ */ new Set(); this.subscribe = this.subscribe.bind(this); } subscribe(listener) { this.listeners.add(listener); this.onSubscribe(); return () => { this.listeners.delete(listener); this.onUnsubscribe(); }; } hasListeners() { return this.listeners.size > 0; } onSubscribe() {} onUnsubscribe() {} }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/focusManager.js var FocusManager = class extends Subscribable { #focused; #cleanup; #setup; constructor() { super(); this.#setup = (onFocus) => { if (typeof window !== "undefined" && window.addEventListener) { const listener = () => onFocus(); window.addEventListener("visibilitychange", listener, false); return () => { window.removeEventListener("visibilitychange", listener); }; } }; } onSubscribe() { if (!this.#cleanup) this.setEventListener(this.#setup); } onUnsubscribe() { if (!this.hasListeners()) { this.#cleanup?.(); this.#cleanup = void 0; } } setEventListener(setup) { this.#setup = setup; this.#cleanup?.(); this.#cleanup = setup((focused) => { if (typeof focused === "boolean") this.setFocused(focused); else this.onFocus(); }); } setFocused(focused) { if (this.#focused !== focused) { this.#focused = focused; this.onFocus(); } } onFocus() { const isFocused = this.isFocused(); this.listeners.forEach((listener) => { listener(isFocused); }); } isFocused() { if (typeof this.#focused === "boolean") return this.#focused; return globalThis.document?.visibilityState !== "hidden"; } }; var focusManager = new FocusManager(); //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/timeoutManager.js var defaultTimeoutProvider = { setTimeout: (callback, delay) => setTimeout(callback, delay), clearTimeout: (timeoutId) => clearTimeout(timeoutId), setInterval: (callback, delay) => setInterval(callback, delay), clearInterval: (intervalId) => clearInterval(intervalId) }; var TimeoutManager = class { #provider = defaultTimeoutProvider; #providerCalled = false; setTimeoutProvider(provider) { this.#provider = provider; } setTimeout(callback, delay) { return this.#provider.setTimeout(callback, delay); } clearTimeout(timeoutId) { this.#provider.clearTimeout(timeoutId); } setInterval(callback, delay) { return this.#provider.setInterval(callback, delay); } clearInterval(intervalId) { this.#provider.clearInterval(intervalId); } }; var timeoutManager = new TimeoutManager(); function systemSetTimeoutZero(callback) { setTimeout(callback, 0); } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/utils.js var isServer = typeof window === "undefined" || "Deno" in globalThis; function noop() {} function functionalUpdate(updater, input) { return typeof updater === "function" ? updater(input) : updater; } function isValidTimeout(value) { return typeof value === "number" && value >= 0 && value !== Infinity; } function timeUntilStale(updatedAt, staleTime) { return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0); } function resolveStaleTime(staleTime, query) { return typeof staleTime === "function" ? staleTime(query) : staleTime; } function resolveQueryBoolean(option, query) { return typeof option === "function" ? option(query) : option; } function matchQuery(filters, query) { const { type = "all", exact, fetchStatus, predicate, queryKey, stale } = filters; if (queryKey) { if (exact) { if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) return false; } else if (!partialMatchKey(query.queryKey, queryKey)) return false; } if (type !== "all") { const isActive = query.isActive(); if (type === "active" && !isActive) return false; if (type === "inactive" && isActive) return false; } if (typeof stale === "boolean" && query.isStale() !== stale) return false; if (fetchStatus && fetchStatus !== query.state.fetchStatus) return false; if (predicate && !predicate(query)) return false; return true; } function matchMutation(filters, mutation) { const { exact, status, predicate, mutationKey } = filters; if (mutationKey) { if (!mutation.options.mutationKey) return false; if (exact) { if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) return false; } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) return false; } if (status && mutation.state.status !== status) return false; if (predicate && !predicate(mutation)) return false; return true; } function hashQueryKeyByOptions(queryKey, options) { return (options?.queryKeyHashFn || hashKey)(queryKey); } function hashKey(queryKey) { return JSON.stringify(queryKey, (_, val) => isPlainObject$1(val) ? Object.keys(val).sort().reduce((result, key) => { result[key] = val[key]; return result; }, {}) : val); } function partialMatchKey(a, b) { if (a === b) return true; if (typeof a !== typeof b) return false; if (a && b && typeof a === "object" && typeof b === "object") return Object.keys(b).every((key) => partialMatchKey(a[key], b[key])); return false; } var hasOwn = Object.prototype.hasOwnProperty; function replaceEqualDeep(a, b, depth = 0) { if (a === b) return a; if (depth > 500) return b; const array = isPlainArray(a) && isPlainArray(b); if (!array && !(isPlainObject$1(a) && isPlainObject$1(b))) return b; const aSize = (array ? a : Object.keys(a)).length; const bItems = array ? b : Object.keys(b); const bSize = bItems.length; const copy = array ? new Array(bSize) : {}; let equalItems = 0; for (let i = 0; i < bSize; i++) { const key = array ? i : bItems[i]; const aItem = a[key]; const bItem = b[key]; if (aItem === bItem) { copy[key] = aItem; if (array ? i < aSize : hasOwn.call(a, key)) equalItems++; continue; } if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") { copy[key] = bItem; continue; } const v = replaceEqualDeep(aItem, bItem, depth + 1); copy[key] = v; if (v === aItem) equalItems++; } return aSize === bSize && equalItems === aSize ? a : copy; } function shallowEqualObjects(a, b) { if (!b || Object.keys(a).length !== Object.keys(b).length) return false; for (const key in a) if (a[key] !== b[key]) return false; return true; } function isPlainArray(value) { return Array.isArray(value) && value.length === Object.keys(value).length; } function isPlainObject$1(o) { if (!hasObjectPrototype(o)) return false; const ctor = o.constructor; if (ctor === void 0) return true; const prot = ctor.prototype; if (!hasObjectPrototype(prot)) return false; if (!prot.hasOwnProperty("isPrototypeOf")) return false; if (Object.getPrototypeOf(o) !== Object.prototype) return false; return true; } function hasObjectPrototype(o) { return Object.prototype.toString.call(o) === "[object Object]"; } function sleep(timeout) { return new Promise((resolve) => { timeoutManager.setTimeout(resolve, timeout); }); } function replaceData(prevData, data, options) { if (typeof options.structuralSharing === "function") return options.structuralSharing(prevData, data); else if (options.structuralSharing !== false) return replaceEqualDeep(prevData, data); return data; } function addToEnd(items, item, max = 0) { const newItems = [...items, item]; return max && newItems.length > max ? newItems.slice(1) : newItems; } function addToStart(items, item, max = 0) { const newItems = [item, ...items]; return max && newItems.length > max ? newItems.slice(0, -1) : newItems; } var skipToken = /* @__PURE__ */ Symbol(); function ensureQueryFn(options, fetchOptions) { if (!options.queryFn && fetchOptions?.initialPromise) return () => fetchOptions.initialPromise; if (!options.queryFn || options.queryFn === skipToken) return () => Promise.reject(/* @__PURE__ */ new Error(`Missing queryFn: '${options.queryHash}'`)); return options.queryFn; } function shouldThrowError(throwOnError, params) { if (typeof throwOnError === "function") return throwOnError(...params); return !!throwOnError; } function addConsumeAwareSignal(object, getSignal, onCancelled) { let consumed = false; let signal; Object.defineProperty(object, "signal", { enumerable: true, get: () => { signal ??= getSignal(); if (consumed) return signal; consumed = true; if (signal.aborted) onCancelled(); else signal.addEventListener("abort", onCancelled, { once: true }); return signal; } }); return object; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/environmentManager.js var environmentManager = /* @__PURE__ */ (() => { let isServerFn = () => isServer; return { /** * Returns whether the current runtime should be treated as a server environment. */ isServer() { return isServerFn(); }, /** * Overrides the server check globally. */ setIsServer(isServerValue) { isServerFn = isServerValue; } }; })(); //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/thenable.js function pendingThenable() { let resolve; let reject; const thenable = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); thenable.status = "pending"; thenable.catch(() => {}); function finalize(data) { Object.assign(thenable, data); delete thenable.resolve; delete thenable.reject; } thenable.resolve = (value) => { finalize({ status: "fulfilled", value }); resolve(value); }; thenable.reject = (reason) => { finalize({ status: "rejected", reason }); reject(reason); }; return thenable; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/notifyManager.js var defaultScheduler = systemSetTimeoutZero; function createNotifyManager() { let queue = []; let transactions = 0; let notifyFn = (callback) => { callback(); }; let batchNotifyFn = (callback) => { callback(); }; let scheduleFn = defaultScheduler; const schedule = (callback) => { if (transactions) queue.push(callback); else scheduleFn(() => { notifyFn(callback); }); }; const flush = () => { const originalQueue = queue; queue = []; if (originalQueue.length) scheduleFn(() => { batchNotifyFn(() => { originalQueue.forEach((callback) => { notifyFn(callback); }); }); }); }; return { batch: (callback) => { let result; transactions++; try { result = callback(); } finally { transactions--; if (!transactions) flush(); } return result; }, /** * All calls to the wrapped function will be batched. */ batchCalls: (callback) => { return (...args) => { schedule(() => { callback(...args); }); }; }, schedule, /** * Use this method to set a custom notify function. * This can be used to for example wrap notifications with `React.act` while running tests. */ setNotifyFunction: (fn) => { notifyFn = fn; }, /** * Use this method to set a custom function to batch notifications together into a single tick. * By default React Query will use the batch function provided by ReactDOM or React Native. */ setBatchNotifyFunction: (fn) => { batchNotifyFn = fn; }, setScheduler: (fn) => { scheduleFn = fn; } }; } var notifyManager = createNotifyManager(); //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/onlineManager.js var OnlineManager = class extends Subscribable { #online = true; #cleanup; #setup; constructor() { super(); this.#setup = (onOnline) => { if (typeof window !== "undefined" && window.addEventListener) { const onlineListener = () => onOnline(true); const offlineListener = () => onOnline(false); window.addEventListener("online", onlineListener, false); window.addEventListener("offline", offlineListener, false); return () => { window.removeEventListener("online", onlineListener); window.removeEventListener("offline", offlineListener); }; } }; } onSubscribe() { if (!this.#cleanup) this.setEventListener(this.#setup); } onUnsubscribe() { if (!this.hasListeners()) { this.#cleanup?.(); this.#cleanup = void 0; } } setEventListener(setup) { this.#setup = setup; this.#cleanup?.(); this.#cleanup = setup(this.setOnline.bind(this)); } setOnline(online) { if (this.#online !== online) { this.#online = online; this.listeners.forEach((listener) => { listener(online); }); } } isOnline() { return this.#online; } }; var onlineManager = new OnlineManager(); //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/retryer.js function defaultRetryDelay(failureCount) { return Math.min(1e3 * 2 ** failureCount, 3e4); } function canFetch(networkMode) { return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true; } var CancelledError = class extends Error { constructor(options) { super("CancelledError"); this.revert = options?.revert; this.silent = options?.silent; } }; function createRetryer(config) { let isRetryCancelled = false; let failureCount = 0; let continueFn; const thenable = pendingThenable(); const isResolved = () => thenable.status !== "pending"; const cancel = (cancelOptions) => { if (!isResolved()) { const error = new CancelledError(cancelOptions); reject(error); config.onCancel?.(error); } }; const cancelRetry = () => { isRetryCancelled = true; }; const continueRetry = () => { isRetryCancelled = false; }; const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun(); const canStart = () => canFetch(config.networkMode) && config.canRun(); const resolve = (value) => { if (!isResolved()) { continueFn?.(); thenable.resolve(value); } }; const reject = (value) => { if (!isResolved()) { continueFn?.(); thenable.reject(value); } }; const pause = () => { return new Promise((continueResolve) => { continueFn = (value) => { if (isResolved() || canContinue()) continueResolve(value); }; config.onPause?.(); }).then(() => { continueFn = void 0; if (!isResolved()) config.onContinue?.(); }); }; const run = () => { if (isResolved()) return; let promiseOrValue; const initialPromise = failureCount === 0 ? config.initialPromise : void 0; try { promiseOrValue = initialPromise ?? config.fn(); } catch (error) { promiseOrValue = Promise.reject(error); } Promise.resolve(promiseOrValue).then(resolve).catch((error) => { if (isResolved()) return; const retry = config.retry ?? (environmentManager.isServer() ? 0 : 3); const retryDelay = config.retryDelay ?? defaultRetryDelay; const delay = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay; const shouldRetry = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error); if (isRetryCancelled || !shouldRetry) { reject(error); return; } failureCount++; config.onFail?.(failureCount, error); sleep(delay).then(() => { return canContinue() ? void 0 : pause(); }).then(() => { if (isRetryCancelled) reject(error); else run(); }); }); }; return { promise: thenable, status: () => thenable.status, cancel, continue: () => { continueFn?.(); return thenable; }, cancelRetry, continueRetry, canStart, start: () => { if (canStart()) run(); else pause().then(run); return thenable; } }; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/removable.js var Removable = class { #gcTimeout; destroy() { this.clearGcTimeout(); } scheduleGc() { this.clearGcTimeout(); if (isValidTimeout(this.gcTime)) this.#gcTimeout = timeoutManager.setTimeout(() => { this.optionalRemove(); }, this.gcTime); } updateGcTime(newGcTime) { this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (environmentManager.isServer() ? Infinity : 300 * 1e3)); } clearGcTimeout() { if (this.#gcTimeout !== void 0) { timeoutManager.clearTimeout(this.#gcTimeout); this.#gcTimeout = void 0; } } }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js function infiniteQueryBehavior(pages) { return { onFetch: (context, query) => { const options = context.options; const direction = context.fetchOptions?.meta?.fetchMore?.direction; const oldPages = context.state.data?.pages || []; const oldPageParams = context.state.data?.pageParams || []; let result = { pages: [], pageParams: [] }; let currentPage = 0; const fetchFn = async () => { let cancelled = false; const addSignalProperty = (object) => { addConsumeAwareSignal(object, () => context.signal, () => cancelled = true); }; const queryFn = ensureQueryFn(context.options, context.fetchOptions); const fetchPage = async (data, param, previous) => { if (cancelled) return Promise.reject(context.signal.reason); if (param == null && data.pages.length) return Promise.resolve(data); const createQueryFnContext = () => { const queryFnContext2 = { client: context.client, queryKey: context.queryKey, pageParam: param, direction: previous ? "backward" : "forward", meta: context.options.meta }; addSignalProperty(queryFnContext2); return queryFnContext2; }; const page = await queryFn(createQueryFnContext()); const { maxPages } = context.options; const addTo = previous ? addToStart : addToEnd; return { pages: addTo(data.pages, page, maxPages), pageParams: addTo(data.pageParams, param, maxPages) }; }; if (direction && oldPages.length) { const previous = direction === "backward"; const pageParamFn = previous ? getPreviousPageParam : getNextPageParam; const oldData = { pages: oldPages, pageParams: oldPageParams }; result = await fetchPage(oldData, pageParamFn(options, oldData), previous); } else { const remainingPages = pages ?? oldPages.length; do { const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result); if (currentPage > 0 && param == null) break; result = await fetchPage(result, param); currentPage++; } while (currentPage < remainingPages); } return result; }; if (context.options.persister) context.fetchFn = () => { return context.options.persister?.(fetchFn, { client: context.client, queryKey: context.queryKey, meta: context.options.meta, signal: context.signal }, query); }; else context.fetchFn = fetchFn; } }; } function getNextPageParam(options, { pages, pageParams }) { const lastIndex = pages.length - 1; return pages.length > 0 ? options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams) : void 0; } function getPreviousPageParam(options, { pages, pageParams }) { return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/query.js var Query = class extends Removable { #queryType; #initialState; #revertState; #cache; #client; #retryer; #defaultOptions; #abortSignalConsumed; constructor(config) { super(); this.#abortSignalConsumed = false; this.#defaultOptions = config.defaultOptions; this.setOptions(config.options); this.observers = []; this.#client = config.client; this.#cache = this.#client.getQueryCache(); this.queryKey = config.queryKey; this.queryHash = config.queryHash; this.#initialState = getDefaultState$1(this.options); this.state = config.state ?? this.#initialState; this.scheduleGc(); } get meta() { return this.options.meta; } get queryType() { return this.#queryType; } get promise() { return this.#retryer?.promise; } setOptions(options) { this.options = { ...this.#defaultOptions, ...options }; if (options?._type) this.#queryType = options._type; this.updateGcTime(this.options.gcTime); if (this.state && this.state.data === void 0) { const defaultState = getDefaultState$1(this.options); if (defaultState.data !== void 0) { this.setState(successState(defaultState.data, defaultState.dataUpdatedAt)); this.#initialState = defaultState; } } } optionalRemove() { if (!this.observers.length && this.state.fetchStatus === "idle") this.#cache.remove(this); } setData(newData, options) { const data = replaceData(this.state.data, newData, this.options); this.#dispatch({ data, type: "success", dataUpdatedAt: options?.updatedAt, manual: options?.manual }); return data; } setState(state) { this.#dispatch({ type: "setState", state }); } cancel(options) { const promise = this.#retryer?.promise; this.#retryer?.cancel(options); return promise ? promise.then(noop).catch(noop) : Promise.resolve(); } destroy() { super.destroy(); this.cancel({ silent: true }); } get resetState() { return this.#initialState; } reset() { this.destroy(); this.setState(this.resetState); } isActive() { return this.observers.some((observer) => resolveQueryBoolean(observer.options.enabled, this) !== false); } isDisabled() { if (this.getObserversCount() > 0) return !this.isActive(); return this.options.queryFn === skipToken || !this.isFetched(); } isFetched() { return this.state.dataUpdateCount + this.state.errorUpdateCount > 0; } isStatic() { if (this.getObserversCount() > 0) return this.observers.some((observer) => resolveStaleTime(observer.options.staleTime, this) === "static"); return false; } isStale() { if (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale); return this.state.data === void 0 || this.state.isInvalidated; } isStaleByTime(staleTime = 0) { if (this.state.data === void 0) return true; if (staleTime === "static") return false; if (this.state.isInvalidated) return true; return !timeUntilStale(this.state.dataUpdatedAt, staleTime); } onFocus() { this.observers.find((x) => x.shouldFetchOnWindowFocus())?.refetch({ cancelRefetch: false }); this.#retryer?.continue(); } onOnline() { this.observers.find((x) => x.shouldFetchOnReconnect())?.refetch({ cancelRefetch: false }); this.#retryer?.continue(); } addObserver(observer) { if (!this.observers.includes(observer)) { this.observers.push(observer); this.clearGcTimeout(); this.#cache.notify({ type: "observerAdded", query: this, observer }); } } removeObserver(observer) { if (this.observers.includes(observer)) { this.observers = this.observers.filter((x) => x !== observer); if (!this.observers.length) { if (this.#retryer) if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) this.#retryer.cancel({ revert: true }); else this.#retryer.cancelRetry(); this.scheduleGc(); } this.#cache.notify({ type: "observerRemoved", query: this, observer }); } } getObserversCount() { return this.observers.length; } #isInitialPausedFetch() { return this.state.fetchStatus === "paused" && this.state.status === "pending"; } invalidate() { if (!this.state.isInvalidated) this.#dispatch({ type: "invalidate" }); } async fetch(options, fetchOptions) { if (this.state.fetchStatus !== "idle" && this.#retryer?.status() !== "rejected") { if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) this.cancel({ silent: true }); else if (this.#retryer) { this.#retryer.continueRetry(); return this.#retryer.promise; } } if (options) this.setOptions(options); if (!this.options.queryFn) { const observer = this.observers.find((x) => x.options.queryFn); if (observer) this.setOptions(observer.options); } const abortController = new AbortController(); const addSignalProperty = (object) => { Object.defineProperty(object, "signal", { enumerable: true, get: () => { this.#abortSignalConsumed = true; return abortController.signal; } }); }; const fetchFn = () => { const queryFn = ensureQueryFn(this.options, fetchOptions); const createQueryFnContext = () => { const queryFnContext2 = { client: this.#client, queryKey: this.queryKey, meta: this.meta }; addSignalProperty(queryFnContext2); return queryFnContext2; }; const queryFnContext = createQueryFnContext(); this.#abortSignalConsumed = false; if (this.options.persister) return this.options.persister(queryFn, queryFnContext, this); return queryFn(queryFnContext); }; const createFetchContext = () => { const context2 = { fetchOptions, options: this.options, queryKey: this.queryKey, client: this.#client, state: this.state, fetchFn }; addSignalProperty(context2); return context2; }; const context = createFetchContext(); (this.#queryType === "infinite" ? infiniteQueryBehavior(this.options.pages) : this.options.behavior)?.onFetch(context, this); this.#revertState = this.state; if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== context.fetchOptions?.meta) this.#dispatch({ type: "fetch", meta: context.fetchOptions?.meta }); this.#retryer = createRetryer({ initialPromise: fetchOptions?.initialPromise, fn: context.fetchFn, onCancel: (error) => { if (error instanceof CancelledError && error.revert) this.setState({ ...this.#revertState, fetchStatus: "idle" }); abortController.abort(); }, onFail: (failureCount, error) => { this.#dispatch({ type: "failed", failureCount, error }); }, onPause: () => { this.#dispatch({ type: "pause" }); }, onContinue: () => { this.#dispatch({ type: "continue" }); }, retry: context.options.retry, retryDelay: context.options.retryDelay, networkMode: context.options.networkMode, canRun: () => true }); try { const data = await this.#retryer.start(); if (data === void 0) throw new Error(`${this.queryHash} data is undefined`); this.setData(data); this.#cache.config.onSuccess?.(data, this); this.#cache.config.onSettled?.(data, this.state.error, this); return data; } catch (error) { if (error instanceof CancelledError) { if (error.silent) return this.#retryer.promise; else if (error.revert) { if (this.state.data === void 0) throw error; return this.state.data; } } this.#dispatch({ type: "error", error }); this.#cache.config.onError?.(error, this); this.#cache.config.onSettled?.(this.state.data, error, this); throw error; } finally { this.scheduleGc(); } } #dispatch(action) { const reducer = (state) => { switch (action.type) { case "failed": return { ...state, fetchFailureCount: action.failureCount, fetchFailureReason: action.error }; case "pause": return { ...state, fetchStatus: "paused" }; case "continue": return { ...state, fetchStatus: "fetching" }; case "fetch": return { ...state, ...fetchState(state.data, this.options), fetchMeta: action.meta ?? null }; case "success": const newState = { ...state, ...successState(action.data, action.dataUpdatedAt), dataUpdateCount: state.dataUpdateCount + 1, ...!action.manual && { fetchStatus: "idle", fetchFailureCount: 0, fetchFailureReason: null } }; this.#revertState = action.manual ? newState : void 0; return newState; case "error": const error = action.error; return { ...state, error, errorUpdateCount: state.errorUpdateCount + 1, errorUpdatedAt: Date.now(), fetchFailureCount: state.fetchFailureCount + 1, fetchFailureReason: error, fetchStatus: "idle", status: "error", isInvalidated: true }; case "invalidate": return { ...state, isInvalidated: true }; case "setState": return { ...state, ...action.state }; } }; this.state = reducer(this.state); notifyManager.batch(() => { this.observers.forEach((observer) => { observer.onQueryUpdate(); }); this.#cache.notify({ query: this, type: "updated", action }); }); } }; function fetchState(data, options) { return { fetchFailureCount: 0, fetchFailureReason: null, fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused", ...data === void 0 && { error: null, status: "pending" } }; } function successState(data, dataUpdatedAt) { return { data, dataUpdatedAt: dataUpdatedAt ?? Date.now(), error: null, isInvalidated: false, status: "success" }; } function getDefaultState$1(options) { const data = typeof options.initialData === "function" ? options.initialData() : options.initialData; const hasData = data !== void 0; const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0; return { data, dataUpdateCount: 0, dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0, error: null, errorUpdateCount: 0, errorUpdatedAt: 0, fetchFailureCount: 0, fetchFailureReason: null, fetchMeta: null, isInvalidated: false, status: hasData ? "success" : "pending", fetchStatus: "idle" }; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/queryObserver.js var QueryObserver = class extends Subscribable { constructor(client, options) { super(); this.options = options; this.#client = client; this.#selectError = null; this.#currentThenable = pendingThenable(); this.bindMethods(); this.setOptions(options); } #client; #currentQuery = void 0; #currentQueryInitialState = void 0; #currentResult = void 0; #currentResultState; #currentResultOptions; #currentThenable; #selectError; #selectFn; #selectResult; #lastQueryWithDefinedData; #staleTimeoutId; #refetchIntervalId; #currentRefetchInterval; #trackedProps = /* @__PURE__ */ new Set(); bindMethods() { this.refetch = this.refetch.bind(this); } onSubscribe() { if (this.listeners.size === 1) { this.#currentQuery.addObserver(this); if (shouldFetchOnMount(this.#currentQuery, this.options)) this.#executeFetch(); else this.updateResult(); this.#updateTimers(); } } onUnsubscribe() { if (!this.hasListeners()) this.destroy(); } shouldFetchOnReconnect() { return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect); } shouldFetchOnWindowFocus() { return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus); } destroy() { this.listeners = /* @__PURE__ */ new Set(); this.#clearStaleTimeout(); this.#clearRefetchInterval(); this.#currentQuery.removeObserver(this); } setOptions(options) { const prevOptions = this.options; const prevQuery = this.#currentQuery; this.options = this.#client.defaultQueryOptions(options); if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== "boolean") throw new Error("Expected enabled to be a boolean or a callback that returns a boolean"); this.#updateQuery(); this.#currentQuery.setOptions(this.options); if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) this.#client.getQueryCache().notify({ type: "observerOptionsUpdated", query: this.#currentQuery, observer: this }); const mounted = this.hasListeners(); if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) this.#executeFetch(); this.updateResult(); if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) this.#updateStaleTimeout(); const nextRefetchInterval = this.#computeRefetchInterval(); if (mounted && (this.#currentQuery !== prevQuery || resolveQueryBoolean(this.options.enabled, this.#currentQuery) !== resolveQueryBoolean(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) this.#updateRefetchInterval(nextRefetchInterval); } getOptimisticResult(options) { const query = this.#client.getQueryCache().build(this.#client, options); const result = this.createResult(query, options); if (shouldAssignObserverCurrentProperties(this, result)) { this.#currentResult = result; this.#currentResultOptions = this.options; this.#currentResultState = this.#currentQuery.state; } return result; } getCurrentResult() { return this.#currentResult; } trackResult(result, onPropTracked) { return new Proxy(result, { get: (target, key) => { this.trackProp(key); onPropTracked?.(key); if (key === "promise") { this.trackProp("data"); if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === "pending") this.#currentThenable.reject(/* @__PURE__ */ new Error("experimental_prefetchInRender feature flag is not enabled")); } return Reflect.get(target, key); } }); } trackProp(key) { this.#trackedProps.add(key); } getCurrentQuery() { return this.#currentQuery; } refetch({ ...options } = {}) { return this.fetch({ ...options }); } fetchOptimistic(options) { const defaultedOptions = this.#client.defaultQueryOptions(options); const query = this.#client.getQueryCache().build(this.#client, defaultedOptions); return query.fetch().then(() => this.createResult(query, defaultedOptions)); } fetch(fetchOptions) { return this.#executeFetch({ ...fetchOptions, cancelRefetch: fetchOptions.cancelRefetch ?? true }).then(() => { this.updateResult(); return this.#currentResult; }); } #executeFetch(fetchOptions) { this.#updateQuery(); let promise = this.#currentQuery.fetch(this.options, fetchOptions); if (!fetchOptions?.throwOnError) promise = promise.catch(noop); return promise; } #updateStaleTimeout() { this.#clearStaleTimeout(); const staleTime = resolveStaleTime(this.options.staleTime, this.#currentQuery); if (environmentManager.isServer() || this.#currentResult.isStale || !isValidTimeout(staleTime)) return; const timeout = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + 1; this.#staleTimeoutId = timeoutManager.setTimeout(() => { if (!this.#currentResult.isStale) this.updateResult(); }, timeout); } #computeRefetchInterval() { return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false; } #updateRefetchInterval(nextInterval) { this.#clearRefetchInterval(); this.#currentRefetchInterval = nextInterval; if (environmentManager.isServer() || resolveQueryBoolean(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) return; this.#refetchIntervalId = timeoutManager.setInterval(() => { if (this.options.refetchIntervalInBackground || focusManager.isFocused()) this.#executeFetch(); }, this.#currentRefetchInterval); } #updateTimers() { this.#updateStaleTimeout(); this.#updateRefetchInterval(this.#computeRefetchInterval()); } #clearStaleTimeout() { if (this.#staleTimeoutId !== void 0) { timeoutManager.clearTimeout(this.#staleTimeoutId); this.#staleTimeoutId = void 0; } } #clearRefetchInterval() { if (this.#refetchIntervalId !== void 0) { timeoutManager.clearInterval(this.#refetchIntervalId); this.#refetchIntervalId = void 0; } } createResult(query, options) { const prevQuery = this.#currentQuery; const prevOptions = this.options; const prevResult = this.#currentResult; const prevResultState = this.#currentResultState; const prevResultOptions = this.#currentResultOptions; const queryInitialState = query !== prevQuery ? query.state : this.#currentQueryInitialState; const { state } = query; let newState = { ...state }; let isPlaceholderData = false; let data; if (options._optimisticResults) { const mounted = this.hasListeners(); const fetchOnMount = !mounted && shouldFetchOnMount(query, options); const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions); if (fetchOnMount || fetchOptionally) newState = { ...newState, ...fetchState(state.data, query.options) }; if (options._optimisticResults === "isRestoring") newState.fetchStatus = "idle"; } let { error, errorUpdatedAt, status } = newState; data = newState.data; let skipSelect = false; if (options.placeholderData !== void 0 && data === void 0 && status === "pending") { let placeholderData; if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) { placeholderData = prevResult.data; skipSelect = true; } else placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(this.#lastQueryWithDefinedData?.state.data, this.#lastQueryWithDefinedData) : options.placeholderData; if (placeholderData !== void 0) { status = "success"; data = replaceData(prevResult?.data, placeholderData, options); isPlaceholderData = true; } } if (options.select && data !== void 0 && !skipSelect) if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) data = this.#selectResult; else try { this.#selectFn = options.select; data = options.select(data); data = replaceData(prevResult?.data, data, options); this.#selectResult = data; this.#selectError = null; } catch (selectError) { this.#selectError = selectError; } if (this.#selectError) { error = this.#selectError; data = this.#selectResult; errorUpdatedAt = Date.now(); status = "error"; } const isFetching = newState.fetchStatus === "fetching"; const isPending = status === "pending"; const isError = status === "error"; const isLoading = isPending && isFetching; const hasData = data !== void 0; const nextResult = { status, fetchStatus: newState.fetchStatus, isPending, isSuccess: status === "success", isError, isInitialLoading: isLoading, isLoading, data, dataUpdatedAt: newState.dataUpdatedAt, error, errorUpdatedAt, failureCount: newState.fetchFailureCount, failureReason: newState.fetchFailureReason, errorUpdateCount: newState.errorUpdateCount, isFetched: query.isFetched(), isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount, isFetching, isRefetching: isFetching && !isPending, isLoadingError: isError && !hasData, isPaused: newState.fetchStatus === "paused", isPlaceholderData, isRefetchError: isError && hasData, isStale: isStale(query, options), refetch: this.refetch, promise: this.#currentThenable, isEnabled: resolveQueryBoolean(options.enabled, query) !== false }; if (this.options.experimental_prefetchInRender) { const hasResultData = nextResult.data !== void 0; const isErrorWithoutData = nextResult.status === "error" && !hasResultData; const finalizeThenableIfPossible = (thenable) => { if (isErrorWithoutData) thenable.reject(nextResult.error); else if (hasResultData) thenable.resolve(nextResult.data); }; const recreateThenable = () => { finalizeThenableIfPossible(this.#currentThenable = nextResult.promise = pendingThenable()); }; const prevThenable = this.#currentThenable; switch (prevThenable.status) { case "pending": if (query.queryHash === prevQuery.queryHash) finalizeThenableIfPossible(prevThenable); break; case "fulfilled": if (isErrorWithoutData || nextResult.data !== prevThenable.value) recreateThenable(); break; case "rejected": if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) recreateThenable(); break; } } return nextResult; } updateResult() { const prevResult = this.#currentResult; const nextResult = this.createResult(this.#currentQuery, this.options); this.#currentResultState = this.#currentQuery.state; this.#currentResultOptions = this.options; if (this.#currentResultState.data !== void 0) this.#lastQueryWithDefinedData = this.#currentQuery; if (shallowEqualObjects(nextResult, prevResult)) return; this.#currentResult = nextResult; const shouldNotifyListeners = () => { if (!prevResult) return true; const { notifyOnChangeProps } = this.options; const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps; if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) return true; const includedProps = new Set(notifyOnChangePropsValue ?? this.#trackedProps); if (this.options.throwOnError) includedProps.add("error"); return Object.keys(this.#currentResult).some((key) => { const typedKey = key; return this.#currentResult[typedKey] !== prevResult[typedKey] && includedProps.has(typedKey); }); }; this.#notify({ listeners: shouldNotifyListeners() }); } #updateQuery() { const query = this.#client.getQueryCache().build(this.#client, this.options); if (query === this.#currentQuery) return; const prevQuery = this.#currentQuery; this.#currentQuery = query; this.#currentQueryInitialState = query.state; if (this.hasListeners()) { prevQuery?.removeObserver(this); query.addObserver(this); } } onQueryUpdate() { this.updateResult(); if (this.hasListeners()) this.#updateTimers(); } #notify(notifyOptions) { notifyManager.batch(() => { if (notifyOptions.listeners) this.listeners.forEach((listener) => { listener(this.#currentResult); }); this.#client.getQueryCache().notify({ query: this.#currentQuery, type: "observerResultsUpdated" }); }); } }; function shouldLoadOnMount(query, options) { return resolveQueryBoolean(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && resolveQueryBoolean(options.retryOnMount, query) === false); } function shouldFetchOnMount(query, options) { return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount); } function shouldFetchOn(query, options, field) { if (resolveQueryBoolean(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== "static") { const value = typeof field === "function" ? field(query) : field; return value === "always" || value !== false && isStale(query, options); } return false; } function shouldFetchOptionally(query, prevQuery, options, prevOptions) { return (query !== prevQuery || resolveQueryBoolean(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options); } function isStale(query, options) { return resolveQueryBoolean(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query)); } function shouldAssignObserverCurrentProperties(observer, optimisticResult) { if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) return true; return false; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/mutation.js var Mutation = class extends Removable { #client; #observers; #mutationCache; #retryer; constructor(config) { super(); this.#client = config.client; this.mutationId = config.mutationId; this.#mutationCache = config.mutationCache; this.#observers = []; this.state = config.state || getDefaultState(); this.setOptions(config.options); this.scheduleGc(); } setOptions(options) { this.options = options; this.updateGcTime(this.options.gcTime); } get meta() { return this.options.meta; } addObserver(observer) { if (!this.#observers.includes(observer)) { this.#observers.push(observer); this.clearGcTimeout(); this.#mutationCache.notify({ type: "observerAdded", mutation: this, observer }); } } removeObserver(observer) { this.#observers = this.#observers.filter((x) => x !== observer); this.scheduleGc(); this.#mutationCache.notify({ type: "observerRemoved", mutation: this, observer }); } optionalRemove() { if (!this.#observers.length) if (this.state.status === "pending") this.scheduleGc(); else this.#mutationCache.remove(this); } continue() { return this.#retryer?.continue() ?? this.execute(this.state.variables); } async execute(variables) { const onContinue = () => { this.#dispatch({ type: "continue" }); }; const mutationFnContext = { client: this.#client, meta: this.options.meta, mutationKey: this.options.mutationKey }; this.#retryer = createRetryer({ fn: () => { if (!this.options.mutationFn) return Promise.reject(/* @__PURE__ */ new Error("No mutationFn found")); return this.options.mutationFn(variables, mutationFnContext); }, onFail: (failureCount, error) => { this.#dispatch({ type: "failed", failureCount, error }); }, onPause: () => { this.#dispatch({ type: "pause" }); }, onContinue, retry: this.options.retry ?? 0, retryDelay: this.options.retryDelay, networkMode: this.options.networkMode, canRun: () => this.#mutationCache.canRun(this) }); const restored = this.state.status === "pending"; const isPaused = !this.#retryer.canStart(); try { if (restored) onContinue(); else { this.#dispatch({ type: "pending", variables, isPaused }); if (this.#mutationCache.config.onMutate) await this.#mutationCache.config.onMutate(variables, this, mutationFnContext); const context = await this.options.onMutate?.(variables, mutationFnContext); if (context !== this.state.context) this.#dispatch({ type: "pending", context, variables, isPaused }); } const data = await this.#retryer.start(); await this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this, mutationFnContext); await this.options.onSuccess?.(data, variables, this.state.context, mutationFnContext); await this.#mutationCache.config.onSettled?.(data, null, this.state.variables, this.state.context, this, mutationFnContext); await this.options.onSettled?.(data, null, variables, this.state.context, mutationFnContext); this.#dispatch({ type: "success", data }); return data; } catch (error) { try { await this.#mutationCache.config.onError?.(error, variables, this.state.context, this, mutationFnContext); } catch (e) { Promise.reject(e); } try { await this.options.onError?.(error, variables, this.state.context, mutationFnContext); } catch (e) { Promise.reject(e); } try { await this.#mutationCache.config.onSettled?.(void 0, error, this.state.variables, this.state.context, this, mutationFnContext); } catch (e) { Promise.reject(e); } try { await this.options.onSettled?.(void 0, error, variables, this.state.context, mutationFnContext); } catch (e) { Promise.reject(e); } this.#dispatch({ type: "error", error }); throw error; } finally { this.#mutationCache.runNext(this); } } #dispatch(action) { const reducer = (state) => { switch (action.type) { case "failed": return { ...state, failureCount: action.failureCount, failureReason: action.error }; case "pause": return { ...state, isPaused: true }; case "continue": return { ...state, isPaused: false }; case "pending": return { ...state, context: action.context, data: void 0, failureCount: 0, failureReason: null, error: null, isPaused: action.isPaused, status: "pending", variables: action.variables, submittedAt: Date.now() }; case "success": return { ...state, data: action.data, failureCount: 0, failureReason: null, error: null, status: "success", isPaused: false }; case "error": return { ...state, data: void 0, error: action.error, failureCount: state.failureCount + 1, failureReason: action.error, isPaused: false, status: "error" }; } }; this.state = reducer(this.state); notifyManager.batch(() => { this.#observers.forEach((observer) => { observer.onMutationUpdate(action); }); this.#mutationCache.notify({ mutation: this, type: "updated", action }); }); } }; function getDefaultState() { return { context: void 0, data: void 0, error: null, failureCount: 0, failureReason: null, isPaused: false, status: "idle", variables: void 0, submittedAt: 0 }; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/mutationCache.js var MutationCache$1 = class extends Subscribable { constructor(config = {}) { super(); this.config = config; this.#mutations = /* @__PURE__ */ new Set(); this.#scopes = /* @__PURE__ */ new Map(); this.#mutationId = 0; } #mutations; #scopes; #mutationId; build(client, options, state) { const mutation = new Mutation({ client, mutationCache: this, mutationId: ++this.#mutationId, options: client.defaultMutationOptions(options), state }); this.add(mutation); return mutation; } add(mutation) { this.#mutations.add(mutation); const scope = scopeFor(mutation); if (typeof scope === "string") { const scopedMutations = this.#scopes.get(scope); if (scopedMutations) scopedMutations.push(mutation); else this.#scopes.set(scope, [mutation]); } this.notify({ type: "added", mutation }); } remove(mutation) { if (this.#mutations.delete(mutation)) { const scope = scopeFor(mutation); if (typeof scope === "string") { const scopedMutations = this.#scopes.get(scope); if (scopedMutations) { if (scopedMutations.length > 1) { const index = scopedMutations.indexOf(mutation); if (index !== -1) scopedMutations.splice(index, 1); } else if (scopedMutations[0] === mutation) this.#scopes.delete(scope); } } } this.notify({ type: "removed", mutation }); } canRun(mutation) { const scope = scopeFor(mutation); if (typeof scope === "string") { const firstPendingMutation = this.#scopes.get(scope)?.find((m) => m.state.status === "pending"); return !firstPendingMutation || firstPendingMutation === mutation; } else return true; } runNext(mutation) { const scope = scopeFor(mutation); if (typeof scope === "string") return (this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused))?.continue() ?? Promise.resolve(); else return Promise.resolve(); } clear() { notifyManager.batch(() => { this.#mutations.forEach((mutation) => { this.notify({ type: "removed", mutation }); }); this.#mutations.clear(); this.#scopes.clear(); }); } getAll() { return Array.from(this.#mutations); } find(filters) { const defaultedFilters = { exact: true, ...filters }; return this.getAll().find((mutation) => matchMutation(defaultedFilters, mutation)); } findAll(filters = {}) { return this.getAll().filter((mutation) => matchMutation(filters, mutation)); } notify(event) { notifyManager.batch(() => { this.listeners.forEach((listener) => { listener(event); }); }); } resumePausedMutations() { const pausedMutations = this.getAll().filter((x) => x.state.isPaused); return notifyManager.batch(() => Promise.all(pausedMutations.map((mutation) => mutation.continue().catch(noop)))); } }; function scopeFor(mutation) { return mutation.options.scope?.id; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/queryCache.js var QueryCache$1 = class extends Subscribable { constructor(config = {}) { super(); this.config = config; this.#queries = /* @__PURE__ */ new Map(); } #queries; build(client, options, state) { const queryKey = options.queryKey; const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options); let query = this.get(queryHash); if (!query) { query = new Query({ client, queryKey, queryHash, options: client.defaultQueryOptions(options), state, defaultOptions: client.getQueryDefaults(queryKey) }); this.add(query); } return query; } add(query) { if (!this.#queries.has(query.queryHash)) { this.#queries.set(query.queryHash, query); this.notify({ type: "added", query }); } } remove(query) { const queryInMap = this.#queries.get(query.queryHash); if (queryInMap) { query.destroy(); if (queryInMap === query) this.#queries.delete(query.queryHash); this.notify({ type: "removed", query }); } } clear() { notifyManager.batch(() => { this.getAll().forEach((query) => { this.remove(query); }); }); } get(queryHash) { return this.#queries.get(queryHash); } getAll() { return [...this.#queries.values()]; } find(filters) { const defaultedFilters = { exact: true, ...filters }; return this.getAll().find((query) => matchQuery(defaultedFilters, query)); } findAll(filters = {}) { const queries = this.getAll(); return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries; } notify(event) { notifyManager.batch(() => { this.listeners.forEach((listener) => { listener(event); }); }); } onFocus() { notifyManager.batch(() => { this.getAll().forEach((query) => { query.onFocus(); }); }); } onOnline() { notifyManager.batch(() => { this.getAll().forEach((query) => { query.onOnline(); }); }); } }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+query-core@5.100.6/node_modules/@tanstack/query-core/build/modern/queryClient.js var QueryClient$1 = class { #queryCache; #mutationCache; #defaultOptions; #queryDefaults; #mutationDefaults; #mountCount; #unsubscribeFocus; #unsubscribeOnline; constructor(config = {}) { this.#queryCache = config.queryCache || new QueryCache$1(); this.#mutationCache = config.mutationCache || new MutationCache$1(); this.#defaultOptions = config.defaultOptions || {}; this.#queryDefaults = /* @__PURE__ */ new Map(); this.#mutationDefaults = /* @__PURE__ */ new Map(); this.#mountCount = 0; } mount() { this.#mountCount++; if (this.#mountCount !== 1) return; this.#unsubscribeFocus = focusManager.subscribe(async (focused) => { if (focused) { await this.resumePausedMutations(); this.#queryCache.onFocus(); } }); this.#unsubscribeOnline = onlineManager.subscribe(async (online) => { if (online) { await this.resumePausedMutations(); this.#queryCache.onOnline(); } }); } unmount() { this.#mountCount--; if (this.#mountCount !== 0) return; this.#unsubscribeFocus?.(); this.#unsubscribeFocus = void 0; this.#unsubscribeOnline?.(); this.#unsubscribeOnline = void 0; } isFetching(filters) { return this.#queryCache.findAll({ ...filters, fetchStatus: "fetching" }).length; } isMutating(filters) { return this.#mutationCache.findAll({ ...filters, status: "pending" }).length; } /** * Imperative (non-reactive) way to retrieve data for a QueryKey. * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. * * Hint: Do not use this function inside a component, because it won't receive updates. * Use `useQuery` to create a `QueryObserver` that subscribes to changes. */ getQueryData(queryKey) { const options = this.defaultQueryOptions({ queryKey }); return this.#queryCache.get(options.queryHash)?.state.data; } ensureQueryData(options) { const defaultedOptions = this.defaultQueryOptions(options); const query = this.#queryCache.build(this, defaultedOptions); const cachedData = query.state.data; if (cachedData === void 0) return this.fetchQuery(options); if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) this.prefetchQuery(defaultedOptions); return Promise.resolve(cachedData); } getQueriesData(filters) { return this.#queryCache.findAll(filters).map(({ queryKey, state }) => { return [queryKey, state.data]; }); } setQueryData(queryKey, updater, options) { const defaultedOptions = this.defaultQueryOptions({ queryKey }); const prevData = this.#queryCache.get(defaultedOptions.queryHash)?.state.data; const data = functionalUpdate(updater, prevData); if (data === void 0) return; return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true }); } setQueriesData(filters, updater, options) { return notifyManager.batch(() => this.#queryCache.findAll(filters).map(({ queryKey }) => [queryKey, this.setQueryData(queryKey, updater, options)])); } getQueryState(queryKey) { const options = this.defaultQueryOptions({ queryKey }); return this.#queryCache.get(options.queryHash)?.state; } removeQueries(filters) { const queryCache = this.#queryCache; notifyManager.batch(() => { queryCache.findAll(filters).forEach((query) => { queryCache.remove(query); }); }); } resetQueries(filters, options) { const queryCache = this.#queryCache; return notifyManager.batch(() => { queryCache.findAll(filters).forEach((query) => { query.reset(); }); return this.refetchQueries({ type: "active", ...filters }, options); }); } cancelQueries(filters, cancelOptions = {}) { const defaultedCancelOptions = { revert: true, ...cancelOptions }; const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions))); return Promise.all(promises).then(noop).catch(noop); } invalidateQueries(filters, options = {}) { return notifyManager.batch(() => { this.#queryCache.findAll(filters).forEach((query) => { query.invalidate(); }); if (filters?.refetchType === "none") return Promise.resolve(); return this.refetchQueries({ ...filters, type: filters?.refetchType ?? filters?.type ?? "active" }, options); }); } refetchQueries(filters, options = {}) { const fetchOptions = { ...options, cancelRefetch: options.cancelRefetch ?? true }; const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => { let promise = query.fetch(void 0, fetchOptions); if (!fetchOptions.throwOnError) promise = promise.catch(noop); return query.state.fetchStatus === "paused" ? Promise.resolve() : promise; })); return Promise.all(promises).then(noop); } fetchQuery(options) { const defaultedOptions = this.defaultQueryOptions(options); if (defaultedOptions.retry === void 0) defaultedOptions.retry = false; const query = this.#queryCache.build(this, defaultedOptions); return query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query)) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data); } prefetchQuery(options) { return this.fetchQuery(options).then(noop).catch(noop); } fetchInfiniteQuery(options) { options._type = "infinite"; return this.fetchQuery(options); } prefetchInfiniteQuery(options) { return this.fetchInfiniteQuery(options).then(noop).catch(noop); } ensureInfiniteQueryData(options) { options._type = "infinite"; return this.ensureQueryData(options); } resumePausedMutations() { if (onlineManager.isOnline()) return this.#mutationCache.resumePausedMutations(); return Promise.resolve(); } getQueryCache() { return this.#queryCache; } getMutationCache() { return this.#mutationCache; } getDefaultOptions() { return this.#defaultOptions; } setDefaultOptions(options) { this.#defaultOptions = options; } setQueryDefaults(queryKey, options) { this.#queryDefaults.set(hashKey(queryKey), { queryKey, defaultOptions: options }); } getQueryDefaults(queryKey) { const defaults = [...this.#queryDefaults.values()]; const result = {}; defaults.forEach((queryDefault) => { if (partialMatchKey(queryKey, queryDefault.queryKey)) Object.assign(result, queryDefault.defaultOptions); }); return result; } setMutationDefaults(mutationKey, options) { this.#mutationDefaults.set(hashKey(mutationKey), { mutationKey, defaultOptions: options }); } getMutationDefaults(mutationKey) { const defaults = [...this.#mutationDefaults.values()]; const result = {}; defaults.forEach((queryDefault) => { if (partialMatchKey(mutationKey, queryDefault.mutationKey)) Object.assign(result, queryDefault.defaultOptions); }); return result; } defaultQueryOptions(options) { if (options._defaulted) return options; const defaultedOptions = { ...this.#defaultOptions.queries, ...this.getQueryDefaults(options.queryKey), ...options, _defaulted: true }; if (!defaultedOptions.queryHash) defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions); if (defaultedOptions.refetchOnReconnect === void 0) defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always"; if (defaultedOptions.throwOnError === void 0) defaultedOptions.throwOnError = !!defaultedOptions.suspense; if (!defaultedOptions.networkMode && defaultedOptions.persister) defaultedOptions.networkMode = "offlineFirst"; if (defaultedOptions.queryFn === skipToken) defaultedOptions.enabled = false; return defaultedOptions; } defaultMutationOptions(options) { if (options?._defaulted) return options; return { ...this.#defaultOptions.mutations, ...options?.mutationKey && this.getMutationDefaults(options.mutationKey), ...options, _defaulted: true }; } clear() { this.#queryCache.clear(); this.#mutationCache.clear(); } }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/utils.js var VUE_QUERY_CLIENT = "VUE_QUERY_CLIENT"; function getClientKey(key) { return `${VUE_QUERY_CLIENT}${key ? `:${key}` : ""}`; } function updateState(state, update) { Object.keys(state).forEach((key) => { state[key] = update[key]; }); } function _cloneDeep(value, customize, currentKey = "", currentLevel = 0) { if (customize) { const result = customize(value, currentKey, currentLevel); if (result === void 0 && /* @__PURE__ */ isRef(value)) return result; if (result !== void 0) return result; } if (Array.isArray(value)) return value.map((val, index) => _cloneDeep(val, customize, String(index), currentLevel + 1)); if (typeof value === "object" && isPlainObject(value)) { const entries = Object.entries(value).map(([key, val]) => [key, _cloneDeep(val, customize, key, currentLevel + 1)]); return Object.fromEntries(entries); } return value; } function cloneDeep(value, customize) { return _cloneDeep(value, customize); } function cloneDeepUnref(obj, unrefGetters = false) { return cloneDeep(obj, (val, key, level) => { if (level === 1 && key === "queryKey") return cloneDeepUnref(val, true); if (unrefGetters && isFunction(val)) return cloneDeepUnref(val(), unrefGetters); if (/* @__PURE__ */ isRef(val)) return cloneDeepUnref(unref(val), unrefGetters); }); } function isPlainObject(value) { if (Object.prototype.toString.call(value) !== "[object Object]") return false; const prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.prototype; } function isFunction(value) { return typeof value === "function"; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/useQueryClient.js function useQueryClient(id = "") { if (!hasInjectionContext()) throw new Error("vue-query hooks can only be used inside setup() function or functions that support injection context."); const queryClient = inject(getClientKey(id)); if (!queryClient) throw new Error("No 'queryClient' found in Vue context, use 'VueQueryPlugin' to properly initialize the library."); return queryClient; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/queryCache.js var QueryCache = class extends QueryCache$1 { find(filters) { return super.find(cloneDeepUnref(filters)); } findAll(filters = {}) { return super.findAll(cloneDeepUnref(filters)); } }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/mutationCache.js var MutationCache = class extends MutationCache$1 { find(filters) { return super.find(cloneDeepUnref(filters)); } findAll(filters = {}) { return super.findAll(cloneDeepUnref(filters)); } }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/queryClient.js var QueryClient = class extends QueryClient$1 { constructor(config = {}) { const vueQueryConfig = { defaultOptions: config.defaultOptions, queryCache: config.queryCache || new QueryCache(), mutationCache: config.mutationCache || new MutationCache() }; super(vueQueryConfig); this.isRestoring = /* @__PURE__ */ ref(false); } isFetching(filters = {}) { return super.isFetching(cloneDeepUnref(filters)); } isMutating(filters = {}) { return super.isMutating(cloneDeepUnref(filters)); } getQueryData(queryKey) { return super.getQueryData(cloneDeepUnref(queryKey)); } ensureQueryData(options) { return super.ensureQueryData(cloneDeepUnref(options)); } getQueriesData(filters) { return super.getQueriesData(cloneDeepUnref(filters)); } setQueryData(queryKey, updater, options = {}) { return super.setQueryData(cloneDeepUnref(queryKey), updater, cloneDeepUnref(options)); } setQueriesData(filters, updater, options = {}) { return super.setQueriesData(cloneDeepUnref(filters), updater, cloneDeepUnref(options)); } getQueryState(queryKey) { return super.getQueryState(cloneDeepUnref(queryKey)); } removeQueries(filters = {}) { return super.removeQueries(cloneDeepUnref(filters)); } resetQueries(filters = {}, options = {}) { return super.resetQueries(cloneDeepUnref(filters), cloneDeepUnref(options)); } cancelQueries(filters = {}, options = {}) { return super.cancelQueries(cloneDeepUnref(filters), cloneDeepUnref(options)); } invalidateQueries(filters = {}, options = {}) { const filtersCloned = cloneDeepUnref(filters); const optionsCloned = cloneDeepUnref(options); super.invalidateQueries({ ...filtersCloned, refetchType: "none" }, optionsCloned); if (filtersCloned.refetchType === "none") return Promise.resolve(); const refetchFilters = { ...filtersCloned, type: filtersCloned.refetchType ?? filtersCloned.type ?? "active" }; return nextTick().then(() => { return super.refetchQueries(refetchFilters, optionsCloned); }); } refetchQueries(filters = {}, options = {}) { return super.refetchQueries(cloneDeepUnref(filters), cloneDeepUnref(options)); } fetchQuery(options) { return super.fetchQuery(cloneDeepUnref(options)); } prefetchQuery(options) { return super.prefetchQuery(cloneDeepUnref(options)); } fetchInfiniteQuery(options) { return super.fetchInfiniteQuery(cloneDeepUnref(options)); } prefetchInfiniteQuery(options) { return super.prefetchInfiniteQuery(cloneDeepUnref(options)); } setDefaultOptions(options) { super.setDefaultOptions(cloneDeepUnref(options)); } setQueryDefaults(queryKey, options) { super.setQueryDefaults(cloneDeepUnref(queryKey), cloneDeepUnref(options)); } getQueryDefaults(queryKey) { return super.getQueryDefaults(cloneDeepUnref(queryKey)); } setMutationDefaults(mutationKey, options) { super.setMutationDefaults(cloneDeepUnref(mutationKey), cloneDeepUnref(options)); } getMutationDefaults(mutationKey) { return super.getMutationDefaults(cloneDeepUnref(mutationKey)); } }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/vueQueryPlugin.js var VueQueryPlugin = { install: (app, options = {}) => { const clientKey = getClientKey(options.queryClientKey); let client; if ("queryClient" in options && options.queryClient) client = options.queryClient; else client = new QueryClient("queryClientConfig" in options ? options.queryClientConfig : void 0); if (!isServer) client.mount(); let persisterUnmount = () => {}; if (options.clientPersister) { if (client.isRestoring) client.isRestoring.value = true; const [unmount, promise] = options.clientPersister(client); persisterUnmount = unmount; promise.then(() => { if (client.isRestoring) client.isRestoring.value = false; options.clientPersisterOnSuccess?.(client); }); } const cleanup = () => { client.unmount(); persisterUnmount(); }; if (app.onUnmount) app.onUnmount(cleanup); else { const originalUnmount = app.unmount; app.unmount = function vueQueryUnmount() { cleanup(); originalUnmount(); }; } app.provide(clientKey, client); } }; //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/useBaseQuery.js function useBaseQuery(Observer, options, queryClient) { const client = queryClient || useQueryClient(); const defaultedOptions = computed(() => { let resolvedOptions = options; if (typeof resolvedOptions === "function") resolvedOptions = resolvedOptions(); const clonedOptions = cloneDeepUnref(resolvedOptions); if (typeof clonedOptions.enabled === "function") clonedOptions.enabled = clonedOptions.enabled(); const defaulted = client.defaultQueryOptions(clonedOptions); defaulted._optimisticResults = client.isRestoring?.value ? "isRestoring" : "optimistic"; return defaulted; }); const observer = new Observer(client, defaultedOptions.value); const state = defaultedOptions.value.shallow ? /* @__PURE__ */ shallowReactive(observer.getCurrentResult()) : /* @__PURE__ */ reactive(observer.getCurrentResult()); let unsubscribe = () => {}; if (client.isRestoring) watch(client.isRestoring, (isRestoring) => { if (!isRestoring) { unsubscribe(); unsubscribe = observer.subscribe((result) => { updateState(state, result); }); } }, { immediate: true }); const updater = () => { observer.setOptions(defaultedOptions.value); updateState(state, observer.getCurrentResult()); }; watch(defaultedOptions, updater); onScopeDispose(() => { unsubscribe(); }); const refetch = (...args) => { updater(); return state.refetch(...args); }; const suspense = () => { return new Promise((resolve, reject) => { let stopWatch = () => {}; const run = () => { if (defaultedOptions.value.enabled !== false) { observer.setOptions(defaultedOptions.value); const optimisticResult = observer.getOptimisticResult(defaultedOptions.value); if (optimisticResult.isStale) { stopWatch(); observer.fetchOptimistic(defaultedOptions.value).then(resolve, (error) => { if (shouldThrowError(defaultedOptions.value.throwOnError, [error, observer.getCurrentQuery()])) reject(error); else resolve(observer.getCurrentResult()); }); } else { stopWatch(); resolve(optimisticResult); } } }; run(); stopWatch = watch(defaultedOptions, run); }); }; watch(() => state.error, (error) => { if (state.isError && !state.isFetching && shouldThrowError(defaultedOptions.value.throwOnError, [error, observer.getCurrentQuery()])) throw error; }); const object = /* @__PURE__ */ toRefs(defaultedOptions.value.shallow ? /* @__PURE__ */ shallowReadonly(state) : /* @__PURE__ */ readonly(state)); for (const key in state) if (typeof state[key] === "function") object[key] = state[key]; object.suspense = suspense; object.refetch = refetch; return object; } //#endregion //#region ../../node_modules/.pnpm/@tanstack+vue-query@5.100.6_vue@3.5.33_typescript@5.9.3_/node_modules/@tanstack/vue-query/build/modern/useQuery.js function useQuery(options, queryClient) { return useBaseQuery(QueryObserver, options, queryClient); } //#endregion //#region ../send/frontend/src/lib/auth.ts /** * useAuth is a composable that manages authentication state and actions. * It returns the login status and methods to refetch and log out. * It's important to note that this composable should only be used inside vue components. */ function useAuth() { const { api } = useApiStore(); const authStore = useAuthStore(); const { isLoggedIn } = storeToRefs(authStore); const { refetch: refetchAuth, isLoading } = useQuery({ queryKey: ["session"], queryFn: async () => { try { if (await authStore.checkAuthStatus()) { isLoggedIn.value = true; return true; } } catch (error) { console.debug("OIDC auth check failed:", error); } const isValid = await validateToken(api); isLoggedIn.value = isValid; return isValid; }, refetchOnMount: !isLoggedIn.value ? true : false, refetchOnWindowFocus: !isLoggedIn.value ? true : false }); const logOutAuth = async () => { try { await authStore.logoutFromOIDC(); } catch (error) { console.error("OIDC logout failed:", error); } try { await api.removeAuthToken(); } catch (error) { console.error("Legacy logout failed:", error); } isLoggedIn.value = false; }; return { isLoggedIn, refetchAuth, logOutAuth, isLoadingAuth: isLoading }; } //#endregion //#region ../send/frontend/src/lib/errorMessages.ts var ERROR_MESSAGES = { SIZE_EXCEEDED: `Your upload exceeds the maximum upload size (${formatBytes(MAX_FILE_SIZE)}). Please remove the oversized files and try again.` }; var STORAGE_LIMIT_EXCEEDED = "You have exceeded your storage limit. Please remove files to continue uploading. Try re opening this page after freeing up space."; //#endregion //#region ../send/frontend/src/lib/login.ts /** * Open a URL in its own popup window and invoke `finishLogin` once that window * is closed. Returns `true` if the window was created, `false` if it failed — * callers rely on this so they don't get stuck in an "opening…" state when the * window never appears (the `finishLogin` callback only runs on close). */ async function openPopup(authUrl, finishLogin) { try { const popup = await browser.windows.create({ url: authUrl, type: "popup", allowScriptsToClose: true }); const checkPopupClosed = (windowId) => { if (windowId === popup.id) { browser.windows.onRemoved.removeListener(checkPopupClosed); finishLogin(); } }; browser.windows.onRemoved.addListener(checkPopupClosed); return true; } catch (e) { console.log(`popup failed`); console.log(e); return false; } } //#endregion //#region ../send/frontend/src/lib/queries.ts var canUploadQuery = async () => { const { api } = useApiStore(); const canUpload = await api.call("uploads/can-upload"); if (!canUpload) throw new Error(STORAGE_LIMIT_EXCEEDED); return canUpload; }; //#endregion //#region ../send/frontend/src/apps/send/components/FileUploadTemplate.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$8 = { class: "modal-container" }; var _hoisted_2$6 = { class: "modal-header" }; var _hoisted_3$6 = { class: "header-content" }; var _hoisted_4$5 = { class: "header-left" }; var _hoisted_5$5 = { key: 0, class: "step-indicator" }; var _hoisted_6$4 = { class: "modal-title" }; var _hoisted_7$3 = { class: "modal-content" }; var _hoisted_8$2 = { key: 0, class: "error-banner" }; var _hoisted_9$1 = { class: "error-text" }; var _hoisted_10$1 = { class: "modal-footer" }; var _hoisted_11$1 = ["disabled"]; var _hoisted_12$1 = { key: 0, class: "loading-spinner" }; //#endregion //#region ../send/frontend/src/apps/send/components/FileUploadTemplate.vue var FileUploadTemplate_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "FileUploadTemplate", props: { step: {}, showCloseButton: { type: Boolean }, showBackButton: { type: Boolean }, showPrimaryButton: { type: Boolean }, primaryButtonText: {}, primaryButtonDisabled: { type: Boolean }, showSecondaryButton: { type: Boolean }, secondaryButtonText: {}, isLoading: { type: Boolean }, errorMessage: {} }, emits: [ "close", "back", "primary", "secondary" ], setup(__props, { emit: __emit }) { const props = __props; const emit = __emit; const showStepIndicator = computed(() => { return props.step && props.step.totalSteps > 1; }); const stepText = computed(() => { if (!props.step) return ""; return `STEP ${props.step.stepNumber} OF ${props.step.totalSteps}`; }); return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1$8, [ createBaseVNode("div", _hoisted_2$6, [createBaseVNode("div", _hoisted_3$6, [createBaseVNode("div", _hoisted_4$5, [showStepIndicator.value ? (openBlock(), createElementBlock("div", _hoisted_5$5, toDisplayString(stepText.value), 1)) : createCommentVNode("", true), createBaseVNode("h2", _hoisted_6$4, toDisplayString(__props.step?.title || ""), 1)])])]), createBaseVNode("div", _hoisted_7$3, [__props.errorMessage ? (openBlock(), createElementBlock("div", _hoisted_8$2, [createBaseVNode("span", _hoisted_9$1, toDisplayString(__props.errorMessage), 1)])) : createCommentVNode("", true), renderSlot(_ctx.$slots, "default", {}, void 0, true)]), createBaseVNode("div", _hoisted_10$1, [ __props.showBackButton ? (openBlock(), createElementBlock("button", { key: 0, class: "button button-secondary", "data-test": "back-button", onClick: _cache[0] || (_cache[0] = ($event) => emit("back")) }, toDisplayString(__props.secondaryButtonText || "Back"), 1)) : createCommentVNode("", true), __props.showSecondaryButton && !__props.showBackButton ? (openBlock(), createElementBlock("button", { key: 1, class: "button button-secondary", "data-test": "secondary-button", onClick: _cache[1] || (_cache[1] = ($event) => emit("secondary")) }, toDisplayString(__props.secondaryButtonText || "Cancel"), 1)) : createCommentVNode("", true), __props.showPrimaryButton ? (openBlock(), createElementBlock("button", { key: 2, class: "button button-primary", "data-test": "primary-button", disabled: __props.primaryButtonDisabled || __props.isLoading, onClick: _cache[2] || (_cache[2] = ($event) => emit("primary")) }, [__props.isLoading ? (openBlock(), createElementBlock("span", _hoisted_12$1)) : createCommentVNode("", true), createBaseVNode("span", null, toDisplayString(__props.primaryButtonText || "Next"), 1)], 8, _hoisted_11$1)) : createCommentVNode("", true) ]) ]); }; } }), [["__scopeId", "data-v-b19c9e70"]]); //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/ErrorStep.vue var ErrorStep_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "ErrorStep", props: { uploadError: {} }, emits: ["close", "retry"], setup(__props, { emit: __emit }) { const emit = __emit; function handleClose() { emit("close"); } function handleRetry() { emit("retry"); } return (_ctx, _cache) => { return openBlock(), createBlock(FileUploadTemplate_default, { step: { stepNumber: 2, totalSteps: 2, title: "Select File Expiration" }, "show-close-button": true, "show-primary-button": true, "primary-button-text": "Try again", "error-message": __props.uploadError, onClose: handleClose, onPrimary: handleRetry }, { default: withCtx(() => [..._cache[0] || (_cache[0] = [createBaseVNode("div", { class: "error-container" }, [ createBaseVNode("div", { class: "error-icon" }, [createBaseVNode("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }, [ createBaseVNode("circle", { cx: "12", cy: "12", r: "10" }), createBaseVNode("line", { x1: "12", y1: "8", x2: "12", y2: "12" }), createBaseVNode("line", { x1: "12", y1: "16", x2: "12.01", y2: "16" }) ])]), createBaseVNode("h3", { class: "error-title" }, "Upload failed"), createBaseVNode("p", { class: "error-description" }, " We encountered an error while uploading your file. This could be due to network issues or file size limitations. Please check your connection and try again. ") ], -1)])]), _: 1 }, 8, ["error-message"]); }; } }), [["__scopeId", "data-v-26312c37"]]); //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/ExpirationStep.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$7 = { class: "radio-group" }; var _hoisted_2$5 = { class: "radio-option" }; var _hoisted_3$5 = ["checked"]; var _hoisted_4$4 = { class: "radio-option" }; var _hoisted_5$4 = ["checked"]; var _hoisted_6$3 = { class: "radio-option" }; var _hoisted_7$2 = ["checked"]; var _hoisted_8$1 = { class: "radio-option" }; var _hoisted_9 = ["checked"]; var _hoisted_10 = { class: "radio-option" }; var _hoisted_11 = ["checked"]; var _hoisted_12 = { key: 0, class: "custom-datetime" }; var _hoisted_13 = { class: "field-group" }; var _hoisted_14 = ["value"]; //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/ExpirationStep.vue var ExpirationStep_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "ExpirationStep", props: { selectedExpiration: {}, customDateTime: {}, isExtension: { type: Boolean } }, emits: [ "update:selectedExpiration", "update:customDateTime", "back", "close", "createLink", "setExpiredForTesting" ], setup(__props, { emit: __emit }) { const props = __props; const emit = __emit; const isCustomSelected = computed(() => { return props.selectedExpiration === "custom"; }); function handleBack() { emit("back"); } function handleClose() { emit("close"); } function handleCreateLink() { emit("createLink"); } function updateSelectedExpiration(value) { emit("update:selectedExpiration", value); } function updateCustomDateTime(value) { emit("update:customDateTime", value); } function handleSetExpiredForTesting() { emit("setExpiredForTesting"); } return (_ctx, _cache) => { return openBlock(), createBlock(FileUploadTemplate_default, { step: { stepNumber: 2, totalSteps: 2, title: "Select File Expiration" }, "show-close-button": true, "show-back-button": true, "show-primary-button": true, "primary-button-text": "Create Link", "back-button-text": "Back", onClose: handleClose, onBack: handleBack, onPrimary: handleCreateLink }, { default: withCtx(() => [ _cache[12] || (_cache[12] = createBaseVNode("p", { class: "description" }, "Choose when the download link expires", -1)), createBaseVNode("div", _hoisted_1$7, [ createBaseVNode("label", _hoisted_2$5, [createBaseVNode("input", { checked: __props.selectedExpiration === "never", type: "radio", name: "expiration", value: "never", class: "radio-input", onChange: _cache[0] || (_cache[0] = ($event) => updateSelectedExpiration("never")) }, null, 40, _hoisted_3$5), _cache[6] || (_cache[6] = createBaseVNode("span", { class: "radio-label" }, "Never expire", -1))]), createBaseVNode("label", _hoisted_4$4, [createBaseVNode("input", { checked: __props.selectedExpiration === "24hours", type: "radio", name: "expiration", value: "24hours", class: "radio-input", onChange: _cache[1] || (_cache[1] = ($event) => updateSelectedExpiration("24hours")) }, null, 40, _hoisted_5$4), _cache[7] || (_cache[7] = createBaseVNode("span", { class: "radio-label" }, "Expire in 24 hours", -1))]), createBaseVNode("label", _hoisted_6$3, [createBaseVNode("input", { checked: __props.selectedExpiration === "14days", type: "radio", name: "expiration", value: "14days", class: "radio-input", onChange: _cache[2] || (_cache[2] = ($event) => updateSelectedExpiration("14days")) }, null, 40, _hoisted_7$2), _cache[8] || (_cache[8] = createBaseVNode("span", { class: "radio-label" }, "Expire in 14 days (default)", -1))]), createBaseVNode("label", _hoisted_8$1, [createBaseVNode("input", { checked: __props.selectedExpiration === "30days", type: "radio", name: "expiration", value: "30days", class: "radio-input", onChange: _cache[3] || (_cache[3] = ($event) => updateSelectedExpiration("30days")) }, null, 40, _hoisted_9), _cache[9] || (_cache[9] = createBaseVNode("span", { class: "radio-label" }, "Expire in 30 days", -1))]), createBaseVNode("label", _hoisted_10, [createBaseVNode("input", { checked: __props.selectedExpiration === "custom", type: "radio", name: "expiration", value: "custom", class: "radio-input", onChange: _cache[4] || (_cache[4] = ($event) => updateSelectedExpiration("custom")) }, null, 40, _hoisted_11), _cache[10] || (_cache[10] = createBaseVNode("span", { class: "radio-label" }, "Select date and time", -1))]) ]), isCustomSelected.value ? (openBlock(), createElementBlock("div", _hoisted_12, [createBaseVNode("div", _hoisted_13, [_cache[11] || (_cache[11] = createBaseVNode("label", { for: "select-datetime", class: "field-label" }, " Select date and time ", -1)), createBaseVNode("input", { id: "select-datetime", value: __props.customDateTime, type: "datetime-local", class: "input-field", onInput: _cache[5] || (_cache[5] = ($event) => updateCustomDateTime($event.target.value)) }, null, 40, _hoisted_14)])])) : createCommentVNode("", true), !__props.isExtension ? (openBlock(), createElementBlock("button", { key: 1, type: "button", class: "test-expired-button", onClick: handleSetExpiredForTesting }, " 🧪 Set Expired (10 days ago) - For Testing ")) : createCommentVNode("", true) ]), _: 1 }); }; } }), [["__scopeId", "data-v-9fcc9438"]]); //#endregion //#region ../../node_modules/.pnpm/@tabler+icons-vue@2.47.0_vue@3.5.33_typescript@5.9.3_/node_modules/@tabler/icons-vue/dist/esm/defaultAttributes.js /** * @tabler/icons-vue v2.47.0 - MIT */ var defaultAttributes = { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round" }; //#endregion //#region ../../node_modules/.pnpm/@tabler+icons-vue@2.47.0_vue@3.5.33_typescript@5.9.3_/node_modules/@tabler/icons-vue/dist/esm/createVueComponent.js /** * @tabler/icons-vue v2.47.0 - MIT */ var __defProp = 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 = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) { for (var prop of __getOwnPropSymbols(b)) if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __objRest = (source, exclude) => { var target = {}; for (var prop in source) if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) target[prop] = source[prop]; if (source != null && __getOwnPropSymbols) { for (var prop of __getOwnPropSymbols(source)) if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) target[prop] = source[prop]; } return target; }; var createVueComponent = (iconName, iconNamePascal, iconNode) => (_a, { attrs, slots }) => { var _b = _a, { size, color, strokeWidth } = _b, props = __objRest(_b, [ "size", "color", "strokeWidth" ]); return h$3("svg", __spreadValues(__spreadProps(__spreadValues(__spreadProps(__spreadValues({}, defaultAttributes), { width: size || defaultAttributes.width, height: size || defaultAttributes.height, stroke: color || defaultAttributes.stroke, "stroke-width": strokeWidth || defaultAttributes["stroke-width"] }), attrs), { class: [ "tabler-icon", `tabler-icon-${iconName}`, (attrs == null ? void 0 : attrs.class) || "" ] }), props), [...iconNode.map((child) => h$3(...child)), ...slots.default ? [slots.default()] : []]); }; //#endregion //#region ../../node_modules/.pnpm/@tabler+icons-vue@2.47.0_vue@3.5.33_typescript@5.9.3_/node_modules/@tabler/icons-vue/dist/esm/icons/IconEyeClosed.js /** * @tabler/icons-vue v2.47.0 - MIT */ var IconEyeClosed = createVueComponent("eye-closed", "IconEyeClosed", [ ["path", { d: "M21 9c-2.4 2.667 -5.4 4 -9 4c-3.6 0 -6.6 -1.333 -9 -4", key: "svg-0" }], ["path", { d: "M3 15l2.5 -3.8", key: "svg-1" }], ["path", { d: "M21 14.976l-2.492 -3.776", key: "svg-2" }], ["path", { d: "M9 17l.5 -4", key: "svg-3" }], ["path", { d: "M15 17l-.5 -4", key: "svg-4" }] ]); //#endregion //#region ../../node_modules/.pnpm/@tabler+icons-vue@2.47.0_vue@3.5.33_typescript@5.9.3_/node_modules/@tabler/icons-vue/dist/esm/icons/IconEye.js /** * @tabler/icons-vue v2.47.0 - MIT */ var IconEye = createVueComponent("eye", "IconEye", [["path", { d: "M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0", key: "svg-0" }], ["path", { d: "M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6", key: "svg-1" }]]); //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/PasswordStep.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$6 = { class: "checkbox-container" }; var _hoisted_2$4 = ["checked"]; var _hoisted_3$4 = { key: 0, class: "form-fields" }; var _hoisted_4$3 = { class: "field-group" }; var _hoisted_5$3 = { class: "password-input-wrapper" }; var _hoisted_6$2 = ["value", "type"]; var _hoisted_7$1 = ["aria-label"]; //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/PasswordStep.vue var PasswordStep_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "PasswordStep", props: { isPasswordProtected: { type: Boolean }, password: {}, passwordHint: {} }, emits: [ "update:isPasswordProtected", "update:password", "update:passwordHint", "next", "close" ], setup(__props, { emit: __emit }) { const props = __props; const emit = __emit; const passwordFieldType = /* @__PURE__ */ ref("password"); const isPasswordVisible = computed(() => { return passwordFieldType.value === "text"; }); const canProceed = computed(() => { return !props.isPasswordProtected || props.password.length > 0; }); function togglePasswordVisibility() { passwordFieldType.value = passwordFieldType.value === "password" ? "text" : "password"; } function handleNext() { emit("next"); } function handleClose() { emit("close"); } function updateIsPasswordProtected(value) { emit("update:isPasswordProtected", value); } function updatePassword(value) { emit("update:password", value); } return (_ctx, _cache) => { return openBlock(), createBlock(FileUploadTemplate_default, { step: { stepNumber: 1, totalSteps: 2, title: "Create File Password" }, "show-close-button": true, "show-primary-button": true, "primary-button-text": "Next", "primary-button-disabled": !canProceed.value, onClose: handleClose, onPrimary: handleNext }, { default: withCtx(() => [ _cache[5] || (_cache[5] = createBaseVNode("p", { class: "description" }, " A file password provides an extra layer of security in case your email is accessed by an unintended recipient. ", -1)), createBaseVNode("div", _hoisted_1$6, [createBaseVNode("input", { id: "password-checkbox", checked: __props.isPasswordProtected, type: "checkbox", class: "checkbox", onChange: _cache[0] || (_cache[0] = ($event) => updateIsPasswordProtected($event.target.checked)) }, null, 40, _hoisted_2$4), _cache[2] || (_cache[2] = createBaseVNode("label", { for: "password-checkbox", class: "checkbox-label" }, " Protect this file with a password (recommended) ", -1))]), __props.isPasswordProtected ? (openBlock(), createElementBlock("div", _hoisted_3$4, [createBaseVNode("div", _hoisted_4$3, [ _cache[3] || (_cache[3] = createBaseVNode("label", { for: "file-password", class: "field-label" }, [createTextVNode(" File Password "), createBaseVNode("span", { class: "required" }, "*")], -1)), createBaseVNode("div", _hoisted_5$3, [createBaseVNode("input", { id: "file-password", value: __props.password, type: passwordFieldType.value, class: "input-field", placeholder: "Enter password", autocomplete: "new-password", onInput: _cache[1] || (_cache[1] = ($event) => updatePassword($event.target.value)) }, null, 40, _hoisted_6$2), createBaseVNode("button", { type: "button", class: "password-toggle", "aria-label": isPasswordVisible.value ? "Hide password" : "Show password", onClick: togglePasswordVisibility }, [!isPasswordVisible.value ? (openBlock(), createBlock(unref(IconEye), { key: 0, size: 20 })) : createCommentVNode("", true), isPasswordVisible.value ? (openBlock(), createBlock(unref(IconEyeClosed), { key: 1, size: 20 })) : createCommentVNode("", true)], 8, _hoisted_7$1)]), _cache[4] || (_cache[4] = createBaseVNode("p", { class: "field-help" }, " Share this password with your recipient using a separate communication channel. ", -1)) ])])) : createCommentVNode("", true) ]), _: 1 }, 8, ["primary-button-disabled"]); }; } }), [["__scopeId", "data-v-78f20f8d"]]); //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/SuccessStep.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$5 = { class: "success-container" }; var _hoisted_2$3 = { class: "url-container" }; var _hoisted_3$3 = ["value"]; //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/SuccessStep.vue var SuccessStep_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "SuccessStep", props: { shareUrl: {} }, emits: ["close", "copyToClipboard"], setup(__props, { emit: __emit }) { const emit = __emit; function handleClose() { emit("close"); } function handleCopyToClipboard() { emit("copyToClipboard"); } return (_ctx, _cache) => { return openBlock(), createBlock(FileUploadTemplate_default, { step: { stepNumber: 2, totalSteps: 2, title: "Link Created Successfully" }, "show-close-button": true, "show-primary-button": true, "primary-button-text": "Close", onClose: handleClose, onPrimary: handleClose }, { default: withCtx(() => [createBaseVNode("div", _hoisted_1$5, [ _cache[1] || (_cache[1] = createBaseVNode("div", { class: "success-icon" }, [createBaseVNode("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }, [createBaseVNode("circle", { cx: "12", cy: "12", r: "10" }), createBaseVNode("path", { d: "M9 12l2 2 4-4" })])], -1)), _cache[2] || (_cache[2] = createBaseVNode("h3", { class: "success-title" }, "Your file has been uploaded!", -1)), _cache[3] || (_cache[3] = createBaseVNode("p", { class: "success-description" }, " Share this link with your recipient. They will need the password to access the file. ", -1)), createBaseVNode("div", _hoisted_2$3, [createBaseVNode("input", { value: __props.shareUrl, readonly: "", class: "url-input", onFocus: _cache[0] || (_cache[0] = ($event) => $event.target.select()) }, null, 40, _hoisted_3$3), createBaseVNode("button", { class: "copy-button", onClick: handleCopyToClipboard }, "Copy")]) ])]), _: 1 }); }; } }), [["__scopeId", "data-v-ad17875a"]]); //#endregion //#region ../send/frontend/src/apps/send/components/ProgressBar.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$4 = { class: "progress-content" }; var _hoisted_2$2 = { class: "title" }; var _hoisted_3$2 = { class: "progress-info" }; var _hoisted_4$2 = { class: "progress-bar-container" }; var _hoisted_5$2 = { class: "progress-percentage" }; //#endregion //#region ../send/frontend/src/apps/send/components/ProgressBar.vue var ProgressBar_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "ProgressBar", setup(__props) { const { progress } = useStatusStore(); onUnmounted(() => { progress.initialize(); }); return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1$4, [createBaseVNode("h2", _hoisted_2$2, toDisplayString(unref(progress).text), 1), createBaseVNode("div", _hoisted_3$2, [createBaseVNode("div", _hoisted_4$2, [createBaseVNode("div", { class: "progress-bar", style: normalizeStyle({ width: unref(progress).percentage + "%" }) }, null, 4)]), createBaseVNode("span", _hoisted_5$2, toDisplayString(unref(progress).percentage) + "%", 1)])]); }; } }), [["__scopeId", "data-v-4538f998"]]); //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/UploadingStep.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$3 = { class: "upload-container" }; var _hoisted_2$1 = { key: 0, class: "file-status-list" }; var _hoisted_3$1 = { class: "file-status-icon" }; var _hoisted_4$1 = { key: 0, class: "status-pending" }; var _hoisted_5$1 = { key: 1, class: "status-uploading" }; var _hoisted_6$1 = { key: 2, class: "status-completed" }; var _hoisted_7 = { key: 3, class: "status-error" }; var _hoisted_8 = { class: "file-name" }; //#endregion //#region ../send/frontend/src/apps/send/components/upload-steps/UploadingStep.vue var UploadingStep_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "UploadingStep", props: { fileUploadStatuses: {} }, setup(__props) { return (_ctx, _cache) => { return openBlock(), createBlock(FileUploadTemplate_default, { step: { stepNumber: 2, totalSteps: 2, title: "Select File Expiration" }, "show-close-button": false }, { default: withCtx(() => [createBaseVNode("div", _hoisted_1$3, [createVNode(ProgressBar_default), __props.fileUploadStatuses.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_2$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.fileUploadStatuses, (file, index) => { return openBlock(), createElementBlock("div", { key: index, class: "file-status-item" }, [createBaseVNode("span", _hoisted_3$1, [ file.status === "pending" ? (openBlock(), createElementBlock("span", _hoisted_4$1, "⏳")) : createCommentVNode("", true), file.status === "uploading" ? (openBlock(), createElementBlock("span", _hoisted_5$1, "📤")) : createCommentVNode("", true), file.status === "completed" ? (openBlock(), createElementBlock("span", _hoisted_6$1, "✅")) : createCommentVNode("", true), file.status === "error" ? (openBlock(), createElementBlock("span", _hoisted_7, "❌")) : createCommentVNode("", true) ]), createBaseVNode("span", _hoisted_8, toDisplayString(file.name), 1)]); }), 128))])) : createCommentVNode("", true)])]), _: 1 }); }; } }), [["__scopeId", "data-v-de45c1ba"]]); //#endregion //#region ../send/frontend/src/apps/send/pages/UploadPage.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$2 = { id: "send-page", class: "container" }; //#endregion //#region ../send/frontend/src/apps/send/pages/UploadPage.vue var UploadPage_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "UploadPage", props: { files: { default: null }, onUploadAndShare: { type: Function, default: void 0 } }, setup(__props) { const props = __props; const userStore = useUserStore(); const { keychain } = useKeychainStore(); const folderStore = useFolderStore(); const sharingStore = useSharingStore(); const { api } = useApiStore(); const { initializeClientMetrics } = useMetricsStore(); const { progress } = useStatusStore(); const { isThunderbirdHost } = useConfigStore(); const currentStep = /* @__PURE__ */ ref("password"); const password = /* @__PURE__ */ ref(""); const passwordHint = /* @__PURE__ */ ref(""); const isPasswordProtected = /* @__PURE__ */ ref(true); const selectedExpiration = /* @__PURE__ */ ref("14days"); const customDateTime = /* @__PURE__ */ ref(""); const isUploading = /* @__PURE__ */ ref(false); const uploadError = /* @__PURE__ */ ref(""); const shareUrl = /* @__PURE__ */ ref(""); const fileUploadStatuses = /* @__PURE__ */ ref([]); const dummyFile = /* @__PURE__ */ ref(null); const isExtension = isThunderbirdHost; function handleNext() { currentStep.value = "expiration"; } function handleBack() { currentStep.value = "password"; } function handleClose() { currentStep.value = "password"; password.value = ""; passwordHint.value = ""; isPasswordProtected.value = true; selectedExpiration.value = "14days"; uploadError.value = ""; shareUrl.value = ""; fileUploadStatuses.value = []; progress.initialize(); } function setExpiredForTesting() { selectedExpiration.value = "custom"; const pastDate = /* @__PURE__ */ new Date(); pastDate.setDate(pastDate.getDate() - 10); customDateTime.value = `${pastDate.getFullYear()}-${String(pastDate.getMonth() + 1).padStart(2, "0")}-${String(pastDate.getDate()).padStart(2, "0")}T${String(pastDate.getHours()).padStart(2, "0")}:${String(pastDate.getMinutes()).padStart(2, "0")}`; } async function handleCreateLink() { currentStep.value = "uploading"; isUploading.value = true; uploadError.value = ""; try { const filesToUpload = props.files && props.files.length > 0 ? props.files : null; if (filesToUpload) fileUploadStatuses.value = filesToUpload.map((file) => ({ name: file.name, status: "pending" })); else if (!dummyFile.value) { const dummyContent = "This is a test file created for demonstration purposes.\n".repeat(100); const blob = new Blob([dummyContent], { type: "text/plain" }); dummyFile.value = new File([blob], "test-document.txt", { type: "text/plain" }); fileUploadStatuses.value = [{ name: "test-document.txt", status: "pending" }]; } if (isExtension && props.onUploadAndShare && filesToUpload) { const finalPassword = isPasswordProtected.value ? password.value : ""; const expirationDate = getExpirationDate(selectedExpiration.value, customDateTime.value); await props.onUploadAndShare(filesToUpload, finalPassword, expirationDate, (fileIndex, status) => { if (fileUploadStatuses.value[fileIndex]) fileUploadStatuses.value[fileIndex].status = status; }); return; } const rootFolderId = await folderStore.getDefaultFolderId(); let uploadedItems = []; if (filesToUpload) for (let i = 0; i < filesToUpload.length; i++) { const fileItem = filesToUpload[i]; fileUploadStatuses.value[i].status = "uploading"; const items = await folderStore.uploadItem(fileItem.data, rootFolderId, api); if (items && items.length > 0) { uploadedItems.push(...items); fileUploadStatuses.value[i].status = "completed"; } } else { if (!dummyFile.value) { const dummyContent = "This is a test file created for demonstration purposes.\n".repeat(100); const blob = new Blob([dummyContent], { type: "text/plain" }); dummyFile.value = new File([blob], "test-document.txt", { type: "text/plain" }); } fileUploadStatuses.value[0].status = "uploading"; const items = await folderStore.uploadItem(dummyFile.value, rootFolderId, api); if (items && items.length > 0) { uploadedItems.push(...items); fileUploadStatuses.value[0].status = "completed"; } } if (!uploadedItems || uploadedItems.length === 0) throw new Error("Could not upload file"); const organizedFiles = organizeFiles(uploadedItems); const finalPassword = isPasswordProtected.value ? password.value : ""; const expirationDate = getExpirationDate(selectedExpiration.value, customDateTime.value); const url = await sharingStore.shareItems(organizedFiles, finalPassword, expirationDate); if (!url) throw new Error("Did not get URL back from sharing"); shareUrl.value = url; if (isExtension) { browser.runtime.sendMessage({ type: ALL_UPLOADS_COMPLETE, url, results: uploadedItems, aborted: false }); window.close(); } else currentStep.value = "success"; } catch (error) { console.error("Upload/Share failed:", error); uploadError.value = error.message || "Upload failed. Please try again."; if (isExtension) { browser.runtime.sendMessage({ type: ALL_UPLOADS_ABORTED, aborted: true }); window.close(); } else currentStep.value = "error"; } finally { isUploading.value = false; } } function handleRetry() { currentStep.value = "expiration"; uploadError.value = ""; progress.initialize(); } function copyToClipboard() { if (typeof window !== "undefined" && window.navigator?.clipboard) window.navigator.clipboard.writeText(shareUrl.value); } onMounted(async () => { await init$2(userStore, keychain, folderStore); const uid = userStore.user.uniqueHash; initializeClientMetrics(uid); }); useMetricsUpdate(); return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1$2, [ currentStep.value === "password" ? (openBlock(), createBlock(PasswordStep_default, { key: 0, "is-password-protected": isPasswordProtected.value, "onUpdate:isPasswordProtected": _cache[0] || (_cache[0] = ($event) => isPasswordProtected.value = $event), password: password.value, "onUpdate:password": _cache[1] || (_cache[1] = ($event) => password.value = $event), "password-hint": passwordHint.value, "onUpdate:passwordHint": _cache[2] || (_cache[2] = ($event) => passwordHint.value = $event), onNext: handleNext, onClose: handleClose }, null, 8, [ "is-password-protected", "password", "password-hint" ])) : createCommentVNode("", true), currentStep.value === "expiration" ? (openBlock(), createBlock(ExpirationStep_default, { key: 1, "selected-expiration": selectedExpiration.value, "onUpdate:selectedExpiration": _cache[3] || (_cache[3] = ($event) => selectedExpiration.value = $event), "custom-date-time": customDateTime.value, "onUpdate:customDateTime": _cache[4] || (_cache[4] = ($event) => customDateTime.value = $event), "is-extension": unref(isExtension), onBack: handleBack, onClose: handleClose, onCreateLink: handleCreateLink, onSetExpiredForTesting: setExpiredForTesting }, null, 8, [ "selected-expiration", "custom-date-time", "is-extension" ])) : createCommentVNode("", true), currentStep.value === "uploading" ? (openBlock(), createBlock(UploadingStep_default, { key: 2, "file-upload-statuses": fileUploadStatuses.value }, null, 8, ["file-upload-statuses"])) : createCommentVNode("", true), currentStep.value === "success" && !unref(isExtension) ? (openBlock(), createBlock(SuccessStep_default, { key: 3, "share-url": shareUrl.value, onClose: handleClose, onCopyToClipboard: copyToClipboard }, null, 8, ["share-url"])) : createCommentVNode("", true), currentStep.value === "error" && !unref(isExtension) ? (openBlock(), createBlock(ErrorStep_default, { key: 4, "upload-error": uploadError.value, onClose: handleClose, onRetry: handleRetry }, null, 8, ["upload-error"])) : createCommentVNode("", true) ]); }; } }), [["__scopeId", "data-v-5d1cc8b5"]]); //#endregion //#region ../send/frontend/src/apps/send/views/PopupView.vue?vue&type=script&setup=true&lang.ts var _hoisted_1$1 = { key: 1 }; var _hoisted_2 = { key: 0, class: "finish-setup" }; var _hoisted_3 = { key: 1 }; var _hoisted_4 = { key: 0 }; var _hoisted_5 = { key: 1 }; var _hoisted_6 = { key: 0 }; //#endregion //#region ../send/frontend/src/apps/send/views/PopupView.vue var PopupView_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "PopupView", setup(__props) { const userStore = useUserStore(); const { keychain } = useKeychainStore(); const { api } = useApiStore(); const { validators, progress } = useStatusStore(); const { isLoggedIn, refetchAuth, isLoadingAuth } = useAuth(); const folderStore = useFolderStore(); const { isError: uploadingError, uploadAndShare } = useUploadAndShare(); const files = /* @__PURE__ */ ref(null); const message = /* @__PURE__ */ ref(""); async function handleUploadAndShare(files, password, expiration, onStatusUpdate) { if (!files || files.length === 0) return; await uploadAndShare(files, password, expiration, onStatusUpdate); } const { error: uploadBlockedDuetoSize } = useQuery({ queryKey: ["can-upload"], queryFn: canUploadQuery }); const { data: isConfigured, refetch, isLoading: isLoadingConfigured } = useQuery({ queryKey: ["is-configured-for-upload"], queryFn: async () => { await refetchAuth(); const { hasBackedUpKeys, isTokenValid, hasForcedLogin } = await validators(); if (!hasBackedUpKeys) { message.value = `Please make sure you have backed up or restored your keys. Go back to the compositon panel and follow the instructions`; return false; } if (!isTokenValid || hasForcedLogin) { message.value = `You're not logged in properly. Please go back to the compositon panel to log back in`; return false; } await initialize(); return true; }, refetchOnWindowFocus: true, refetchOnMount: true }); const isSecurityPopupOpen = /* @__PURE__ */ ref(false); async function openSecurityPopup() { if (isSecurityPopupOpen.value) return; isSecurityPopupOpen.value = true; if (!await openPopup(`https://send.tb.pro/send/security-and-privacy?closeOnComplete=true`, () => { isSecurityPopupOpen.value = false; refetch(); })) isSecurityPopupOpen.value = false; } watch(isConfigured, (configured) => { if (configured === false && isLoggedIn.value) openSecurityPopup(); }); const initialize = async () => { try { await restoreKeysUsingLocalStorage(keychain, api); await init$2(userStore, keychain, folderStore); console.log(`adding listener in Popup for runtime messages`); browser.runtime.onMessage.addListener(async (message) => { if (message.type === "FILE_LIST") files.value = message.files; }); browser.runtime.sendMessage({ type: POPUP_READY }); } catch { console.log(`Cannot access browser.runtime, probably not running as an extension`); } for (let i = 0; i < files.value?.length; i++) if (files.value[i].data.size > 2e10) { progress.error = ERROR_MESSAGES.SIZE_EXCEEDED; console.log(`Max file size exceeded`); uploadingError.value = true; browser.runtime.sendMessage({ type: ALL_UPLOADS_ABORTED, url: "", aborted: true }); return; } }; return (_ctx, _cache) => { return openBlock(), createBlock(WithLoader_default, { "is-loading": unref(isLoadingAuth) || unref(isLoadingConfigured) }, { default: withCtx(() => [!unref(isLoggedIn) ? (openBlock(), createBlock(PromptLogin_default, { key: 0 })) : (openBlock(), createElementBlock("div", _hoisted_1$1, [!unref(isConfigured) ? (openBlock(), createElementBlock("div", _hoisted_2, [ _cache[1] || (_cache[1] = createBaseVNode("h1", null, "Finish setting up Send", -1)), _cache[2] || (_cache[2] = createBaseVNode("p", null, " To continue your upload, please complete your passphrase setup/recovery. ", -1)), !isSecurityPopupOpen.value ? (openBlock(), createBlock(ProButton_default, { key: 0, onClick: openSecurityPopup }, { default: withCtx(() => [..._cache[0] || (_cache[0] = [createTextVNode(" Continue Setup ", -1)])]), _: 1 })) : createCommentVNode("", true) ])) : (openBlock(), createElementBlock("div", _hoisted_3, [unref(uploadBlockedDuetoSize) ? (openBlock(), createElementBlock("h1", _hoisted_4, toDisplayString(unref(uploadBlockedDuetoSize)), 1)) : createCommentVNode("", true), !unref(uploadBlockedDuetoSize) ? (openBlock(), createElementBlock("div", _hoisted_5, [unref(uploadingError) ? (openBlock(), createElementBlock("div", _hoisted_6, [createVNode(ErrorUploading_default)])) : createCommentVNode("", true), createBaseVNode("div", null, [createVNode(UploadPage_default, { files: files.value, "on-upload-and-share": handleUploadAndShare }, null, 8, ["files"])])])) : createCommentVNode("", true)]))]))]), _: 1 }, 8, ["is-loading"]); }; } }), [["__scopeId", "data-v-e83e3188"]]); //#endregion //#region ../send/frontend/src/apps/send/ExtensionPage.vue?vue&type=script&setup=true&lang.ts var _hoisted_1 = { id: "send-page", class: "container" }; //#endregion //#region ../send/frontend/src/apps/send/ExtensionPage.vue var ExtensionPage_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ __name: "ExtensionPage", setup(__props) { const userStore = useUserStore(); const { keychain } = useKeychainStore(); const folderStore = useFolderStore(); const { initializeClientMetrics } = useMetricsStore(); onMounted(async () => { await init$2(userStore, keychain, folderStore); const uid = userStore.user.uniqueHash; initializeClientMetrics(uid); }); useMetricsUpdate(); return (_ctx, _cache) => { return openBlock(), createElementBlock("div", _hoisted_1, [createVNode(PopupView_default), createVNode(VersionTag_default)]); }; } }), [["__scopeId", "data-v-6e3b044b"]]); //#endregion //#region ../send/frontend/src/lib/sentry.ts var TRACING_LEVELS_PROD = ["error", "warn"]; /** * Drops the query string and fragment from a URL. Send access links carry the * decryption secret in the URL fragment (as split off by * `getAccessLinkWithoutPasswordHash` in lib/utils.ts) and query params can carry * tokens, so neither may reach Sentry. See issue #892 / #990. */ function stripUrlSecrets(url) { return url.split(/[?#]/)[0]; } /** * Scrubs user identity and sensitive request payloads from an outgoing event. * Extracted so the privacy hardening is unit-testable independently of * Sentry.init. */ function scrubEvent(event) { delete event.user; if (event.request) { delete event.request.cookies; delete event.request.headers; delete event.request.query_string; delete event.request.data; if (typeof event.request.url === "string") event.request.url = stripUrlSecrets(event.request.url); } return event; } /** * Scrubs auto-captured breadcrumbs before they attach to an event. Navigation * breadcrumbs record the URL in `data.to`/`data.from` and fetch/xhr breadcrumbs * in `data.url`; each can carry the access-link secret (fragment) or tokens * (query string). Keep the breadcrumb for debugging context but strip those. * See issue #892 / #990. */ function scrubBreadcrumb(breadcrumb) { const { data } = breadcrumb; if (data) { for (const key of [ "url", "to", "from" ]) if (typeof data[key] === "string") data[key] = stripUrlSecrets(data[key]); } return breadcrumb; } var initialized = false; var initSentry = (app) => { if (initialized && getClient()) return; init({ app, dsn: "https://af0e7594fd7dedb0d5c59ec7ecf169b5@o4505428107853824.ingest.us.sentry.io/4507567067758592", integrations: [browserTracingIntegration(), captureConsoleIntegration({ levels: TRACING_LEVELS_PROD })], tracesSampleRate: .5, environment: "production", sendDefaultPii: false, beforeSend: scrubEvent, beforeBreadcrumb: scrubBreadcrumb }); setTag("environmentName", getEnvironmentName({ "BASE_URL": "/", "DEV": false, "MODE": "production", "PROD": true, "SSR": false, "VITE_DEPRECATION_VERSION": "153.0.0", "VITE_OIDC_CLIENT_ID": "desktop", "VITE_OIDC_ROOT_URL": "https://auth.tb.pro/realms/tbpro/", "VITE_POSTHOG_HOST": "https://us.i.posthog.com", "VITE_POSTHOG_PROJECT_KEY": "phc_61NZH7teRtwmtZQHpKRltXUEEO7acpEAjpjdSiE5tdu", "VITE_SEND_CLIENT_URL": "https://send.tb.pro", "VITE_SEND_SERVER_URL": "https://send-backend.tb.pro", "VITE_SENTRY_AUTH_TOKEN": "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", "VITE_SENTRY_DSN": "https://af0e7594fd7dedb0d5c59ec7ecf169b5@o4505428107853824.ingest.us.sentry.io/4507567067758592" })); initialized = true; }; //#endregion //#region ../send/frontend/src/lib/logger.ts var version = "2.0.5"; var LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }; var originalConsole = { ...console }; var originalLog = originalConsole.log; var originalWarn = originalConsole.warn; var originalError = originalConsole.error; var getConfiguredLevel = () => { return LOG_LEVELS.warn; }; var shouldLog = (messageLevel) => { const configuredLevel = getConfiguredLevel(); return LOG_LEVELS[messageLevel] >= configuredLevel; }; console.debug = (...args) => { if (shouldLog("debug")) originalLog(`[${version}]`, ...args); }; console.log = (...args) => { if (shouldLog("info")) originalLog(`[${version}]`, ...args); }; console.info = (...args) => { if (shouldLog("info")) originalLog(`[${version}]`, ...args); }; console.warn = (...args) => { if (shouldLog("warn")) originalWarn(`[${version}]`, ...args); }; console.error = (...args) => { if (shouldLog("error")) originalError(`[${version}]`, ...args); }; //#endregion //#region ../../node_modules/.pnpm/@floating-ui+utils@0.2.11/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs /** * Custom positioning reference element. * @see https://floating-ui.com/docs/virtual-elements */ var sides = [ "top", "right", "bottom", "left" ]; var alignments = ["start", "end"]; var placements = /*#__PURE__*/ sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), []); var min = Math.min; var max = Math.max; var oppositeSideMap = { left: "right", right: "left", bottom: "top", top: "bottom" }; function clamp(start, value, end) { return max(start, min(value, end)); } function evaluate(value, param) { return typeof value === "function" ? value(param) : value; } function getSide(placement) { return placement.split("-")[0]; } function getAlignment(placement) { return placement.split("-")[1]; } function getOppositeAxis(axis) { return axis === "x" ? "y" : "x"; } function getAxisLength(axis) { return axis === "y" ? "height" : "width"; } function getSideAxis(placement) { const firstChar = placement[0]; return firstChar === "t" || firstChar === "b" ? "y" : "x"; } function getAlignmentAxis(placement) { return getOppositeAxis(getSideAxis(placement)); } function getAlignmentSides(placement, rects, rtl) { if (rtl === void 0) rtl = false; const alignment = getAlignment(placement); const alignmentAxis = getAlignmentAxis(placement); const length = getAxisLength(alignmentAxis); let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top"; if (rects.reference[length] > rects.floating[length]) mainAlignmentSide = getOppositePlacement(mainAlignmentSide); return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)]; } function getExpandedPlacements(placement) { const oppositePlacement = getOppositePlacement(placement); return [ getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement) ]; } function getOppositeAlignmentPlacement(placement) { return placement.includes("start") ? placement.replace("start", "end") : placement.replace("end", "start"); } var lrPlacement = ["left", "right"]; var rlPlacement = ["right", "left"]; var tbPlacement = ["top", "bottom"]; var btPlacement = ["bottom", "top"]; function getSideList(side, isStart, rtl) { switch (side) { case "top": case "bottom": if (rtl) return isStart ? rlPlacement : lrPlacement; return isStart ? lrPlacement : rlPlacement; case "left": case "right": return isStart ? tbPlacement : btPlacement; default: return []; } } function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { const alignment = getAlignment(placement); let list = getSideList(getSide(placement), direction === "start", rtl); if (alignment) { list = list.map((side) => side + "-" + alignment); if (flipAlignment) list = list.concat(list.map(getOppositeAlignmentPlacement)); } return list; } function getOppositePlacement(placement) { const side = getSide(placement); return oppositeSideMap[side] + placement.slice(side.length); } function expandPaddingObject(padding) { return { top: 0, right: 0, bottom: 0, left: 0, ...padding }; } function getPaddingObject(padding) { return typeof padding !== "number" ? expandPaddingObject(padding) : { top: padding, right: padding, bottom: padding, left: padding }; } function rectToClientRect(rect) { const { x, y, width, height } = rect; return { width, height, top: y, left: x, right: x + width, bottom: y + height, x, y }; } //#endregion //#region ../../node_modules/.pnpm/@floating-ui+core@1.7.5/node_modules/@floating-ui/core/dist/floating-ui.core.mjs function computeCoordsFromPlacement(_ref, placement, rtl) { let { reference, floating } = _ref; const sideAxis = getSideAxis(placement); const alignmentAxis = getAlignmentAxis(placement); const alignLength = getAxisLength(alignmentAxis); const side = getSide(placement); const isVertical = sideAxis === "y"; const commonX = reference.x + reference.width / 2 - floating.width / 2; const commonY = reference.y + reference.height / 2 - floating.height / 2; const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case "top": coords = { x: commonX, y: reference.y - floating.height }; break; case "bottom": coords = { x: commonX, y: reference.y + reference.height }; break; case "right": coords = { x: reference.x + reference.width, y: commonY }; break; case "left": coords = { x: reference.x - floating.width, y: commonY }; break; default: coords = { x: reference.x, y: reference.y }; } switch (getAlignment(placement)) { case "start": coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); break; case "end": coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); break; } return coords; } /** * Resolves with an object of overflow side offsets that determine how much the * element is overflowing a given clipping boundary on each side. * - positive = overflowing the boundary by that number of pixels * - negative = how many pixels left before it will overflow * - 0 = lies flush with the boundary * @see https://floating-ui.com/docs/detectOverflow */ async function detectOverflow(state, options) { var _await$platform$isEle; if (options === void 0) options = {}; const { x, y, platform, rects, elements, strategy } = state; const { boundary = "clippingAncestors", rootBoundary = "viewport", elementContext = "floating", altBoundary = false, padding = 0 } = evaluate(options, state); const paddingObject = getPaddingObject(padding); const element = elements[altBoundary ? elementContext === "floating" ? "reference" : "floating" : elementContext]; const clippingClientRect = rectToClientRect(await platform.getClippingRect({ element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating)), boundary, rootBoundary, strategy })); const rect = elementContext === "floating" ? { x, y, width: rects.floating.width, height: rects.floating.height } : rects.reference; const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); const offsetScale = await (platform.isElement == null ? void 0 : platform.isElement(offsetParent)) ? await (platform.getScale == null ? void 0 : platform.getScale(offsetParent)) || { x: 1, y: 1 } : { x: 1, y: 1 }; const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ elements, rect, offsetParent, strategy }) : rect); return { top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x }; } var MAX_RESET_COUNT = 50; /** * Computes the `x` and `y` coordinates that will place the floating element * next to a given reference element. * * This export does not have any `platform` interface logic. You will need to * write one for the platform you are using Floating UI with. */ var computePosition = async (reference, floating, config) => { const { placement = "bottom", strategy = "absolute", middleware = [], platform } = config; const platformWithDetectOverflow = platform.detectOverflow ? platform : { ...platform, detectOverflow }; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); let rects = await platform.getElementRects({ reference, floating, strategy }); let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); let statefulPlacement = placement; let resetCount = 0; const middlewareData = {}; for (let i = 0; i < middleware.length; i++) { const currentMiddleware = middleware[i]; if (!currentMiddleware) continue; const { name, fn } = currentMiddleware; const { x: nextX, y: nextY, data, reset } = await fn({ x, y, initialPlacement: placement, placement: statefulPlacement, strategy, middlewareData, rects, platform: platformWithDetectOverflow, elements: { reference, floating } }); x = nextX != null ? nextX : x; y = nextY != null ? nextY : y; middlewareData[name] = { ...middlewareData[name], ...data }; if (reset && resetCount < MAX_RESET_COUNT) { resetCount++; if (typeof reset === "object") { if (reset.placement) statefulPlacement = reset.placement; if (reset.rects) rects = reset.rects === true ? await platform.getElementRects({ reference, floating, strategy }) : reset.rects; ({x, y} = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } i = -1; } } return { x, y, placement: statefulPlacement, strategy, middlewareData }; }; /** * Provides data to position an inner element of the floating element so that it * appears centered to the reference element. * @see https://floating-ui.com/docs/arrow */ var arrow = (options) => ({ name: "arrow", options, async fn(state) { const { x, y, placement, rects, platform, elements, middlewareData } = state; const { element, padding = 0 } = evaluate(options, state) || {}; if (element == null) return {}; const paddingObject = getPaddingObject(padding); const coords = { x, y }; const axis = getAlignmentAxis(placement); const length = getAxisLength(axis); const arrowDimensions = await platform.getDimensions(element); const isYAxis = axis === "y"; const minProp = isYAxis ? "top" : "left"; const maxProp = isYAxis ? "bottom" : "right"; const clientProp = isYAxis ? "clientHeight" : "clientWidth"; const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; const startDiff = coords[axis] - rects.reference[axis]; const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; if (!clientSize || !await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent))) clientSize = elements.floating[clientProp] || rects.floating[length]; const centerToReference = endDiff / 2 - startDiff / 2; const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; const minPadding = min(paddingObject[minProp], largestPossiblePadding); const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); const min$1 = minPadding; const max = clientSize - arrowDimensions[length] - maxPadding; const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; const offset = clamp(min$1, center, max); const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; return { [axis]: coords[axis] + alignmentOffset, data: { [axis]: offset, centerOffset: center - offset - alignmentOffset, ...shouldAddOffset && { alignmentOffset } }, reset: shouldAddOffset }; } }); function getPlacementList(alignment, autoAlignment, allowedPlacements) { return (alignment ? [...allowedPlacements.filter((placement) => getAlignment(placement) === alignment), ...allowedPlacements.filter((placement) => getAlignment(placement) !== alignment)] : allowedPlacements.filter((placement) => getSide(placement) === placement)).filter((placement) => { if (alignment) return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); return true; }); } /** * Optimizes the visibility of the floating element by choosing the placement * that has the most space available automatically, without needing to specify a * preferred placement. Alternative to `flip`. * @see https://floating-ui.com/docs/autoPlacement */ var autoPlacement = function(options) { if (options === void 0) options = {}; return { name: "autoPlacement", options, async fn(state) { var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; const { rects, middlewareData, placement, platform, elements } = state; const { crossAxis = false, alignment, allowedPlacements = placements, autoAlignment = true, ...detectOverflowOptions } = evaluate(options, state); const placements$1 = alignment !== void 0 || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; const overflow = await platform.detectOverflow(state, detectOverflowOptions); const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; const currentPlacement = placements$1[currentIndex]; if (currentPlacement == null) return {}; const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); if (placement !== currentPlacement) return { reset: { placement: placements$1[0] } }; const currentOverflows = [ overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]] ]; const allOverflows = [...((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || [], { placement: currentPlacement, overflows: currentOverflows }]; const nextPlacement = placements$1[currentIndex + 1]; if (nextPlacement) return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: nextPlacement } }; const placementsSortedByMostSpace = allOverflows.map((d) => { const alignment = getAlignment(d.placement); return [ d.placement, alignment && crossAxis ? d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : d.overflows[0], d.overflows ]; }).sort((a, b) => a[1] - b[1]); const resetPlacement = ((_placementsThatFitOnE = placementsSortedByMostSpace.filter((d) => d[2].slice(0, getAlignment(d[0]) ? 2 : 3).every((v) => v <= 0))[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; if (resetPlacement !== placement) return { data: { index: currentIndex + 1, overflows: allOverflows }, reset: { placement: resetPlacement } }; return {}; } }; }; /** * Optimizes the visibility of the floating element by flipping the `placement` * in order to keep it in view when the preferred placement(s) will overflow the * clipping boundary. Alternative to `autoPlacement`. * @see https://floating-ui.com/docs/flip */ var flip = function(options) { if (options === void 0) options = {}; return { name: "flip", options, async fn(state) { var _middlewareData$arrow, _middlewareData$flip; const { placement, middlewareData, rects, initialPlacement, platform, elements } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true, fallbackPlacements: specifiedFallbackPlacements, fallbackStrategy = "bestFit", fallbackAxisSideDirection = "none", flipAlignment = true, ...detectOverflowOptions } = evaluate(options, state); if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) return {}; const side = getSide(placement); const initialSideAxis = getSideAxis(initialPlacement); const isBasePlacement = getSide(initialPlacement) === initialPlacement; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none"; if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); const placements = [initialPlacement, ...fallbackPlacements]; const overflow = await platform.detectOverflow(state, detectOverflowOptions); const overflows = []; let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; if (checkMainAxis) overflows.push(overflow[side]); if (checkCrossAxis) { const sides = getAlignmentSides(placement, rects, rtl); overflows.push(overflow[sides[0]], overflow[sides[1]]); } overflowsData = [...overflowsData, { placement, overflows }]; if (!overflows.every((side) => side <= 0)) { var _middlewareData$flip2, _overflowsData$filter; const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; const nextPlacement = placements[nextIndex]; if (nextPlacement) { if (!(checkCrossAxis === "alignment" ? initialSideAxis !== getSideAxis(nextPlacement) : false) || overflowsData.every((d) => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) return { data: { index: nextIndex, overflows: overflowsData }, reset: { placement: nextPlacement } }; } let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; if (!resetPlacement) switch (fallbackStrategy) { case "bestFit": { var _overflowsData$filter2; const placement = (_overflowsData$filter2 = overflowsData.filter((d) => { if (hasFallbackAxisSideDirection) { const currentSideAxis = getSideAxis(d.placement); return currentSideAxis === initialSideAxis || currentSideAxis === "y"; } return true; }).map((d) => [d.placement, d.overflows.filter((overflow) => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; if (placement) resetPlacement = placement; break; } case "initialPlacement": resetPlacement = initialPlacement; break; } if (placement !== resetPlacement) return { reset: { placement: resetPlacement } }; } return {}; } }; }; var originSides = /*#__PURE__*/ new Set(["left", "top"]); async function convertValueToCoords(state, options) { const { placement, platform, elements } = state; const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); const side = getSide(placement); const alignment = getAlignment(placement); const isVertical = getSideAxis(placement) === "y"; const mainAxisMulti = originSides.has(side) ? -1 : 1; const crossAxisMulti = rtl && isVertical ? -1 : 1; const rawValue = evaluate(options, state); let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === "number" ? { mainAxis: rawValue, crossAxis: 0, alignmentAxis: null } : { mainAxis: rawValue.mainAxis || 0, crossAxis: rawValue.crossAxis || 0, alignmentAxis: rawValue.alignmentAxis }; if (alignment && typeof alignmentAxis === "number") crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis; return isVertical ? { x: crossAxis * crossAxisMulti, y: mainAxis * mainAxisMulti } : { x: mainAxis * mainAxisMulti, y: crossAxis * crossAxisMulti }; } /** * Modifies the placement by translating the floating element along the * specified axes. * A number (shorthand for `mainAxis` or distance), or an axes configuration * object may be passed. * @see https://floating-ui.com/docs/offset */ var offset = function(options) { if (options === void 0) options = 0; return { name: "offset", options, async fn(state) { var _middlewareData$offse, _middlewareData$arrow; const { x, y, placement, middlewareData } = state; const diffCoords = await convertValueToCoords(state, options); if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) return {}; return { x: x + diffCoords.x, y: y + diffCoords.y, data: { ...diffCoords, placement } }; } }; }; /** * Optimizes the visibility of the floating element by shifting it in order to * keep it in view when it will overflow the clipping boundary. * @see https://floating-ui.com/docs/shift */ var shift = function(options) { if (options === void 0) options = {}; return { name: "shift", options, async fn(state) { const { x, y, placement, platform } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: (_ref) => { let { x, y } = _ref; return { x, y }; } }, ...detectOverflowOptions } = evaluate(options, state); const coords = { x, y }; const overflow = await platform.detectOverflow(state, detectOverflowOptions); const crossAxis = getSideAxis(getSide(placement)); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; if (checkMainAxis) { const minSide = mainAxis === "y" ? "top" : "left"; const maxSide = mainAxis === "y" ? "bottom" : "right"; const min = mainAxisCoord + overflow[minSide]; const max = mainAxisCoord - overflow[maxSide]; mainAxisCoord = clamp(min, mainAxisCoord, max); } if (checkCrossAxis) { const minSide = crossAxis === "y" ? "top" : "left"; const maxSide = crossAxis === "y" ? "bottom" : "right"; const min = crossAxisCoord + overflow[minSide]; const max = crossAxisCoord - overflow[maxSide]; crossAxisCoord = clamp(min, crossAxisCoord, max); } const limitedCoords = limiter.fn({ ...state, [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }); return { ...limitedCoords, data: { x: limitedCoords.x - x, y: limitedCoords.y - y, enabled: { [mainAxis]: checkMainAxis, [crossAxis]: checkCrossAxis } } }; } }; }; /** * Provides data that allows you to change the size of the floating element — * for instance, prevent it from overflowing the clipping boundary or match the * width of the reference element. * @see https://floating-ui.com/docs/size */ var size = function(options) { if (options === void 0) options = {}; return { name: "size", options, async fn(state) { var _state$middlewareData, _state$middlewareData2; const { placement, rects, platform, elements } = state; const { apply = () => {}, ...detectOverflowOptions } = evaluate(options, state); const overflow = await platform.detectOverflow(state, detectOverflowOptions); const side = getSide(placement); const alignment = getAlignment(placement); const isYAxis = getSideAxis(placement) === "y"; const { width, height } = rects.floating; let heightSide; let widthSide; if (side === "top" || side === "bottom") { heightSide = side; widthSide = alignment === (await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right"; } else { widthSide = side; heightSide = alignment === "end" ? "top" : "bottom"; } const maximumClippingHeight = height - overflow.top - overflow.bottom; const maximumClippingWidth = width - overflow.left - overflow.right; const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); const noShift = !state.middlewareData.shift; let availableHeight = overflowAvailableHeight; let availableWidth = overflowAvailableWidth; if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) availableWidth = maximumClippingWidth; if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) availableHeight = maximumClippingHeight; if (noShift && !alignment) { const xMin = max(overflow.left, 0); const xMax = max(overflow.right, 0); const yMin = max(overflow.top, 0); const yMax = max(overflow.bottom, 0); if (isYAxis) availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); else availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } await apply({ ...state, availableWidth, availableHeight }); const nextDimensions = await platform.getDimensions(elements.floating); if (width !== nextDimensions.width || height !== nextDimensions.height) return { reset: { rects: true } }; return {}; } }; }; //#endregion //#region ../../node_modules/.pnpm/@floating-ui+dom@1.1.1/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs function n$1(t) { var e; return (null == (e = t.ownerDocument) ? void 0 : e.defaultView) || window; } function o(t) { return n$1(t).getComputedStyle(t); } var i = Math.min, r = Math.max, l = Math.round; function c$1(t) { const e = o(t); let n = parseFloat(e.width), i = parseFloat(e.height); const r = t.offsetWidth, c = t.offsetHeight, s = l(n) !== r || l(i) !== c; return s && (n = r, i = c), { width: n, height: i, fallback: s }; } function s(t) { return h$1(t) ? (t.nodeName || "").toLowerCase() : ""; } var f; function u() { if (f) return f; const t = navigator.userAgentData; return t && Array.isArray(t.brands) ? (f = t.brands.map(((t) => t.brand + "/" + t.version)).join(" "), f) : navigator.userAgent; } function a(t) { return t instanceof n$1(t).HTMLElement; } function d$1(t) { return t instanceof n$1(t).Element; } function h$1(t) { return t instanceof n$1(t).Node; } function p(t) { if ("undefined" == typeof ShadowRoot) return !1; return t instanceof n$1(t).ShadowRoot || t instanceof ShadowRoot; } function g$1(t) { const { overflow: e, overflowX: n, overflowY: i, display: r } = o(t); return /auto|scroll|overlay|hidden|clip/.test(e + i + n) && !["inline", "contents"].includes(r); } function m$1(t) { return [ "table", "td", "th" ].includes(s(t)); } function y$1(t) { const e = /firefox/i.test(u()), n = o(t), i = n.backdropFilter || n.WebkitBackdropFilter; return "none" !== n.transform || "none" !== n.perspective || !!i && "none" !== i || e && "filter" === n.willChange || e && !!n.filter && "none" !== n.filter || ["transform", "perspective"].some(((t) => n.willChange.includes(t))) || [ "paint", "layout", "strict", "content" ].some(((t) => { const e = n.contain; return null != e && e.includes(t); })); } function x$1() { return !/^((?!chrome|android).)*safari/i.test(u()); } function w(t) { return [ "html", "body", "#document" ].includes(s(t)); } function v(t) { return d$1(t) ? t : t.contextElement; } var b$1 = { x: 1, y: 1 }; function L(t) { const e = v(t); if (!a(e)) return b$1; const n = e.getBoundingClientRect(), { width: o, height: i, fallback: r } = c$1(e); let s = (r ? l(n.width) : n.width) / o, f = (r ? l(n.height) : n.height) / i; return s && Number.isFinite(s) || (s = 1), f && Number.isFinite(f) || (f = 1), { x: s, y: f }; } function E$1(t, e, o, i) { var r, l; void 0 === e && (e = !1), void 0 === o && (o = !1); const c = t.getBoundingClientRect(), s = v(t); let f = b$1; e && (i ? d$1(i) && (f = L(i)) : f = L(t)); const u = s ? n$1(s) : window, a = !x$1() && o; let h = (c.left + (a && (null == (r = u.visualViewport) ? void 0 : r.offsetLeft) || 0)) / f.x, p = (c.top + (a && (null == (l = u.visualViewport) ? void 0 : l.offsetTop) || 0)) / f.y, g = c.width / f.x, m = c.height / f.y; if (s) { const t = n$1(s), e = i && d$1(i) ? n$1(i) : i; let o = t.frameElement; for (; o && i && e !== t;) { const t = L(o), e = o.getBoundingClientRect(), i = getComputedStyle(o); e.x += (o.clientLeft + parseFloat(i.paddingLeft)) * t.x, e.y += (o.clientTop + parseFloat(i.paddingTop)) * t.y, h *= t.x, p *= t.y, g *= t.x, m *= t.y, h += e.x, p += e.y, o = n$1(o).frameElement; } } return { width: g, height: m, top: p, right: h + g, bottom: p + m, left: h, x: h, y: p }; } function R(t) { return ((h$1(t) ? t.ownerDocument : t.document) || window.document).documentElement; } function T(t) { return d$1(t) ? { scrollLeft: t.scrollLeft, scrollTop: t.scrollTop } : { scrollLeft: t.pageXOffset, scrollTop: t.pageYOffset }; } function C$1(t) { return E$1(R(t)).left + T(t).scrollLeft; } function F(t) { if ("html" === s(t)) return t; const e = t.assignedSlot || t.parentNode || p(t) && t.host || R(t); return p(e) ? e.host : e; } function W$1(t) { const e = F(t); return w(e) ? e.ownerDocument.body : a(e) && g$1(e) ? e : W$1(e); } function D(t, e) { var o; void 0 === e && (e = []); const i = W$1(t), r = i === (null == (o = t.ownerDocument) ? void 0 : o.body), l = n$1(i); return r ? e.concat(l, l.visualViewport || [], g$1(i) ? i : []) : e.concat(i, D(i)); } function S$1(e, i, l) { return "viewport" === i ? rectToClientRect(function(t, e) { const o = n$1(t), i = R(t), r = o.visualViewport; let l = i.clientWidth, c = i.clientHeight, s = 0, f = 0; if (r) { l = r.width, c = r.height; const t = x$1(); (t || !t && "fixed" === e) && (s = r.offsetLeft, f = r.offsetTop); } return { width: l, height: c, x: s, y: f }; }(e, l)) : d$1(i) ? rectToClientRect(function(t, e) { const n = E$1(t, !0, "fixed" === e), o = n.top + t.clientTop, i = n.left + t.clientLeft, r = a(t) ? L(t) : { x: 1, y: 1 }; return { width: t.clientWidth * r.x, height: t.clientHeight * r.y, x: i * r.x, y: o * r.y }; }(i, l)) : rectToClientRect(function(t) { const e = R(t), n = T(t), i = t.ownerDocument.body, l = r(e.scrollWidth, e.clientWidth, i.scrollWidth, i.clientWidth), c = r(e.scrollHeight, e.clientHeight, i.scrollHeight, i.clientHeight); let s = -n.scrollLeft + C$1(t); const f = -n.scrollTop; return "rtl" === o(i).direction && (s += r(e.clientWidth, i.clientWidth) - l), { width: l, height: c, x: s, y: f }; }(R(e))); } function A(t) { return a(t) && "fixed" !== o(t).position ? t.offsetParent : null; } function H$2(t) { const e = n$1(t); let i = A(t); for (; i && m$1(i) && "static" === o(i).position;) i = A(i); return i && ("html" === s(i) || "body" === s(i) && "static" === o(i).position && !y$1(i)) ? e : i || function(t) { let e = F(t); for (; a(e) && !w(e);) { if (y$1(e)) return e; e = F(e); } return null; }(t) || e; } function O(t, e, n) { const o = a(e), i = R(e), r = E$1(t, !0, "fixed" === n, e); let l = { scrollLeft: 0, scrollTop: 0 }; const c = { x: 0, y: 0 }; if (o || !o && "fixed" !== n) if (("body" !== s(e) || g$1(i)) && (l = T(e)), a(e)) { const t = E$1(e, !0); c.x = t.x + e.clientLeft, c.y = t.y + e.clientTop; } else i && (c.x = C$1(i)); return { x: r.left + l.scrollLeft - c.x, y: r.top + l.scrollTop - c.y, width: r.width, height: r.height }; } var P = { getClippingRect: function(t) { let { element: e, boundary: n, rootBoundary: l, strategy: c } = t; const u = [..."clippingAncestors" === n ? function(t, e) { const n = e.get(t); if (n) return n; let i = D(t).filter(((t) => d$1(t) && "body" !== s(t))), r = null; const l = "fixed" === o(t).position; let c = l ? F(t) : t; for (; d$1(c) && !w(c);) { const t = o(c), e = y$1(c); (l ? e || r : e || "static" !== t.position || !r || !["absolute", "fixed"].includes(r.position)) ? r = t : i = i.filter(((t) => t !== c)), c = F(c); } return e.set(t, i), i; }(e, this._c) : [].concat(n), l], a = u[0], h = u.reduce(((t, n) => { const o = S$1(e, n, c); return t.top = r(o.top, t.top), t.right = i(o.right, t.right), t.bottom = i(o.bottom, t.bottom), t.left = r(o.left, t.left), t; }), S$1(e, a, c)); return { width: h.right - h.left, height: h.bottom - h.top, x: h.left, y: h.top }; }, convertOffsetParentRelativeRectToViewportRelativeRect: function(t) { let { rect: e, offsetParent: n, strategy: o } = t; const i = a(n), r = R(n); if (n === r) return e; let l = { scrollLeft: 0, scrollTop: 0 }, c = { x: 1, y: 1 }; const f = { x: 0, y: 0 }; if ((i || !i && "fixed" !== o) && (("body" !== s(n) || g$1(r)) && (l = T(n)), a(n))) { const t = E$1(n); c = L(n), f.x = t.x + n.clientLeft, f.y = t.y + n.clientTop; } return { width: e.width * c.x, height: e.height * c.y, x: e.x * c.x - l.scrollLeft * c.x + f.x, y: e.y * c.y - l.scrollTop * c.y + f.y }; }, isElement: d$1, getDimensions: function(t) { return a(t) ? c$1(t) : t.getBoundingClientRect(); }, getOffsetParent: H$2, getDocumentElement: R, getScale: L, async getElementRects(t) { let { reference: e, floating: n, strategy: o } = t; const i = this.getOffsetParent || H$2, r = this.getDimensions; return { reference: O(e, await i(n), o), floating: { x: 0, y: 0, ...await r(n) } }; }, getClientRects: (t) => Array.from(t.getClientRects()), isRTL: (t) => "rtl" === o(t).direction }; var B$1 = (t, n, o) => { const i = /* @__PURE__ */ new Map(), r = { platform: P, ...o }, l = { ...r.platform, _c: i }; return computePosition(t, n, { ...r, platform: l }); }; //#endregion //#region ../../node_modules/.pnpm/floating-vue@5.2.2_vue@3.5.33_typescript@5.9.3_/node_modules/floating-vue/dist/floating-vue.mjs function ye(e, t) { for (const o in t) Object.prototype.hasOwnProperty.call(t, o) && (typeof t[o] == "object" && e[o] ? ye(e[o], t[o]) : e[o] = t[o]); } var h = { disabled: !1, distance: 5, skidding: 0, container: "body", boundary: void 0, instantMove: !1, disposeTimeout: 150, popperTriggers: [], strategy: "absolute", preventOverflow: !0, flip: !0, shift: !0, overflowPadding: 0, arrowPadding: 0, arrowOverflow: !0, /** * By default, compute autohide on 'click'. */ autoHideOnMousedown: !1, themes: { tooltip: { placement: "top", triggers: [ "hover", "focus", "touch" ], hideTriggers: (e) => [...e, "click"], delay: { show: 200, hide: 0 }, handleResize: !1, html: !1, loadingContent: "..." }, dropdown: { placement: "bottom", triggers: ["click"], delay: 0, handleResize: !0, autoHide: !0 }, menu: { $extend: "dropdown", triggers: ["hover", "focus"], popperTriggers: ["hover"], delay: { show: 0, hide: 400 } } } }; function S(e, t) { let o = h.themes[e] || {}, i; do i = o[t], typeof i > "u" ? o.$extend ? o = h.themes[o.$extend] || {} : (o = null, i = h[t]) : o = null; while (o); return i; } function Ze(e) { const t = [e]; let o = h.themes[e] || {}; do o.$extend && !o.$resetCss ? (t.push(o.$extend), o = h.themes[o.$extend] || {}) : o = null; while (o); return t.map((i) => `v-popper--theme-${i}`); } function re(e) { const t = [e]; let o = h.themes[e] || {}; do o.$extend ? (t.push(o.$extend), o = h.themes[o.$extend] || {}) : o = null; while (o); return t; } var $$1 = !1; if (typeof window < "u") { $$1 = !1; try { const e = Object.defineProperty({}, "passive", { get() { $$1 = !0; } }); window.addEventListener("test", null, e); } catch {} } var _e = !1; typeof window < "u" && typeof navigator < "u" && (_e = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream); var Te = [ "auto", "top", "bottom", "left", "right" ].reduce((e, t) => e.concat([ t, `${t}-start`, `${t}-end` ]), []), pe = { hover: "mouseenter", focus: "focus", click: "click", touch: "touchstart", pointer: "pointerdown" }, ae = { hover: "mouseleave", focus: "blur", click: "click", touch: "touchend", pointer: "pointerup" }; function de(e, t) { const o = e.indexOf(t); o !== -1 && e.splice(o, 1); } function G$1() { return new Promise((e) => requestAnimationFrame(() => { requestAnimationFrame(e); })); } var d = []; var g = null; var le$1 = {}; function he(e) { let t = le$1[e]; return t || (t = le$1[e] = []), t; } var Y = function() {}; typeof window < "u" && (Y = window.Element); function n(e) { return function(t) { return S(t.theme, e); }; } var q$1 = "__floating-vue__popper", Q = () => /* @__PURE__ */ defineComponent({ name: "VPopper", provide() { return { [q$1]: { parentPopper: this } }; }, inject: { [q$1]: { default: null } }, props: { theme: { type: String, required: !0 }, targetNodes: { type: Function, required: !0 }, referenceNode: { type: Function, default: null }, popperNode: { type: Function, required: !0 }, shown: { type: Boolean, default: !1 }, showGroup: { type: String, default: null }, ariaId: { default: null }, disabled: { type: Boolean, default: n("disabled") }, positioningDisabled: { type: Boolean, default: n("positioningDisabled") }, placement: { type: String, default: n("placement"), validator: (e) => Te.includes(e) }, delay: { type: [ String, Number, Object ], default: n("delay") }, distance: { type: [Number, String], default: n("distance") }, skidding: { type: [Number, String], default: n("skidding") }, triggers: { type: Array, default: n("triggers") }, showTriggers: { type: [Array, Function], default: n("showTriggers") }, hideTriggers: { type: [Array, Function], default: n("hideTriggers") }, popperTriggers: { type: Array, default: n("popperTriggers") }, popperShowTriggers: { type: [Array, Function], default: n("popperShowTriggers") }, popperHideTriggers: { type: [Array, Function], default: n("popperHideTriggers") }, container: { type: [ String, Object, Y, Boolean ], default: n("container") }, boundary: { type: [String, Y], default: n("boundary") }, strategy: { type: String, validator: (e) => ["absolute", "fixed"].includes(e), default: n("strategy") }, autoHide: { type: [Boolean, Function], default: n("autoHide") }, handleResize: { type: Boolean, default: n("handleResize") }, instantMove: { type: Boolean, default: n("instantMove") }, eagerMount: { type: Boolean, default: n("eagerMount") }, popperClass: { type: [ String, Array, Object ], default: n("popperClass") }, computeTransformOrigin: { type: Boolean, default: n("computeTransformOrigin") }, /** * @deprecated */ autoMinSize: { type: Boolean, default: n("autoMinSize") }, autoSize: { type: [Boolean, String], default: n("autoSize") }, /** * @deprecated */ autoMaxSize: { type: Boolean, default: n("autoMaxSize") }, autoBoundaryMaxSize: { type: Boolean, default: n("autoBoundaryMaxSize") }, preventOverflow: { type: Boolean, default: n("preventOverflow") }, overflowPadding: { type: [Number, String], default: n("overflowPadding") }, arrowPadding: { type: [Number, String], default: n("arrowPadding") }, arrowOverflow: { type: Boolean, default: n("arrowOverflow") }, flip: { type: Boolean, default: n("flip") }, shift: { type: Boolean, default: n("shift") }, shiftCrossAxis: { type: Boolean, default: n("shiftCrossAxis") }, noAutoFocus: { type: Boolean, default: n("noAutoFocus") }, disposeTimeout: { type: Number, default: n("disposeTimeout") } }, emits: { show: () => !0, hide: () => !0, "update:shown": (e) => !0, "apply-show": () => !0, "apply-hide": () => !0, "close-group": () => !0, "close-directive": () => !0, "auto-hide": () => !0, resize: () => !0 }, data() { return { isShown: !1, isMounted: !1, skipTransition: !1, classes: { showFrom: !1, showTo: !1, hideFrom: !1, hideTo: !0 }, result: { x: 0, y: 0, placement: "", strategy: this.strategy, arrow: { x: 0, y: 0, centerOffset: 0 }, transformOrigin: null }, randomId: `popper_${[Math.random(), Date.now()].map((e) => e.toString(36).substring(2, 10)).join("_")}`, shownChildren: /* @__PURE__ */ new Set(), lastAutoHide: !0, pendingHide: !1, containsGlobalTarget: !1, isDisposed: !0, mouseDownContains: !1 }; }, computed: { popperId() { return this.ariaId != null ? this.ariaId : this.randomId; }, shouldMountContent() { return this.eagerMount || this.isMounted; }, slotData() { return { popperId: this.popperId, isShown: this.isShown, shouldMountContent: this.shouldMountContent, skipTransition: this.skipTransition, autoHide: typeof this.autoHide == "function" ? this.lastAutoHide : this.autoHide, show: this.show, hide: this.hide, handleResize: this.handleResize, onResize: this.onResize, classes: { ...this.classes, popperClass: this.popperClass }, result: this.positioningDisabled ? null : this.result, attrs: this.$attrs }; }, parentPopper() { var e; return (e = this[q$1]) == null ? void 0 : e.parentPopper; }, hasPopperShowTriggerHover() { var e, t; return ((e = this.popperTriggers) == null ? void 0 : e.includes("hover")) || ((t = this.popperShowTriggers) == null ? void 0 : t.includes("hover")); } }, watch: { shown: "$_autoShowHide", disabled(e) { e ? this.dispose() : this.init(); }, async container() { this.isShown && (this.$_ensureTeleport(), await this.$_computePosition()); }, triggers: { handler: "$_refreshListeners", deep: !0 }, positioningDisabled: "$_refreshListeners", ...[ "placement", "distance", "skidding", "boundary", "strategy", "overflowPadding", "arrowPadding", "preventOverflow", "shift", "shiftCrossAxis", "flip" ].reduce((e, t) => (e[t] = "$_computePosition", e), {}) }, created() { this.autoMinSize && console.warn("[floating-vue] `autoMinSize` option is deprecated. Use `autoSize=\"min\"` instead."), this.autoMaxSize && console.warn("[floating-vue] `autoMaxSize` option is deprecated. Use `autoBoundaryMaxSize` instead."); }, mounted() { this.init(), this.$_detachPopperNode(); }, activated() { this.$_autoShowHide(); }, deactivated() { this.hide(); }, beforeUnmount() { this.dispose(); }, methods: { show({ event: e = null, skipDelay: t = !1, force: o = !1 } = {}) { var i, s; (i = this.parentPopper) != null && i.lockedChild && this.parentPopper.lockedChild !== this || (this.pendingHide = !1, (o || !this.disabled) && (((s = this.parentPopper) == null ? void 0 : s.lockedChild) === this && (this.parentPopper.lockedChild = null), this.$_scheduleShow(e, t), this.$emit("show"), this.$_showFrameLocked = !0, requestAnimationFrame(() => { this.$_showFrameLocked = !1; })), this.$emit("update:shown", !0)); }, hide({ event: e = null, skipDelay: t = !1 } = {}) { var o; if (!this.$_hideInProgress) { if (this.shownChildren.size > 0) { this.pendingHide = !0; return; } if (this.hasPopperShowTriggerHover && this.$_isAimingPopper()) { this.parentPopper && (this.parentPopper.lockedChild = this, clearTimeout(this.parentPopper.lockedChildTimer), this.parentPopper.lockedChildTimer = setTimeout(() => { this.parentPopper.lockedChild === this && (this.parentPopper.lockedChild.hide({ skipDelay: t }), this.parentPopper.lockedChild = null); }, 1e3)); return; } ((o = this.parentPopper) == null ? void 0 : o.lockedChild) === this && (this.parentPopper.lockedChild = null), this.pendingHide = !1, this.$_scheduleHide(e, t), this.$emit("hide"), this.$emit("update:shown", !1); } }, init() { var e; this.isDisposed && (this.isDisposed = !1, this.isMounted = !1, this.$_events = [], this.$_preventShow = !1, this.$_referenceNode = ((e = this.referenceNode) == null ? void 0 : e.call(this)) ?? this.$el, this.$_targetNodes = this.targetNodes().filter((t) => t.nodeType === t.ELEMENT_NODE), this.$_popperNode = this.popperNode(), this.$_innerNode = this.$_popperNode.querySelector(".v-popper__inner"), this.$_arrowNode = this.$_popperNode.querySelector(".v-popper__arrow-container"), this.$_swapTargetAttrs("title", "data-original-title"), this.$_detachPopperNode(), this.triggers.length && this.$_addEventListeners(), this.shown && this.show()); }, dispose() { this.isDisposed || (this.isDisposed = !0, this.$_removeEventListeners(), this.hide({ skipDelay: !0 }), this.$_detachPopperNode(), this.isMounted = !1, this.isShown = !1, this.$_updateParentShownChildren(!1), this.$_swapTargetAttrs("data-original-title", "title")); }, async onResize() { this.isShown && (await this.$_computePosition(), this.$emit("resize")); }, async $_computePosition() { if (this.isDisposed || this.positioningDisabled) return; const e = { strategy: this.strategy, middleware: [] }; (this.distance || this.skidding) && e.middleware.push(offset({ mainAxis: this.distance, crossAxis: this.skidding })); const t = this.placement.startsWith("auto"); if (t ? e.middleware.push(autoPlacement({ alignment: this.placement.split("-")[1] ?? "" })) : e.placement = this.placement, this.preventOverflow && (this.shift && e.middleware.push(shift({ padding: this.overflowPadding, boundary: this.boundary, crossAxis: this.shiftCrossAxis })), !t && this.flip && e.middleware.push(flip({ padding: this.overflowPadding, boundary: this.boundary }))), e.middleware.push(arrow({ element: this.$_arrowNode, padding: this.arrowPadding })), this.arrowOverflow && e.middleware.push({ name: "arrowOverflow", fn: ({ placement: i, rects: s, middlewareData: r }) => { let p; const { centerOffset: a } = r.arrow; return i.startsWith("top") || i.startsWith("bottom") ? p = Math.abs(a) > s.reference.width / 2 : p = Math.abs(a) > s.reference.height / 2, { data: { overflow: p } }; } }), this.autoMinSize || this.autoSize) { const i = this.autoSize ? this.autoSize : this.autoMinSize ? "min" : null; e.middleware.push({ name: "autoSize", fn: ({ rects: s, placement: r, middlewareData: p }) => { var u; if ((u = p.autoSize) != null && u.skip) return {}; let a, l; return r.startsWith("top") || r.startsWith("bottom") ? a = s.reference.width : l = s.reference.height, this.$_innerNode.style[i === "min" ? "minWidth" : i === "max" ? "maxWidth" : "width"] = a != null ? `${a}px` : null, this.$_innerNode.style[i === "min" ? "minHeight" : i === "max" ? "maxHeight" : "height"] = l != null ? `${l}px` : null, { data: { skip: !0 }, reset: { rects: !0 } }; } }); } (this.autoMaxSize || this.autoBoundaryMaxSize) && (this.$_innerNode.style.maxWidth = null, this.$_innerNode.style.maxHeight = null, e.middleware.push(size({ boundary: this.boundary, padding: this.overflowPadding, apply: ({ availableWidth: i, availableHeight: s }) => { this.$_innerNode.style.maxWidth = i != null ? `${i}px` : null, this.$_innerNode.style.maxHeight = s != null ? `${s}px` : null; } }))); const o = await B$1(this.$_referenceNode, this.$_popperNode, e); Object.assign(this.result, { x: o.x, y: o.y, placement: o.placement, strategy: o.strategy, arrow: { ...o.middlewareData.arrow, ...o.middlewareData.arrowOverflow } }); }, $_scheduleShow(e, t = !1) { if (this.$_updateParentShownChildren(!0), this.$_hideInProgress = !1, clearTimeout(this.$_scheduleTimer), g && this.instantMove && g.instantMove && g !== this.parentPopper) { g.$_applyHide(!0), this.$_applyShow(!0); return; } t ? this.$_applyShow() : this.$_scheduleTimer = setTimeout(this.$_applyShow.bind(this), this.$_computeDelay("show")); }, $_scheduleHide(e, t = !1) { if (this.shownChildren.size > 0) { this.pendingHide = !0; return; } this.$_updateParentShownChildren(!1), this.$_hideInProgress = !0, clearTimeout(this.$_scheduleTimer), this.isShown && (g = this), t ? this.$_applyHide() : this.$_scheduleTimer = setTimeout(this.$_applyHide.bind(this), this.$_computeDelay("hide")); }, $_computeDelay(e) { const t = this.delay; return parseInt(t && t[e] || t || 0); }, async $_applyShow(e = !1) { clearTimeout(this.$_disposeTimer), clearTimeout(this.$_scheduleTimer), this.skipTransition = e, !this.isShown && (this.$_ensureTeleport(), await G$1(), await this.$_computePosition(), await this.$_applyShowEffect(), this.positioningDisabled || this.$_registerEventListeners([...D(this.$_referenceNode), ...D(this.$_popperNode)], "scroll", () => { this.$_computePosition(); })); }, async $_applyShowEffect() { if (this.$_hideInProgress) return; if (this.computeTransformOrigin) { const t = this.$_referenceNode.getBoundingClientRect(), o = this.$_popperNode.querySelector(".v-popper__wrapper"), i = o.parentNode.getBoundingClientRect(), s = t.x + t.width / 2 - (i.left + o.offsetLeft), r = t.y + t.height / 2 - (i.top + o.offsetTop); this.result.transformOrigin = `${s}px ${r}px`; } this.isShown = !0, this.$_applyAttrsToTarget({ "aria-describedby": this.popperId, "data-popper-shown": "" }); const e = this.showGroup; if (e) { let t; for (let o = 0; o < d.length; o++) t = d[o], t.showGroup !== e && (t.hide(), t.$emit("close-group")); } d.push(this), document.body.classList.add("v-popper--some-open"); for (const t of re(this.theme)) he(t).push(this), document.body.classList.add(`v-popper--some-open--${t}`); this.$emit("apply-show"), this.classes.showFrom = !0, this.classes.showTo = !1, this.classes.hideFrom = !1, this.classes.hideTo = !1, await G$1(), this.classes.showFrom = !1, this.classes.showTo = !0, this.noAutoFocus || this.$_popperNode.focus(); }, async $_applyHide(e = !1) { if (this.shownChildren.size > 0) { this.pendingHide = !0, this.$_hideInProgress = !1; return; } if (clearTimeout(this.$_scheduleTimer), !this.isShown) return; this.skipTransition = e, de(d, this), d.length === 0 && document.body.classList.remove("v-popper--some-open"); for (const o of re(this.theme)) { const i = he(o); de(i, this), i.length === 0 && document.body.classList.remove(`v-popper--some-open--${o}`); } g === this && (g = null), this.isShown = !1, this.$_applyAttrsToTarget({ "aria-describedby": void 0, "data-popper-shown": void 0 }), clearTimeout(this.$_disposeTimer); const t = this.disposeTimeout; t !== null && (this.$_disposeTimer = setTimeout(() => { this.$_popperNode && (this.$_detachPopperNode(), this.isMounted = !1); }, t)), this.$_removeEventListeners("scroll"), this.$emit("apply-hide"), this.classes.showFrom = !1, this.classes.showTo = !1, this.classes.hideFrom = !0, this.classes.hideTo = !1, await G$1(), this.classes.hideFrom = !1, this.classes.hideTo = !0; }, $_autoShowHide() { this.shown ? this.show() : this.hide(); }, $_ensureTeleport() { if (this.isDisposed) return; let e = this.container; if (typeof e == "string" ? e = window.document.querySelector(e) : e === !1 && (e = this.$_targetNodes[0].parentNode), !e) throw new Error("No container for popover: " + this.container); e.appendChild(this.$_popperNode), this.isMounted = !0; }, $_addEventListeners() { const e = (o) => { this.isShown && !this.$_hideInProgress || (o.usedByTooltip = !0, !this.$_preventShow && this.show({ event: o })); }; this.$_registerTriggerListeners(this.$_targetNodes, pe, this.triggers, this.showTriggers, e), this.$_registerTriggerListeners([this.$_popperNode], pe, this.popperTriggers, this.popperShowTriggers, e); const t = (o) => { o.usedByTooltip || this.hide({ event: o }); }; this.$_registerTriggerListeners(this.$_targetNodes, ae, this.triggers, this.hideTriggers, t), this.$_registerTriggerListeners([this.$_popperNode], ae, this.popperTriggers, this.popperHideTriggers, t); }, $_registerEventListeners(e, t, o) { this.$_events.push({ targetNodes: e, eventType: t, handler: o }), e.forEach((i) => i.addEventListener(t, o, $$1 ? { passive: !0 } : void 0)); }, $_registerTriggerListeners(e, t, o, i, s) { let r = o; i != null && (r = typeof i == "function" ? i(r) : i), r.forEach((p) => { const a = t[p]; a && this.$_registerEventListeners(e, a, s); }); }, $_removeEventListeners(e) { const t = []; this.$_events.forEach((o) => { const { targetNodes: i, eventType: s, handler: r } = o; !e || e === s ? i.forEach((p) => p.removeEventListener(s, r)) : t.push(o); }), this.$_events = t; }, $_refreshListeners() { this.isDisposed || (this.$_removeEventListeners(), this.$_addEventListeners()); }, $_handleGlobalClose(e, t = !1) { this.$_showFrameLocked || (this.hide({ event: e }), e.closePopover ? this.$emit("close-directive") : this.$emit("auto-hide"), t && (this.$_preventShow = !0, setTimeout(() => { this.$_preventShow = !1; }, 300))); }, $_detachPopperNode() { this.$_popperNode.parentNode && this.$_popperNode.parentNode.removeChild(this.$_popperNode); }, $_swapTargetAttrs(e, t) { for (const o of this.$_targetNodes) { const i = o.getAttribute(e); i && (o.removeAttribute(e), o.setAttribute(t, i)); } }, $_applyAttrsToTarget(e) { for (const t of this.$_targetNodes) for (const o in e) { const i = e[o]; i == null ? t.removeAttribute(o) : t.setAttribute(o, i); } }, $_updateParentShownChildren(e) { let t = this.parentPopper; for (; t;) e ? t.shownChildren.add(this.randomId) : (t.shownChildren.delete(this.randomId), t.pendingHide && t.hide()), t = t.parentPopper; }, $_isAimingPopper() { const e = this.$_referenceNode.getBoundingClientRect(); if (y >= e.left && y <= e.right && _ >= e.top && _ <= e.bottom) { const t = this.$_popperNode.getBoundingClientRect(), o = y - c, i = _ - m, r = t.left + t.width / 2 - c + (t.top + t.height / 2) - m + t.width + t.height, p = c + o * r, a = m + i * r; return C(c, m, p, a, t.left, t.top, t.left, t.bottom) || C(c, m, p, a, t.left, t.top, t.right, t.top) || C(c, m, p, a, t.right, t.top, t.right, t.bottom) || C(c, m, p, a, t.left, t.bottom, t.right, t.bottom); } return !1; } }, render() { return this.$slots.default(this.slotData); } }); if (typeof document < "u" && typeof window < "u") { if (_e) { const e = $$1 ? { passive: !0, capture: !0 } : !0; document.addEventListener("touchstart", (t) => ue(t, !0), e), document.addEventListener("touchend", (t) => fe$1(t, !0), e); } else window.addEventListener("mousedown", (e) => ue(e, !1), !0), window.addEventListener("click", (e) => fe$1(e, !1), !0); window.addEventListener("resize", tt); } function ue(e, t) { if (h.autoHideOnMousedown) Pe(e, t); else for (let o = 0; o < d.length; o++) { const i = d[o]; try { i.mouseDownContains = i.popperNode().contains(e.target); } catch {} } } function fe$1(e, t) { h.autoHideOnMousedown || Pe(e, t); } function Pe(e, t) { const o = {}; for (let i = d.length - 1; i >= 0; i--) { const s = d[i]; try { const r = s.containsGlobalTarget = s.mouseDownContains || s.popperNode().contains(e.target); s.pendingHide = !1, requestAnimationFrame(() => { if (s.pendingHide = !1, !o[s.randomId] && ce(s, r, e)) { if (s.$_handleGlobalClose(e, t), !e.closeAllPopover && e.closePopover && r) { let a = s.parentPopper; for (; a;) o[a.randomId] = !0, a = a.parentPopper; return; } let p = s.parentPopper; for (; p && ce(p, p.containsGlobalTarget, e);) { p.$_handleGlobalClose(e, t); p = p.parentPopper; } } }); } catch {} } } function ce(e, t, o) { return o.closeAllPopover || o.closePopover && t || et(e, o) && !t; } function et(e, t) { if (typeof e.autoHide == "function") { const o = e.autoHide(t); return e.lastAutoHide = o, o; } return e.autoHide; } function tt() { for (let e = 0; e < d.length; e++) d[e].$_computePosition(); } var c = 0, m = 0, y = 0, _ = 0; typeof window < "u" && window.addEventListener("mousemove", (e) => { c = y, m = _, y = e.clientX, _ = e.clientY; }, $$1 ? { passive: !0 } : void 0); function C(e, t, o, i, s, r, p, a) { const l = ((p - s) * (t - r) - (a - r) * (e - s)) / ((a - r) * (o - e) - (p - s) * (i - t)), u = ((o - e) * (t - r) - (i - t) * (e - s)) / ((a - r) * (o - e) - (p - s) * (i - t)); return l >= 0 && l <= 1 && u >= 0 && u <= 1; } var ot = { extends: Q() }, B = (e, t) => { const o = e.__vccOpts || e; for (const [i, s] of t) o[i] = s; return o; }; function it(e, t, o, i, s, r) { return openBlock(), createElementBlock("div", { ref: "reference", class: normalizeClass(["v-popper", { "v-popper--shown": e.slotData.isShown }]) }, [renderSlot(e.$slots, "default", normalizeProps(guardReactiveProps(e.slotData)))], 2); } var st = /* @__PURE__ */ B(ot, [["render", it]]); function nt() { var e = window.navigator.userAgent, t = e.indexOf("MSIE "); if (t > 0) return parseInt(e.substring(t + 5, e.indexOf(".", t)), 10); if (e.indexOf("Trident/") > 0) { var i = e.indexOf("rv:"); return parseInt(e.substring(i + 3, e.indexOf(".", i)), 10); } var s = e.indexOf("Edge/"); return s > 0 ? parseInt(e.substring(s + 5, e.indexOf(".", s)), 10) : -1; } var z; function X$1() { X$1.init || (X$1.init = !0, z = nt() !== -1); } var E = { name: "ResizeObserver", props: { emitOnMount: { type: Boolean, default: !1 }, ignoreWidth: { type: Boolean, default: !1 }, ignoreHeight: { type: Boolean, default: !1 } }, emits: ["notify"], mounted() { X$1(), nextTick(() => { this._w = this.$el.offsetWidth, this._h = this.$el.offsetHeight, this.emitOnMount && this.emitSize(); }); const e = document.createElement("object"); this._resizeObject = e, e.setAttribute("aria-hidden", "true"), e.setAttribute("tabindex", -1), e.onload = this.addResizeHandlers, e.type = "text/html", z && this.$el.appendChild(e), e.data = "about:blank", z || this.$el.appendChild(e); }, beforeUnmount() { this.removeResizeHandlers(); }, methods: { compareAndNotify() { (!this.ignoreWidth && this._w !== this.$el.offsetWidth || !this.ignoreHeight && this._h !== this.$el.offsetHeight) && (this._w = this.$el.offsetWidth, this._h = this.$el.offsetHeight, this.emitSize()); }, emitSize() { this.$emit("notify", { width: this._w, height: this._h }); }, addResizeHandlers() { this._resizeObject.contentDocument.defaultView.addEventListener("resize", this.compareAndNotify), this.compareAndNotify(); }, removeResizeHandlers() { this._resizeObject && this._resizeObject.onload && (!z && this._resizeObject.contentDocument && this._resizeObject.contentDocument.defaultView.removeEventListener("resize", this.compareAndNotify), this.$el.removeChild(this._resizeObject), this._resizeObject.onload = null, this._resizeObject = null); } } }; var rt = /* @__PURE__ */ withScopeId("data-v-b329ee4c"); pushScopeId("data-v-b329ee4c"); var pt = { class: "resize-observer", tabindex: "-1" }; popScopeId(); E.render = /* @__PURE__ */ rt((e, t, o, i, s, r) => (openBlock(), createBlock("div", pt))); E.__scopeId = "data-v-b329ee4c"; E.__file = "src/components/ResizeObserver.vue"; var Z$1 = (e = "theme") => ({ computed: { themeClass() { return Ze(this[e]); } } }), dt = /* @__PURE__ */ defineComponent({ name: "VPopperContent", components: { ResizeObserver: E }, mixins: [Z$1()], props: { popperId: String, theme: String, shown: Boolean, mounted: Boolean, skipTransition: Boolean, autoHide: Boolean, handleResize: Boolean, classes: Object, result: Object }, emits: ["hide", "resize"], methods: { toPx(e) { return e != null && !isNaN(e) ? `${e}px` : null; } } }), lt = [ "id", "aria-hidden", "tabindex", "data-popper-placement" ], ht = { ref: "inner", class: "v-popper__inner" }, ct = [/* @__PURE__ */ createBaseVNode("div", { class: "v-popper__arrow-outer" }, null, -1), /* @__PURE__ */ createBaseVNode("div", { class: "v-popper__arrow-inner" }, null, -1)]; function mt(e, t, o, i, s, r) { const p = resolveComponent("ResizeObserver"); return openBlock(), createElementBlock("div", { id: e.popperId, ref: "popover", class: normalizeClass(["v-popper__popper", [ e.themeClass, e.classes.popperClass, { "v-popper__popper--shown": e.shown, "v-popper__popper--hidden": !e.shown, "v-popper__popper--show-from": e.classes.showFrom, "v-popper__popper--show-to": e.classes.showTo, "v-popper__popper--hide-from": e.classes.hideFrom, "v-popper__popper--hide-to": e.classes.hideTo, "v-popper__popper--skip-transition": e.skipTransition, "v-popper__popper--arrow-overflow": e.result && e.result.arrow.overflow, "v-popper__popper--no-positioning": !e.result } ]]), style: normalizeStyle(e.result ? { position: e.result.strategy, transform: `translate3d(${Math.round(e.result.x)}px,${Math.round(e.result.y)}px,0)` } : void 0), "aria-hidden": e.shown ? "false" : "true", tabindex: e.autoHide ? 0 : void 0, "data-popper-placement": e.result ? e.result.placement : void 0, onKeyup: t[2] || (t[2] = withKeys((a) => e.autoHide && e.$emit("hide"), ["esc"])) }, [createBaseVNode("div", { class: "v-popper__backdrop", onClick: t[0] || (t[0] = (a) => e.autoHide && e.$emit("hide")) }), createBaseVNode("div", { class: "v-popper__wrapper", style: normalizeStyle(e.result ? { transformOrigin: e.result.transformOrigin } : void 0) }, [createBaseVNode("div", ht, [e.mounted ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createBaseVNode("div", null, [renderSlot(e.$slots, "default")]), e.handleResize ? (openBlock(), createBlock(p, { key: 0, onNotify: t[1] || (t[1] = (a) => e.$emit("resize", a)) })) : createCommentVNode("", !0)], 64)) : createCommentVNode("", !0)], 512), createBaseVNode("div", { ref: "arrow", class: "v-popper__arrow-container", style: normalizeStyle(e.result ? { left: e.toPx(e.result.arrow.x), top: e.toPx(e.result.arrow.y) } : void 0) }, ct, 4)], 4)], 46, lt); } var ee = /* @__PURE__ */ B(dt, [["render", mt]]), te = { methods: { show(...e) { return this.$refs.popper.show(...e); }, hide(...e) { return this.$refs.popper.hide(...e); }, dispose(...e) { return this.$refs.popper.dispose(...e); }, onResize(...e) { return this.$refs.popper.onResize(...e); } } }; var K$1 = function() {}; typeof window < "u" && (K$1 = window.Element); var gt = /* @__PURE__ */ defineComponent({ name: "VPopperWrapper", components: { Popper: st, PopperContent: ee }, mixins: [te, Z$1("finalTheme")], props: { theme: { type: String, default: null }, referenceNode: { type: Function, default: null }, shown: { type: Boolean, default: !1 }, showGroup: { type: String, default: null }, ariaId: { default: null }, disabled: { type: Boolean, default: void 0 }, positioningDisabled: { type: Boolean, default: void 0 }, placement: { type: String, default: void 0 }, delay: { type: [ String, Number, Object ], default: void 0 }, distance: { type: [Number, String], default: void 0 }, skidding: { type: [Number, String], default: void 0 }, triggers: { type: Array, default: void 0 }, showTriggers: { type: [Array, Function], default: void 0 }, hideTriggers: { type: [Array, Function], default: void 0 }, popperTriggers: { type: Array, default: void 0 }, popperShowTriggers: { type: [Array, Function], default: void 0 }, popperHideTriggers: { type: [Array, Function], default: void 0 }, container: { type: [ String, Object, K$1, Boolean ], default: void 0 }, boundary: { type: [String, K$1], default: void 0 }, strategy: { type: String, default: void 0 }, autoHide: { type: [Boolean, Function], default: void 0 }, handleResize: { type: Boolean, default: void 0 }, instantMove: { type: Boolean, default: void 0 }, eagerMount: { type: Boolean, default: void 0 }, popperClass: { type: [ String, Array, Object ], default: void 0 }, computeTransformOrigin: { type: Boolean, default: void 0 }, /** * @deprecated */ autoMinSize: { type: Boolean, default: void 0 }, autoSize: { type: [Boolean, String], default: void 0 }, /** * @deprecated */ autoMaxSize: { type: Boolean, default: void 0 }, autoBoundaryMaxSize: { type: Boolean, default: void 0 }, preventOverflow: { type: Boolean, default: void 0 }, overflowPadding: { type: [Number, String], default: void 0 }, arrowPadding: { type: [Number, String], default: void 0 }, arrowOverflow: { type: Boolean, default: void 0 }, flip: { type: Boolean, default: void 0 }, shift: { type: Boolean, default: void 0 }, shiftCrossAxis: { type: Boolean, default: void 0 }, noAutoFocus: { type: Boolean, default: void 0 }, disposeTimeout: { type: Number, default: void 0 } }, emits: { show: () => !0, hide: () => !0, "update:shown": (e) => !0, "apply-show": () => !0, "apply-hide": () => !0, "close-group": () => !0, "close-directive": () => !0, "auto-hide": () => !0, resize: () => !0 }, computed: { finalTheme() { return this.theme ?? this.$options.vPopperTheme; } }, methods: { getTargetNodes() { return Array.from(this.$el.children).filter((e) => e !== this.$refs.popperContent.$el); } } }); function wt(e, t, o, i, s, r) { const p = resolveComponent("PopperContent"), a = resolveComponent("Popper"); return openBlock(), createBlock(a, mergeProps({ ref: "popper" }, e.$props, { theme: e.finalTheme, "target-nodes": e.getTargetNodes, "popper-node": () => e.$refs.popperContent.$el, class: [e.themeClass], onShow: t[0] || (t[0] = () => e.$emit("show")), onHide: t[1] || (t[1] = () => e.$emit("hide")), "onUpdate:shown": t[2] || (t[2] = (l) => e.$emit("update:shown", l)), onApplyShow: t[3] || (t[3] = () => e.$emit("apply-show")), onApplyHide: t[4] || (t[4] = () => e.$emit("apply-hide")), onCloseGroup: t[5] || (t[5] = () => e.$emit("close-group")), onCloseDirective: t[6] || (t[6] = () => e.$emit("close-directive")), onAutoHide: t[7] || (t[7] = () => e.$emit("auto-hide")), onResize: t[8] || (t[8] = () => e.$emit("resize")) }), { default: withCtx(({ popperId: l, isShown: u, shouldMountContent: L, skipTransition: D, autoHide: I, show: F, hide: v, handleResize: R, onResize: j, classes: V, result: Ee }) => [renderSlot(e.$slots, "default", { shown: u, show: F, hide: v }), createVNode(p, { ref: "popperContent", "popper-id": l, theme: e.finalTheme, shown: u, mounted: L, "skip-transition": D, "auto-hide": I, "handle-resize": R, classes: V, result: Ee, onHide: v, onResize: j }, { default: withCtx(() => [renderSlot(e.$slots, "popper", { shown: u, hide: v })]), _: 2 }, 1032, [ "popper-id", "theme", "shown", "mounted", "skip-transition", "auto-hide", "handle-resize", "classes", "result", "onHide", "onResize" ])]), _: 3 }, 16, [ "theme", "target-nodes", "popper-node", "class" ]); } var k = /* @__PURE__ */ B(gt, [["render", wt]]), Se = { ...k, name: "VDropdown", vPopperTheme: "dropdown" }, be$1 = { ...k, name: "VMenu", vPopperTheme: "menu" }, Ce = { ...k, name: "VTooltip", vPopperTheme: "tooltip" }, $t = /* @__PURE__ */ defineComponent({ name: "VTooltipDirective", components: { Popper: Q(), PopperContent: ee }, mixins: [te], inheritAttrs: !1, props: { theme: { type: String, default: "tooltip" }, html: { type: Boolean, default: (e) => S(e.theme, "html") }, content: { type: [ String, Number, Function ], default: null }, loadingContent: { type: String, default: (e) => S(e.theme, "loadingContent") }, targetNodes: { type: Function, required: !0 } }, data() { return { asyncContent: null }; }, computed: { isContentAsync() { return typeof this.content == "function"; }, loading() { return this.isContentAsync && this.asyncContent == null; }, finalContent() { return this.isContentAsync ? this.loading ? this.loadingContent : this.asyncContent : this.content; } }, watch: { content: { handler() { this.fetchContent(!0); }, immediate: !0 }, async finalContent() { await this.$nextTick(), this.$refs.popper.onResize(); } }, created() { this.$_fetchId = 0; }, methods: { fetchContent(e) { if (typeof this.content == "function" && this.$_isShown && (e || !this.$_loading && this.asyncContent == null)) { this.asyncContent = null, this.$_loading = !0; const t = ++this.$_fetchId, o = this.content(this); o.then ? o.then((i) => this.onResult(t, i)) : this.onResult(t, o); } }, onResult(e, t) { e === this.$_fetchId && (this.$_loading = !1, this.asyncContent = t); }, onShow() { this.$_isShown = !0, this.fetchContent(); }, onHide() { this.$_isShown = !1; } } }), vt = ["innerHTML"], yt = ["textContent"]; function _t(e, t, o, i, s, r) { const p = resolveComponent("PopperContent"), a = resolveComponent("Popper"); return openBlock(), createBlock(a, mergeProps({ ref: "popper" }, e.$attrs, { theme: e.theme, "target-nodes": e.targetNodes, "popper-node": () => e.$refs.popperContent.$el, onApplyShow: e.onShow, onApplyHide: e.onHide }), { default: withCtx(({ popperId: l, isShown: u, shouldMountContent: L, skipTransition: D, autoHide: I, hide: F, handleResize: v, onResize: R, classes: j, result: V }) => [createVNode(p, { ref: "popperContent", class: normalizeClass({ "v-popper--tooltip-loading": e.loading }), "popper-id": l, theme: e.theme, shown: u, mounted: L, "skip-transition": D, "auto-hide": I, "handle-resize": v, classes: j, result: V, onHide: F, onResize: R }, { default: withCtx(() => [e.html ? (openBlock(), createElementBlock("div", { key: 0, innerHTML: e.finalContent }, null, 8, vt)) : (openBlock(), createElementBlock("div", { key: 1, textContent: toDisplayString(e.finalContent) }, null, 8, yt))]), _: 2 }, 1032, [ "class", "popper-id", "theme", "shown", "mounted", "skip-transition", "auto-hide", "handle-resize", "classes", "result", "onHide", "onResize" ])]), _: 1 }, 16, [ "theme", "target-nodes", "popper-node", "onApplyShow", "onApplyHide" ]); } var ze = /* @__PURE__ */ B($t, [["render", _t]]), Ae = "v-popper--has-tooltip"; function Tt(e, t) { let o = e.placement; if (!o && t) for (const i of Te) t[i] && (o = i); return o || (o = S(e.theme || "tooltip", "placement")), o; } function Ne$1(e, t, o) { let i; const s = typeof t; return s === "string" ? i = { content: t } : t && s === "object" ? i = t : i = { content: !1 }, i.placement = Tt(i, o), i.targetNodes = () => [e], i.referenceNode = () => e, i; } var x, b, Pt = 0; function St() { if (x) return; b = /* @__PURE__ */ ref([]), x = createApp({ name: "VTooltipDirectiveApp", setup() { return { directives: b }; }, render() { return this.directives.map((t) => h$3(ze, { ...t.options, shown: t.shown || t.options.shown, key: t.id })); }, devtools: { hide: !0 } }); const e = document.createElement("div"); document.body.appendChild(e), x.mount(e); } function bt(e, t, o) { St(); const i = /* @__PURE__ */ ref(Ne$1(e, t, o)), s = /* @__PURE__ */ ref(!1), r = { id: Pt++, options: i, shown: s }; return b.value.push(r), e.classList && e.classList.add(Ae), e.$_popper = { options: i, item: r, show() { s.value = !0; }, hide() { s.value = !1; } }; } function He$1(e) { if (e.$_popper) { const t = b.value.indexOf(e.$_popper.item); t !== -1 && b.value.splice(t, 1), delete e.$_popper, delete e.$_popperOldShown, delete e.$_popperMountTarget; } e.classList && e.classList.remove(Ae); } function me(e, { value: t, modifiers: o }) { const i = Ne$1(e, t, o); if (!i.content || S(i.theme || "tooltip", "disabled")) He$1(e); else { let s; e.$_popper ? (s = e.$_popper, s.options.value = i) : s = bt(e, t, o), typeof t.shown < "u" && t.shown !== e.$_popperOldShown && (e.$_popperOldShown = t.shown, t.shown ? s.show() : s.hide()); } } var oe$1 = { beforeMount: me, updated: me, beforeUnmount(e) { He$1(e); } }; function ge(e) { e.addEventListener("mousedown", H$1), e.addEventListener("click", H$1), e.addEventListener("touchstart", Oe$1, $$1 ? { passive: !0 } : !1); } function we(e) { e.removeEventListener("mousedown", H$1), e.removeEventListener("click", H$1), e.removeEventListener("touchstart", Oe$1), e.removeEventListener("touchend", Me), e.removeEventListener("touchcancel", Be); } function H$1(e) { const t = e.currentTarget; e.closePopover = !t.$_vclosepopover_touch, e.closeAllPopover = t.$_closePopoverModifiers && !!t.$_closePopoverModifiers.all; } function Oe$1(e) { if (e.changedTouches.length === 1) { const t = e.currentTarget; t.$_vclosepopover_touch = !0; t.$_vclosepopover_touchPoint = e.changedTouches[0], t.addEventListener("touchend", Me), t.addEventListener("touchcancel", Be); } } function Me(e) { const t = e.currentTarget; if (t.$_vclosepopover_touch = !1, e.changedTouches.length === 1) { const o = e.changedTouches[0], i = t.$_vclosepopover_touchPoint; e.closePopover = Math.abs(o.screenY - i.screenY) < 20 && Math.abs(o.screenX - i.screenX) < 20, e.closeAllPopover = t.$_closePopoverModifiers && !!t.$_closePopoverModifiers.all; } } function Be(e) { const t = e.currentTarget; t.$_vclosepopover_touch = !1; } var ie = { beforeMount(e, { value: t, modifiers: o }) { e.$_closePopoverModifiers = o, (typeof t > "u" || t) && ge(e); }, updated(e, { value: t, oldValue: o, modifiers: i }) { e.$_closePopoverModifiers = i, t !== o && (typeof t > "u" || t ? ge(e) : we(e)); }, beforeUnmount(e) { we(e); } }; function Ct(e, t = {}) { e.$_vTooltipInstalled || (e.$_vTooltipInstalled = !0, ye(h, t), e.directive("tooltip", oe$1), e.directive("close-popper", ie), e.component("VTooltip", Ce), e.component("VDropdown", Se), e.component("VMenu", be$1)); } var Gt = { version: "5.2.2", install: Ct, options: h }; //#endregion //#region ../send/frontend/src/lib/shared-pinia.ts var piniaInstance = null; /** * Gets or creates the shared Pinia instance. * This ensures both background.ts and extension contexts use the same instance. */ function getSharedPinia() { if (!piniaInstance) { piniaInstance = createPinia(); setActivePinia(piniaInstance); } return piniaInstance; } var isClient = typeof window !== "undefined" && typeof document !== "undefined"; typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope; isClient && window.document; isClient && window.navigator; isClient && window.location; Number.POSITIVE_INFINITY; /*! * tabbable 6.4.0 * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE */ var candidateSelector = /* #__PURE__ */ [ "input:not([inert]):not([inert] *)", "select:not([inert]):not([inert] *)", "textarea:not([inert]):not([inert] *)", "a[href]:not([inert]):not([inert] *)", "button:not([inert]):not([inert] *)", "[tabindex]:not(slot):not([inert]):not([inert] *)", "audio[controls]:not([inert]):not([inert] *)", "video[controls]:not([inert]):not([inert] *)", "[contenteditable]:not([contenteditable=\"false\"]):not([inert]):not([inert] *)", "details>summary:first-of-type:not([inert]):not([inert] *)", "details:not([inert]):not([inert] *)" ].join(","); var NoElement = typeof Element === "undefined"; var matches = NoElement ? function() {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector; !NoElement && Element.prototype.getRootNode; /** * Determines if a node is inert or in an inert ancestor. * @param {Node} [node] * @param {boolean} [lookUp] If true and `node` is not inert, looks up at ancestors to * see if any of them are inert. If false, only `node` itself is considered. * @returns {boolean} True if inert itself or by way of being in an inert ancestor. * False if `node` is falsy. */ var _isInert = function isInert(node, lookUp) { var _node$getAttribute; if (lookUp === void 0) lookUp = true; var inertAtt = node === null || node === void 0 ? void 0 : (_node$getAttribute = node.getAttribute) === null || _node$getAttribute === void 0 ? void 0 : _node$getAttribute.call(node, "inert"); return inertAtt === "" || inertAtt === "true" || lookUp && node && (typeof node.closest === "function" ? node.closest("[inert]") : _isInert(node.parentNode)); }; /** * Determines if a node's content is editable. * @param {Element} [node] * @returns True if it's content-editable; false if it's not or `node` is falsy. */ var isContentEditable = function isContentEditable(node) { var _node$getAttribute2; var attValue = node === null || node === void 0 ? void 0 : (_node$getAttribute2 = node.getAttribute) === null || _node$getAttribute2 === void 0 ? void 0 : _node$getAttribute2.call(node, "contenteditable"); return attValue === "" || attValue === "true"; }; /** * @callback GetShadowRoot * @param {Element} element to check for shadow root * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available. */ /** * @callback ShadowRootFilter * @param {Element} shadowHostNode the element which contains shadow content * @returns {boolean} true if a shadow root could potentially contain valid candidates. */ /** * @typedef {Object} CandidateScope * @property {Element} scopeParent contains inner candidates * @property {Element[]} candidates list of candidates found in the scope parent */ /** * @typedef {Object} IterativeOptions * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not; * if a function, implies shadow support is enabled and either returns the shadow root of an element * or a boolean stating if it has an undisclosed shadow root * @property {(node: Element) => boolean} filter filter candidates * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list * @property {ShadowRootFilter} shadowRootFilter filter shadow roots; */ /** * @param {Element[]} elements list of element containers to match candidates from * @param {boolean} includeContainer add container list to check * @param {IterativeOptions} options * @returns {Array.} */ var _getCandidatesIteratively = function getCandidatesIteratively(elements, includeContainer, options) { var candidates = []; var elementsToCheck = Array.from(elements); while (elementsToCheck.length) { var element = elementsToCheck.shift(); if (_isInert(element, false)) continue; if (element.tagName === "SLOT") { var assigned = element.assignedElements(); var nestedCandidates = _getCandidatesIteratively(assigned.length ? assigned : element.children, true, options); if (options.flatten) candidates.push.apply(candidates, nestedCandidates); else candidates.push({ scopeParent: element, candidates: nestedCandidates }); } else { if (matches.call(element, candidateSelector) && options.filter(element) && (includeContainer || !elements.includes(element))) candidates.push(element); var shadowRoot = element.shadowRoot || typeof options.getShadowRoot === "function" && options.getShadowRoot(element); var validShadowRoot = !_isInert(shadowRoot, false) && (!options.shadowRootFilter || options.shadowRootFilter(element)); if (shadowRoot && validShadowRoot) { var _nestedCandidates = _getCandidatesIteratively(shadowRoot === true ? element.children : shadowRoot.children, true, options); if (options.flatten) candidates.push.apply(candidates, _nestedCandidates); else candidates.push({ scopeParent: element, candidates: _nestedCandidates }); } else elementsToCheck.unshift.apply(elementsToCheck, element.children); } } return candidates; }; /** * @private * Determines if the node has an explicitly specified `tabindex` attribute. * @param {HTMLElement} node * @returns {boolean} True if so; false if not. */ var hasTabIndex = function hasTabIndex(node) { return !isNaN(parseInt(node.getAttribute("tabindex"), 10)); }; /** * Determine the tab index of a given node. * @param {HTMLElement} node * @returns {number} Tab order (negative, 0, or positive number). * @throws {Error} If `node` is falsy. */ var getTabIndex = function getTabIndex(node) { if (!node) throw new Error("No node provided"); if (node.tabIndex < 0) { if ((/^(AUDIO|VIDEO|DETAILS)$/.test(node.tagName) || isContentEditable(node)) && !hasTabIndex(node)) return 0; } return node.tabIndex; }; /** * Determine the tab index of a given node __for sort order purposes__. * @param {HTMLElement} node * @param {boolean} [isScope] True for a custom element with shadow root or slot that, by default, * has tabIndex -1, but needs to be sorted by document order in order for its content to be * inserted into the correct sort position. * @returns {number} Tab order (negative, 0, or positive number). */ var getSortOrderTabIndex = function getSortOrderTabIndex(node, isScope) { var tabIndex = getTabIndex(node); if (tabIndex < 0 && isScope && !hasTabIndex(node)) return 0; return tabIndex; }; var sortOrderedTabbables = function sortOrderedTabbables(a, b) { return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex; }; /** * @param {Array.} candidates * @returns Element[] */ var _sortByOrder = function sortByOrder(candidates) { var regularTabbables = []; var orderedTabbables = []; candidates.forEach(function(item, i) { var isScope = !!item.scopeParent; var element = isScope ? item.scopeParent : item; var candidateTabindex = getSortOrderTabIndex(element, isScope); var elements = isScope ? _sortByOrder(item.candidates) : element; if (candidateTabindex === 0) isScope ? regularTabbables.push.apply(regularTabbables, elements) : regularTabbables.push(element); else orderedTabbables.push({ documentOrder: i, tabIndex: candidateTabindex, item, isScope, content: elements }); }); return orderedTabbables.sort(sortOrderedTabbables).reduce(function(acc, sortable) { sortable.isScope ? acc.push.apply(acc, sortable.content) : acc.push(sortable.content); return acc; }, []).concat(regularTabbables); }; /*! * focus-trap 7.6.4 * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE */ if (typeof window < "u") { const e = { get passive() {} }; window.addEventListener("testPassive", null, e), window.removeEventListener("testPassive", null, e); } typeof window < "u" && window.navigator && window.navigator.platform && (/iP(ad|hone|od)/.test(window.navigator.platform) || window.navigator.platform === "MacIntel" && window.navigator.maxTouchPoints); var Ye = Symbol("vfm"); function zo() { const e = /* @__PURE__ */ shallowReactive([]), o = /* @__PURE__ */ shallowReactive([]), c = markRaw({ install(a) { a.provide(Ye, c), a.config.globalProperties.$vfm = c; }, modals: e, openedModals: o, openedModalOverlays: /* @__PURE__ */ shallowReactive([]), dynamicModals: /* @__PURE__ */ shallowReactive([]), modalsContainers: /* @__PURE__ */ ref([]), get(a) { return e.find((n) => { var t, r; return ((r = (t = Z(n)) == null ? void 0 : t.value.modalId) == null ? void 0 : r.value) === a; }); }, toggle(a, n) { var r; return (r = Z(c.get(a))) == null ? void 0 : r.value.toggle(n); }, open(a) { return c.toggle(a, !0); }, close(a) { return c.toggle(a, !1); }, closeAll() { return Promise.allSettled(o.reduce((a, n) => { const t = Z(n), r = t == null ? void 0 : t.value.toggle(!1); return r && a.push(r), a; }, [])); } }); return c; } function Z(e) { var o; return (o = e == null ? void 0 : e.exposed) == null ? void 0 : o.modalExposed; } ({ .../* @__PURE__ */ defineComponent({ inheritAttrs: !1 }) }); //#endregion //#region ../send/frontend/src/apps/send/setup.js var i18nStubMessages = { "footer.copywrite": "Thunderbird is part of {mzlaLink}, a wholly owned subsidiary of the not-for-profit Mozilla.org. Portions of this content are ©1998–{currentYear} by individual contributors. Content available under a {creativeCommonsLink}.", "footer.mzlaLinkText": "MZLA Technologies Corporation", "footer.creativeCommonsLinkText": "Creative Commons license" }; var I18nTStub = { name: "i18n-t", props: ["keypath", "tag"], render() { const message = i18nStubMessages[this.keypath] || this.keypath; const slots = this.$slots; return h$3(this.tag || "span", null, message.split(/(\{[^}]+\})/g).map((part) => { const match = part.match(/^\{(.+)\}$/); if (match && slots[match[1]]) return slots[match[1]](); return part; })); } }; function setupApp(app, telemetryAllowed = false) { const pinia = getSharedPinia(); app.use(VueQueryPlugin); app.use(pinia); app.use(Gt); app.use(posthog_default); setPosthogConsent(telemetryAllowed); app.config.globalProperties.$t = (key) => i18nStubMessages[key] || key; app.component("i18n-t", I18nTStub); } function mountApp(app, nodeName) { const vfm = zo(); app.use(vfm).mount(nodeName); } //#endregion //#region src/apps/extension.js var app = createApp(ExtensionPage_default); initSentry(app); setupApp(app); mountApp(app, "#extension-page"); //#endregion