kolibri-sentry-plugin 0.1.0__py2.py3-none-any.whl → 0.2.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kolibri_sentry_plugin/__init__.py +1 -1
- kolibri_sentry_plugin/build/kolibri_sentry_plugin.main_stats.json +25 -1
- kolibri_sentry_plugin/kolibri_plugin.py +1 -3
- kolibri_sentry_plugin/options.py +5 -0
- kolibri_sentry_plugin/settings.py +7 -4
- kolibri_sentry_plugin/static/kolibri_sentry_plugin.main/kolibri_sentry_plugin.main-0.2.0.js +2 -0
- kolibri_sentry_plugin/static/kolibri_sentry_plugin.main/kolibri_sentry_plugin.main-0.2.0.js.map +1 -0
- kolibri_sentry_plugin-0.2.0.dist-info/AUTHORS.rst +12 -0
- kolibri_sentry_plugin-0.2.0.dist-info/LICENSE +20 -0
- {kolibri_sentry_plugin-0.1.0.dist-info → kolibri_sentry_plugin-0.2.0.dist-info}/METADATA +14 -9
- kolibri_sentry_plugin-0.2.0.dist-info/RECORD +14 -0
- {kolibri_sentry_plugin-0.1.0.dist-info → kolibri_sentry_plugin-0.2.0.dist-info}/WHEEL +1 -1
- kolibri_sentry_plugin/build/kolibri_sentry_plugin_module_stats.json +0 -1
- kolibri_sentry_plugin/build/main_stats.json +0 -1
- kolibri_sentry_plugin/static/kolibri_sentry_plugin.main/kolibri_sentry_plugin.main-0.1.0.js +0 -2
- kolibri_sentry_plugin/static/kolibri_sentry_plugin.main/kolibri_sentry_plugin.main-0.1.0.js.map +0 -1
- kolibri_sentry_plugin/static/kolibri_sentry_plugin_module/kolibri_sentry_plugin_module-0.0.1.js +0 -2
- kolibri_sentry_plugin/static/kolibri_sentry_plugin_module/kolibri_sentry_plugin_module-0.0.1.js.map +0 -1
- kolibri_sentry_plugin-0.1.0.dist-info/DESCRIPTION.rst +0 -4
- kolibri_sentry_plugin-0.1.0.dist-info/RECORD +0 -18
- kolibri_sentry_plugin-0.1.0.dist-info/metadata.json +0 -1
- {kolibri_sentry_plugin-0.1.0.dist-info → kolibri_sentry_plugin-0.2.0.dist-info}/entry_points.txt +0 -0
- {kolibri_sentry_plugin-0.1.0.dist-info → kolibri_sentry_plugin-0.2.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2 @@
|
|
1
|
+
window.kolibriCoreAppGlobal.registerLanguageAssets("kolibri_sentry_plugin.main"),function(){var __webpack_modules__={606:function(module){var cachedSetTimeout,cachedClearTimeout,process=module.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,function(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}}},__webpack_module_cache__={};function __webpack_require__(moduleId){var cachedModule=__webpack_module_cache__[moduleId];if(void 0!==cachedModule)return cachedModule.exports;var module=__webpack_module_cache__[moduleId]={exports:{}};return __webpack_modules__[moduleId](module,module.exports,__webpack_require__),module.exports}__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module.default}:function(){return module};return __webpack_require__.d(getter,{a:getter}),getter},__webpack_require__.d=function(exports,definition){for(var key in definition)__webpack_require__.o(definition,key)&&!__webpack_require__.o(exports,key)&&Object.defineProperty(exports,key,{enumerable:!0,get:definition[key]})},__webpack_require__.o=function(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)},function(){"use strict";const worldwide_GLOBAL_OBJ=globalThis,objectToString=Object.prototype.toString;function isError(wat){switch(objectToString.call(wat)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return isInstanceOf(wat,Error)}}function isBuiltin(wat,className){return objectToString.call(wat)===`[object ${className}]`}function isErrorEvent(wat){return isBuiltin(wat,"ErrorEvent")}function isDOMError(wat){return isBuiltin(wat,"DOMError")}function isString(wat){return isBuiltin(wat,"String")}function is_isParameterizedString(wat){return"object"==typeof wat&&null!==wat&&"__sentry_template_string__"in wat&&"__sentry_template_values__"in wat}function is_isPrimitive(wat){return null===wat||is_isParameterizedString(wat)||"object"!=typeof wat&&"function"!=typeof wat}function isPlainObject(wat){return isBuiltin(wat,"Object")}function isEvent(wat){return"undefined"!=typeof Event&&isInstanceOf(wat,Event)}function is_isThenable(wat){return Boolean(wat?.then&&"function"==typeof wat.then)}function isInstanceOf(wat,base){try{return wat instanceof base}catch(_e){return!1}}function isVueViewModel(wat){return!("object"!=typeof wat||null===wat||!wat.__isVue&&!wat._isVue)}const browser_WINDOW=worldwide_GLOBAL_OBJ;function htmlTreeAsString(elem,options={}){if(!elem)return"<unknown>";try{let currentElem=elem;const MAX_TRAVERSE_HEIGHT=5,out=[];let height=0,len=0;const separator=" > ",sepLength=separator.length;let nextStr;const keyAttrs=Array.isArray(options)?options:options.keyAttrs,maxStringLength=!Array.isArray(options)&&options.maxStringLength||80;for(;currentElem&&height++<MAX_TRAVERSE_HEIGHT&&(nextStr=_htmlElementAsString(currentElem,keyAttrs),!("html"===nextStr||height>1&&len+out.length*sepLength+nextStr.length>=maxStringLength));)out.push(nextStr),len+=nextStr.length,currentElem=currentElem.parentNode;return out.reverse().join(separator)}catch(_oO){return"<unknown>"}}function _htmlElementAsString(el,keyAttrs){const elem=el,out=[];if(!elem?.tagName)return"";if(browser_WINDOW.HTMLElement&&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?.length?keyAttrs.filter((keyAttr=>elem.getAttribute(keyAttr))).map((keyAttr=>[keyAttr,elem.getAttribute(keyAttr)])):null;if(keyAttrPairs?.length)keyAttrPairs.forEach((keyAttrPair=>{out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`)}));else{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}`)}}const allowedAttrs=["aria-label","type","name","title","alt"];for(const k of allowedAttrs){const attr=elem.getAttribute(k);attr&&out.push(`[${k}="${attr}"]`)}return out.join("")}function getLocationHref(){try{return browser_WINDOW.document.location.href}catch(oO){return""}}const debug_build_DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function carrier_getMainCarrier(){return carrier_getSentryCarrier(worldwide_GLOBAL_OBJ),worldwide_GLOBAL_OBJ}function carrier_getSentryCarrier(carrier){const __SENTRY__=carrier.__SENTRY__=carrier.__SENTRY__||{};return __SENTRY__.version=__SENTRY__.version||"9.13.0",__SENTRY__["9.13.0"]=__SENTRY__["9.13.0"]||{}}function getGlobalSingleton(name,creator,obj=worldwide_GLOBAL_OBJ){const __SENTRY__=obj.__SENTRY__=obj.__SENTRY__||{},carrier=__SENTRY__["9.13.0"]=__SENTRY__["9.13.0"]||{};return carrier[name]||(carrier[name]=creator())}const CONSOLE_LEVELS=["debug","info","warn","error","log","assert","trace"],originalConsoleMethods={};function consoleSandbox(callback){if(!("console"in worldwide_GLOBAL_OBJ))return callback();const console=worldwide_GLOBAL_OBJ.console,wrappedFuncs={},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]}))}}const logger_logger=getGlobalSingleton("logger",(function(){let enabled=!1;const logger={enable:()=>{enabled=!0},disable:()=>{enabled=!1},isEnabled:()=>enabled};return debug_build_DEBUG_BUILD?CONSOLE_LEVELS.forEach((name=>{logger[name]=(...args)=>{enabled&&consoleSandbox((()=>{worldwide_GLOBAL_OBJ.console[name](`Sentry Logger [${name}]:`,...args)}))}})):CONSOLE_LEVELS.forEach((name=>{logger[name]=()=>{}})),logger}));function truncate(str,max=0){return"string"!=typeof str||0===max||str.length<=max?str:`${str.slice(0,max)}...`}function safeJoin(input,delimiter){if(!Array.isArray(input))return"";const output=[];for(let i=0;i<input.length;i++){const value=input[i];try{isVueViewModel(value)?output.push("[VueViewModel]"):output.push(String(value))}catch(e){output.push("[value cannot be serialized]")}}return output.join(delimiter)}function isMatchingPattern(value,pattern,requireExactStringMatch=!1){return!!isString(value)&&(isBuiltin(pattern,"RegExp")?pattern.test(value):!!isString(pattern)&&(requireExactStringMatch?value===pattern:value.includes(pattern)))}function stringMatchesSomePattern(testString,patterns=[],requireExactStringMatch=!1){return patterns.some((pattern=>isMatchingPattern(testString,pattern,requireExactStringMatch)))}function fill(source,name,replacementFactory){if(!(name in source))return;const original=source[name];if("function"!=typeof original)return;const wrapped=replacementFactory(original);"function"==typeof wrapped&&markFunctionWrapped(wrapped,original);try{source[name]=wrapped}catch{debug_build_DEBUG_BUILD&&logger_logger.log(`Failed to replace method "${name}" in object`,source)}}function addNonEnumerableProperty(obj,name,value){try{Object.defineProperty(obj,name,{value:value,writable:!0,configurable:!0})}catch(o_O){debug_build_DEBUG_BUILD&&logger_logger.log(`Failed to add non-enumerable property "${name}" to object`,obj)}}function markFunctionWrapped(wrapped,original){try{const proto=original.prototype||{};wrapped.prototype=original.prototype=proto,addNonEnumerableProperty(wrapped,"__sentry_original__",original)}catch(o_O){}}function getOriginalFunction(func){return func.__sentry_original__}function convertToPlainObject(value){if(isError(value))return{message:value.message,name:value.name,stack:value.stack,...getOwnProperties(value)};if(isEvent(value)){const newObj={type:value.type,target:serializeEventTarget(value.target),currentTarget:serializeEventTarget(value.currentTarget),...getOwnProperties(value)};return"undefined"!=typeof CustomEvent&&isInstanceOf(value,CustomEvent)&&(newObj.detail=value.detail),newObj}return value}function serializeEventTarget(target){try{return wat=target,"undefined"!=typeof Element&&isInstanceOf(wat,Element)?htmlTreeAsString(target):Object.prototype.toString.call(target)}catch(_oO){return"<unknown>"}var wat}function getOwnProperties(obj){if("object"==typeof obj&&null!==obj){const extractedProps={};for(const property in obj)Object.prototype.hasOwnProperty.call(obj,property)&&(extractedProps[property]=obj[property]);return extractedProps}return{}}const WEBPACK_ERROR_REGEXP=/\(error: (.*)\)/,STRIP_FRAME_REGEXP=/captureMessage|captureException/;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=[],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: /)){for(const parser of sortedParsers){const frame=parser(cleanedLine);if(frame){frames.push(frame);break}}if(frames.length>=50+framesToPop)break}}return function(stack){if(!stack.length)return[];const localStack=Array.from(stack);/sentryWrapped/.test(getLastStackFrame(localStack).function||"")&&localStack.pop();localStack.reverse(),STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function||"")&&(localStack.pop(),STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function||"")&&localStack.pop());return localStack.slice(0,50).map((frame=>({...frame,filename:frame.filename||getLastStackFrame(localStack).filename,function:frame.function||"?"})))}(frames.slice(framesToPop))}}function getLastStackFrame(arr){return arr[arr.length-1]||{}}function getFunctionName(fn){try{return fn&&"function"==typeof fn&&fn.name||"<anonymous>"}catch(e){return"<anonymous>"}}function getFramesFromEvent(event){const exception=event.exception;if(exception){const frames=[];try{return exception.values.forEach((value=>{value.stacktrace.frames&&frames.push(...value.stacktrace.frames)})),frames}catch(_oO){return}}}function normalize(input,depth=100,maxProperties=1/0){try{return visit("",input,depth,maxProperties)}catch(err){return{ERROR:`**non-serializable** (${err})`}}}function normalizeToSize(object,depth=3,maxSize=102400){const normalized=normalize(object,depth);return value=normalized,function(value){return~-encodeURI(value).split(/%..|./).length}(JSON.stringify(value))>maxSize?normalizeToSize(object,depth-1,maxSize):normalized;var value}function visit(key,value,depth=1/0,maxProperties=1/0,memo=function(){const inner=new WeakSet;function memoize(obj){return!!inner.has(obj)||(inner.add(obj),!1)}function unmemoize(obj){inner.delete(obj)}return[memoize,unmemoize]}()){const[memoize,unmemoize]=memo;if(null==value||["boolean","string"].includes(typeof value)||"number"==typeof value&&Number.isFinite(value))return value;const stringified=function(key,value){try{if("domain"===key&&value&&"object"==typeof value&&value._events)return"[Domain]";if("domainEmitter"===key)return"[DomainEmitter]";if("undefined"!=typeof global&&value===global)return"[Global]";if("undefined"!=typeof window&&value===window)return"[Window]";if("undefined"!=typeof document&&value===document)return"[Document]";if(isVueViewModel(value))return"[VueViewModel]";if(isPlainObject(wat=value)&&"nativeEvent"in wat&&"preventDefault"in wat&&"stopPropagation"in wat)return"[SyntheticEvent]";if("number"==typeof value&&!Number.isFinite(value))return`[${value}]`;if("function"==typeof value)return`[Function: ${getFunctionName(value)}]`;if("symbol"==typeof value)return`[${String(value)}]`;if("bigint"==typeof value)return`[BigInt: ${String(value)}]`;const objName=function(value){const prototype=Object.getPrototypeOf(value);return prototype?.constructor?prototype.constructor.name:"null prototype"}(value);return/^HTML(\w*)Element$/.test(objName)?`[HTMLElement: ${objName}]`:`[object ${objName}]`}catch(err){return`**non-serializable** (${err})`}var wat}(key,value);if(!stringified.startsWith("[object "))return stringified;if(value.__sentry_skip_normalization__)return value;const remainingDepth="number"==typeof value.__sentry_override_normalization_depth__?value.__sentry_override_normalization_depth__:depth;if(0===remainingDepth)return stringified.replace("object ","");if(memoize(value))return"[Circular ~]";const valueWithToJSON=value;if(valueWithToJSON&&"function"==typeof valueWithToJSON.toJSON)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++}return unmemoize(value),normalized}function dateTimestampInSeconds(){return Date.now()/1e3}const time_timestampInSeconds=function(){const{performance:performance}=worldwide_GLOBAL_OBJ;if(!performance?.now)return dateTimestampInSeconds;const approxStartingTimeOrigin=Date.now()-performance.now(),timeOrigin=null==performance.timeOrigin?approxStartingTimeOrigin:performance.timeOrigin;return()=>(timeOrigin+performance.now())/1e3}();let cachedTimeOrigin;function browserPerformanceTimeOrigin(){return cachedTimeOrigin||(cachedTimeOrigin=function(){const{performance:performance}=worldwide_GLOBAL_OBJ;if(!performance?.now)return[void 0,"none"];const performanceNow=performance.now(),dateNow=Date.now(),timeOriginDelta=performance.timeOrigin?Math.abs(performance.timeOrigin+performanceNow-dateNow):36e5,timeOriginIsReliable=timeOriginDelta<36e5,navigationStart=performance.timing?.navigationStart,navigationStartDelta="number"==typeof navigationStart?Math.abs(navigationStart+performanceNow-dateNow):36e5;return timeOriginIsReliable||navigationStartDelta<36e5?timeOriginDelta<=navigationStartDelta?[performance.timeOrigin,"timeOrigin"]:[navigationStart,"navigationStart"]:[dateNow,"dateNow"]}()),cachedTimeOrigin[0]}function misc_uuid4(crypto=function(){const gbl=worldwide_GLOBAL_OBJ;return gbl.crypto||gbl.msCrypto}()){let getRandomByte=()=>16*Math.random();try{if(crypto?.randomUUID)return crypto.randomUUID().replace(/-/g,"");crypto?.getRandomValues&&(getRandomByte=()=>{const typedArray=new Uint8Array(1);return crypto.getRandomValues(typedArray),typedArray[0]})}catch(_){}return([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g,(c=>(c^(15&getRandomByte())>>c/4).toString(16)))}function getFirstException(event){return event.exception?.values?.[0]}function getEventDescription(event){const{message:message,event_id:eventId}=event;if(message)return message;const firstException=getFirstException(event);return firstException?firstException.type&&firstException.value?`${firstException.type}: ${firstException.value}`:firstException.type||firstException.value||eventId||"<unknown>":eventId||"<unknown>"}function addExceptionTypeValue(event,value,type){const exception=event.exception=event.exception||{},values=exception.values=exception.values||[],firstException=values[0]=values[0]||{};firstException.value||(firstException.value=value||""),firstException.type||(firstException.type=type||"Error")}function addExceptionMechanism(event,newMechanism){const firstException=getFirstException(event);if(!firstException)return;const currentMechanism=firstException.mechanism;if(firstException.mechanism={type:"generic",handled:!0,...currentMechanism,...newMechanism},newMechanism&&"data"in newMechanism){const mergedData={...currentMechanism?.data,...newMechanism.data};firstException.mechanism.data=mergedData}}function checkOrSetAlreadyCaught(exception){if(function(exception){try{return exception.__sentry_captured__}catch{}}(exception))return!0;try{addNonEnumerableProperty(exception,"__sentry_captured__",!0)}catch(err){}return!1}function makeSession(context){const startingTime=time_timestampInSeconds(),session={sid:misc_uuid4(),init:!0,timestamp:startingTime,started:startingTime,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>function(session){return{sid:`${session.sid}`,init:session.init,started:new Date(1e3*session.started).toISOString(),timestamp:new Date(1e3*session.timestamp).toISOString(),status:session.status,errors:session.errors,did:"number"==typeof session.did||"string"==typeof session.did?`${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}}}(session)};return context&&updateSession(session,context),session}function updateSession(session,context={}){if(context.user&&(!session.ipAddress&&context.user.ip_address&&(session.ipAddress=context.user.ip_address),session.did||context.did||(session.did=context.user.id||context.user.email||context.user.username)),session.timestamp=context.timestamp||time_timestampInSeconds(),context.abnormal_mechanism&&(session.abnormal_mechanism=context.abnormal_mechanism),context.ignoreDuration&&(session.ignoreDuration=context.ignoreDuration),context.sid&&(session.sid=32===context.sid.length?context.sid:misc_uuid4()),void 0!==context.init&&(session.init=context.init),!session.did&&context.did&&(session.did=`${context.did}`),"number"==typeof context.started&&(session.started=context.started),session.ignoreDuration)session.duration=void 0;else if("number"==typeof context.duration)session.duration=context.duration;else{const duration=session.timestamp-session.started;session.duration=duration>=0?duration:0}context.release&&(session.release=context.release),context.environment&&(session.environment=context.environment),!session.ipAddress&&context.ipAddress&&(session.ipAddress=context.ipAddress),!session.userAgent&&context.userAgent&&(session.userAgent=context.userAgent),"number"==typeof context.errors&&(session.errors=context.errors),context.status&&(session.status=context.status)}function propagationContext_generateTraceId(){return misc_uuid4()}function generateSpanId(){return misc_uuid4().substring(16)}function merge(initialObj,mergeObj,levels=2){if(!mergeObj||"object"!=typeof mergeObj||levels<=0)return mergeObj;if(initialObj&&0===Object.keys(mergeObj).length)return initialObj;const output={...initialObj};for(const key in mergeObj)Object.prototype.hasOwnProperty.call(mergeObj,key)&&(output[key]=merge(output[key],mergeObj[key],levels-1));return output}function spanOnScope_setSpanForScope(scope,span){span?addNonEnumerableProperty(scope,"_sentrySpan",span):delete scope._sentrySpan}function spanOnScope_getSpanForScope(scope){return scope._sentrySpan}class Scope{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:propagationContext_generateTraceId(),sampleRand:Math.random()}}clone(){const newScope=new Scope;return newScope._breadcrumbs=[...this._breadcrumbs],newScope._tags={...this._tags},newScope._extra={...this._extra},newScope._contexts={...this._contexts},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._attachments=[...this._attachments],newScope._sdkProcessingMetadata={...this._sdkProcessingMetadata},newScope._propagationContext={...this._propagationContext},newScope._client=this._client,newScope._lastEventId=this._lastEventId,spanOnScope_setSpanForScope(newScope,spanOnScope_getSpanForScope(this)),newScope}setClient(client){this._client=client}setLastEventId(lastEventId){this._lastEventId=lastEventId}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(callback){this._scopeListeners.push(callback)}addEventProcessor(callback){return this._eventProcessors.push(callback),this}setUser(user){return this._user=user||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&updateSession(this._session,{user:user}),this._notifyScopeListeners(),this}getUser(){return this._user}setTags(tags){return this._tags={...this._tags,...tags},this._notifyScopeListeners(),this}setTag(key,value){return this._tags={...this._tags,[key]:value},this._notifyScopeListeners(),this}setExtras(extras){return this._extra={...this._extra,...extras},this._notifyScopeListeners(),this}setExtra(key,extra){return this._extra={...this._extra,[key]:extra},this._notifyScopeListeners(),this}setFingerprint(fingerprint){return this._fingerprint=fingerprint,this._notifyScopeListeners(),this}setLevel(level){return this._level=level,this._notifyScopeListeners(),this}setTransactionName(name){return this._transactionName=name,this._notifyScopeListeners(),this}setContext(key,context){return null===context?delete this._contexts[key]:this._contexts[key]=context,this._notifyScopeListeners(),this}setSession(session){return session?this._session=session:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(captureContext){if(!captureContext)return this;const scopeToMerge="function"==typeof captureContext?captureContext(this):captureContext,scopeInstance=scopeToMerge instanceof Scope?scopeToMerge.getScopeData():isPlainObject(scopeToMerge)?captureContext:void 0,{tags:tags,extra:extra,user:user,contexts:contexts,level:level,fingerprint:fingerprint=[],propagationContext:propagationContext}=scopeInstance||{};return this._tags={...this._tags,...tags},this._extra={...this._extra,...extra},this._contexts={...this._contexts,...contexts},user&&Object.keys(user).length&&(this._user=user),level&&(this._level=level),fingerprint.length&&(this._fingerprint=fingerprint),propagationContext&&(this._propagationContext=propagationContext),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._session=void 0,spanOnScope_setSpanForScope(this,void 0),this._attachments=[],this.setPropagationContext({traceId:propagationContext_generateTraceId(),sampleRand:Math.random()}),this._notifyScopeListeners(),this}addBreadcrumb(breadcrumb,maxBreadcrumbs){const maxCrumbs="number"==typeof maxBreadcrumbs?maxBreadcrumbs:100;if(maxCrumbs<=0)return this;const mergedBreadcrumb={timestamp:dateTimestampInSeconds(),...breadcrumb,message:breadcrumb.message?truncate(breadcrumb.message,2048):breadcrumb.message};return this._breadcrumbs.push(mergedBreadcrumb),this._breadcrumbs.length>maxCrumbs&&(this._breadcrumbs=this._breadcrumbs.slice(-maxCrumbs),this._client?.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(attachment){return this._attachments.push(attachment),this}clearAttachments(){return this._attachments=[],this}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:spanOnScope_getSpanForScope(this)}}setSDKProcessingMetadata(newData){return this._sdkProcessingMetadata=merge(this._sdkProcessingMetadata,newData,2),this}setPropagationContext(context){return this._propagationContext=context,this}getPropagationContext(){return this._propagationContext}captureException(exception,hint){const eventId=hint?.event_id||misc_uuid4();if(!this._client)return logger_logger.warn("No client configured on scope - will not capture exception!"),eventId;const syntheticException=new Error("Sentry syntheticException");return this._client.captureException(exception,{originalException:exception,syntheticException:syntheticException,...hint,event_id:eventId},this),eventId}captureMessage(message,level,hint){const eventId=hint?.event_id||misc_uuid4();if(!this._client)return logger_logger.warn("No client configured on scope - will not capture message!"),eventId;const syntheticException=new Error(message);return this._client.captureMessage(message,level,{originalException:message,syntheticException:syntheticException,...hint,event_id:eventId},this),eventId}captureEvent(event,hint){const eventId=hint?.event_id||misc_uuid4();return this._client?(this._client.captureEvent(event,{...hint,event_id:eventId},this),eventId):(logger_logger.warn("No client configured on scope - will not capture event!"),eventId)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach((callback=>{callback(this)})),this._notifyingListeners=!1)}}class AsyncContextStack{constructor(scope,isolationScope){let assignedScope,assignedIsolationScope;assignedScope=scope||new Scope,assignedIsolationScope=isolationScope||new Scope,this._stack=[{scope:assignedScope}],this._isolationScope=assignedIsolationScope}withScope(callback){const scope=this._pushScope();let maybePromiseResult;try{maybePromiseResult=callback(scope)}catch(e){throw this._popScope(),e}return is_isThenable(maybePromiseResult)?maybePromiseResult.then((res=>(this._popScope(),res)),(e=>{throw this._popScope(),e})):(this._popScope(),maybePromiseResult)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const scope=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:scope}),scope}_popScope(){return!(this._stack.length<=1)&&!!this._stack.pop()}}function getAsyncContextStack(){const sentry=carrier_getSentryCarrier(carrier_getMainCarrier());return sentry.stack=sentry.stack||new AsyncContextStack(getGlobalSingleton("defaultCurrentScope",(()=>new Scope)),getGlobalSingleton("defaultIsolationScope",(()=>new Scope)))}function stackStrategy_withScope(callback){return getAsyncContextStack().withScope(callback)}function withSetScope(scope,callback){const stack=getAsyncContextStack();return stack.withScope((()=>(stack.getStackTop().scope=scope,callback(scope))))}function stackStrategy_withIsolationScope(callback){return getAsyncContextStack().withScope((()=>callback(getAsyncContextStack().getIsolationScope())))}function asyncContext_getAsyncContextStrategy(carrier){const sentry=carrier_getSentryCarrier(carrier);return sentry.acs?sentry.acs:{withIsolationScope:stackStrategy_withIsolationScope,withScope:stackStrategy_withScope,withSetScope:withSetScope,withSetIsolationScope:(_isolationScope,callback)=>stackStrategy_withIsolationScope(callback),getCurrentScope:()=>getAsyncContextStack().getScope(),getIsolationScope:()=>getAsyncContextStack().getIsolationScope()}}function currentScopes_getCurrentScope(){return asyncContext_getAsyncContextStrategy(carrier_getMainCarrier()).getCurrentScope()}function currentScopes_getIsolationScope(){return asyncContext_getAsyncContextStrategy(carrier_getMainCarrier()).getIsolationScope()}function currentScopes_withScope(...rest){const acs=asyncContext_getAsyncContextStrategy(carrier_getMainCarrier());if(2===rest.length){const[scope,callback]=rest;return scope?acs.withSetScope(scope,callback):acs.withScope(callback)}return acs.withScope(rest[0])}function currentScopes_getClient(){return currentScopes_getCurrentScope().getClient()}function currentScopes_getTraceContextFromScope(scope){const propagationContext=scope.getPropagationContext(),{traceId:traceId,parentSpanId:parentSpanId,propagationSpanId:propagationSpanId}=propagationContext,traceContext={trace_id:traceId,span_id:propagationSpanId||generateSpanId()};return parentSpanId&&(traceContext.parent_span_id=parentSpanId),traceContext}const DEFAULT_BREADCRUMBS=100;function addBreadcrumb(breadcrumb,hint){const client=currentScopes_getClient(),isolationScope=currentScopes_getIsolationScope();if(!client)return;const{beforeBreadcrumb:beforeBreadcrumb=null,maxBreadcrumbs:maxBreadcrumbs=DEFAULT_BREADCRUMBS}=client.getOptions();if(maxBreadcrumbs<=0)return;const mergedBreadcrumb={timestamp:dateTimestampInSeconds(),...breadcrumb},finalBreadcrumb=beforeBreadcrumb?consoleSandbox((()=>beforeBreadcrumb(mergedBreadcrumb,hint))):mergedBreadcrumb;null!==finalBreadcrumb&&(client.emit&&client.emit("beforeAddBreadcrumb",finalBreadcrumb,hint),isolationScope.addBreadcrumb(finalBreadcrumb,maxBreadcrumbs))}function severityLevelFromString(level){return"warn"===level?"warning":["fatal","error","warning","log","info","debug"].includes(level)?level:"log"}const DEFAULT_ENVIRONMENT="production",esm_debug_build_DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;var States;function resolvedSyncPromise(value){return new SyncPromise((resolve=>{resolve(value)}))}function rejectedSyncPromise(reason){return new SyncPromise(((_,reject)=>{reject(reason)}))}!function(States){States[States.PENDING=0]="PENDING";States[States.RESOLVED=1]="RESOLVED";States[States.REJECTED=2]="REJECTED"}(States||(States={}));class SyncPromise{constructor(executor){this._state=States.PENDING,this._handlers=[],this._runExecutor(executor)}then(onfulfilled,onrejected){return new SyncPromise(((resolve,reject)=>{this._handlers.push([!1,result=>{if(onfulfilled)try{resolve(onfulfilled(result))}catch(e){reject(e)}else resolve(result)},reason=>{if(onrejected)try{resolve(onrejected(reason))}catch(e){reject(e)}else reject(reason)}]),this._executeHandlers()}))}catch(onrejected){return this.then((val=>val),onrejected)}finally(onfinally){return new SyncPromise(((resolve,reject)=>{let val,isRejected;return this.then((value=>{isRejected=!1,val=value,onfinally&&onfinally()}),(reason=>{isRejected=!0,val=reason,onfinally&&onfinally()})).then((()=>{isRejected?reject(val):resolve(val)}))}))}_executeHandlers(){if(this._state===States.PENDING)return;const cachedHandlers=this._handlers.slice();this._handlers=[],cachedHandlers.forEach((handler=>{handler[0]||(this._state===States.RESOLVED&&handler[1](this._value),this._state===States.REJECTED&&handler[2](this._value),handler[0]=!0)}))}_runExecutor(executor){const setResult=(state,value)=>{this._state===States.PENDING&&(is_isThenable(value)?value.then(resolve,reject):(this._state=state,this._value=value,this._executeHandlers()))},resolve=value=>{setResult(States.RESOLVED,value)},reject=reason=>{setResult(States.REJECTED,reason)};try{executor(resolve,reject)}catch(e){reject(e)}}}function notifyEventProcessors(processors,event,hint,index=0){return new SyncPromise(((resolve,reject)=>{const processor=processors[index];if(null===event||"function"!=typeof processor)resolve(event);else{const result=processor({...event},hint);esm_debug_build_DEBUG_BUILD&&processor.id&&null===result&&logger_logger.log(`Event processor "${processor.id}" dropped event`),is_isThenable(result)?result.then((final=>notifyEventProcessors(processors,final,hint,index+1).then(resolve))).then(null,reject):notifyEventProcessors(processors,result,hint,index+1).then(resolve).then(null,reject)}}))}let parsedStackResults,lastKeysCount,cachedFilenameDebugIds;function getFilenameToDebugIdMap(stackParser){const debugIdMap=worldwide_GLOBAL_OBJ._sentryDebugIds;if(!debugIdMap)return{};const debugIdKeys=Object.keys(debugIdMap);return cachedFilenameDebugIds&&debugIdKeys.length===lastKeysCount||(lastKeysCount=debugIdKeys.length,cachedFilenameDebugIds=debugIdKeys.reduce(((acc,stackKey)=>{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],filename=stackFrame?.filename,debugId=debugIdMap[stackKey];if(filename&&debugId){acc[filename]=debugId,parsedStackResults[stackKey]=[filename,debugId];break}}}return acc}),{})),cachedFilenameDebugIds}const semanticAttributes_SEMANTIC_ATTRIBUTE_SENTRY_SOURCE="sentry.source",SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE="sentry.sample_rate",SEMANTIC_ATTRIBUTE_SENTRY_OP="sentry.op",SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN="sentry.origin",SEMANTIC_ATTRIBUTE_PROFILE_ID="sentry.profile_id",SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME="sentry.exclusive_time",SENTRY_BAGGAGE_KEY_PREFIX_REGEX=/^sentry-/;function baggageHeaderToDynamicSamplingContext(baggageHeader){const baggageObject=function(baggageHeader){if(!baggageHeader||!isString(baggageHeader)&&!Array.isArray(baggageHeader))return;if(Array.isArray(baggageHeader))return baggageHeader.reduce(((acc,curr)=>{const currBaggageObject=baggageHeaderToObject(curr);return Object.entries(currBaggageObject).forEach((([key,value])=>{acc[key]=value})),acc}),{});return baggageHeaderToObject(baggageHeader)}(baggageHeader);if(!baggageObject)return;const dynamicSamplingContext=Object.entries(baggageObject).reduce(((acc,[key,value])=>{if(key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)){acc[key.slice(7)]=value}return acc}),{});return Object.keys(dynamicSamplingContext).length>0?dynamicSamplingContext:void 0}function baggageHeaderToObject(baggageHeader){return baggageHeader.split(",").map((baggageEntry=>baggageEntry.split("=").map((keyOrValue=>decodeURIComponent(keyOrValue.trim()))))).reduce(((acc,[key,value])=>(key&&value&&(acc[key]=value),acc)),{})}function hasSpansEnabled(maybeOptions){if("boolean"==typeof __SENTRY_TRACING__&&!__SENTRY_TRACING__)return!1;const options=maybeOptions||currentScopes_getClient()?.getOptions();return!(!options||null==options.tracesSampleRate&&!options.tracesSampler)}function getCapturedScopesOnSpan(span){return{scope:span._sentryScope,isolationScope:span._sentryIsolationScope}}let hasShownSpanDropWarning=!1;function spanToTransactionTraceContext(span){const{spanId:span_id,traceId:trace_id}=span.spanContext(),{data:data,op:op,parent_span_id:parent_span_id,status:status,origin:origin,links:links}=spanUtils_spanToJSON(span);return{parent_span_id:parent_span_id,span_id:span_id,trace_id:trace_id,data:data,op:op,status:status,origin:origin,links:links}}function spanUtils_spanToTraceContext(span){const{spanId:spanId,traceId:trace_id,isRemote:isRemote}=span.spanContext(),parent_span_id=isRemote?spanId:spanUtils_spanToJSON(span).parent_span_id,scope=getCapturedScopesOnSpan(span).scope;return{parent_span_id:parent_span_id,span_id:isRemote?scope?.getPropagationContext().propagationSpanId||generateSpanId():spanId,trace_id:trace_id}}function convertSpanLinksForEnvelope(links){return links&&links.length>0?links.map((({context:{spanId:spanId,traceId:traceId,traceFlags:traceFlags,...restContext},attributes:attributes})=>({span_id:spanId,trace_id:traceId,sampled:1===traceFlags,attributes:attributes,...restContext}))):void 0}function spanTimeInputToSeconds(input){return"number"==typeof input?ensureTimestampInSeconds(input):Array.isArray(input)?input[0]+input[1]/1e9:input instanceof Date?ensureTimestampInSeconds(input.getTime()):time_timestampInSeconds()}function ensureTimestampInSeconds(timestamp){return timestamp>9999999999?timestamp/1e3:timestamp}function spanUtils_spanToJSON(span){if(function(span){return"function"==typeof span.getSpanJSON}(span))return span.getSpanJSON();const{spanId:span_id,traceId:trace_id}=span.spanContext();if(function(span){const castSpan=span;return!!(castSpan.attributes&&castSpan.startTime&&castSpan.name&&castSpan.endTime&&castSpan.status)}(span)){const{attributes:attributes,startTime:startTime,name:name,endTime:endTime,parentSpanId:parentSpanId,status:status,links:links}=span;return{span_id:span_id,trace_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["sentry.op"],origin:attributes["sentry.origin"],links:convertSpanLinksForEnvelope(links)}}return{span_id:span_id,trace_id:trace_id,start_timestamp:0,data:{}}}function spanIsSampled(span){const{traceFlags:traceFlags}=span.spanContext();return 1===traceFlags}function getStatusMessage(status){if(status&&0!==status.code)return 1===status.code?"ok":status.message||"unknown_error"}function addChildSpanToSpan(span,childSpan){addNonEnumerableProperty(childSpan,"_sentryRootSpan",span._sentryRootSpan||span),span._sentryChildSpans?span._sentryChildSpans.add(childSpan):addNonEnumerableProperty(span,"_sentryChildSpans",new Set([childSpan]))}function spanUtils_getRootSpan(span){return span._sentryRootSpan||span}function spanUtils_getActiveSpan(){const acs=asyncContext_getAsyncContextStrategy(carrier_getMainCarrier());return acs.getActiveSpan?acs.getActiveSpan():spanOnScope_getSpanForScope(currentScopes_getCurrentScope())}function showSpanDropWarning(){hasShownSpanDropWarning||(consoleSandbox((()=>{console.warn("[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.")})),hasShownSpanDropWarning=!0)}function freezeDscOnSpan(span,dsc){addNonEnumerableProperty(span,"_frozenDsc",dsc)}function getDynamicSamplingContextFromClient(trace_id,client){const options=client.getOptions(),{publicKey:public_key}=client.getDsn()||{},dsc={environment:options.environment||DEFAULT_ENVIRONMENT,release:options.release,public_key:public_key,trace_id:trace_id};return client.emit("createDsc",dsc),dsc}function dynamicSamplingContext_getDynamicSamplingContextFromSpan(span){const client=currentScopes_getClient();if(!client)return{};const rootSpan=spanUtils_getRootSpan(span),rootSpanJson=spanUtils_spanToJSON(rootSpan),rootSpanAttributes=rootSpanJson.data,traceState=rootSpan.spanContext().traceState,rootSpanSampleRate=traceState?.get("sentry.sample_rate")??rootSpanAttributes["sentry.sample_rate"];function applyLocalSampleRateToDsc(dsc){return"number"!=typeof rootSpanSampleRate&&"string"!=typeof rootSpanSampleRate||(dsc.sample_rate=`${rootSpanSampleRate}`),dsc}const frozenDsc=rootSpan._frozenDsc;if(frozenDsc)return applyLocalSampleRateToDsc(frozenDsc);const traceStateDsc=traceState?.get("sentry.dsc"),dscOnTraceState=traceStateDsc&&baggageHeaderToDynamicSamplingContext(traceStateDsc);if(dscOnTraceState)return applyLocalSampleRateToDsc(dscOnTraceState);const dsc=getDynamicSamplingContextFromClient(span.spanContext().traceId,client),source=rootSpanAttributes["sentry.source"],name=rootSpanJson.description;return"url"!==source&&name&&(dsc.transaction=name),hasSpansEnabled()&&(dsc.sampled=String(spanIsSampled(rootSpan)),dsc.sample_rand=traceState?.get("sentry.sample_rand")??getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString()),applyLocalSampleRateToDsc(dsc),client.emit("createDsc",dsc,rootSpan),dsc}function applyScopeDataToEvent(event,data){const{fingerprint:fingerprint,span:span,breadcrumbs:breadcrumbs,sdkProcessingMetadata:sdkProcessingMetadata}=data;!function(event,data){const{extra:extra,tags:tags,user:user,contexts:contexts,level:level,transactionName:transactionName}=data;Object.keys(extra).length&&(event.extra={...extra,...event.extra});Object.keys(tags).length&&(event.tags={...tags,...event.tags});Object.keys(user).length&&(event.user={...user,...event.user});Object.keys(contexts).length&&(event.contexts={...contexts,...event.contexts});level&&(event.level=level);transactionName&&"transaction"!==event.type&&(event.transaction=transactionName)}(event,data),span&&function(event,span){event.contexts={trace:spanUtils_spanToTraceContext(span),...event.contexts},event.sdkProcessingMetadata={dynamicSamplingContext:dynamicSamplingContext_getDynamicSamplingContextFromSpan(span),...event.sdkProcessingMetadata};const rootSpan=spanUtils_getRootSpan(span),transactionName=spanUtils_spanToJSON(rootSpan).description;transactionName&&!event.transaction&&"transaction"===event.type&&(event.transaction=transactionName)}(event,span),function(event,fingerprint){event.fingerprint=event.fingerprint?Array.isArray(event.fingerprint)?event.fingerprint:[event.fingerprint]:[],fingerprint&&(event.fingerprint=event.fingerprint.concat(fingerprint));event.fingerprint.length||delete event.fingerprint}(event,fingerprint),function(event,breadcrumbs){const mergedBreadcrumbs=[...event.breadcrumbs||[],...breadcrumbs];event.breadcrumbs=mergedBreadcrumbs.length?mergedBreadcrumbs:void 0}(event,breadcrumbs),function(event,sdkProcessingMetadata){event.sdkProcessingMetadata={...event.sdkProcessingMetadata,...sdkProcessingMetadata}}(event,sdkProcessingMetadata)}function mergeScopeData(data,mergeData){const{extra:extra,tags:tags,user:user,contexts:contexts,level:level,sdkProcessingMetadata:sdkProcessingMetadata,breadcrumbs:breadcrumbs,fingerprint:fingerprint,eventProcessors:eventProcessors,attachments:attachments,propagationContext:propagationContext,transactionName:transactionName,span: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),level&&(data.level=level),transactionName&&(data.transactionName=transactionName),span&&(data.span=span),breadcrumbs.length&&(data.breadcrumbs=[...data.breadcrumbs,...breadcrumbs]),fingerprint.length&&(data.fingerprint=[...data.fingerprint,...fingerprint]),eventProcessors.length&&(data.eventProcessors=[...data.eventProcessors,...eventProcessors]),attachments.length&&(data.attachments=[...data.attachments,...attachments]),data.propagationContext={...data.propagationContext,...propagationContext}}function mergeAndOverwriteScopeData(data,prop,mergeVal){data[prop]=merge(data[prop],mergeVal,1)}function prepareEvent(options,event,hint,scope,client,isolationScope){const{normalizeDepth:normalizeDepth=3,normalizeMaxBreadth:normalizeMaxBreadth=1e3}=options,prepared={...event,event_id:event.event_id||hint.event_id||misc_uuid4(),timestamp:event.timestamp||dateTimestampInSeconds()},integrations=hint.integrations||options.integrations.map((i=>i.name));!function(event,options){const{environment:environment,release:release,dist:dist,maxValueLength:maxValueLength=250}=options;event.environment=event.environment||environment||DEFAULT_ENVIRONMENT,!event.release&&release&&(event.release=release);!event.dist&&dist&&(event.dist=dist);const request=event.request;request?.url&&(request.url=truncate(request.url,maxValueLength))}(prepared,options),function(event,integrationNames){integrationNames.length>0&&(event.sdk=event.sdk||{},event.sdk.integrations=[...event.sdk.integrations||[],...integrationNames])}(prepared,integrations),client&&client.emit("applyFrameMetadata",event),void 0===event.type&&function(event,stackParser){const filenameDebugIdMap=getFilenameToDebugIdMap(stackParser);event.exception?.values?.forEach((exception=>{exception.stacktrace?.frames?.forEach((frame=>{frame.filename&&(frame.debug_id=filenameDebugIdMap[frame.filename])}))}))}(prepared,options.stackParser);const finalScope=function(scope,captureContext){if(!captureContext)return scope;const finalScope=scope?scope.clone():new Scope;return finalScope.update(captureContext),finalScope}(scope,hint.captureContext);hint.mechanism&&addExceptionMechanism(prepared,hint.mechanism);const clientEventProcessors=client?client.getEventProcessors():[],data=getGlobalSingleton("globalScope",(()=>new Scope)).getScopeData();if(isolationScope){mergeScopeData(data,isolationScope.getScopeData())}if(finalScope){mergeScopeData(data,finalScope.getScopeData())}const attachments=[...hint.attachments||[],...data.attachments];attachments.length&&(hint.attachments=attachments),applyScopeDataToEvent(prepared,data);return notifyEventProcessors([...clientEventProcessors,...data.eventProcessors],prepared,hint).then((evt=>(evt&&function(event){const filenameDebugIdMap={};if(event.exception?.values?.forEach((exception=>{exception.stacktrace?.frames?.forEach((frame=>{frame.debug_id&&(frame.abs_path?filenameDebugIdMap[frame.abs_path]=frame.debug_id:frame.filename&&(filenameDebugIdMap[frame.filename]=frame.debug_id),delete frame.debug_id)}))})),0===Object.keys(filenameDebugIdMap).length)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:debug_id})}))}(evt),"number"==typeof normalizeDepth&&normalizeDepth>0?function(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)}};event.contexts?.trace&&normalized.contexts&&(normalized.contexts.trace=event.contexts.trace,event.contexts.trace.data&&(normalized.contexts.trace.data=normalize(event.contexts.trace.data,depth,maxBreadth)));event.spans&&(normalized.spans=event.spans.map((span=>({...span,...span.data&&{data:normalize(span.data,depth,maxBreadth)}}))));event.contexts?.flags&&normalized.contexts&&(normalized.contexts.flags=normalize(event.contexts.flags,3,maxBreadth));return normalized}(evt,normalizeDepth,normalizeMaxBreadth):evt)))}function parseEventHintOrCaptureContext(hint){if(hint)return function(hint){return hint instanceof Scope||"function"==typeof hint}(hint)||function(hint){return Object.keys(hint).some((key=>captureContextKeys.includes(key)))}(hint)?{captureContext:hint}:hint}const captureContextKeys=["user","level","extra","contexts","tags","fingerprint","propagationContext"];function captureException(exception,hint){return currentScopes_getCurrentScope().captureException(exception,parseEventHintOrCaptureContext(hint))}function captureEvent(event,hint){return currentScopes_getCurrentScope().captureEvent(event,hint)}function setTag(key,value){currentScopes_getIsolationScope().setTag(key,value)}function startSession(context){const isolationScope=currentScopes_getIsolationScope(),currentScope=currentScopes_getCurrentScope(),{userAgent:userAgent}=worldwide_GLOBAL_OBJ.navigator||{},session=makeSession({user:currentScope.getUser()||isolationScope.getUser(),...userAgent&&{userAgent:userAgent},...context}),currentSession=isolationScope.getSession();return"ok"===currentSession?.status&&updateSession(currentSession,{status:"exited"}),endSession(),isolationScope.setSession(session),session}function endSession(){const isolationScope=currentScopes_getIsolationScope(),session=currentScopes_getCurrentScope().getSession()||isolationScope.getSession();session&&function(session,status){let context={};status?context={status:status}:"ok"===session.status&&(context={status:"exited"}),updateSession(session,context)}(session),_sendSessionUpdate(),isolationScope.setSession()}function _sendSessionUpdate(){const isolationScope=currentScopes_getIsolationScope(),client=currentScopes_getClient(),session=isolationScope.getSession();session&&client&&client.captureSession(session)}function captureSession(end=!1){end?endSession():_sendSessionUpdate()}function isSentryRequestUrl(url,client){const dsn=client?.getDsn(),tunnel=client?.getOptions().tunnel;return function(url,dsn){return!!dsn&&url.includes(dsn.host)}(url,dsn)||function(url,tunnel){if(!tunnel)return!1;return removeTrailingSlash(url)===removeTrailingSlash(tunnel)}(url,tunnel)}function removeTrailingSlash(str){return"/"===str[str.length-1]?str.slice(0,-1):str}const DSN_REGEX=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function dsn_dsnToString(dsn,withPassword=!1){const{host:host,path:path,pass:pass,port:port,projectId:projectId,protocol:protocol,publicKey:publicKey}=dsn;return`${protocol}://${publicKey}${withPassword&&pass?`:${pass}`:""}@${host}${port?`:${port}`:""}/${path?`${path}/`:path}${projectId}`}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 dsn_makeDsn(from){const components="string"==typeof from?function(str){const match=DSN_REGEX.exec(str);if(!match)return void consoleSandbox((()=>{console.error(`Invalid Sentry Dsn: ${str}`)}));const[protocol,publicKey,pass="",host="",port="",lastPath=""]=match.slice(1);let path="",projectId=lastPath;const split=projectId.split("/");if(split.length>1&&(path=split.slice(0,-1).join("/"),projectId=split.pop()),projectId){const projectMatch=projectId.match(/^\d+/);projectMatch&&(projectId=projectMatch[0])}return dsnFromComponents({host:host,pass:pass,path:path,projectId:projectId,port:port,protocol:protocol,publicKey:publicKey})}(from):dsnFromComponents(from);if(components&&function(dsn){if(!debug_build_DEBUG_BUILD)return!0;const{port:port,projectId:projectId,protocol:protocol}=dsn;return!(["protocol","publicKey","host","projectId"].find((component=>!dsn[component]&&(logger_logger.error(`Invalid Sentry Dsn: ${component} missing`),!0)))||(projectId.match(/^\d+$/)?function(protocol){return"http"===protocol||"https"===protocol}(protocol)?port&&isNaN(parseInt(port,10))&&(logger_logger.error(`Invalid Sentry Dsn: Invalid port ${port}`),1):(logger_logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`),1):(logger_logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`),1)))}(components))return components}function createEnvelope(headers,items=[]){return[headers,items]}function addItemToEnvelope(envelope,newItem){const[headers,items]=envelope;return[headers,[...items,newItem]]}function forEachEnvelopeItem(envelope,callback){const envelopeItems=envelope[1];for(const envelopeItem of envelopeItems){if(callback(envelopeItem,envelopeItem[0].type))return!0}return!1}function encodeUTF8(input){const carrier=carrier_getSentryCarrier(worldwide_GLOBAL_OBJ);return carrier.encodePolyfill?carrier.encodePolyfill(input):(new TextEncoder).encode(input)}function serializeEnvelope(envelope){const[envHeaders,items]=envelope;let parts=JSON.stringify(envHeaders);function append(next){"string"==typeof parts?parts="string"==typeof next?parts+next:[encodeUTF8(parts),next]:parts.push("string"==typeof next?encodeUTF8(next):next)}for(const item of items){const[itemHeaders,payload]=item;if(append(`\n${JSON.stringify(itemHeaders)}\n`),"string"==typeof payload||payload instanceof Uint8Array)append(payload);else{let stringifiedPayload;try{stringifiedPayload=JSON.stringify(payload)}catch(e){stringifiedPayload=JSON.stringify(normalize(payload))}append(stringifiedPayload)}}return"string"==typeof parts?parts:function(buffers){const totalLength=buffers.reduce(((acc,buf)=>acc+buf.length),0),merged=new Uint8Array(totalLength);let offset=0;for(const buffer of buffers)merged.set(buffer,offset),offset+=buffer.length;return merged}(parts)}function createSpanEnvelopeItem(spanJson){return[{type:"span"},spanJson]}function createAttachmentEnvelopeItem(attachment){const buffer="string"==typeof attachment.data?encodeUTF8(attachment.data):attachment.data;return[{type:"attachment",length:buffer.length,filename:attachment.filename,content_type:attachment.contentType,attachment_type:attachment.attachmentType},buffer]}const ITEM_TYPE_TO_DATA_CATEGORY_MAP={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",raw_security:"security",otel_log:"log_item"};function envelopeItemTypeToDataCategory(type){return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]}function getSdkMetadataForEnvelopeHeader(metadataOrEvent){if(!metadataOrEvent?.sdk)return;const{name:name,version:version}=metadataOrEvent.sdk;return{name:name,version:version}}function createEventEnvelopeHeaders(event,sdkInfo,tunnel,dsn){const dynamicSamplingContext=event.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:event.event_id,sent_at:(new Date).toISOString(),...sdkInfo&&{sdk:sdkInfo},...!!tunnel&&dsn&&{dsn:dsn_dsnToString(dsn)},...dynamicSamplingContext&&{trace:dynamicSamplingContext}}}function isRateLimited(limits,dataCategory,now=Date.now()){return function(limits,dataCategory){return limits[dataCategory]||limits.all||0}(limits,dataCategory)>now}function updateRateLimits(limits,{statusCode:statusCode,headers:headers},now=Date.now()){const updatedRateLimits={...limits},rateLimitHeader=headers?.["x-sentry-rate-limits"],retryAfterHeader=headers?.["retry-after"];if(rateLimitHeader)for(const limit of rateLimitHeader.trim().split(",")){const[retryAfter,categories,,,namespaces]=limit.split(":",5),headerDelay=parseInt(retryAfter,10),delay=1e3*(isNaN(headerDelay)?60:headerDelay);if(categories)for(const category of categories.split(";"))"metric_bucket"===category&&namespaces&&!namespaces.split(";").includes("custom")||(updatedRateLimits[category]=now+delay);else updatedRateLimits.all=now+delay}else retryAfterHeader?updatedRateLimits.all=now+function(header,now=Date.now()){const headerDelay=parseInt(`${header}`,10);if(!isNaN(headerDelay))return 1e3*headerDelay;const headerDate=Date.parse(`${header}`);return isNaN(headerDate)?6e4:headerDate-now}(retryAfterHeader,now):429===statusCode&&(updatedRateLimits.all=now+6e4);return updatedRateLimits}var process=__webpack_require__(606);function isNodeEnv(){return!("undefined"!=typeof __SENTRY_BROWSER_BUNDLE__&&__SENTRY_BROWSER_BUNDLE__)&&"[object process]"===Object.prototype.toString.call(void 0!==process?process:0)}function isBrowser(){return"undefined"!=typeof window&&(!isNodeEnv()||function(){const process=worldwide_GLOBAL_OBJ.process;return"renderer"===process?.type}())}function parseSampleRate(sampleRate){if("boolean"==typeof sampleRate)return Number(sampleRate);const rate="string"==typeof sampleRate?parseFloat(sampleRate):sampleRate;return"number"!=typeof rate||isNaN(rate)||rate<0||rate>1?void 0:rate}const supports_WINDOW=worldwide_GLOBAL_OBJ;function supportsFetch(){if(!("fetch"in supports_WINDOW))return!1;try{return new Headers,new Request("http://www.example.com"),new Response,!0}catch(e){return!1}}function isNativeFunction(func){return func&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString())}const build_esm_debug_build_DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,types_WINDOW=worldwide_GLOBAL_OBJ,cachedImplementations={};function getNativeImplementation(name){const cached=cachedImplementations[name];if(cached)return cached;let impl=types_WINDOW[name];if(isNativeFunction(impl))return cachedImplementations[name]=impl.bind(types_WINDOW);const document=types_WINDOW.document;if(document&&"function"==typeof document.createElement)try{const sandbox=document.createElement("iframe");sandbox.hidden=!0,document.head.appendChild(sandbox);const contentWindow=sandbox.contentWindow;contentWindow?.[name]&&(impl=contentWindow[name]),document.head.removeChild(sandbox)}catch(e){build_esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Could not create sandbox iframe for ${name} check, bailing to window.${name}: `,e)}return impl?cachedImplementations[name]=impl.bind(types_WINDOW):impl}function clearCachedImplementation(name){cachedImplementations[name]=void 0}function getNativeImplementation_setTimeout(...rest){return getNativeImplementation("setTimeout")(...rest)}const bindReporter=(callback,metric,thresholds,reportAllChanges)=>{let prevValue,delta;return forceReport=>{metric.value>=0&&(forceReport||reportAllChanges)&&(delta=metric.value-(prevValue||0),(delta||void 0===prevValue)&&(prevValue=metric.value,metric.delta=delta,metric.rating=((value,thresholds)=>value>thresholds[1]?"poor":value>thresholds[0]?"needs-improvement":"good")(metric.value,thresholds),callback(metric)))}},getNavigationEntry=(checkResponseStart=!0)=>{const navigationEntry=types_WINDOW.performance?.getEntriesByType?.("navigation")[0];if(!checkResponseStart||navigationEntry&&navigationEntry.responseStart>0&&navigationEntry.responseStart<performance.now())return navigationEntry},getActivationStart=()=>{const navEntry=getNavigationEntry();return navEntry?.activationStart||0},initMetric=(name,value)=>{const navEntry=getNavigationEntry();let navigationType="navigate";navEntry&&(types_WINDOW.document?.prerendering||getActivationStart()>0?navigationType="prerender":types_WINDOW.document?.wasDiscarded?navigationType="restore":navEntry.type&&(navigationType=navEntry.type.replace(/_/g,"-")));return{name:name,value:void 0===value?-1:value,rating:"good",delta:0,entries:[],id:`v4-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:navigationType}},observe=(type,callback,opts)=>{try{if(PerformanceObserver.supportedEntryTypes.includes(type)){const po=new PerformanceObserver((list=>{Promise.resolve().then((()=>{callback(list.getEntries())}))}));return po.observe(Object.assign({type:type,buffered:!0},opts||{})),po}}catch(e){}},onHidden=cb=>{const onHiddenOrPageHide=event=>{"pagehide"!==event.type&&"hidden"!==types_WINDOW.document?.visibilityState||cb(event)};types_WINDOW.document&&(addEventListener("visibilitychange",onHiddenOrPageHide,!0),addEventListener("pagehide",onHiddenOrPageHide,!0))},runOnce=cb=>{let called=!1;return()=>{called||(cb(),called=!0)}};let firstHiddenTime=-1;const onVisibilityUpdate=event=>{"hidden"===types_WINDOW.document.visibilityState&&firstHiddenTime>-1&&(firstHiddenTime="visibilitychange"===event.type?event.timeStamp:0,removeChangeListeners())},removeChangeListeners=()=>{removeEventListener("visibilitychange",onVisibilityUpdate,!0),removeEventListener("prerenderingchange",onVisibilityUpdate,!0)},getVisibilityWatcher=()=>(types_WINDOW.document&&firstHiddenTime<0&&(firstHiddenTime="hidden"!==types_WINDOW.document.visibilityState||types_WINDOW.document.prerendering?1/0:0,addEventListener("visibilitychange",onVisibilityUpdate,!0),addEventListener("prerenderingchange",onVisibilityUpdate,!0)),{get firstHiddenTime(){return firstHiddenTime}}),whenActivated=callback=>{types_WINDOW.document?.prerendering?addEventListener("prerenderingchange",(()=>callback()),!0):callback()},FCPThresholds=[1800,3e3],CLSThresholds=[.1,.25],onCLS=(onReport,opts={})=>{((onReport,opts={})=>{whenActivated((()=>{const visibilityWatcher=getVisibilityWatcher(),metric=initMetric("FCP");let report;const po=observe("paint",(entries=>{entries.forEach((entry=>{"first-contentful-paint"===entry.name&&(po.disconnect(),entry.startTime<visibilityWatcher.firstHiddenTime&&(metric.value=Math.max(entry.startTime-getActivationStart(),0),metric.entries.push(entry),report(!0)))}))}));po&&(report=bindReporter(onReport,metric,FCPThresholds,opts.reportAllChanges))}))})(runOnce((()=>{const metric=initMetric("CLS",0);let report,sessionValue=0,sessionEntries=[];const handleEntries=entries=>{entries.forEach((entry=>{if(!entry.hadRecentInput){const firstSessionEntry=sessionEntries[0],lastSessionEntry=sessionEntries[sessionEntries.length-1];sessionValue&&firstSessionEntry&&lastSessionEntry&&entry.startTime-lastSessionEntry.startTime<1e3&&entry.startTime-firstSessionEntry.startTime<5e3?(sessionValue+=entry.value,sessionEntries.push(entry)):(sessionValue=entry.value,sessionEntries=[entry])}})),sessionValue>metric.value&&(metric.value=sessionValue,metric.entries=sessionEntries,report())},po=observe("layout-shift",handleEntries);po&&(report=bindReporter(onReport,metric,CLSThresholds,opts.reportAllChanges),onHidden((()=>{handleEntries(po.takeRecords()),report(!0)})),setTimeout(report,0))})))},FIDThresholds=[100,300];let interactionCountEstimate=0,minKnownInteractionId=1/0,maxKnownInteractionId=0;const updateEstimate=entries=>{entries.forEach((e=>{e.interactionId&&(minKnownInteractionId=Math.min(minKnownInteractionId,e.interactionId),maxKnownInteractionId=Math.max(maxKnownInteractionId,e.interactionId),interactionCountEstimate=maxKnownInteractionId?(maxKnownInteractionId-minKnownInteractionId)/7+1:0)}))};let po;const initInteractionCountPolyfill=()=>{"interactionCount"in performance||po||(po=observe("event",updateEstimate,{type:"event",buffered:!0,durationThreshold:0}))},longestInteractionList=[],longestInteractionMap=new Map;const getInteractionCountForNavigation=()=>(po?interactionCountEstimate:performance.interactionCount||0)-0,entryPreProcessingCallbacks=[],processInteractionEntry=entry=>{if(entryPreProcessingCallbacks.forEach((cb=>cb(entry))),!entry.interactionId&&"first-input"!==entry.entryType)return;const minLongestInteraction=longestInteractionList[longestInteractionList.length-1],existingInteraction=longestInteractionMap.get(entry.interactionId);if(existingInteraction||longestInteractionList.length<10||minLongestInteraction&&entry.duration>minLongestInteraction.latency){if(existingInteraction)entry.duration>existingInteraction.latency?(existingInteraction.entries=[entry],existingInteraction.latency=entry.duration):entry.duration===existingInteraction.latency&&entry.startTime===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)),longestInteractionList.length>10&&longestInteractionList.splice(10).forEach((i=>longestInteractionMap.delete(i.id)))}},whenIdle=cb=>{const rIC=types_WINDOW.requestIdleCallback||types_WINDOW.setTimeout;let handle=-1;return cb=runOnce(cb),"hidden"===types_WINDOW.document?.visibilityState?cb():(handle=rIC(cb),onHidden(cb)),handle},INPThresholds=[200,500],onINP=(onReport,opts={})=>{"PerformanceEventTiming"in types_WINDOW&&"interactionId"in PerformanceEventTiming.prototype&&whenActivated((()=>{initInteractionCountPolyfill();const metric=initMetric("INP");let report;const handleEntries=entries=>{whenIdle((()=>{entries.forEach(processInteractionEntry);const inp=(()=>{const candidateInteractionIndex=Math.min(longestInteractionList.length-1,Math.floor(getInteractionCountForNavigation()/50));return longestInteractionList[candidateInteractionIndex]})();inp&&inp.latency!==metric.value&&(metric.value=inp.latency,metric.entries=inp.entries,report())}))},po=observe("event",handleEntries,{durationThreshold:null!=opts.durationThreshold?opts.durationThreshold:40});report=bindReporter(onReport,metric,INPThresholds,opts.reportAllChanges),po&&(po.observe({type:"first-input",buffered:!0}),onHidden((()=>{handleEntries(po.takeRecords()),report(!0)})))}))},LCPThresholds=[2500,4e3],reportedMetricIDs={},handlers={},instrumented={};let _previousCls,_previousFid,_previousLcp,_previousInp;function addPerformanceInstrumentationHandler(type,callback){return instrument_addHandler(type,callback),instrumented[type]||(!function(type){const options={};"event"===type&&(options.durationThreshold=0);observe(type,(entries=>{instrument_triggerHandlers(type,{entries:entries})}),options)}(type),instrumented[type]=!0),getCleanupCallback(type,callback)}function instrument_triggerHandlers(type,data){const typeHandlers=handlers[type];if(typeHandlers?.length)for(const handler of typeHandlers)try{handler(data)}catch(e){build_esm_debug_build_DEBUG_BUILD&&logger_logger.error(`Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`,e)}}function instrumentCls(){return onCLS((metric=>{instrument_triggerHandlers("cls",{metric:metric}),_previousCls=metric}),{reportAllChanges:!0})}function instrumentFid(){return((onReport,opts={})=>{whenActivated((()=>{const visibilityWatcher=getVisibilityWatcher(),metric=initMetric("FID");let report;const handleEntry=entry=>{entry.startTime<visibilityWatcher.firstHiddenTime&&(metric.value=entry.processingStart-entry.startTime,metric.entries.push(entry),report(!0))},handleEntries=entries=>{entries.forEach(handleEntry)},po=observe("first-input",handleEntries);report=bindReporter(onReport,metric,FIDThresholds,opts.reportAllChanges),po&&onHidden(runOnce((()=>{handleEntries(po.takeRecords()),po.disconnect()})))}))})((metric=>{instrument_triggerHandlers("fid",{metric:metric}),_previousFid=metric}))}function instrumentLcp(){return((onReport,opts={})=>{whenActivated((()=>{const visibilityWatcher=getVisibilityWatcher(),metric=initMetric("LCP");let report;const handleEntries=entries=>{opts.reportAllChanges||(entries=entries.slice(-1)),entries.forEach((entry=>{entry.startTime<visibilityWatcher.firstHiddenTime&&(metric.value=Math.max(entry.startTime-getActivationStart(),0),metric.entries=[entry],report())}))},po=observe("largest-contentful-paint",handleEntries);if(po){report=bindReporter(onReport,metric,LCPThresholds,opts.reportAllChanges);const stopListening=runOnce((()=>{reportedMetricIDs[metric.id]||(handleEntries(po.takeRecords()),po.disconnect(),reportedMetricIDs[metric.id]=!0,report(!0))}));["keydown","click"].forEach((type=>{types_WINDOW.document&&addEventListener(type,(()=>whenIdle(stopListening)),{once:!0,capture:!0})})),onHidden(stopListening)}}))})((metric=>{instrument_triggerHandlers("lcp",{metric:metric}),_previousLcp=metric}),{reportAllChanges:!0})}function instrumentInp(){return onINP((metric=>{instrument_triggerHandlers("inp",{metric:metric}),_previousInp=metric}))}function addMetricObserver(type,callback,instrumentFn,previousValue,stopOnCallback=!1){let stopListening;return instrument_addHandler(type,callback),instrumented[type]||(stopListening=instrumentFn(),instrumented[type]=!0),previousValue&&callback({metric:previousValue}),getCleanupCallback(type,callback,stopOnCallback?stopListening:void 0)}function instrument_addHandler(type,handler){handlers[type]=handlers[type]||[],handlers[type].push(handler)}function getCleanupCallback(type,callback,stopListening){return()=>{stopListening&&stopListening();const typeHandlers=handlers[type];if(!typeHandlers)return;const index=typeHandlers.indexOf(callback);-1!==index&&typeHandlers.splice(index,1)}}function serializeFormData(formData){return new URLSearchParams(formData).toString()}function getBodyString(body,_logger=logger_logger){try{if("string"==typeof body)return[body];if(body instanceof URLSearchParams)return[body.toString()];if(body instanceof FormData)return[serializeFormData(body)];if(!body)return[void 0]}catch(error){return build_esm_debug_build_DEBUG_BUILD&&_logger.error(error,"Failed to serialize body",body),[void 0,"BODY_PARSE_ERROR"]}return build_esm_debug_build_DEBUG_BUILD&&_logger.info("Skipping network body because of body type",body),[void 0,"UNPARSEABLE_BODY_TYPE"]}function getFetchRequestArgBody(fetchArgs=[]){if(2===fetchArgs.length&&"object"==typeof fetchArgs[1])return fetchArgs[1].body}const handlers_handlers={},handlers_instrumented={};function handlers_addHandler(type,handler){handlers_handlers[type]=handlers_handlers[type]||[],handlers_handlers[type].push(handler)}function handlers_maybeInstrument(type,instrumentFn){if(!handlers_instrumented[type]){handlers_instrumented[type]=!0;try{instrumentFn()}catch(e){debug_build_DEBUG_BUILD&&logger_logger.error(`Error while instrumenting ${type}`,e)}}}function handlers_triggerHandlers(type,data){const typeHandlers=type&&handlers_handlers[type];if(typeHandlers)for(const handler of typeHandlers)try{handler(data)}catch(e){debug_build_DEBUG_BUILD&&logger_logger.error(`Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`,e)}}function instrumentXHR(){if(!types_WINDOW.XMLHttpRequest)return;const xhrproto=XMLHttpRequest.prototype;xhrproto.open=new Proxy(xhrproto.open,{apply(originalOpen,xhrOpenThisArg,xhrOpenArgArray){const virtualError=new Error,startTimestamp=1e3*time_timestampInSeconds(),method=isString(xhrOpenArgArray[0])?xhrOpenArgArray[0].toUpperCase():void 0,url=function(url){if(isString(url))return url;try{return url.toString()}catch{}return}(xhrOpenArgArray[1]);if(!method||!url)return originalOpen.apply(xhrOpenThisArg,xhrOpenArgArray);xhrOpenThisArg.__sentry_xhr_v3__={method:method,url:url,request_headers:{}},"POST"===method&&url.match(/sentry_key/)&&(xhrOpenThisArg.__sentry_own_request__=!0);const onreadystatechangeHandler=()=>{const xhrInfo=xhrOpenThisArg.__sentry_xhr_v3__;if(xhrInfo&&4===xhrOpenThisArg.readyState){try{xhrInfo.status_code=xhrOpenThisArg.status}catch(e){}handlers_triggerHandlers("xhr",{endTimestamp:1e3*time_timestampInSeconds(),startTimestamp:startTimestamp,xhr:xhrOpenThisArg,virtualError:virtualError})}};return"onreadystatechange"in xhrOpenThisArg&&"function"==typeof xhrOpenThisArg.onreadystatechange?xhrOpenThisArg.onreadystatechange=new Proxy(xhrOpenThisArg.onreadystatechange,{apply(originalOnreadystatechange,onreadystatechangeThisArg,onreadystatechangeArgArray){return onreadystatechangeHandler(),originalOnreadystatechange.apply(onreadystatechangeThisArg,onreadystatechangeArgArray)}}):xhrOpenThisArg.addEventListener("readystatechange",onreadystatechangeHandler),xhrOpenThisArg.setRequestHeader=new Proxy(xhrOpenThisArg.setRequestHeader,{apply(originalSetRequestHeader,setRequestHeaderThisArg,setRequestHeaderArgArray){const[header,value]=setRequestHeaderArgArray,xhrInfo=setRequestHeaderThisArg.__sentry_xhr_v3__;return xhrInfo&&isString(header)&&isString(value)&&(xhrInfo.request_headers[header.toLowerCase()]=value),originalSetRequestHeader.apply(setRequestHeaderThisArg,setRequestHeaderArgArray)}}),originalOpen.apply(xhrOpenThisArg,xhrOpenArgArray)}}),xhrproto.send=new Proxy(xhrproto.send,{apply(originalSend,sendThisArg,sendArgArray){const sentryXhrData=sendThisArg.__sentry_xhr_v3__;if(!sentryXhrData)return originalSend.apply(sendThisArg,sendArgArray);void 0!==sendArgArray[0]&&(sentryXhrData.body=sendArgArray[0]);return handlers_triggerHandlers("xhr",{startTimestamp:1e3*time_timestampInSeconds(),xhr:sendThisArg}),originalSend.apply(sendThisArg,sendArgArray)}})}let debounceTimerID,lastCapturedEventType,lastCapturedEventTargetId,lastHref;function addClickKeypressInstrumentationHandler(handler){handlers_addHandler("dom",handler),handlers_maybeInstrument("dom",instrumentDOM)}function instrumentDOM(){if(!types_WINDOW.document)return;const triggerDOMHandler=handlers_triggerHandlers.bind(null,"dom"),globalDOMEventHandler=makeDOMEventHandler(triggerDOMHandler,!0);types_WINDOW.document.addEventListener("click",globalDOMEventHandler,!1),types_WINDOW.document.addEventListener("keypress",globalDOMEventHandler,!1),["EventTarget","Node"].forEach((target=>{const globalObject=types_WINDOW,proto=globalObject[target]?.prototype;proto?.hasOwnProperty?.("addEventListener")&&(fill(proto,"addEventListener",(function(originalAddEventListener){return function(type,listener,options){if("click"===type||"keypress"==type)try{const handlers=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},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("click"===type||"keypress"==type)try{const handlers=this.__sentry_instrumentation_handlers__||{},handlerForType=handlers[type];handlerForType&&(handlerForType.refCount--,handlerForType.refCount<=0&&(originalRemoveEventListener.call(this,type,handlerForType.handler,options),handlerForType.handler=void 0,delete handlers[type]),0===Object.keys(handlers).length&&delete this.__sentry_instrumentation_handlers__)}catch(e){}return originalRemoveEventListener.call(this,type,listener,options)}})))}))}function makeDOMEventHandler(handler,globalListener=!1){return event=>{if(!event||event._sentryCaptured)return;const target=function(event){try{return event.target}catch(e){return null}}(event);if(function(eventType,target){return"keypress"===eventType&&(!target?.tagName||"INPUT"!==target.tagName&&"TEXTAREA"!==target.tagName&&!target.isContentEditable)}(event.type,target))return;addNonEnumerableProperty(event,"_sentryCaptured",!0),target&&!target._sentryId&&addNonEnumerableProperty(target,"_sentryId",misc_uuid4());const name="keypress"===event.type?"input":event.type;if(!function(event){if(event.type!==lastCapturedEventType)return!1;try{if(!event.target||event.target._sentryId!==lastCapturedEventTargetId)return!1}catch(e){}return!0}(event)){handler({event:event,name:name,global:globalListener}),lastCapturedEventType=event.type,lastCapturedEventTargetId=target?target._sentryId:void 0}clearTimeout(debounceTimerID),debounceTimerID=types_WINDOW.setTimeout((()=>{lastCapturedEventTargetId=void 0,lastCapturedEventType=void 0}),1e3)}}function addHistoryInstrumentationHandler(handler){handlers_addHandler("history",handler),handlers_maybeInstrument("history",instrumentHistory)}function instrumentHistory(){function historyReplacementFunction(originalHistoryFunction){return function(...args){const url=args.length>2?args[2]:void 0;if(url){const from=lastHref,to=String(url);if(lastHref=to,from===to)return originalHistoryFunction.apply(this,args);handlers_triggerHandlers("history",{from:from,to:to})}return originalHistoryFunction.apply(this,args)}}types_WINDOW.addEventListener("popstate",(()=>{const to=types_WINDOW.location.href,from=lastHref;if(lastHref=to,from===to)return;handlers_triggerHandlers("history",{from:from,to:to})})),"history"in supports_WINDOW&&supports_WINDOW.history&&(fill(types_WINDOW.history,"pushState",historyReplacementFunction),fill(types_WINDOW.history,"replaceState",historyReplacementFunction))}const esm_WINDOW=worldwide_GLOBAL_OBJ;var __defProp$1=Object.defineProperty,__publicField$1=(obj,key,value)=>((obj,key,value)=>key in obj?__defProp$1(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value)(obj,"symbol"!=typeof key?key+"":key,value),NodeType$2=(NodeType2=>(NodeType2[NodeType2.Document=0]="Document",NodeType2[NodeType2.DocumentType=1]="DocumentType",NodeType2[NodeType2.Element=2]="Element",NodeType2[NodeType2.Text=3]="Text",NodeType2[NodeType2.CDATA=4]="CDATA",NodeType2[NodeType2.Comment=5]="Comment",NodeType2))(NodeType$2||{});function isShadowRoot(n2){const host=n2?.host;return Boolean(host?.shadowRoot===n2)}function isNativeShadowDom(shadowRoot){return"[object ShadowRoot]"===Object.prototype.toString.call(shadowRoot)}function stringifyStylesheet(s2){try{const rules2=s2.rules||s2.cssRules;return rules2?((cssText=Array.from(rules2,stringifyRule).join("")).includes(" background-clip: text;")&&!cssText.includes(" -webkit-background-clip: text;")&&(cssText=cssText.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),cssText):null}catch(error){return null}var cssText}function stringifyRule(rule){let importStringified;if(function(rule){return"styleSheet"in rule}(rule))try{importStringified=stringifyStylesheet(rule.styleSheet)||function(rule){const{cssText:cssText}=rule;if(cssText.split('"').length<3)return cssText;const statement=["@import",`url(${JSON.stringify(rule.href)})`];return""===rule.layerName?statement.push("layer"):rule.layerName&&statement.push(`layer(${rule.layerName})`),rule.supportsText&&statement.push(`supports(${rule.supportsText})`),rule.media.length&&statement.push(rule.media.mediaText),statement.join(" ")+";"}(rule)}catch(error){}else if(function(rule){return"selectorText"in rule}(rule)){let cssText=rule.cssText;const needsSafariColonFix=rule.selectorText.includes(":"),needsAllFix="string"==typeof rule.style.all&&rule.style.all;if(needsAllFix&&(cssText=function(rule){let styles="";for(let i2=0;i2<rule.style.length;i2++){const styleDeclaration=rule.style,attribute=styleDeclaration[i2],isImportant=styleDeclaration.getPropertyPriority(attribute);styles+=`${attribute}:${styleDeclaration.getPropertyValue(attribute)}${isImportant?" !important":""};`}return`${rule.selectorText} { ${styles} }`}(rule)),needsSafariColonFix&&(cssText=function(cssStringified){const regex=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return cssStringified.replace(regex,"$1\\$2")}(cssText)),needsSafariColonFix||needsAllFix)return cssText}return importStringified||rule.cssText}class Mirror{constructor(){__publicField$1(this,"idNodeMap",new Map),__publicField$1(this,"nodeMetaMap",new WeakMap)}getId(n2){if(!n2)return-1;const id=this.getMeta(n2)?.id;return id??-1}getNode(id){return this.idNodeMap.get(id)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(n2){return this.nodeMetaMap.get(n2)||null}removeNodeFromMap(n2){const id=this.getId(n2);this.idNodeMap.delete(id),n2.childNodes&&n2.childNodes.forEach((childNode=>this.removeNodeFromMap(childNode)))}has(id){return this.idNodeMap.has(id)}hasNode(node){return this.nodeMetaMap.has(node)}add(n2,meta){const id=meta.id;this.idNodeMap.set(id,n2),this.nodeMetaMap.set(n2,meta)}replace(id,n2){const oldNode=this.getNode(id);if(oldNode){const meta=this.nodeMetaMap.get(oldNode);meta&&this.nodeMetaMap.set(n2,meta)}this.idNodeMap.set(id,n2)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function shouldMaskInput({maskInputOptions:maskInputOptions,tagName:tagName,type:type}){return"OPTION"===tagName&&(tagName="SELECT"),Boolean(maskInputOptions[tagName.toLowerCase()]||type&&maskInputOptions[type]||"password"===type||"INPUT"===tagName&&!type&&maskInputOptions.text)}function maskInputValue({isMasked:isMasked,element:element,value:value,maskInputFn:maskInputFn}){let text=value||"";return isMasked?(maskInputFn&&(text=maskInputFn(text,element)),"*".repeat(text.length)):text}function toLowerCase(str){return str.toLowerCase()}function toUpperCase(str){return str.toUpperCase()}function getInputType(element){const type=element.type;return element.hasAttribute("data-rr-is-password")?"password":type?toLowerCase(type):null}function getInputValue(el,tagName,type){return"INPUT"!==tagName||"radio"!==type&&"checkbox"!==type?el.value:el.getAttribute("value")||""}function extractFileExtension(path,baseURL){let url;try{url=new URL(path,baseURL??window.location.href)}catch(err){return null}const match=url.pathname.match(/\.([0-9a-z]+)(?:$)/i);return match?.[1]??null}const cachedImplementations$1={};function getImplementation$1(name){const cached=cachedImplementations$1[name];if(cached)return cached;const document2=window.document;let impl=window[name];if(document2&&"function"==typeof document2.createElement)try{const sandbox=document2.createElement("iframe");sandbox.hidden=!0,document2.head.appendChild(sandbox);const contentWindow=sandbox.contentWindow;contentWindow&&contentWindow[name]&&(impl=contentWindow[name]),document2.head.removeChild(sandbox)}catch(e2){}return cachedImplementations$1[name]=impl.bind(window)}function setTimeout$2(...rest){return getImplementation$1("setTimeout")(...rest)}function clearTimeout$1(...rest){return getImplementation$1("clearTimeout")(...rest)}function getIframeContentDocument(iframe){try{return iframe.contentDocument}catch(e2){}}let _id=1;const tagNameRegex=new RegExp("[^a-z0-9-_:]");function genId(){return _id++}let canvasService,canvasCtx;const URL_IN_CSS_REF=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,URL_PROTOCOL_MATCH=/^(?:[a-z+]+:)?\/\//i,URL_WWW_MATCH=/^www\..*/i,DATA_URI=/^(data:)([^,]*),(.*)/i;function absoluteToStylesheet(cssText,href){return(cssText||"").replace(URL_IN_CSS_REF,((origin,quote1,path1,quote2,path2,path3)=>{const filePath=path1||path2||path3,maybeQuote=quote1||quote2||"";if(!filePath)return origin;if(URL_PROTOCOL_MATCH.test(filePath)||URL_WWW_MATCH.test(filePath))return`url(${maybeQuote}${filePath}${maybeQuote})`;if(DATA_URI.test(filePath))return`url(${maybeQuote}${filePath}${maybeQuote})`;if("/"===filePath[0])return`url(${maybeQuote}${function(url){let origin="";return origin=url.indexOf("//")>-1?url.split("/").slice(0,3).join("/"):url.split("/")[0],origin=origin.split("?")[0],origin}(href)+filePath}${maybeQuote})`;const stack=href.split("/"),parts=filePath.split("/");stack.pop();for(const part of parts)"."!==part&&(".."===part?stack.pop():stack.push(part));return`url(${maybeQuote}${stack.join("/")}${maybeQuote})`}))}const SRCSET_NOT_SPACES=/^[^ \t\n\r\u000c]+/,SRCSET_COMMAS_OR_SPACES=/^[, \t\n\r\u000c]+/;const cachedDocument=new WeakMap;function absoluteToDoc(doc,attributeValue){return attributeValue&&""!==attributeValue.trim()?getHref(doc,attributeValue):attributeValue}function isSVGElement(el){return Boolean("svg"===el.tagName||el.ownerSVGElement)}function getHref(doc,customHref){let a2=cachedDocument.get(doc);if(a2||(a2=doc.createElement("a"),cachedDocument.set(doc,a2)),customHref){if(customHref.startsWith("blob:")||customHref.startsWith("data:"))return customHref}else customHref="";return a2.setAttribute("href",customHref),a2.href}function transformAttribute(doc,tagName,name,value,element,maskAttributeFn){return value?"src"===name||"href"===name&&("use"!==tagName||"#"!==value[0])||"xlink:href"===name&&"#"!==value[0]?absoluteToDoc(doc,value):"background"!==name||"table"!==tagName&&"td"!==tagName&&"th"!==tagName?"srcset"===name?function(doc,attributeValue){if(""===attributeValue.trim())return attributeValue;let pos=0;function collectCharacters(regEx){let chars2;const match=regEx.exec(attributeValue.substring(pos));return match?(chars2=match[0],pos+=chars2.length,chars2):""}const output=[];for(;collectCharacters(SRCSET_COMMAS_OR_SPACES),!(pos>=attributeValue.length);){let url=collectCharacters(SRCSET_NOT_SPACES);if(","===url.slice(-1))url=absoluteToDoc(doc,url.substring(0,url.length-1)),output.push(url);else{let descriptorsStr="";url=absoluteToDoc(doc,url);let inParens=!1;for(;;){const c2=attributeValue.charAt(pos);if(""===c2){output.push((url+descriptorsStr).trim());break}if(inParens)")"===c2&&(inParens=!1);else{if(","===c2){pos+=1,output.push((url+descriptorsStr).trim());break}"("===c2&&(inParens=!0)}descriptorsStr+=c2,pos+=1}}}return output.join(", ")}(doc,value):"style"===name?absoluteToStylesheet(value,getHref(doc)):"object"===tagName&&"data"===name?absoluteToDoc(doc,value):"function"==typeof maskAttributeFn?maskAttributeFn(name,value,element):value:absoluteToDoc(doc,value):value}function ignoreAttribute(tagName,name,_value){return("video"===tagName||"audio"===tagName)&&"autoplay"===name}function _isBlockedElement(element,blockClass,blockSelector,unblockSelector){try{if(unblockSelector&&element.matches(unblockSelector))return!1;if("string"==typeof blockClass){if(element.classList.contains(blockClass))return!0}else for(let eIndex=element.classList.length;eIndex--;){const className=element.classList[eIndex];if(blockClass.test(className))return!0}if(blockSelector)return element.matches(blockSelector)}catch(e2){}return!1}function distanceToMatch(node,matchPredicate,limit=1/0,distance=0){return node?node.nodeType!==node.ELEMENT_NODE||distance>limit?-1:matchPredicate(node)?distance:distanceToMatch(node.parentNode,matchPredicate,limit,distance+1):-1}function createMatchPredicate(className,selector){return node=>{const el=node;if(null===el)return!1;try{if(className)if("string"==typeof className){if(el.matches(`.${className}`))return!0}else if(function(el,regex){for(let eIndex=el.classList.length;eIndex--;){const className=el.classList[eIndex];if(regex.test(className))return!0}return!1}(el,className))return!0;return!(!selector||!el.matches(selector))}catch{return!1}}}function needMaskingText(node,maskTextClass,maskTextSelector,unmaskTextClass,unmaskTextSelector,maskAllText){try{const el=node.nodeType===node.ELEMENT_NODE?node:node.parentElement;if(null===el)return!1;if("INPUT"===el.tagName){const autocomplete=el.getAttribute("autocomplete");if(["current-password","new-password","cc-number","cc-exp","cc-exp-month","cc-exp-year","cc-csc"].includes(autocomplete))return!0}let maskDistance=-1,unmaskDistance=-1;if(maskAllText){if(unmaskDistance=distanceToMatch(el,createMatchPredicate(unmaskTextClass,unmaskTextSelector)),unmaskDistance<0)return!0;maskDistance=distanceToMatch(el,createMatchPredicate(maskTextClass,maskTextSelector),unmaskDistance>=0?unmaskDistance:1/0)}else{if(maskDistance=distanceToMatch(el,createMatchPredicate(maskTextClass,maskTextSelector)),maskDistance<0)return!1;unmaskDistance=distanceToMatch(el,createMatchPredicate(unmaskTextClass,unmaskTextSelector),maskDistance>=0?maskDistance:1/0)}return maskDistance>=0?!(unmaskDistance>=0)||maskDistance<=unmaskDistance:!(unmaskDistance>=0)&&!!maskAllText}catch(e2){}return!!maskAllText}function serializeNode(n2,options){const{doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maskAllText:maskAllText,maskAttributeFn:maskAttributeFn,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,inlineStylesheet:inlineStylesheet,maskInputOptions:maskInputOptions={},maskTextFn:maskTextFn,maskInputFn:maskInputFn,dataURLOptions:dataURLOptions={},inlineImages:inlineImages,recordCanvas:recordCanvas,keepIframeSrcFn:keepIframeSrcFn,newlyAddedElement:newlyAddedElement=!1}=options,rootId=function(doc,mirror2){if(!mirror2.hasNode(doc))return;const docId=mirror2.getId(doc);return 1===docId?void 0:docId}(doc,mirror2);switch(n2.nodeType){case n2.DOCUMENT_NODE:return"CSS1Compat"!==n2.compatMode?{type:NodeType$2.Document,childNodes:[],compatMode:n2.compatMode}:{type:NodeType$2.Document,childNodes:[]};case n2.DOCUMENT_TYPE_NODE:return{type:NodeType$2.DocumentType,name:n2.name,publicId:n2.publicId,systemId:n2.systemId,rootId:rootId};case n2.ELEMENT_NODE:return function(n2,options){const{doc:doc,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,inlineStylesheet:inlineStylesheet,maskInputOptions:maskInputOptions={},maskAttributeFn:maskAttributeFn,maskInputFn:maskInputFn,dataURLOptions:dataURLOptions={},inlineImages:inlineImages,recordCanvas:recordCanvas,keepIframeSrcFn:keepIframeSrcFn,newlyAddedElement:newlyAddedElement=!1,rootId:rootId,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector}=options,needBlock=_isBlockedElement(n2,blockClass,blockSelector,unblockSelector),tagName=function(element){if(element instanceof HTMLFormElement)return"form";const processedTagName=toLowerCase(element.tagName);return tagNameRegex.test(processedTagName)?"div":processedTagName}(n2);let attributes2={};const len=n2.attributes.length;for(let i2=0;i2<len;i2++){const attr=n2.attributes[i2];attr.name&&!ignoreAttribute(tagName,attr.name,attr.value)&&(attributes2[attr.name]=transformAttribute(doc,tagName,toLowerCase(attr.name),attr.value,n2,maskAttributeFn))}if("link"===tagName&&inlineStylesheet){const stylesheet=Array.from(doc.styleSheets).find((s2=>s2.href===n2.href));let cssText=null;stylesheet&&(cssText=stringifyStylesheet(stylesheet)),cssText&&(attributes2.rel=null,attributes2.href=null,attributes2.crossorigin=null,attributes2._cssText=absoluteToStylesheet(cssText,stylesheet.href))}if("style"===tagName&&n2.sheet&&!(n2.innerText||n2.textContent||"").trim().length){const cssText=stringifyStylesheet(n2.sheet);cssText&&(attributes2._cssText=absoluteToStylesheet(cssText,getHref(doc)))}if("input"===tagName||"textarea"===tagName||"select"===tagName||"option"===tagName){const el=n2,type=getInputType(el),value=getInputValue(el,toUpperCase(tagName),type),checked=el.checked;if("submit"!==type&&"button"!==type&&value){const forceMask=needMaskingText(el,maskTextClass,maskTextSelector,unmaskTextClass,unmaskTextSelector,shouldMaskInput({type:type,tagName:toUpperCase(tagName),maskInputOptions:maskInputOptions}));attributes2.value=maskInputValue({isMasked:forceMask,element:el,value:value,maskInputFn:maskInputFn})}checked&&(attributes2.checked=checked)}"option"===tagName&&(n2.selected&&!maskInputOptions.select?attributes2.selected=!0:delete attributes2.selected);if("canvas"===tagName&&recordCanvas)if("2d"===n2.__context)(function(canvas){const ctx=canvas.getContext("2d");if(!ctx)return!0;for(let x=0;x<canvas.width;x+=50)for(let y=0;y<canvas.height;y+=50){const getImageData=ctx.getImageData,originalGetImageData="__rrweb_original__"in getImageData?getImageData.__rrweb_original__:getImageData;if(new Uint32Array(originalGetImageData.call(ctx,x,y,Math.min(50,canvas.width-x),Math.min(50,canvas.height-y)).data.buffer).some((pixel=>0!==pixel)))return!1}return!0})(n2)||(attributes2.rr_dataURL=n2.toDataURL(dataURLOptions.type,dataURLOptions.quality));else if(!("__context"in n2)){const canvasDataURL=n2.toDataURL(dataURLOptions.type,dataURLOptions.quality),blankCanvas=doc.createElement("canvas");blankCanvas.width=n2.width,blankCanvas.height=n2.height;canvasDataURL!==blankCanvas.toDataURL(dataURLOptions.type,dataURLOptions.quality)&&(attributes2.rr_dataURL=canvasDataURL)}if("img"===tagName&&inlineImages){canvasService||(canvasService=doc.createElement("canvas"),canvasCtx=canvasService.getContext("2d"));const image=n2,imageSrc=image.currentSrc||image.getAttribute("src")||"<unknown-src>",priorCrossOrigin=image.crossOrigin,recordInlineImage=()=>{image.removeEventListener("load",recordInlineImage);try{canvasService.width=image.naturalWidth,canvasService.height=image.naturalHeight,canvasCtx.drawImage(image,0,0),attributes2.rr_dataURL=canvasService.toDataURL(dataURLOptions.type,dataURLOptions.quality)}catch(err){if("anonymous"!==image.crossOrigin)return image.crossOrigin="anonymous",void(image.complete&&0!==image.naturalWidth?recordInlineImage():image.addEventListener("load",recordInlineImage));console.warn(`Cannot inline img src=${imageSrc}! Error: ${err}`)}"anonymous"===image.crossOrigin&&(priorCrossOrigin?attributes2.crossOrigin=priorCrossOrigin:image.removeAttribute("crossorigin"))};image.complete&&0!==image.naturalWidth?recordInlineImage():image.addEventListener("load",recordInlineImage)}"audio"!==tagName&&"video"!==tagName||(attributes2.rr_mediaState=n2.paused?"paused":"played",attributes2.rr_mediaCurrentTime=n2.currentTime);newlyAddedElement||(n2.scrollLeft&&(attributes2.rr_scrollLeft=n2.scrollLeft),n2.scrollTop&&(attributes2.rr_scrollTop=n2.scrollTop));if(needBlock){const{width:width,height:height}=n2.getBoundingClientRect();attributes2={class:attributes2.class,rr_width:`${width}px`,rr_height:`${height}px`}}"iframe"!==tagName||keepIframeSrcFn(attributes2.src)||(needBlock||getIframeContentDocument(n2)||(attributes2.rr_src=attributes2.src),delete attributes2.src);let isCustomElement;try{customElements.get(tagName)&&(isCustomElement=!0)}catch(e2){}return{type:NodeType$2.Element,tagName:tagName,attributes:attributes2,childNodes:[],isSVG:isSVGElement(n2)||void 0,needBlock:needBlock,rootId:rootId,isCustom:isCustomElement}}(n2,{doc:doc,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,inlineStylesheet:inlineStylesheet,maskAttributeFn:maskAttributeFn,maskInputOptions:maskInputOptions,maskInputFn:maskInputFn,dataURLOptions:dataURLOptions,inlineImages:inlineImages,recordCanvas:recordCanvas,keepIframeSrcFn:keepIframeSrcFn,newlyAddedElement:newlyAddedElement,rootId:rootId,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector});case n2.TEXT_NODE:return function(n2,options){const{maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,maskTextFn:maskTextFn,maskInputOptions:maskInputOptions,maskInputFn:maskInputFn,rootId:rootId}=options,parentTagName=n2.parentNode&&n2.parentNode.tagName;let textContent=n2.textContent;const isStyle="STYLE"===parentTagName||void 0,isScript="SCRIPT"===parentTagName||void 0,isTextarea="TEXTAREA"===parentTagName||void 0;if(isStyle&&textContent){try{n2.nextSibling||n2.previousSibling||n2.parentNode.sheet?.cssRules&&(textContent=stringifyStylesheet(n2.parentNode.sheet))}catch(err){console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`,n2)}textContent=absoluteToStylesheet(textContent,getHref(options.doc))}isScript&&(textContent="SCRIPT_PLACEHOLDER");const forceMask=needMaskingText(n2,maskTextClass,maskTextSelector,unmaskTextClass,unmaskTextSelector,maskAllText);isStyle||isScript||isTextarea||!textContent||!forceMask||(textContent=maskTextFn?maskTextFn(textContent,n2.parentElement):textContent.replace(/[\S]/g,"*"));isTextarea&&textContent&&(maskInputOptions.textarea||forceMask)&&(textContent=maskInputFn?maskInputFn(textContent,n2.parentNode):textContent.replace(/[\S]/g,"*"));if("OPTION"===parentTagName&&textContent){textContent=maskInputValue({isMasked:needMaskingText(n2,maskTextClass,maskTextSelector,unmaskTextClass,unmaskTextSelector,shouldMaskInput({type:null,tagName:parentTagName,maskInputOptions:maskInputOptions})),element:n2,value:textContent,maskInputFn:maskInputFn})}return{type:NodeType$2.Text,textContent:textContent||"",isStyle:isStyle,rootId:rootId}}(n2,{doc:doc,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,maskTextFn:maskTextFn,maskInputOptions:maskInputOptions,maskInputFn:maskInputFn,rootId:rootId});case n2.CDATA_SECTION_NODE:return{type:NodeType$2.CDATA,textContent:"",rootId:rootId};case n2.COMMENT_NODE:return{type:NodeType$2.Comment,textContent:n2.textContent||"",rootId:rootId};default:return!1}}function lowerIfExists(maybeAttr){return null==maybeAttr?"":maybeAttr.toLowerCase()}function serializeNodeWithId(n2,options){const{doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,skipChild:skipChild=!1,inlineStylesheet:inlineStylesheet=!0,maskInputOptions:maskInputOptions={},maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,slimDOMOptions:slimDOMOptions,dataURLOptions:dataURLOptions={},inlineImages:inlineImages=!1,recordCanvas:recordCanvas=!1,onSerialize:onSerialize,onIframeLoad:onIframeLoad,iframeLoadTimeout:iframeLoadTimeout=5e3,onStylesheetLoad:onStylesheetLoad,stylesheetLoadTimeout:stylesheetLoadTimeout=5e3,keepIframeSrcFn:keepIframeSrcFn=()=>!1,newlyAddedElement:newlyAddedElement=!1}=options;let{preserveWhiteSpace:preserveWhiteSpace=!0}=options;const _serializedNode=serializeNode(n2,{doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,maskAllText:maskAllText,unblockSelector:unblockSelector,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,inlineStylesheet:inlineStylesheet,maskInputOptions:maskInputOptions,maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,dataURLOptions:dataURLOptions,inlineImages:inlineImages,recordCanvas:recordCanvas,keepIframeSrcFn:keepIframeSrcFn,newlyAddedElement:newlyAddedElement});if(!_serializedNode)return console.warn(n2,"not serialized"),null;let id;id=mirror2.hasNode(n2)?mirror2.getId(n2):!function(sn,slimDOMOptions){if(slimDOMOptions.comment&&sn.type===NodeType$2.Comment)return!0;if(sn.type===NodeType$2.Element){if(slimDOMOptions.script&&("script"===sn.tagName||"link"===sn.tagName&&("preload"===sn.attributes.rel||"modulepreload"===sn.attributes.rel)||"link"===sn.tagName&&"prefetch"===sn.attributes.rel&&"string"==typeof sn.attributes.href&&"js"===extractFileExtension(sn.attributes.href)))return!0;if(slimDOMOptions.headFavicon&&("link"===sn.tagName&&"shortcut icon"===sn.attributes.rel||"meta"===sn.tagName&&(lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===lowerIfExists(sn.attributes.name)||"icon"===lowerIfExists(sn.attributes.rel)||"apple-touch-icon"===lowerIfExists(sn.attributes.rel)||"shortcut icon"===lowerIfExists(sn.attributes.rel))))return!0;if("meta"===sn.tagName){if(slimDOMOptions.headMetaDescKeywords&&lowerIfExists(sn.attributes.name).match(/^description|keywords$/))return!0;if(slimDOMOptions.headMetaSocial&&(lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/)||lowerIfExists(sn.attributes.name).match(/^(og|twitter):/)||"pinterest"===lowerIfExists(sn.attributes.name)))return!0;if(slimDOMOptions.headMetaRobots&&("robots"===lowerIfExists(sn.attributes.name)||"googlebot"===lowerIfExists(sn.attributes.name)||"bingbot"===lowerIfExists(sn.attributes.name)))return!0;if(slimDOMOptions.headMetaHttpEquiv&&void 0!==sn.attributes["http-equiv"])return!0;if(slimDOMOptions.headMetaAuthorship&&("author"===lowerIfExists(sn.attributes.name)||"generator"===lowerIfExists(sn.attributes.name)||"framework"===lowerIfExists(sn.attributes.name)||"publisher"===lowerIfExists(sn.attributes.name)||"progid"===lowerIfExists(sn.attributes.name)||lowerIfExists(sn.attributes.property).match(/^article:/)||lowerIfExists(sn.attributes.property).match(/^product:/)))return!0;if(slimDOMOptions.headMetaVerification&&("google-site-verification"===lowerIfExists(sn.attributes.name)||"yandex-verification"===lowerIfExists(sn.attributes.name)||"csrf-token"===lowerIfExists(sn.attributes.name)||"p:domain_verify"===lowerIfExists(sn.attributes.name)||"verify-v1"===lowerIfExists(sn.attributes.name)||"verification"===lowerIfExists(sn.attributes.name)||"shopify-checkout-api-token"===lowerIfExists(sn.attributes.name)))return!0}}return!1}(_serializedNode,slimDOMOptions)&&(preserveWhiteSpace||_serializedNode.type!==NodeType$2.Text||_serializedNode.isStyle||_serializedNode.textContent.replace(/^\s+|\s+$/gm,"").length)?genId():-2;const serializedNode2=Object.assign(_serializedNode,{id:id});if(mirror2.add(n2,serializedNode2),-2===id)return null;onSerialize&&onSerialize(n2);let recordChild=!skipChild;if(serializedNode2.type===NodeType$2.Element){recordChild=recordChild&&!serializedNode2.needBlock,delete serializedNode2.needBlock;const shadowRoot=n2.shadowRoot;shadowRoot&&isNativeShadowDom(shadowRoot)&&(serializedNode2.isShadowHost=!0)}if((serializedNode2.type===NodeType$2.Document||serializedNode2.type===NodeType$2.Element)&&recordChild){slimDOMOptions.headWhitespace&&serializedNode2.type===NodeType$2.Element&&"head"===serializedNode2.tagName&&(preserveWhiteSpace=!1);const bypassOptions={doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,maskAllText:maskAllText,unblockSelector:unblockSelector,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,skipChild:skipChild,inlineStylesheet:inlineStylesheet,maskInputOptions:maskInputOptions,maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,slimDOMOptions:slimDOMOptions,dataURLOptions:dataURLOptions,inlineImages:inlineImages,recordCanvas:recordCanvas,preserveWhiteSpace:preserveWhiteSpace,onSerialize:onSerialize,onIframeLoad:onIframeLoad,iframeLoadTimeout:iframeLoadTimeout,onStylesheetLoad:onStylesheetLoad,stylesheetLoadTimeout:stylesheetLoadTimeout,keepIframeSrcFn:keepIframeSrcFn};for(const childN of Array.from(n2.childNodes)){const serializedChildNode=serializeNodeWithId(childN,bypassOptions);serializedChildNode&&serializedNode2.childNodes.push(serializedChildNode)}if(function(n2){return n2.nodeType===n2.ELEMENT_NODE}(n2)&&n2.shadowRoot)for(const childN of Array.from(n2.shadowRoot.childNodes)){const serializedChildNode=serializeNodeWithId(childN,bypassOptions);serializedChildNode&&(isNativeShadowDom(n2.shadowRoot)&&(serializedChildNode.isShadow=!0),serializedNode2.childNodes.push(serializedChildNode))}}return n2.parentNode&&isShadowRoot(n2.parentNode)&&isNativeShadowDom(n2.parentNode)&&(serializedNode2.isShadow=!0),serializedNode2.type!==NodeType$2.Element||"iframe"!==serializedNode2.tagName||_isBlockedElement(n2,blockClass,blockSelector,unblockSelector)||function(iframeEl,listener,iframeLoadTimeout){const win=iframeEl.contentWindow;if(!win)return;let readyState,fired=!1;try{readyState=win.document.readyState}catch(error){return}if("complete"!==readyState){const timer=setTimeout$2((()=>{fired||(listener(),fired=!0)}),iframeLoadTimeout);return void iframeEl.addEventListener("load",(()=>{clearTimeout$1(timer),fired=!0,listener()}))}if("about:blank"!==win.location.href||"about:blank"===iframeEl.src||""===iframeEl.src)return setTimeout$2(listener,0),iframeEl.addEventListener("load",listener);iframeEl.addEventListener("load",listener)}(n2,(()=>{const iframeDoc=getIframeContentDocument(n2);if(iframeDoc&&onIframeLoad){const serializedIframeNode=serializeNodeWithId(iframeDoc,{doc:iframeDoc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,skipChild:!1,inlineStylesheet:inlineStylesheet,maskInputOptions:maskInputOptions,maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,slimDOMOptions:slimDOMOptions,dataURLOptions:dataURLOptions,inlineImages:inlineImages,recordCanvas:recordCanvas,preserveWhiteSpace:preserveWhiteSpace,onSerialize:onSerialize,onIframeLoad:onIframeLoad,iframeLoadTimeout:iframeLoadTimeout,onStylesheetLoad:onStylesheetLoad,stylesheetLoadTimeout:stylesheetLoadTimeout,keepIframeSrcFn:keepIframeSrcFn});serializedIframeNode&&onIframeLoad(n2,serializedIframeNode)}}),iframeLoadTimeout),serializedNode2.type===NodeType$2.Element&&"link"===serializedNode2.tagName&&"string"==typeof serializedNode2.attributes.rel&&("stylesheet"===serializedNode2.attributes.rel||"preload"===serializedNode2.attributes.rel&&"string"==typeof serializedNode2.attributes.href&&"css"===extractFileExtension(serializedNode2.attributes.href))&&function(link,listener,styleSheetLoadTimeout){let styleSheetLoaded,fired=!1;try{styleSheetLoaded=link.sheet}catch(error){return}if(styleSheetLoaded)return;const timer=setTimeout$2((()=>{fired||(listener(),fired=!0)}),styleSheetLoadTimeout);link.addEventListener("load",(()=>{clearTimeout$1(timer),fired=!0,listener()}))}(n2,(()=>{if(onStylesheetLoad){const serializedLinkNode=serializeNodeWithId(n2,{doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,skipChild:!1,inlineStylesheet:inlineStylesheet,maskInputOptions:maskInputOptions,maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,slimDOMOptions:slimDOMOptions,dataURLOptions:dataURLOptions,inlineImages:inlineImages,recordCanvas:recordCanvas,preserveWhiteSpace:preserveWhiteSpace,onSerialize:onSerialize,onIframeLoad:onIframeLoad,iframeLoadTimeout:iframeLoadTimeout,onStylesheetLoad:onStylesheetLoad,stylesheetLoadTimeout:stylesheetLoadTimeout,keepIframeSrcFn:keepIframeSrcFn});serializedLinkNode&&onStylesheetLoad(n2,serializedLinkNode)}}),stylesheetLoadTimeout),serializedNode2}function on(type,fn,target=document){const options={capture:!0,passive:!0};return target.addEventListener(type,fn,options),()=>target.removeEventListener(type,fn,options)}const DEPARTED_MIRROR_ACCESS_WARNING="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";let _mirror={map:{},getId(){return console.error(DEPARTED_MIRROR_ACCESS_WARNING),-1},getNode(){return console.error(DEPARTED_MIRROR_ACCESS_WARNING),null},removeNodeFromMap(){console.error(DEPARTED_MIRROR_ACCESS_WARNING)},has(){return console.error(DEPARTED_MIRROR_ACCESS_WARNING),!1},reset(){console.error(DEPARTED_MIRROR_ACCESS_WARNING)}};function throttle$1(func,wait,options={}){let timeout=null,previous=0;return function(...args){const now=Date.now();previous||!1!==options.leading||(previous=now);const remaining=wait-(now-previous),context=this;remaining<=0||remaining>wait?(timeout&&(!function(...rest){getImplementation("clearTimeout")(...rest)}(timeout),timeout=null),previous=now,func.apply(context,args)):timeout||!1===options.trailing||(timeout=setTimeout$1((()=>{previous=!1===options.leading?0:Date.now(),timeout=null,func.apply(context,args)}),remaining))}}function hookSetter(target,key,d,isRevoked,win=window){const original=win.Object.getOwnPropertyDescriptor(target,key);return win.Object.defineProperty(target,key,isRevoked?d:{set(value){setTimeout$1((()=>{d.set.call(this,value)}),0),original&&original.set&&original.set.call(this,value)}}),()=>hookSetter(target,key,original||{},!0)}function patch(source,name,replacement){try{if(!(name in source))return()=>{};const original=source[name],wrapped=replacement(original);return"function"==typeof wrapped&&(wrapped.prototype=wrapped.prototype||{},Object.defineProperties(wrapped,{__rrweb_original__:{enumerable:!1,value:original}})),source[name]=wrapped,()=>{source[name]=original}}catch{return()=>{}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(_mirror=new Proxy(_mirror,{get(target,prop,receiver){return"map"===prop&&console.error(DEPARTED_MIRROR_ACCESS_WARNING),Reflect.get(target,prop,receiver)}}));let nowTimestamp=Date.now;function getWindowScroll(win){const doc=win.document;return{left:doc.scrollingElement?doc.scrollingElement.scrollLeft:void 0!==win.pageXOffset?win.pageXOffset:doc?.documentElement.scrollLeft||doc?.body?.parentElement?.scrollLeft||doc?.body?.scrollLeft||0,top:doc.scrollingElement?doc.scrollingElement.scrollTop:void 0!==win.pageYOffset?win.pageYOffset:doc?.documentElement.scrollTop||doc?.body?.parentElement?.scrollTop||doc?.body?.scrollTop||0}}function getWindowHeight(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function getWindowWidth(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function closestElementOfNode(node){if(!node)return null;try{return node.nodeType===node.ELEMENT_NODE?node:node.parentElement}catch(error){return null}}function isBlocked(node,blockClass,blockSelector,unblockSelector,checkAncestors){if(!node)return!1;const el=closestElementOfNode(node);if(!el)return!1;const blockedPredicate=createMatchPredicate(blockClass,blockSelector);if(!checkAncestors){const isUnblocked=unblockSelector&&el.matches(unblockSelector);return blockedPredicate(el)&&!isUnblocked}const blockDistance=distanceToMatch(el,blockedPredicate);let unblockDistance=-1;return!(blockDistance<0)&&(unblockSelector&&(unblockDistance=distanceToMatch(el,createMatchPredicate(null,unblockSelector))),blockDistance>-1&&unblockDistance<0||blockDistance<unblockDistance)}function isIgnored(n2,mirror2){return-2===mirror2.getId(n2)}function isAncestorRemoved(target,mirror2){if(isShadowRoot(target))return!1;const id=mirror2.getId(target);return!mirror2.has(id)||(!target.parentNode||target.parentNode.nodeType!==target.DOCUMENT_NODE)&&(!target.parentNode||isAncestorRemoved(target.parentNode,mirror2))}function legacy_isTouchEvent(event){return Boolean(event.changedTouches)}function isSerializedIframe(n2,mirror2){return Boolean("IFRAME"===n2.nodeName&&mirror2.getMeta(n2))}function isSerializedStylesheet(n2,mirror2){return Boolean("LINK"===n2.nodeName&&n2.nodeType===n2.ELEMENT_NODE&&n2.getAttribute&&"stylesheet"===n2.getAttribute("rel")&&mirror2.getMeta(n2))}function hasShadowRoot(n2){return Boolean(n2?.shadowRoot)}/[1-9][0-9]{12}/.test(Date.now().toString())||(nowTimestamp=()=>(new Date).getTime());class StyleSheetMirror{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(stylesheet){return this.styleIDMap.get(stylesheet)??-1}has(stylesheet){return this.styleIDMap.has(stylesheet)}add(stylesheet,id){if(this.has(stylesheet))return this.getId(stylesheet);let newId;return newId=void 0===id?this.id++:id,this.styleIDMap.set(stylesheet,newId),this.idStyleMap.set(newId,stylesheet),newId}getStyle(id){return this.idStyleMap.get(id)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function getShadowHost(n2){let shadowHost=null;return n2.getRootNode?.()?.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&n2.getRootNode().host&&(shadowHost=n2.getRootNode().host),shadowHost}function shadowHostInDom(n2){const doc=n2.ownerDocument;if(!doc)return!1;const shadowHost=function(n2){let shadowHost,rootShadowHost=n2;for(;shadowHost=getShadowHost(rootShadowHost);)rootShadowHost=shadowHost;return rootShadowHost}(n2);return doc.contains(shadowHost)}function inDom(n2){const doc=n2.ownerDocument;return!!doc&&(doc.contains(n2)||shadowHostInDom(n2))}const esm_cachedImplementations={};function getImplementation(name){const cached=esm_cachedImplementations[name];if(cached)return cached;const document2=window.document;let impl=window[name];if(document2&&"function"==typeof document2.createElement)try{const sandbox=document2.createElement("iframe");sandbox.hidden=!0,document2.head.appendChild(sandbox);const contentWindow=sandbox.contentWindow;contentWindow&&contentWindow[name]&&(impl=contentWindow[name]),document2.head.removeChild(sandbox)}catch(e2){}return esm_cachedImplementations[name]=impl.bind(window)}function setTimeout$1(...rest){return getImplementation("setTimeout")(...rest)}var EventType=(EventType2=>(EventType2[EventType2.DomContentLoaded=0]="DomContentLoaded",EventType2[EventType2.Load=1]="Load",EventType2[EventType2.FullSnapshot=2]="FullSnapshot",EventType2[EventType2.IncrementalSnapshot=3]="IncrementalSnapshot",EventType2[EventType2.Meta=4]="Meta",EventType2[EventType2.Custom=5]="Custom",EventType2[EventType2.Plugin=6]="Plugin",EventType2))(EventType||{}),IncrementalSource=(IncrementalSource2=>(IncrementalSource2[IncrementalSource2.Mutation=0]="Mutation",IncrementalSource2[IncrementalSource2.MouseMove=1]="MouseMove",IncrementalSource2[IncrementalSource2.MouseInteraction=2]="MouseInteraction",IncrementalSource2[IncrementalSource2.Scroll=3]="Scroll",IncrementalSource2[IncrementalSource2.ViewportResize=4]="ViewportResize",IncrementalSource2[IncrementalSource2.Input=5]="Input",IncrementalSource2[IncrementalSource2.TouchMove=6]="TouchMove",IncrementalSource2[IncrementalSource2.MediaInteraction=7]="MediaInteraction",IncrementalSource2[IncrementalSource2.StyleSheetRule=8]="StyleSheetRule",IncrementalSource2[IncrementalSource2.CanvasMutation=9]="CanvasMutation",IncrementalSource2[IncrementalSource2.Font=10]="Font",IncrementalSource2[IncrementalSource2.Log=11]="Log",IncrementalSource2[IncrementalSource2.Drag=12]="Drag",IncrementalSource2[IncrementalSource2.StyleDeclaration=13]="StyleDeclaration",IncrementalSource2[IncrementalSource2.Selection=14]="Selection",IncrementalSource2[IncrementalSource2.AdoptedStyleSheet=15]="AdoptedStyleSheet",IncrementalSource2[IncrementalSource2.CustomElement=16]="CustomElement",IncrementalSource2))(IncrementalSource||{}),MouseInteractions=(MouseInteractions2=>(MouseInteractions2[MouseInteractions2.MouseUp=0]="MouseUp",MouseInteractions2[MouseInteractions2.MouseDown=1]="MouseDown",MouseInteractions2[MouseInteractions2.Click=2]="Click",MouseInteractions2[MouseInteractions2.ContextMenu=3]="ContextMenu",MouseInteractions2[MouseInteractions2.DblClick=4]="DblClick",MouseInteractions2[MouseInteractions2.Focus=5]="Focus",MouseInteractions2[MouseInteractions2.Blur=6]="Blur",MouseInteractions2[MouseInteractions2.TouchStart=7]="TouchStart",MouseInteractions2[MouseInteractions2.TouchMove_Departed=8]="TouchMove_Departed",MouseInteractions2[MouseInteractions2.TouchEnd=9]="TouchEnd",MouseInteractions2[MouseInteractions2.TouchCancel=10]="TouchCancel",MouseInteractions2))(MouseInteractions||{}),PointerTypes=(PointerTypes2=>(PointerTypes2[PointerTypes2.Mouse=0]="Mouse",PointerTypes2[PointerTypes2.Pen=1]="Pen",PointerTypes2[PointerTypes2.Touch=2]="Touch",PointerTypes2))(PointerTypes||{}),MediaInteractions=(MediaInteractions2=>(MediaInteractions2[MediaInteractions2.Play=0]="Play",MediaInteractions2[MediaInteractions2.Pause=1]="Pause",MediaInteractions2[MediaInteractions2.Seeked=2]="Seeked",MediaInteractions2[MediaInteractions2.VolumeChange=3]="VolumeChange",MediaInteractions2[MediaInteractions2.RateChange=4]="RateChange",MediaInteractions2))(MediaInteractions||{});function getIFrameContentDocument(iframe){try{return iframe.contentDocument}catch(e2){}}function isNodeInLinkedList(n2){return"__ln"in n2}class DoubleLinkedList{constructor(){this.length=0,this.head=null,this.tail=null}get(position){if(position>=this.length)throw new Error("Position outside of list range");let current=this.head;for(let index=0;index<position;index++)current=current?.next||null;return current}addNode(n2){const node={value:n2,previous:null,next:null};if(n2.__ln=node,n2.previousSibling&&isNodeInLinkedList(n2.previousSibling)){const current=n2.previousSibling.__ln.next;node.next=current,node.previous=n2.previousSibling.__ln,n2.previousSibling.__ln.next=node,current&&(current.previous=node)}else if(n2.nextSibling&&isNodeInLinkedList(n2.nextSibling)&&n2.nextSibling.__ln.previous){const current=n2.nextSibling.__ln.previous;node.previous=current,node.next=n2.nextSibling.__ln,n2.nextSibling.__ln.previous=node,current&&(current.next=node)}else this.head&&(this.head.previous=node),node.next=this.head,this.head=node;null===node.next&&(this.tail=node),this.length++}removeNode(n2){const current=n2.__ln;this.head&&(current.previous?(current.previous.next=current.next,current.next?current.next.previous=current.previous:this.tail=current.previous):(this.head=current.next,this.head?this.head.previous=null:this.tail=null),n2.__ln&&delete n2.__ln,this.length--)}}const moveKey=(id,parentId)=>`${id}@${parentId}`;class MutationBuffer{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=mutations=>{mutations.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;const adds=[],addedIds=new Set,addList=new DoubleLinkedList,getNextId=n2=>{let ns=n2,nextId=-2;for(;-2===nextId;)ns=ns&&ns.nextSibling,nextId=ns&&this.mirror.getId(ns);return nextId},pushAdd=n2=>{if(!n2.parentNode||!inDom(n2))return;const parentId=isShadowRoot(n2.parentNode)?this.mirror.getId(getShadowHost(n2)):this.mirror.getId(n2.parentNode),nextId=getNextId(n2);if(-1===parentId||-1===nextId)return addList.addNode(n2);const sn=serializeNodeWithId(n2,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskAllText:this.maskAllText,unblockSelector:this.unblockSelector,maskTextClass:this.maskTextClass,unmaskTextClass:this.unmaskTextClass,maskTextSelector:this.maskTextSelector,unmaskTextSelector:this.unmaskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskAttributeFn:this.maskAttributeFn,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:currentN=>{isSerializedIframe(currentN,this.mirror)&&!isBlocked(currentN,this.blockClass,this.blockSelector,this.unblockSelector,!1)&&this.iframeManager.addIframe(currentN),isSerializedStylesheet(currentN,this.mirror)&&this.stylesheetManager.trackLinkElement(currentN),hasShadowRoot(n2)&&this.shadowDomManager.addShadowRoot(n2.shadowRoot,this.doc)},onIframeLoad:(iframe,childSn)=>{isBlocked(iframe,this.blockClass,this.blockSelector,this.unblockSelector,!1)||(this.iframeManager.attachIframe(iframe,childSn),iframe.contentWindow&&this.canvasManager.addWindow(iframe.contentWindow),this.shadowDomManager.observeAttachShadow(iframe))},onStylesheetLoad:(link,childSn)=>{this.stylesheetManager.attachLinkElement(link,childSn)}});sn&&(adds.push({parentId:parentId,nextId:nextId,node:sn}),addedIds.add(sn.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const n2 of this.movedSet)isParentRemoved(this.removes,n2,this.mirror)&&!this.movedSet.has(n2.parentNode)||pushAdd(n2);for(const n2 of this.addedSet)isAncestorInSet(this.droppedSet,n2)||isParentRemoved(this.removes,n2,this.mirror)?isAncestorInSet(this.movedSet,n2)?pushAdd(n2):this.droppedSet.add(n2):pushAdd(n2);let candidate=null;for(;addList.length;){let node=null;if(candidate){const parentId=this.mirror.getId(candidate.value.parentNode),nextId=getNextId(candidate.value);-1!==parentId&&-1!==nextId&&(node=candidate)}if(!node){let tailNode=addList.tail;for(;tailNode;){const _node=tailNode;if(tailNode=tailNode.previous,_node){const parentId=this.mirror.getId(_node.value.parentNode);if(-1===getNextId(_node.value))continue;if(-1!==parentId){node=_node;break}{const unhandledNode=_node.value;if(unhandledNode.parentNode&&unhandledNode.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const shadowHost=unhandledNode.parentNode.host;if(-1!==this.mirror.getId(shadowHost)){node=_node;break}}}}}}if(!node){for(;addList.head;)addList.removeNode(addList.head.value);break}candidate=node.previous,addList.removeNode(node.value),pushAdd(node.value)}const payload={texts:this.texts.map((text=>({id:this.mirror.getId(text.node),value:text.value}))).filter((text=>!addedIds.has(text.id))).filter((text=>this.mirror.has(text.id))),attributes:this.attributes.map((attribute=>{const{attributes:attributes}=attribute;if("string"==typeof attributes.style){const diffAsStr=JSON.stringify(attribute.styleDiff),unchangedAsStr=JSON.stringify(attribute._unchangedStyles);diffAsStr.length<attributes.style.length&&(diffAsStr+unchangedAsStr).split("var(").length===attributes.style.split("var(").length&&(attributes.style=attribute.styleDiff)}return{id:this.mirror.getId(attribute.node),attributes:attributes}})).filter((attribute=>!addedIds.has(attribute.id))).filter((attribute=>this.mirror.has(attribute.id))),removes:this.removes,adds:adds};(payload.texts.length||payload.attributes.length||payload.removes.length||payload.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(payload))},this.processMutation=m=>{if(!isIgnored(m.target,this.mirror))switch(m.type){case"characterData":{const value=m.target.textContent;isBlocked(m.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||value===m.oldValue||this.texts.push({value:needMaskingText(m.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,this.maskAllText)&&value?this.maskTextFn?this.maskTextFn(value,closestElementOfNode(m.target)):value.replace(/[\S]/g,"*"):value,node:m.target});break}case"attributes":{const target=m.target;let attributeName=m.attributeName,value=m.target.getAttribute(attributeName);if("value"===attributeName){const type=getInputType(target),tagName=target.tagName;value=getInputValue(target,tagName,type);const isInputMasked=shouldMaskInput({maskInputOptions:this.maskInputOptions,tagName:tagName,type:type});value=maskInputValue({isMasked:needMaskingText(m.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,isInputMasked),element:target,value:value,maskInputFn:this.maskInputFn})}if(isBlocked(m.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||value===m.oldValue)return;let item=this.attributeMap.get(m.target);if("IFRAME"===target.tagName&&"src"===attributeName&&!this.keepIframeSrcFn(value)){if(getIFrameContentDocument(target))return;attributeName="rr_src"}if(item||(item={node:m.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(item),this.attributeMap.set(m.target,item)),"type"===attributeName&&"INPUT"===target.tagName&&"password"===(m.oldValue||"").toLowerCase()&&target.setAttribute("data-rr-is-password","true"),!ignoreAttribute(target.tagName,attributeName)&&(item.attributes[attributeName]=transformAttribute(this.doc,toLowerCase(target.tagName),toLowerCase(attributeName),value,target,this.maskAttributeFn),"style"===attributeName)){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(e2){this.unattachedDoc=this.doc}const old=this.unattachedDoc.createElement("span");m.oldValue&&old.setAttribute("style",m.oldValue);for(const pname of Array.from(target.style)){const newValue=target.style.getPropertyValue(pname),newPriority=target.style.getPropertyPriority(pname);newValue!==old.style.getPropertyValue(pname)||newPriority!==old.style.getPropertyPriority(pname)?item.styleDiff[pname]=""===newPriority?newValue:[newValue,newPriority]:item._unchangedStyles[pname]=[newValue,newPriority]}for(const pname of Array.from(old.style))""===target.style.getPropertyValue(pname)&&(item.styleDiff[pname]=!1)}break}case"childList":if(isBlocked(m.target,this.blockClass,this.blockSelector,this.unblockSelector,!0))return;m.addedNodes.forEach((n2=>this.genAdds(n2,m.target))),m.removedNodes.forEach((n2=>{const nodeId=this.mirror.getId(n2),parentId=isShadowRoot(m.target)?this.mirror.getId(m.target.host):this.mirror.getId(m.target);isBlocked(m.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||isIgnored(n2,this.mirror)||!function(n2,mirror2){return-1!==mirror2.getId(n2)}(n2,this.mirror)||(this.addedSet.has(n2)?(deepDelete(this.addedSet,n2),this.droppedSet.add(n2)):this.addedSet.has(m.target)&&-1===nodeId||isAncestorRemoved(m.target,this.mirror)||(this.movedSet.has(n2)&&this.movedMap[moveKey(nodeId,parentId)]?deepDelete(this.movedSet,n2):this.removes.push({parentId:parentId,id:nodeId,isShadow:!(!isShadowRoot(m.target)||!isNativeShadowDom(m.target))||void 0})),this.mapRemoves.push(n2))}))}},this.genAdds=(n2,target)=>{if(!this.processedNodeManager.inOtherBuffer(n2,this)&&!this.addedSet.has(n2)&&!this.movedSet.has(n2)){if(this.mirror.hasNode(n2)){if(isIgnored(n2,this.mirror))return;this.movedSet.add(n2);let targetId=null;target&&this.mirror.hasNode(target)&&(targetId=this.mirror.getId(target)),targetId&&-1!==targetId&&(this.movedMap[moveKey(this.mirror.getId(n2),targetId)]=!0)}else this.addedSet.add(n2),this.droppedSet.delete(n2);isBlocked(n2,this.blockClass,this.blockSelector,this.unblockSelector,!1)||(n2.childNodes.forEach((childN=>this.genAdds(childN))),hasShadowRoot(n2)&&n2.shadowRoot.childNodes.forEach((childN=>{this.processedNodeManager.add(childN,this),this.genAdds(childN,n2)})))}}}init(options){["mutationCb","blockClass","blockSelector","unblockSelector","maskAllText","maskTextClass","unmaskTextClass","maskTextSelector","unmaskTextSelector","inlineStylesheet","maskInputOptions","maskAttributeFn","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach((key=>{this[key]=options[key]}))}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function deepDelete(addsSet,n2){addsSet.delete(n2),n2.childNodes.forEach((childN=>deepDelete(addsSet,childN)))}function isParentRemoved(removes,n2,mirror2){return 0!==removes.length&&function(removes,n2,mirror2){let node=n2.parentNode;for(;node;){const parentId=mirror2.getId(node);if(removes.some((r2=>r2.id===parentId)))return!0;node=node.parentNode}return!1}(removes,n2,mirror2)}function isAncestorInSet(set,n2){return 0!==set.size&&_isAncestorInSet(set,n2)}function _isAncestorInSet(set,n2){const{parentNode:parentNode}=n2;return!!parentNode&&(!!set.has(parentNode)||_isAncestorInSet(set,parentNode))}let errorHandler;const callbackWrapper=cb=>{if(!errorHandler)return cb;return(...rest)=>{try{return cb(...rest)}catch(error){if(errorHandler&&!0===errorHandler(error))return()=>{};throw error}}},mutationBuffers=[];function esm_getEventTarget(event){try{if("composedPath"in event){const path=event.composedPath();if(path.length)return path[0]}else if("path"in event&&event.path.length)return event.path[0]}catch{}return event&&event.target}function initMutationObserver(options,rootEl){const mutationBuffer=new MutationBuffer;mutationBuffers.push(mutationBuffer),mutationBuffer.init(options);let mutationObserverCtor=window.MutationObserver||window.__rrMutationObserver;const angularZoneSymbol=window?.Zone?.__symbol__?.("MutationObserver");angularZoneSymbol&&window[angularZoneSymbol]&&(mutationObserverCtor=window[angularZoneSymbol]);const observer=new mutationObserverCtor(callbackWrapper((mutations=>{options.onMutation&&!1===options.onMutation(mutations)||mutationBuffer.processMutations.bind(mutationBuffer)(mutations)})));return observer.observe(rootEl,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),observer}function initMouseInteractionObserver({mouseInteractionCb:mouseInteractionCb,doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,sampling:sampling}){if(!1===sampling.mouseInteraction)return()=>{};const disableMap=!0===sampling.mouseInteraction||void 0===sampling.mouseInteraction?{}:sampling.mouseInteraction,handlers=[];let currentPointerType=null;return Object.keys(MouseInteractions).filter((key=>Number.isNaN(Number(key))&&!key.endsWith("_Departed")&&!1!==disableMap[key])).forEach((eventKey=>{let eventName=toLowerCase(eventKey);const handler=(eventKey=>event=>{const target=esm_getEventTarget(event);if(isBlocked(target,blockClass,blockSelector,unblockSelector,!0))return;let pointerType=null,thisEventKey=eventKey;if("pointerType"in event){switch(event.pointerType){case"mouse":pointerType=PointerTypes.Mouse;break;case"touch":pointerType=PointerTypes.Touch;break;case"pen":pointerType=PointerTypes.Pen}pointerType===PointerTypes.Touch?MouseInteractions[eventKey]===MouseInteractions.MouseDown?thisEventKey="TouchStart":MouseInteractions[eventKey]===MouseInteractions.MouseUp&&(thisEventKey="TouchEnd"):PointerTypes.Pen}else legacy_isTouchEvent(event)&&(pointerType=PointerTypes.Touch);null!==pointerType?(currentPointerType=pointerType,(thisEventKey.startsWith("Touch")&&pointerType===PointerTypes.Touch||thisEventKey.startsWith("Mouse")&&pointerType===PointerTypes.Mouse)&&(pointerType=null)):MouseInteractions[eventKey]===MouseInteractions.Click&&(pointerType=currentPointerType,currentPointerType=null);const e2=legacy_isTouchEvent(event)?event.changedTouches[0]:event;if(!e2)return;const id=mirror2.getId(target),{clientX:clientX,clientY:clientY}=e2;callbackWrapper(mouseInteractionCb)({type:MouseInteractions[thisEventKey],id:id,x:clientX,y:clientY,...null!==pointerType&&{pointerType:pointerType}})})(eventKey);if(window.PointerEvent)switch(MouseInteractions[eventKey]){case MouseInteractions.MouseDown:case MouseInteractions.MouseUp:eventName=eventName.replace("mouse","pointer");break;case MouseInteractions.TouchStart:case MouseInteractions.TouchEnd:return}handlers.push(on(eventName,handler,doc))})),callbackWrapper((()=>{handlers.forEach((h=>h()))}))}function initScrollObserver({scrollCb:scrollCb,doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,sampling:sampling}){return on("scroll",callbackWrapper(throttle$1(callbackWrapper((evt=>{const target=esm_getEventTarget(evt);if(!target||isBlocked(target,blockClass,blockSelector,unblockSelector,!0))return;const id=mirror2.getId(target);if(target===doc&&doc.defaultView){const scrollLeftTop=getWindowScroll(doc.defaultView);scrollCb({id:id,x:scrollLeftTop.left,y:scrollLeftTop.top})}else scrollCb({id:id,x:target.scrollLeft,y:target.scrollTop})})),sampling.scroll||100)),doc)}const INPUT_TAGS=["INPUT","TEXTAREA","SELECT"],lastInputValueMap=new WeakMap;function initInputObserver({inputCb:inputCb,doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,ignoreClass:ignoreClass,ignoreSelector:ignoreSelector,maskInputOptions:maskInputOptions,maskInputFn:maskInputFn,sampling:sampling,userTriggeredOnInput:userTriggeredOnInput,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector}){function eventHandler(event){let target=esm_getEventTarget(event);const userTriggered=event.isTrusted,tagName=target&&toUpperCase(target.tagName);if("OPTION"===tagName&&(target=target.parentElement),!target||!tagName||INPUT_TAGS.indexOf(tagName)<0||isBlocked(target,blockClass,blockSelector,unblockSelector,!0))return;const el=target;if(el.classList.contains(ignoreClass)||ignoreSelector&&el.matches(ignoreSelector))return;const type=getInputType(target);let text=getInputValue(el,tagName,type),isChecked=!1;const isInputMasked=shouldMaskInput({maskInputOptions:maskInputOptions,tagName:tagName,type:type}),forceMask=needMaskingText(target,maskTextClass,maskTextSelector,unmaskTextClass,unmaskTextSelector,isInputMasked);"radio"!==type&&"checkbox"!==type||(isChecked=target.checked),text=maskInputValue({isMasked:forceMask,element:target,value:text,maskInputFn:maskInputFn}),cbWithDedup(target,userTriggeredOnInput?{text:text,isChecked:isChecked,userTriggered:userTriggered}:{text:text,isChecked:isChecked});const name=target.name;"radio"===type&&name&&isChecked&&doc.querySelectorAll(`input[type="radio"][name="${name}"]`).forEach((el2=>{if(el2!==target){const text2=maskInputValue({isMasked:forceMask,element:el2,value:getInputValue(el2,tagName,type),maskInputFn:maskInputFn});cbWithDedup(el2,userTriggeredOnInput?{text:text2,isChecked:!isChecked,userTriggered:!1}:{text:text2,isChecked:!isChecked})}}))}function cbWithDedup(target,v2){const lastInputValue=lastInputValueMap.get(target);if(!lastInputValue||lastInputValue.text!==v2.text||lastInputValue.isChecked!==v2.isChecked){lastInputValueMap.set(target,v2);const id=mirror2.getId(target);callbackWrapper(inputCb)({...v2,id:id})}}const handlers=("last"===sampling.input?["change"]:["input","change"]).map((eventName=>on(eventName,callbackWrapper(eventHandler),doc))),currentWindow=doc.defaultView;if(!currentWindow)return()=>{handlers.forEach((h=>h()))};const propertyDescriptor=currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype,"value"),hookProperties=[[currentWindow.HTMLInputElement.prototype,"value"],[currentWindow.HTMLInputElement.prototype,"checked"],[currentWindow.HTMLSelectElement.prototype,"value"],[currentWindow.HTMLTextAreaElement.prototype,"value"],[currentWindow.HTMLSelectElement.prototype,"selectedIndex"],[currentWindow.HTMLOptionElement.prototype,"selected"]];return propertyDescriptor&&propertyDescriptor.set&&handlers.push(...hookProperties.map((p=>hookSetter(p[0],p[1],{set(){callbackWrapper(eventHandler)({target:this,isTrusted:!1})}},!1,currentWindow)))),callbackWrapper((()=>{handlers.forEach((h=>h()))}))}function getNestedCSSRulePositions(rule){return function(childRule,pos){if(hasNestedCSSRule("CSSGroupingRule")&&childRule.parentRule instanceof CSSGroupingRule||hasNestedCSSRule("CSSMediaRule")&&childRule.parentRule instanceof CSSMediaRule||hasNestedCSSRule("CSSSupportsRule")&&childRule.parentRule instanceof CSSSupportsRule||hasNestedCSSRule("CSSConditionRule")&&childRule.parentRule instanceof CSSConditionRule){const index=Array.from(childRule.parentRule.cssRules).indexOf(childRule);pos.unshift(index)}else if(childRule.parentStyleSheet){const index=Array.from(childRule.parentStyleSheet.cssRules).indexOf(childRule);pos.unshift(index)}return pos}(rule,[])}function getIdAndStyleId(sheet,mirror2,styleMirror){let id,styleId;return sheet?(sheet.ownerNode?id=mirror2.getId(sheet.ownerNode):styleId=styleMirror.getId(sheet),{styleId:styleId,id:id}):{}}function initAdoptedStyleSheetObserver({mirror:mirror2,stylesheetManager:stylesheetManager},host){let hostId=null;hostId="#document"===host.nodeName?mirror2.getId(host):mirror2.getId(host.host);const patchTarget="#document"===host.nodeName?host.defaultView?.Document:host.ownerDocument?.defaultView?.ShadowRoot,originalPropertyDescriptor=patchTarget?.prototype?Object.getOwnPropertyDescriptor(patchTarget?.prototype,"adoptedStyleSheets"):void 0;return null!==hostId&&-1!==hostId&&patchTarget&&originalPropertyDescriptor?(Object.defineProperty(host,"adoptedStyleSheets",{configurable:originalPropertyDescriptor.configurable,enumerable:originalPropertyDescriptor.enumerable,get(){return originalPropertyDescriptor.get?.call(this)},set(sheets){const result=originalPropertyDescriptor.set?.call(this,sheets);if(null!==hostId&&-1!==hostId)try{stylesheetManager.adoptStyleSheets(sheets,hostId)}catch(e2){}return result}}),callbackWrapper((()=>{Object.defineProperty(host,"adoptedStyleSheets",{configurable:originalPropertyDescriptor.configurable,enumerable:originalPropertyDescriptor.enumerable,get:originalPropertyDescriptor.get,set:originalPropertyDescriptor.set})}))):()=>{}}function initObservers(o2,_hooks={}){const currentWindow=o2.doc.defaultView;if(!currentWindow)return()=>{};let mutationObserver;o2.recordDOM&&(mutationObserver=initMutationObserver(o2,o2.doc));const mousemoveHandler=function({mousemoveCb:mousemoveCb,sampling:sampling,doc:doc,mirror:mirror2}){if(!1===sampling.mousemove)return()=>{};const threshold="number"==typeof sampling.mousemove?sampling.mousemove:50,callbackThreshold="number"==typeof sampling.mousemoveCallback?sampling.mousemoveCallback:500;let timeBaseline,positions=[];const wrappedCb=throttle$1(callbackWrapper((source=>{const totalOffset=Date.now()-timeBaseline;mousemoveCb(positions.map((p=>(p.timeOffset-=totalOffset,p))),source),positions=[],timeBaseline=null})),callbackThreshold),updatePosition=callbackWrapper(throttle$1(callbackWrapper((evt=>{const target=esm_getEventTarget(evt),{clientX:clientX,clientY:clientY}=legacy_isTouchEvent(evt)?evt.changedTouches[0]:evt;timeBaseline||(timeBaseline=nowTimestamp()),positions.push({x:clientX,y:clientY,id:mirror2.getId(target),timeOffset:nowTimestamp()-timeBaseline}),wrappedCb("undefined"!=typeof DragEvent&&evt instanceof DragEvent?IncrementalSource.Drag:evt instanceof MouseEvent?IncrementalSource.MouseMove:IncrementalSource.TouchMove)})),threshold,{trailing:!1})),handlers=[on("mousemove",updatePosition,doc),on("touchmove",updatePosition,doc),on("drag",updatePosition,doc)];return callbackWrapper((()=>{handlers.forEach((h=>h()))}))}(o2),mouseInteractionHandler=initMouseInteractionObserver(o2),scrollHandler=initScrollObserver(o2),viewportResizeHandler=function({viewportResizeCb:viewportResizeCb},{win:win}){let lastH=-1,lastW=-1;return on("resize",callbackWrapper(throttle$1(callbackWrapper((()=>{const height=getWindowHeight(),width=getWindowWidth();lastH===height&&lastW===width||(viewportResizeCb({width:Number(width),height:Number(height)}),lastH=height,lastW=width)})),200)),win)}(o2,{win:currentWindow}),inputHandler=initInputObserver(o2),mediaInteractionHandler=function({mediaInteractionCb:mediaInteractionCb,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,mirror:mirror2,sampling:sampling,doc:doc}){const handler=callbackWrapper((type=>throttle$1(callbackWrapper((event=>{const target=esm_getEventTarget(event);if(!target||isBlocked(target,blockClass,blockSelector,unblockSelector,!0))return;const{currentTime:currentTime,volume:volume,muted:muted,playbackRate:playbackRate}=target;mediaInteractionCb({type:type,id:mirror2.getId(target),currentTime:currentTime,volume:volume,muted:muted,playbackRate:playbackRate})})),sampling.media||500))),handlers=[on("play",handler(MediaInteractions.Play),doc),on("pause",handler(MediaInteractions.Pause),doc),on("seeked",handler(MediaInteractions.Seeked),doc),on("volumechange",handler(MediaInteractions.VolumeChange),doc),on("ratechange",handler(MediaInteractions.RateChange),doc)];return callbackWrapper((()=>{handlers.forEach((h=>h()))}))}(o2);let styleSheetObserver=()=>{},adoptedStyleSheetObserver=()=>{},styleDeclarationObserver=()=>{},fontObserver=()=>{};o2.recordDOM&&(styleSheetObserver=function({styleSheetRuleCb:styleSheetRuleCb,mirror:mirror2,stylesheetManager:stylesheetManager},{win:win}){if(!win.CSSStyleSheet||!win.CSSStyleSheet.prototype)return()=>{};const insertRule=win.CSSStyleSheet.prototype.insertRule;win.CSSStyleSheet.prototype.insertRule=new Proxy(insertRule,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[rule,index]=argumentsList,{id:id,styleId:styleId}=getIdAndStyleId(thisArg,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleSheetRuleCb({id:id,styleId:styleId,adds:[{rule:rule,index:index}]}),target.apply(thisArg,argumentsList)}))});const deleteRule=win.CSSStyleSheet.prototype.deleteRule;let replace,replaceSync;win.CSSStyleSheet.prototype.deleteRule=new Proxy(deleteRule,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[index]=argumentsList,{id:id,styleId:styleId}=getIdAndStyleId(thisArg,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleSheetRuleCb({id:id,styleId:styleId,removes:[{index:index}]}),target.apply(thisArg,argumentsList)}))}),win.CSSStyleSheet.prototype.replace&&(replace=win.CSSStyleSheet.prototype.replace,win.CSSStyleSheet.prototype.replace=new Proxy(replace,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[text]=argumentsList,{id:id,styleId:styleId}=getIdAndStyleId(thisArg,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleSheetRuleCb({id:id,styleId:styleId,replace:text}),target.apply(thisArg,argumentsList)}))})),win.CSSStyleSheet.prototype.replaceSync&&(replaceSync=win.CSSStyleSheet.prototype.replaceSync,win.CSSStyleSheet.prototype.replaceSync=new Proxy(replaceSync,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[text]=argumentsList,{id:id,styleId:styleId}=getIdAndStyleId(thisArg,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleSheetRuleCb({id:id,styleId:styleId,replaceSync:text}),target.apply(thisArg,argumentsList)}))}));const supportedNestedCSSRuleTypes={};canMonkeyPatchNestedCSSRule("CSSGroupingRule")?supportedNestedCSSRuleTypes.CSSGroupingRule=win.CSSGroupingRule:(canMonkeyPatchNestedCSSRule("CSSMediaRule")&&(supportedNestedCSSRuleTypes.CSSMediaRule=win.CSSMediaRule),canMonkeyPatchNestedCSSRule("CSSConditionRule")&&(supportedNestedCSSRuleTypes.CSSConditionRule=win.CSSConditionRule),canMonkeyPatchNestedCSSRule("CSSSupportsRule")&&(supportedNestedCSSRuleTypes.CSSSupportsRule=win.CSSSupportsRule));const unmodifiedFunctions={};return Object.entries(supportedNestedCSSRuleTypes).forEach((([typeKey,type])=>{unmodifiedFunctions[typeKey]={insertRule:type.prototype.insertRule,deleteRule:type.prototype.deleteRule},type.prototype.insertRule=new Proxy(unmodifiedFunctions[typeKey].insertRule,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[rule,index]=argumentsList,{id:id,styleId:styleId}=getIdAndStyleId(thisArg.parentStyleSheet,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleSheetRuleCb({id:id,styleId:styleId,adds:[{rule:rule,index:[...getNestedCSSRulePositions(thisArg),index||0]}]}),target.apply(thisArg,argumentsList)}))}),type.prototype.deleteRule=new Proxy(unmodifiedFunctions[typeKey].deleteRule,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[index]=argumentsList,{id:id,styleId:styleId}=getIdAndStyleId(thisArg.parentStyleSheet,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleSheetRuleCb({id:id,styleId:styleId,removes:[{index:[...getNestedCSSRulePositions(thisArg),index]}]}),target.apply(thisArg,argumentsList)}))})})),callbackWrapper((()=>{win.CSSStyleSheet.prototype.insertRule=insertRule,win.CSSStyleSheet.prototype.deleteRule=deleteRule,replace&&(win.CSSStyleSheet.prototype.replace=replace),replaceSync&&(win.CSSStyleSheet.prototype.replaceSync=replaceSync),Object.entries(supportedNestedCSSRuleTypes).forEach((([typeKey,type])=>{type.prototype.insertRule=unmodifiedFunctions[typeKey].insertRule,type.prototype.deleteRule=unmodifiedFunctions[typeKey].deleteRule}))}))}(o2,{win:currentWindow}),adoptedStyleSheetObserver=initAdoptedStyleSheetObserver(o2,o2.doc),styleDeclarationObserver=function({styleDeclarationCb:styleDeclarationCb,mirror:mirror2,ignoreCSSAttributes:ignoreCSSAttributes,stylesheetManager:stylesheetManager},{win:win}){const setProperty=win.CSSStyleDeclaration.prototype.setProperty;win.CSSStyleDeclaration.prototype.setProperty=new Proxy(setProperty,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[property,value,priority]=argumentsList;if(ignoreCSSAttributes.has(property))return setProperty.apply(thisArg,[property,value,priority]);const{id:id,styleId:styleId}=getIdAndStyleId(thisArg.parentRule?.parentStyleSheet,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleDeclarationCb({id:id,styleId:styleId,set:{property:property,value:value,priority:priority},index:getNestedCSSRulePositions(thisArg.parentRule)}),target.apply(thisArg,argumentsList)}))});const removeProperty=win.CSSStyleDeclaration.prototype.removeProperty;return win.CSSStyleDeclaration.prototype.removeProperty=new Proxy(removeProperty,{apply:callbackWrapper(((target,thisArg,argumentsList)=>{const[property]=argumentsList;if(ignoreCSSAttributes.has(property))return removeProperty.apply(thisArg,[property]);const{id:id,styleId:styleId}=getIdAndStyleId(thisArg.parentRule?.parentStyleSheet,mirror2,stylesheetManager.styleMirror);return(id&&-1!==id||styleId&&-1!==styleId)&&styleDeclarationCb({id:id,styleId:styleId,remove:{property:property},index:getNestedCSSRulePositions(thisArg.parentRule)}),target.apply(thisArg,argumentsList)}))}),callbackWrapper((()=>{win.CSSStyleDeclaration.prototype.setProperty=setProperty,win.CSSStyleDeclaration.prototype.removeProperty=removeProperty}))}(o2,{win:currentWindow}),o2.collectFonts&&(fontObserver=function({fontCb:fontCb,doc:doc}){const win=doc.defaultView;if(!win)return()=>{};const handlers=[],fontMap=new WeakMap,originalFontFace=win.FontFace;win.FontFace=function(family,source,descriptors){const fontFace=new originalFontFace(family,source,descriptors);return fontMap.set(fontFace,{family:family,buffer:"string"!=typeof source,descriptors:descriptors,fontSource:"string"==typeof source?source:JSON.stringify(Array.from(new Uint8Array(source)))}),fontFace};const restoreHandler=patch(doc.fonts,"add",(function(original){return function(fontFace){return setTimeout$1(callbackWrapper((()=>{const p=fontMap.get(fontFace);p&&(fontCb(p),fontMap.delete(fontFace))})),0),original.apply(this,[fontFace])}}));return handlers.push((()=>{win.FontFace=originalFontFace})),handlers.push(restoreHandler),callbackWrapper((()=>{handlers.forEach((h=>h()))}))}(o2)));const selectionObserver=function(param){const{doc:doc,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,selectionCb:selectionCb}=param;let collapsed=!0;const updateSelection=callbackWrapper((()=>{const selection=doc.getSelection();if(!selection||collapsed&&selection?.isCollapsed)return;collapsed=selection.isCollapsed||!1;const ranges=[],count=selection.rangeCount||0;for(let i2=0;i2<count;i2++){const range=selection.getRangeAt(i2),{startContainer:startContainer,startOffset:startOffset,endContainer:endContainer,endOffset:endOffset}=range;isBlocked(startContainer,blockClass,blockSelector,unblockSelector,!0)||isBlocked(endContainer,blockClass,blockSelector,unblockSelector,!0)||ranges.push({start:mirror2.getId(startContainer),startOffset:startOffset,end:mirror2.getId(endContainer),endOffset:endOffset})}selectionCb({ranges:ranges})}));return updateSelection(),on("selectionchange",updateSelection)}(o2),customElementObserver=function({doc:doc,customElementCb:customElementCb}){const win=doc.defaultView;return win&&win.customElements?patch(win.customElements,"define",(function(original){return function(name,constructor,options){try{customElementCb({define:{name:name}})}catch(e2){}return original.apply(this,[name,constructor,options])}})):()=>{}}(o2),pluginHandlers=[];for(const plugin of o2.plugins)pluginHandlers.push(plugin.observer(plugin.callback,currentWindow,plugin.options));return callbackWrapper((()=>{mutationBuffers.forEach((b=>b.reset())),mutationObserver?.disconnect(),mousemoveHandler(),mouseInteractionHandler(),scrollHandler(),viewportResizeHandler(),inputHandler(),mediaInteractionHandler(),styleSheetObserver(),adoptedStyleSheetObserver(),styleDeclarationObserver(),fontObserver(),selectionObserver(),customElementObserver(),pluginHandlers.forEach((h=>h()))}))}function hasNestedCSSRule(prop){return void 0!==window[prop]}function canMonkeyPatchNestedCSSRule(prop){return Boolean(void 0!==window[prop]&&window[prop].prototype&&"insertRule"in window[prop].prototype&&"deleteRule"in window[prop].prototype)}class CrossOriginIframeMirror{constructor(generateIdFn){this.generateIdFn=generateIdFn,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(iframe,remoteId,idToRemoteMap,remoteToIdMap){const idToRemoteIdMap=idToRemoteMap||this.getIdToRemoteIdMap(iframe),remoteIdToIdMap=remoteToIdMap||this.getRemoteIdToIdMap(iframe);let id=idToRemoteIdMap.get(remoteId);return id||(id=this.generateIdFn(),idToRemoteIdMap.set(remoteId,id),remoteIdToIdMap.set(id,remoteId)),id}getIds(iframe,remoteId){const idToRemoteIdMap=this.getIdToRemoteIdMap(iframe),remoteIdToIdMap=this.getRemoteIdToIdMap(iframe);return remoteId.map((id=>this.getId(iframe,id,idToRemoteIdMap,remoteIdToIdMap)))}getRemoteId(iframe,id,map){const remoteIdToIdMap=map||this.getRemoteIdToIdMap(iframe);if("number"!=typeof id)return id;const remoteId=remoteIdToIdMap.get(id);return remoteId||-1}getRemoteIds(iframe,ids){const remoteIdToIdMap=this.getRemoteIdToIdMap(iframe);return ids.map((id=>this.getRemoteId(iframe,id,remoteIdToIdMap)))}reset(iframe){if(!iframe)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(iframe),this.iframeRemoteIdToIdMap.delete(iframe)}getIdToRemoteIdMap(iframe){let idToRemoteIdMap=this.iframeIdToRemoteIdMap.get(iframe);return idToRemoteIdMap||(idToRemoteIdMap=new Map,this.iframeIdToRemoteIdMap.set(iframe,idToRemoteIdMap)),idToRemoteIdMap}getRemoteIdToIdMap(iframe){let remoteIdToIdMap=this.iframeRemoteIdToIdMap.get(iframe);return remoteIdToIdMap||(remoteIdToIdMap=new Map,this.iframeRemoteIdToIdMap.set(iframe,remoteIdToIdMap)),remoteIdToIdMap}}class IframeManagerNoop{constructor(){this.crossOriginIframeMirror=new CrossOriginIframeMirror(genId),this.crossOriginIframeRootIdMap=new WeakMap}addIframe(){}addLoadListener(){}attachIframe(){}}class IframeManager{constructor(options){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new CrossOriginIframeMirror(genId),this.crossOriginIframeRootIdMap=new WeakMap,this.mutationCb=options.mutationCb,this.wrappedEmit=options.wrappedEmit,this.stylesheetManager=options.stylesheetManager,this.recordCrossOriginIframes=options.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=options.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(iframeEl){this.iframes.set(iframeEl,!0),iframeEl.contentWindow&&this.crossOriginIframeMap.set(iframeEl.contentWindow,iframeEl)}addLoadListener(cb){this.loadListener=cb}attachIframe(iframeEl,childSn){this.mutationCb({adds:[{parentId:this.mirror.getId(iframeEl),nextId:null,node:childSn}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&iframeEl.contentWindow?.addEventListener("message",this.handleMessage.bind(this)),this.loadListener?.(iframeEl);const iframeDoc=getIFrameContentDocument(iframeEl);iframeDoc&&iframeDoc.adoptedStyleSheets&&iframeDoc.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(iframeDoc.adoptedStyleSheets,this.mirror.getId(iframeDoc))}handleMessage(message){const crossOriginMessageEvent=message;if("rrweb"!==crossOriginMessageEvent.data.type||crossOriginMessageEvent.origin!==crossOriginMessageEvent.data.origin)return;if(!message.source)return;const iframeEl=this.crossOriginIframeMap.get(message.source);if(!iframeEl)return;const transformedEvent=this.transformCrossOriginEvent(iframeEl,crossOriginMessageEvent.data.event);transformedEvent&&this.wrappedEmit(transformedEvent,crossOriginMessageEvent.data.isCheckout)}transformCrossOriginEvent(iframeEl,e2){switch(e2.type){case EventType.FullSnapshot:{this.crossOriginIframeMirror.reset(iframeEl),this.crossOriginIframeStyleMirror.reset(iframeEl),this.replaceIdOnNode(e2.data.node,iframeEl);const rootId=e2.data.node.id;return this.crossOriginIframeRootIdMap.set(iframeEl,rootId),this.patchRootIdOnNode(e2.data.node,rootId),{timestamp:e2.timestamp,type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.Mutation,adds:[{parentId:this.mirror.getId(iframeEl),nextId:null,node:e2.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case EventType.Meta:case EventType.Load:case EventType.DomContentLoaded:return!1;case EventType.Plugin:return e2;case EventType.Custom:return this.replaceIds(e2.data.payload,iframeEl,["id","parentId","previousId","nextId"]),e2;case EventType.IncrementalSnapshot:switch(e2.data.source){case IncrementalSource.Mutation:return e2.data.adds.forEach((n2=>{this.replaceIds(n2,iframeEl,["parentId","nextId","previousId"]),this.replaceIdOnNode(n2.node,iframeEl);const rootId=this.crossOriginIframeRootIdMap.get(iframeEl);rootId&&this.patchRootIdOnNode(n2.node,rootId)})),e2.data.removes.forEach((n2=>{this.replaceIds(n2,iframeEl,["parentId","id"])})),e2.data.attributes.forEach((n2=>{this.replaceIds(n2,iframeEl,["id"])})),e2.data.texts.forEach((n2=>{this.replaceIds(n2,iframeEl,["id"])})),e2;case IncrementalSource.Drag:case IncrementalSource.TouchMove:case IncrementalSource.MouseMove:return e2.data.positions.forEach((p=>{this.replaceIds(p,iframeEl,["id"])})),e2;case IncrementalSource.ViewportResize:return!1;case IncrementalSource.MediaInteraction:case IncrementalSource.MouseInteraction:case IncrementalSource.Scroll:case IncrementalSource.CanvasMutation:case IncrementalSource.Input:return this.replaceIds(e2.data,iframeEl,["id"]),e2;case IncrementalSource.StyleSheetRule:case IncrementalSource.StyleDeclaration:return this.replaceIds(e2.data,iframeEl,["id"]),this.replaceStyleIds(e2.data,iframeEl,["styleId"]),e2;case IncrementalSource.Font:return e2;case IncrementalSource.Selection:return e2.data.ranges.forEach((range=>{this.replaceIds(range,iframeEl,["start","end"])})),e2;case IncrementalSource.AdoptedStyleSheet:return this.replaceIds(e2.data,iframeEl,["id"]),this.replaceStyleIds(e2.data,iframeEl,["styleIds"]),e2.data.styles?.forEach((style=>{this.replaceStyleIds(style,iframeEl,["styleId"])})),e2}}return!1}replace(iframeMirror,obj,iframeEl,keys){for(const key of keys)(Array.isArray(obj[key])||"number"==typeof obj[key])&&(Array.isArray(obj[key])?obj[key]=iframeMirror.getIds(iframeEl,obj[key]):obj[key]=iframeMirror.getId(iframeEl,obj[key]));return obj}replaceIds(obj,iframeEl,keys){return this.replace(this.crossOriginIframeMirror,obj,iframeEl,keys)}replaceStyleIds(obj,iframeEl,keys){return this.replace(this.crossOriginIframeStyleMirror,obj,iframeEl,keys)}replaceIdOnNode(node,iframeEl){this.replaceIds(node,iframeEl,["id","rootId"]),"childNodes"in node&&node.childNodes.forEach((child=>{this.replaceIdOnNode(child,iframeEl)}))}patchRootIdOnNode(node,rootId){node.type===NodeType$2.Document||node.rootId||(node.rootId=rootId),"childNodes"in node&&node.childNodes.forEach((child=>{this.patchRootIdOnNode(child,rootId)}))}}class ShadowDomManagerNoop{init(){}addShadowRoot(){}observeAttachShadow(){}reset(){}}class ShadowDomManager{constructor(options){this.shadowDoms=new WeakSet,this.restoreHandlers=[],this.mutationCb=options.mutationCb,this.scrollCb=options.scrollCb,this.bypassOptions=options.bypassOptions,this.mirror=options.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(shadowRoot,doc){if(!isNativeShadowDom(shadowRoot))return;if(this.shadowDoms.has(shadowRoot))return;this.shadowDoms.add(shadowRoot),this.bypassOptions.canvasManager.addShadowRoot(shadowRoot);const observer=initMutationObserver({...this.bypassOptions,doc:doc,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},shadowRoot);this.restoreHandlers.push((()=>observer.disconnect())),this.restoreHandlers.push(initScrollObserver({...this.bypassOptions,scrollCb:this.scrollCb,doc:shadowRoot,mirror:this.mirror})),setTimeout$1((()=>{shadowRoot.adoptedStyleSheets&&shadowRoot.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets,this.mirror.getId(shadowRoot.host)),this.restoreHandlers.push(initAdoptedStyleSheetObserver({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},shadowRoot))}),0)}observeAttachShadow(iframeElement){const iframeDoc=getIFrameContentDocument(iframeElement),iframeWindow=function(iframe){try{return iframe.contentWindow}catch(e2){}}(iframeElement);iframeDoc&&iframeWindow&&this.patchAttachShadow(iframeWindow.Element,iframeDoc)}patchAttachShadow(element,doc){const manager=this;this.restoreHandlers.push(patch(element.prototype,"attachShadow",(function(original){return function(option){const shadowRoot=original.call(this,option);return this.shadowRoot&&inDom(this)&&manager.addShadowRoot(this.shadowRoot,doc),shadowRoot}})))}reset(){this.restoreHandlers.forEach((handler=>{try{handler()}catch(e2){}})),this.restoreHandlers=[],this.shadowDoms=new WeakSet,this.bypassOptions.canvasManager.resetShadowRoots()}}for(var chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup="undefined"==typeof Uint8Array?[]:new Uint8Array(256),i$1=0;i$1<64;i$1++)lookup[chars.charCodeAt(i$1)]=i$1;class CanvasManagerNoop{reset(){}freeze(){}unfreeze(){}lock(){}unlock(){}snapshot(){}addWindow(){}addShadowRoot(){}resetShadowRoots(){}}class StylesheetManager{constructor(options){this.trackedLinkElements=new WeakSet,this.styleMirror=new StyleSheetMirror,this.mutationCb=options.mutationCb,this.adoptedStyleSheetCb=options.adoptedStyleSheetCb}attachLinkElement(linkEl,childSn){"_cssText"in childSn.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:childSn.id,attributes:childSn.attributes}]}),this.trackLinkElement(linkEl)}trackLinkElement(linkEl){this.trackedLinkElements.has(linkEl)||(this.trackedLinkElements.add(linkEl),this.trackStylesheetInLinkElement(linkEl))}adoptStyleSheets(sheets,hostId){if(0===sheets.length)return;const adoptedStyleSheetData={id:hostId,styleIds:[]},styles=[];for(const sheet of sheets){let styleId;this.styleMirror.has(sheet)?styleId=this.styleMirror.getId(sheet):(styleId=this.styleMirror.add(sheet),styles.push({styleId:styleId,rules:Array.from(sheet.rules||CSSRule,((r2,index)=>({rule:stringifyRule(r2),index:index})))})),adoptedStyleSheetData.styleIds.push(styleId)}styles.length>0&&(adoptedStyleSheetData.styles=styles),this.adoptedStyleSheetCb(adoptedStyleSheetData)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(_linkEl){}}class ProcessedNodeManager{constructor(){this.nodeMap=new WeakMap,this.active=!1}inOtherBuffer(node,thisBuffer){const buffers=this.nodeMap.get(node);return buffers&&Array.from(buffers).some((buffer=>buffer!==thisBuffer))}add(node,buffer){this.active||(this.active=!0,function(...rest){getImplementation("requestAnimationFrame")(...rest)}((()=>{this.nodeMap=new WeakMap,this.active=!1}))),this.nodeMap.set(node,(this.nodeMap.get(node)||new Set).add(buffer))}destroy(){}}let wrappedEmit,_takeFullSnapshot;try{if(2!==Array.from([1],(x=>2*x))[0]){const cleanFrame=document.createElement("iframe");document.body.appendChild(cleanFrame),Array.from=cleanFrame.contentWindow?.Array.from||Array.from,document.body.removeChild(cleanFrame)}}catch(err){console.debug("Unable to override Array.from",err)}const mirror=new Mirror;function record(options={}){const{emit:emit,checkoutEveryNms:checkoutEveryNms,checkoutEveryNth:checkoutEveryNth,blockClass:blockClass="rr-block",blockSelector:blockSelector=null,unblockSelector:unblockSelector=null,ignoreClass:ignoreClass="rr-ignore",ignoreSelector:ignoreSelector=null,maskAllText:maskAllText=!1,maskTextClass:maskTextClass="rr-mask",unmaskTextClass:unmaskTextClass=null,maskTextSelector:maskTextSelector=null,unmaskTextSelector:unmaskTextSelector=null,inlineStylesheet:inlineStylesheet=!0,maskAllInputs:maskAllInputs,maskInputOptions:_maskInputOptions,slimDOMOptions:_slimDOMOptions,maskAttributeFn:maskAttributeFn,maskInputFn:maskInputFn,maskTextFn:maskTextFn,maxCanvasSize:maxCanvasSize=null,packFn:packFn,sampling:sampling={},dataURLOptions:dataURLOptions={},mousemoveWait:mousemoveWait,recordDOM:recordDOM=!0,recordCanvas:recordCanvas=!1,recordCrossOriginIframes:recordCrossOriginIframes=!1,recordAfter:recordAfter=("DOMContentLoaded"===options.recordAfter?options.recordAfter:"load"),userTriggeredOnInput:userTriggeredOnInput=!1,collectFonts:collectFonts=!1,inlineImages:inlineImages=!1,plugins:plugins,keepIframeSrcFn:keepIframeSrcFn=()=>!1,ignoreCSSAttributes:ignoreCSSAttributes=new Set([]),errorHandler:errorHandler2,onMutation:onMutation,getCanvasManager:getCanvasManager}=options;errorHandler=errorHandler2;const inEmittingFrame=!recordCrossOriginIframes||window.parent===window;let passEmitsToParent=!1;if(!inEmittingFrame)try{window.parent.document&&(passEmitsToParent=!1)}catch(e2){passEmitsToParent=!0}if(inEmittingFrame&&!emit)throw new Error("emit function is required");if(!inEmittingFrame&&!passEmitsToParent)return()=>{};void 0!==mousemoveWait&&void 0===sampling.mousemove&&(sampling.mousemove=mousemoveWait),mirror.reset();const maskInputOptions=!0===maskAllInputs?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,radio:!0,checkbox:!0}:void 0!==_maskInputOptions?_maskInputOptions:{},slimDOMOptions=!0===_slimDOMOptions||"all"===_slimDOMOptions?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===_slimDOMOptions,headMetaDescKeywords:"all"===_slimDOMOptions}:_slimDOMOptions||{};let lastFullSnapshotEvent;!function(win=window){"NodeList"in win&&!win.NodeList.prototype.forEach&&(win.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in win&&!win.DOMTokenList.prototype.forEach&&(win.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...args)=>{let node=args[0];if(!(0 in args))throw new TypeError("1 argument is required");do{if(this===node)return!0}while(node=node&&node.parentNode);return!1})}();let incrementalSnapshotCount=0;const eventProcessor=e2=>{for(const plugin of plugins||[])plugin.eventProcessor&&(e2=plugin.eventProcessor(e2));return packFn&&!passEmitsToParent&&(e2=packFn(e2)),e2};wrappedEmit=(r2,isCheckout)=>{const e2=r2;if(e2.timestamp=nowTimestamp(),!mutationBuffers[0]?.isFrozen()||e2.type===EventType.FullSnapshot||e2.type===EventType.IncrementalSnapshot&&e2.data.source===IncrementalSource.Mutation||mutationBuffers.forEach((buf=>buf.unfreeze())),inEmittingFrame)emit?.(eventProcessor(e2),isCheckout);else if(passEmitsToParent){const message={type:"rrweb",event:eventProcessor(e2),origin:window.location.origin,isCheckout:isCheckout};window.parent.postMessage(message,"*")}if(e2.type===EventType.FullSnapshot)lastFullSnapshotEvent=e2,incrementalSnapshotCount=0;else if(e2.type===EventType.IncrementalSnapshot){if(e2.data.source===IncrementalSource.Mutation&&e2.data.isAttachIframe)return;incrementalSnapshotCount++;const exceedCount=checkoutEveryNth&&incrementalSnapshotCount>=checkoutEveryNth,exceedTime=checkoutEveryNms&&lastFullSnapshotEvent&&e2.timestamp-lastFullSnapshotEvent.timestamp>checkoutEveryNms;(exceedCount||exceedTime)&&takeFullSnapshot2(!0)}};const wrappedMutationEmit=m=>{wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.Mutation,...m}})},wrappedScrollEmit=p=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.Scroll,...p}}),wrappedCanvasMutationEmit=p=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.CanvasMutation,...p}}),stylesheetManager=new StylesheetManager({mutationCb:wrappedMutationEmit,adoptedStyleSheetCb:a2=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.AdoptedStyleSheet,...a2}})}),iframeManager="boolean"==typeof __RRWEB_EXCLUDE_IFRAME__&&__RRWEB_EXCLUDE_IFRAME__?new IframeManagerNoop:new IframeManager({mirror:mirror,mutationCb:wrappedMutationEmit,stylesheetManager:stylesheetManager,recordCrossOriginIframes:recordCrossOriginIframes,wrappedEmit:wrappedEmit});for(const plugin of plugins||[])plugin.getMirror&&plugin.getMirror({nodeMirror:mirror,crossOriginIframeMirror:iframeManager.crossOriginIframeMirror,crossOriginIframeStyleMirror:iframeManager.crossOriginIframeStyleMirror});const processedNodeManager=new ProcessedNodeManager,canvasManager=function(getCanvasManagerFn,options){try{return getCanvasManagerFn?getCanvasManagerFn(options):new CanvasManagerNoop}catch{return console.warn("Unable to initialize CanvasManager"),new CanvasManagerNoop}}(getCanvasManager,{mirror:mirror,win:window,mutationCb:p=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.CanvasMutation,...p}}),recordCanvas:recordCanvas,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maxCanvasSize:maxCanvasSize,sampling:sampling.canvas,dataURLOptions:dataURLOptions,errorHandler:errorHandler2}),shadowDomManager="boolean"==typeof __RRWEB_EXCLUDE_SHADOW_DOM__&&__RRWEB_EXCLUDE_SHADOW_DOM__?new ShadowDomManagerNoop:new ShadowDomManager({mutationCb:wrappedMutationEmit,scrollCb:wrappedScrollEmit,bypassOptions:{onMutation:onMutation,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,inlineStylesheet:inlineStylesheet,maskInputOptions:maskInputOptions,dataURLOptions:dataURLOptions,maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,recordCanvas:recordCanvas,inlineImages:inlineImages,sampling:sampling,slimDOMOptions:slimDOMOptions,iframeManager:iframeManager,stylesheetManager:stylesheetManager,canvasManager:canvasManager,keepIframeSrcFn:keepIframeSrcFn,processedNodeManager:processedNodeManager},mirror:mirror}),takeFullSnapshot2=(isCheckout=!1)=>{if(!recordDOM)return;wrappedEmit({type:EventType.Meta,data:{href:window.location.href,width:getWindowWidth(),height:getWindowHeight()}},isCheckout),stylesheetManager.reset(),shadowDomManager.init(),mutationBuffers.forEach((buf=>buf.lock()));const node=function(n2,options){const{mirror:mirror2=new Mirror,blockClass:blockClass="rr-block",blockSelector:blockSelector=null,unblockSelector:unblockSelector=null,maskAllText:maskAllText=!1,maskTextClass:maskTextClass="rr-mask",unmaskTextClass:unmaskTextClass=null,maskTextSelector:maskTextSelector=null,unmaskTextSelector:unmaskTextSelector=null,inlineStylesheet:inlineStylesheet=!0,inlineImages:inlineImages=!1,recordCanvas:recordCanvas=!1,maskAllInputs:maskAllInputs=!1,maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,slimDOM:slimDOM=!1,dataURLOptions:dataURLOptions,preserveWhiteSpace:preserveWhiteSpace,onSerialize:onSerialize,onIframeLoad:onIframeLoad,iframeLoadTimeout:iframeLoadTimeout,onStylesheetLoad:onStylesheetLoad,stylesheetLoadTimeout:stylesheetLoadTimeout,keepIframeSrcFn:keepIframeSrcFn=()=>!1}=options||{};return serializeNodeWithId(n2,{doc:n2,mirror:mirror2,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,skipChild:!1,inlineStylesheet:inlineStylesheet,maskInputOptions:!0===maskAllInputs?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0}:!1===maskAllInputs?{}:maskAllInputs,maskAttributeFn:maskAttributeFn,maskTextFn:maskTextFn,maskInputFn:maskInputFn,slimDOMOptions:!0===slimDOM||"all"===slimDOM?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===slimDOM,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===slimDOM?{}:slimDOM,dataURLOptions:dataURLOptions,inlineImages:inlineImages,recordCanvas:recordCanvas,preserveWhiteSpace:preserveWhiteSpace,onSerialize:onSerialize,onIframeLoad:onIframeLoad,iframeLoadTimeout:iframeLoadTimeout,onStylesheetLoad:onStylesheetLoad,stylesheetLoadTimeout:stylesheetLoadTimeout,keepIframeSrcFn:keepIframeSrcFn,newlyAddedElement:!1})}(document,{mirror:mirror,blockClass:blockClass,blockSelector:blockSelector,unblockSelector:unblockSelector,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,inlineStylesheet:inlineStylesheet,maskAllInputs:maskInputOptions,maskAttributeFn:maskAttributeFn,maskInputFn:maskInputFn,maskTextFn:maskTextFn,slimDOM:slimDOMOptions,dataURLOptions:dataURLOptions,recordCanvas:recordCanvas,inlineImages:inlineImages,onSerialize:n2=>{isSerializedIframe(n2,mirror)&&iframeManager.addIframe(n2),isSerializedStylesheet(n2,mirror)&&stylesheetManager.trackLinkElement(n2),hasShadowRoot(n2)&&shadowDomManager.addShadowRoot(n2.shadowRoot,document)},onIframeLoad:(iframe,childSn)=>{iframeManager.attachIframe(iframe,childSn),iframe.contentWindow&&canvasManager.addWindow(iframe.contentWindow),shadowDomManager.observeAttachShadow(iframe)},onStylesheetLoad:(linkEl,childSn)=>{stylesheetManager.attachLinkElement(linkEl,childSn)},keepIframeSrcFn:keepIframeSrcFn});if(!node)return console.warn("Failed to snapshot the document");wrappedEmit({type:EventType.FullSnapshot,data:{node:node,initialOffset:getWindowScroll(window)}}),mutationBuffers.forEach((buf=>buf.unlock())),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets,mirror.getId(document))};_takeFullSnapshot=takeFullSnapshot2;try{const handlers=[],observe=doc=>callbackWrapper(initObservers)({onMutation:onMutation,mutationCb:wrappedMutationEmit,mousemoveCb:(positions,source)=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:source,positions:positions}}),mouseInteractionCb:d=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.MouseInteraction,...d}}),scrollCb:wrappedScrollEmit,viewportResizeCb:d=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.ViewportResize,...d}}),inputCb:v2=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.Input,...v2}}),mediaInteractionCb:p=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.MediaInteraction,...p}}),styleSheetRuleCb:r2=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.StyleSheetRule,...r2}}),styleDeclarationCb:r2=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.StyleDeclaration,...r2}}),canvasMutationCb:wrappedCanvasMutationEmit,fontCb:p=>wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.Font,...p}}),selectionCb:p=>{wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.Selection,...p}})},customElementCb:c2=>{wrappedEmit({type:EventType.IncrementalSnapshot,data:{source:IncrementalSource.CustomElement,...c2}})},blockClass:blockClass,ignoreClass:ignoreClass,ignoreSelector:ignoreSelector,maskAllText:maskAllText,maskTextClass:maskTextClass,unmaskTextClass:unmaskTextClass,maskTextSelector:maskTextSelector,unmaskTextSelector:unmaskTextSelector,maskInputOptions:maskInputOptions,inlineStylesheet:inlineStylesheet,sampling:sampling,recordDOM:recordDOM,recordCanvas:recordCanvas,inlineImages:inlineImages,userTriggeredOnInput:userTriggeredOnInput,collectFonts:collectFonts,doc:doc,maskAttributeFn:maskAttributeFn,maskInputFn:maskInputFn,maskTextFn:maskTextFn,keepIframeSrcFn:keepIframeSrcFn,blockSelector:blockSelector,unblockSelector:unblockSelector,slimDOMOptions:slimDOMOptions,dataURLOptions:dataURLOptions,mirror:mirror,iframeManager:iframeManager,stylesheetManager:stylesheetManager,shadowDomManager:shadowDomManager,processedNodeManager:processedNodeManager,canvasManager:canvasManager,ignoreCSSAttributes:ignoreCSSAttributes,plugins:plugins?.filter((p=>p.observer))?.map((p=>({observer:p.observer,options:p.options,callback:payload=>wrappedEmit({type:EventType.Plugin,data:{plugin:p.name,payload:payload}})})))||[]},{});iframeManager.addLoadListener((iframeEl=>{try{handlers.push(observe(iframeEl.contentDocument))}catch(error){console.warn(error)}}));const init=()=>{takeFullSnapshot2(),handlers.push(observe(document))};return"interactive"===document.readyState||"complete"===document.readyState?init():(handlers.push(on("DOMContentLoaded",(()=>{wrappedEmit({type:EventType.DomContentLoaded,data:{}}),"DOMContentLoaded"===recordAfter&&init()}))),handlers.push(on("load",(()=>{wrappedEmit({type:EventType.Load,data:{}}),"load"===recordAfter&&init()}),window))),()=>{handlers.forEach((h=>h())),processedNodeManager.destroy(),_takeFullSnapshot=void 0,errorHandler=void 0}}catch(error){console.warn(error)}}var n,t2;record.mirror=mirror,record.takeFullSnapshot=function(isCheckout){if(!_takeFullSnapshot)throw new Error("please take full snapshot after start recording");_takeFullSnapshot(isCheckout)},(t2=n||(n={}))[t2.NotStarted=0]="NotStarted",t2[t2.Running=1]="Running",t2[t2.Stopped=2]="Stopped";function timestampToMs(timestamp){return timestamp>9999999999?timestamp:1e3*timestamp}function timestampToS(timestamp){return timestamp>9999999999?timestamp/1e3:timestamp}function addBreadcrumbEvent(replay,breadcrumb){"sentry.transaction"!==breadcrumb.category&&(["ui.click","ui.input"].includes(breadcrumb.category)?replay.triggerUserActivity():replay.checkAndHandleExpiredSession(),replay.addUpdate((()=>(replay.throttledAddEvent({type:EventType.Custom,timestamp:1e3*(breadcrumb.timestamp||0),data:{tag:"breadcrumb",payload:normalize(breadcrumb,10,1e3)}}),"console"===breadcrumb.category))))}function getClosestInteractive(element){return element.closest("button,a")||element}function getClickTargetNode(event){const target=getTargetNode(event);return target&&target instanceof Element?getClosestInteractive(target):target}function getTargetNode(event){return function(event){return"object"==typeof event&&!!event&&"target"in event}(event)?event.target:event}let esm_handlers;function onWindowOpen(cb){return esm_handlers||(esm_handlers=[],fill(esm_WINDOW,"open",(function(originalWindowOpen){return function(...args){if(esm_handlers)try{esm_handlers.forEach((handler=>handler()))}catch(e){}return originalWindowOpen.apply(esm_WINDOW,args)}}))),esm_handlers.push(cb),()=>{const pos=esm_handlers?esm_handlers.indexOf(cb):-1;pos>-1&&esm_handlers.splice(pos,1)}}const IncrementalMutationSources=new Set([IncrementalSource.Mutation,IncrementalSource.StyleSheetRule,IncrementalSource.StyleDeclaration,IncrementalSource.AdoptedStyleSheet,IncrementalSource.CanvasMutation,IncrementalSource.Selection,IncrementalSource.MediaInteraction]);class ClickDetector{constructor(replay,slowClickConfig,_addBreadcrumbEvent=addBreadcrumbEvent){this._lastMutation=0,this._lastScroll=0,this._clicks=[],this._timeout=slowClickConfig.timeout/1e3,this._threshold=slowClickConfig.threshold/1e3,this._scrollTimeout=slowClickConfig.scrollTimeout/1e3,this._replay=replay,this._ignoreSelector=slowClickConfig.ignoreSelector,this._addBreadcrumbEvent=_addBreadcrumbEvent}addListeners(){const cleanupWindowOpen=onWindowOpen((()=>{this._lastMutation=nowInSeconds()}));this._teardown=()=>{cleanupWindowOpen(),this._clicks=[],this._lastMutation=0,this._lastScroll=0}}removeListeners(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)}handleClick(breadcrumb,node){if(function(node,ignoreSelector){if(!SLOW_CLICK_TAGS.includes(node.tagName))return!0;if("INPUT"===node.tagName&&!["submit","button"].includes(node.getAttribute("type")||""))return!0;if("A"===node.tagName&&(node.hasAttribute("download")||node.hasAttribute("target")&&"_self"!==node.getAttribute("target")))return!0;if(ignoreSelector&&node.matches(ignoreSelector))return!0;return!1}(node,this._ignoreSelector)||!function(breadcrumb){return!(!breadcrumb.data||"number"!=typeof breadcrumb.data.nodeId||!breadcrumb.timestamp)}(breadcrumb))return;const newClick={timestamp:timestampToS(breadcrumb.timestamp),clickBreadcrumb:breadcrumb,clickCount:0,node:node};this._clicks.some((click=>click.node===newClick.node&&Math.abs(click.timestamp-newClick.timestamp)<1))||(this._clicks.push(newClick),1===this._clicks.length&&this._scheduleCheckClicks())}registerMutation(timestamp=Date.now()){this._lastMutation=timestampToS(timestamp)}registerScroll(timestamp=Date.now()){this._lastScroll=timestampToS(timestamp)}registerClick(element){const node=getClosestInteractive(element);this._handleMultiClick(node)}_handleMultiClick(node){this._getClicks(node).forEach((click=>{click.clickCount++}))}_getClicks(node){return this._clicks.filter((click=>click.node===node))}_checkClicks(){const timedOutClicks=[],now=nowInSeconds();this._clicks.forEach((click=>{!click.mutationAfter&&this._lastMutation&&(click.mutationAfter=click.timestamp<=this._lastMutation?this._lastMutation-click.timestamp:void 0),!click.scrollAfter&&this._lastScroll&&(click.scrollAfter=click.timestamp<=this._lastScroll?this._lastScroll-click.timestamp:void 0),click.timestamp+this._timeout<=now&&timedOutClicks.push(click)}));for(const click of timedOutClicks){const pos=this._clicks.indexOf(click);pos>-1&&(this._generateBreadcrumbs(click),this._clicks.splice(pos,1))}this._clicks.length&&this._scheduleCheckClicks()}_generateBreadcrumbs(click){const replay=this._replay,hadScroll=click.scrollAfter&&click.scrollAfter<=this._scrollTimeout,hadMutation=click.mutationAfter&&click.mutationAfter<=this._threshold,isSlowClick=!hadScroll&&!hadMutation,{clickCount:clickCount,clickBreadcrumb:clickBreadcrumb}=click;if(isSlowClick){const timeAfterClickMs=1e3*Math.min(click.mutationAfter||this._timeout,this._timeout),endReason=timeAfterClickMs<1e3*this._timeout?"mutation":"timeout",breadcrumb={type:"default",message:clickBreadcrumb.message,timestamp:clickBreadcrumb.timestamp,category:"ui.slowClickDetected",data:{...clickBreadcrumb.data,url:esm_WINDOW.location.href,route:replay.getCurrentRoute(),timeAfterClickMs:timeAfterClickMs,endReason:endReason,clickCount:clickCount||1}};this._addBreadcrumbEvent(replay,breadcrumb)}else if(clickCount>1){const breadcrumb={type:"default",message:clickBreadcrumb.message,timestamp:clickBreadcrumb.timestamp,category:"ui.multiClick",data:{...clickBreadcrumb.data,url:esm_WINDOW.location.href,route:replay.getCurrentRoute(),clickCount:clickCount,metric:!0}};this._addBreadcrumbEvent(replay,breadcrumb)}}_scheduleCheckClicks(){this._checkClickTimeout&&clearTimeout(this._checkClickTimeout),this._checkClickTimeout=getNativeImplementation_setTimeout((()=>this._checkClicks()),1e3)}}const SLOW_CLICK_TAGS=["A","BUTTON","INPUT"];function nowInSeconds(){return Date.now()/1e3}function updateClickDetectorForRecordingEvent(clickDetector,event){try{if(!function(event){return 3===event.type}(event))return;const{source:source}=event.data;if(IncrementalMutationSources.has(source)&&clickDetector.registerMutation(event.timestamp),source===IncrementalSource.Scroll&&clickDetector.registerScroll(event.timestamp),function(event){return event.data.source===IncrementalSource.MouseInteraction}(event)){const{type:type,id:id}=event.data,node=record.mirror.getNode(id);node instanceof HTMLElement&&type===MouseInteractions.Click&&clickDetector.registerClick(node)}}catch{}}function createBreadcrumb(breadcrumb){return{timestamp:Date.now()/1e3,type:"default",...breadcrumb}}var NodeType=(NodeType2=>(NodeType2[NodeType2.Document=0]="Document",NodeType2[NodeType2.DocumentType=1]="DocumentType",NodeType2[NodeType2.Element=2]="Element",NodeType2[NodeType2.Text=3]="Text",NodeType2[NodeType2.CDATA=4]="CDATA",NodeType2[NodeType2.Comment=5]="Comment",NodeType2))(NodeType||{});const ATTRIBUTES_TO_RECORD=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled","data-sentry-component"]);function getAttributesToRecord(attributes){const obj={};!attributes["data-sentry-component"]&&attributes["data-sentry-element"]&&(attributes["data-sentry-component"]=attributes["data-sentry-element"]);for(const key in attributes)if(ATTRIBUTES_TO_RECORD.has(key)){let normalizedKey=key;"data-testid"!==key&&"data-test-id"!==key||(normalizedKey="testId"),obj[normalizedKey]=attributes[key]}return obj}const handleDomListener=replay=>handlerData=>{if(!replay.isEnabled())return;const result=function(handlerData){const{target:target,message:message}=function(handlerData){const isClick="click"===handlerData.name;let message,target=null;try{target=isClick?getClickTargetNode(handlerData.event):getTargetNode(handlerData.event),message=htmlTreeAsString(target,{maxStringLength:200})||"<unknown>"}catch(e){message="<unknown>"}return{target:target,message:message}}(handlerData);return createBreadcrumb({category:`ui.${handlerData.name}`,...getBaseDomBreadcrumb(target,message)})}(handlerData);if(!result)return;const isClick="click"===handlerData.name,event=isClick?handlerData.event:void 0;var clickDetector,clickBreadcrumb,node;!(isClick&&replay.clickDetector&&event&&event.target)||event.altKey||event.metaKey||event.ctrlKey||event.shiftKey||(clickDetector=replay.clickDetector,clickBreadcrumb=result,node=getClickTargetNode(handlerData.event),clickDetector.handleClick(clickBreadcrumb,node)),addBreadcrumbEvent(replay,result)};function getBaseDomBreadcrumb(target,message){const nodeId=record.mirror.getId(target),node=nodeId&&record.mirror.getNode(nodeId),meta=node&&record.mirror.getMeta(node),element=meta&&function(node){return node.type===NodeType.Element}(meta)?meta:null;return{message:message,data:element?{nodeId:nodeId,node:{id:nodeId,tagName:element.tagName,textContent:Array.from(element.childNodes).map((node=>node.type===NodeType.Text&&node.textContent)).filter(Boolean).map((text=>text.trim())).join(""),attributes:getAttributesToRecord(element.attributes)}}:{}}}function handleKeyboardEvent(replay,event){if(!replay.isEnabled())return;replay.updateUserActivity();const breadcrumb=function(event){const{metaKey:metaKey,shiftKey:shiftKey,ctrlKey:ctrlKey,altKey:altKey,key:key,target:target}=event;if(!target||function(target){return"INPUT"===target.tagName||"TEXTAREA"===target.tagName||target.isContentEditable}(target)||!key)return null;const hasModifierKey=metaKey||ctrlKey||altKey,isCharacterKey=1===key.length;if(!hasModifierKey&&isCharacterKey)return null;const message=htmlTreeAsString(target,{maxStringLength:200})||"<unknown>",baseBreadcrumb=getBaseDomBreadcrumb(target,message);return createBreadcrumb({category:"ui.keyDown",message:message,data:{...baseBreadcrumb.data,metaKey:metaKey,shiftKey:shiftKey,ctrlKey:ctrlKey,altKey:altKey,key:key}})}(event);breadcrumb&&addBreadcrumbEvent(replay,breadcrumb)}const ENTRY_TYPES={resource:function(entry){const{entryType:entryType,initiatorType:initiatorType,name:name,responseEnd:responseEnd,startTime:startTime,decodedBodySize:decodedBodySize,encodedBodySize:encodedBodySize,responseStatus:responseStatus,transferSize:transferSize}=entry;if(["fetch","xmlhttprequest"].includes(initiatorType))return null;return{type:`${entryType}.${initiatorType}`,start:getAbsoluteTime(startTime),end:getAbsoluteTime(responseEnd),name:name,data:{size:transferSize,statusCode:responseStatus,decodedBodySize:decodedBodySize,encodedBodySize:encodedBodySize}}},paint:function(entry){const{duration:duration,entryType:entryType,name:name,startTime:startTime}=entry,start=getAbsoluteTime(startTime);return{type:entryType,name:name,start:start,end:start+duration,data:void 0}},navigation:function(entry){const{entryType:entryType,name:name,decodedBodySize:decodedBodySize,duration:duration,domComplete:domComplete,encodedBodySize:encodedBodySize,domContentLoadedEventStart:domContentLoadedEventStart,domContentLoadedEventEnd:domContentLoadedEventEnd,domInteractive:domInteractive,loadEventStart:loadEventStart,loadEventEnd:loadEventEnd,redirectCount:redirectCount,startTime:startTime,transferSize:transferSize,type:type}=entry;if(0===duration)return null;return{type:`${entryType}.${type}`,start:getAbsoluteTime(startTime),end:getAbsoluteTime(domComplete),name:name,data:{size:transferSize,decodedBodySize:decodedBodySize,encodedBodySize:encodedBodySize,duration:duration,domInteractive:domInteractive,domContentLoadedEventStart:domContentLoadedEventStart,domContentLoadedEventEnd:domContentLoadedEventEnd,loadEventStart:loadEventStart,loadEventEnd:loadEventEnd,domComplete:domComplete,redirectCount:redirectCount}}}};function webVitalHandler(getter,replay){return({metric:metric})=>{replay.replayPerformanceEntries.push(getter(metric))}}function createPerformanceEntry(entry){const entryType=ENTRY_TYPES[entry.entryType];return entryType?entryType(entry):null}function getAbsoluteTime(time){return((browserPerformanceTimeOrigin()||esm_WINDOW.performance.timeOrigin)+time)/1e3}function getLargestContentfulPaint(metric){const lastEntry=metric.entries[metric.entries.length-1];return getWebVital(metric,"largest-contentful-paint",lastEntry?.element?[lastEntry.element]:void 0)}function isLayoutShift(entry){return void 0!==entry.sources}function getCumulativeLayoutShift(metric){const layoutShifts=[],nodes=[];for(const entry of metric.entries)if(isLayoutShift(entry)){const nodeIds=[];for(const source of entry.sources)if(source.node){nodes.push(source.node);const nodeId=record.mirror.getId(source.node);nodeId&&nodeIds.push(nodeId)}layoutShifts.push({value:entry.value,nodeIds:nodeIds.length?nodeIds:void 0})}return getWebVital(metric,"cumulative-layout-shift",nodes,layoutShifts)}function getFirstInputDelay(metric){const lastEntry=metric.entries[metric.entries.length-1];return getWebVital(metric,"first-input-delay",lastEntry?.target?[lastEntry.target]:void 0)}function getInteractionToNextPaint(metric){const lastEntry=metric.entries[metric.entries.length-1];return getWebVital(metric,"interaction-to-next-paint",lastEntry?.target?[lastEntry.target]:void 0)}function getWebVital(metric,name,nodes,attributions){const value=metric.value,rating=metric.rating,end=getAbsoluteTime(value);return{type:"web-vital",name:name,start:end,end:end,data:{value:value,size:value,rating:rating,nodeIds:nodes?nodes.map((node=>record.mirror.getId(node))):void 0,attributions:attributions}}}function setupPerformanceObserver(replay){function addPerformanceEntry(entry){replay.performanceEntries.includes(entry)||replay.performanceEntries.push(entry)}function onEntries({entries:entries}){entries.forEach(addPerformanceEntry)}const clearCallbacks=[];return["navigation","paint","resource"].forEach((type=>{clearCallbacks.push(addPerformanceInstrumentationHandler(type,onEntries))})),clearCallbacks.push(function(callback,stopOnCallback=!1){return addMetricObserver("lcp",callback,instrumentLcp,_previousLcp,stopOnCallback)}(webVitalHandler(getLargestContentfulPaint,replay)),function(callback,stopOnCallback=!1){return addMetricObserver("cls",callback,instrumentCls,_previousCls,stopOnCallback)}(webVitalHandler(getCumulativeLayoutShift,replay)),addMetricObserver("fid",webVitalHandler(getFirstInputDelay,replay),instrumentFid,_previousFid),function(callback){return addMetricObserver("inp",callback,instrumentInp,_previousInp)}(webVitalHandler(getInteractionToNextPaint,replay))),()=>{clearCallbacks.forEach((clearCallback=>clearCallback()))}}const esm_DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;const esm_CONSOLE_LEVELS=["info","warn","error","log"];function _addBreadcrumb(message,level="info"){addBreadcrumb({category:"console",data:{logger:"replay"},level:level,message:`[Replay] ${message}`},{level:level})}const esm_logger=function(){let _capture=!1,_trace=!1;const _logger={exception:()=>{},infoTick:()=>{},setConfig:opts=>{_capture=!!opts.captureExceptions,_trace=!!opts.traceInternals}};return esm_DEBUG_BUILD?(esm_CONSOLE_LEVELS.forEach((name=>{_logger[name]=(...args)=>{logger_logger[name]("[Replay] ",...args),_trace&&_addBreadcrumb(args.join(""),severityLevelFromString(name))}})),_logger.exception=(error,...message)=>{message.length&&_logger.error&&_logger.error(...message),logger_logger.error("[Replay] ",error),_capture?captureException(error):_trace&&_addBreadcrumb(error,"error")},_logger.infoTick=(...args)=>{logger_logger.info("[Replay] ",...args),_trace&&setTimeout((()=>_addBreadcrumb(args[0])),0)}):esm_CONSOLE_LEVELS.forEach((name=>{_logger[name]=()=>{}})),_logger}();class EventBufferSizeExceededError extends Error{constructor(){super("Event buffer exceeded maximum size of 20000000.")}}class EventBufferArray{constructor(){this.events=[],this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return this.events.length>0}get type(){return"sync"}destroy(){this.events=[]}async addEvent(event){const eventSize=JSON.stringify(event).length;if(this._totalSize+=eventSize,this._totalSize>2e7)throw new EventBufferSizeExceededError;this.events.push(event)}finish(){return new Promise((resolve=>{const eventsRet=this.events;this.clear(),resolve(JSON.stringify(eventsRet))}))}clear(){this.events=[],this._totalSize=0,this.hasCheckout=!1}getEarliestTimestamp(){const timestamp=this.events.map((event=>event.timestamp)).sort()[0];return timestamp?timestampToMs(timestamp):null}}class WorkerHandler{constructor(worker){this._worker=worker,this._id=0}ensureReady(){return this._ensureReadyPromise||(this._ensureReadyPromise=new Promise(((resolve,reject)=>{this._worker.addEventListener("message",(({data:data})=>{data.success?resolve():reject()}),{once:!0}),this._worker.addEventListener("error",(error=>{reject(error)}),{once:!0})}))),this._ensureReadyPromise}destroy(){esm_DEBUG_BUILD&&esm_logger.info("Destroying compression worker"),this._worker.terminate()}postMessage(method,arg){const id=this._getAndIncrementId();return new Promise(((resolve,reject)=>{const listener=({data:data})=>{const response=data;if(response.method===method&&response.id===id){if(this._worker.removeEventListener("message",listener),!response.success)return esm_DEBUG_BUILD&&esm_logger.error("Error in compression worker: ",response.response),void reject(new Error("Error in compression worker"));resolve(response.response)}};this._worker.addEventListener("message",listener),this._worker.postMessage({id:id,method:method,arg:arg})}))}_getAndIncrementId(){return this._id++}}class EventBufferCompressionWorker{constructor(worker){this._worker=new WorkerHandler(worker),this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return!!this._earliestTimestamp}get type(){return"worker"}ensureReady(){return this._worker.ensureReady()}destroy(){this._worker.destroy()}addEvent(event){const timestamp=timestampToMs(event.timestamp);(!this._earliestTimestamp||timestamp<this._earliestTimestamp)&&(this._earliestTimestamp=timestamp);const data=JSON.stringify(event);return this._totalSize+=data.length,this._totalSize>2e7?Promise.reject(new EventBufferSizeExceededError):this._sendEventToWorker(data)}finish(){return this._finishRequest()}clear(){this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this._worker.postMessage("clear").then(null,(e=>{esm_DEBUG_BUILD&&esm_logger.exception(e,'Sending "clear" message to worker failed',e)}))}getEarliestTimestamp(){return this._earliestTimestamp}_sendEventToWorker(data){return this._worker.postMessage("addEvent",data)}async _finishRequest(){const response=await this._worker.postMessage("finish");return this._earliestTimestamp=null,this._totalSize=0,response}}class EventBufferProxy{constructor(worker){this._fallback=new EventBufferArray,this._compression=new EventBufferCompressionWorker(worker),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}get waitForCheckout(){return this._used.waitForCheckout}get type(){return this._used.type}get hasEvents(){return this._used.hasEvents}get hasCheckout(){return this._used.hasCheckout}set hasCheckout(value){this._used.hasCheckout=value}set waitForCheckout(value){this._used.waitForCheckout=value}destroy(){this._fallback.destroy(),this._compression.destroy()}clear(){return this._used.clear()}getEarliestTimestamp(){return this._used.getEarliestTimestamp()}addEvent(event){return this._used.addEvent(event)}async finish(){return await this.ensureWorkerIsLoaded(),this._used.finish()}ensureWorkerIsLoaded(){return this._ensureWorkerIsLoadedPromise}async _ensureWorkerIsLoaded(){try{await this._compression.ensureReady()}catch(error){return void(esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to load the compression worker, falling back to simple buffer"))}await this._switchToCompressionWorker()}async _switchToCompressionWorker(){const{events:events,hasCheckout:hasCheckout,waitForCheckout:waitForCheckout}=this._fallback,addEventPromises=[];for(const event of events)addEventPromises.push(this._compression.addEvent(event));this._compression.hasCheckout=hasCheckout,this._compression.waitForCheckout=waitForCheckout,this._used=this._compression;try{await Promise.all(addEventPromises),this._fallback.clear()}catch(error){esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to add events when switching buffers.")}}}function createEventBuffer({useCompression:useCompression,workerUrl:customWorkerUrl}){if(useCompression&&window.Worker){const worker=function(customWorkerUrl){try{const workerUrl=customWorkerUrl||function(){if("undefined"==typeof __SENTRY_EXCLUDE_REPLAY_WORKER__||!__SENTRY_EXCLUDE_REPLAY_WORKER__)return function(){const e=new Blob(['var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,e){for(var i=new n(31),s=0;s<31;++s)i[s]=e+=1<<t[s-1];var a=new r(i[30]);for(s=1;s<30;++s)for(var o=i[s];o<i[s+1];++o)a[o]=o-i[s]<<5|s;return{b:i,r:a}},o=a(e,2),h=o.b,f=o.r;h[28]=258,f[258]=28;for(var l=a(i,0).r,u=new n(32768),c=0;c<32768;++c){var v=(43690&c)>>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,s=0,a=new n(r);s<i;++s)t[s]&&++a[t[s]-1];var o,h=new n(r);for(s=1;s<r;++s)h[s]=h[s-1]+a[s-1]<<1;if(e){o=new n(1<<r);var f=15-r;for(s=0;s<i;++s)if(t[s])for(var l=s<<4|t[s],c=r-t[s],v=h[t[s]-1]++<<c,d=v|(1<<c)-1;v<=d;++v)o[u[v]>>f]=l}else for(o=new n(i),s=0;s<i;++s)t[s]&&(o[s]=u[h[t[s]-1]++]>>15-t[s]);return o},p=new t(288);for(c=0;c<144;++c)p[c]=8;for(c=144;c<256;++c)p[c]=9;for(c=256;c<280;++c)p[c]=7;for(c=280;c<288;++c)p[c]=8;var g=new t(32);for(c=0;c<32;++c)g[c]=5;var w=d(p,9,0),y=d(g,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],s=0;s<r.length;++s)r[s]&&i.push({s:s,f:r[s]});var a=i.length,o=i.slice();if(!a)return{t:F,l:0};if(1==a){var h=new t(i[0].s+1);return h[i[0].s]=1,{t:h,l:1}}i.sort((function(t,n){return t.f-n.f})),i.push({s:-1,f:25001});var f=i[0],l=i[1],u=0,c=1,v=2;for(i[0]={s:-1,f:f.f+l.f,l:f,r:l};c!=a-1;)f=i[i[u].f<i[v].f?u++:v++],l=i[u!=c&&i[u].f<i[v].f?u++:v++],i[c++]={s:-1,f:f.f+l.f,l:f,r:l};var d=o[0].s;for(s=1;s<a;++s)o[s].s>d&&(d=o[s].s);var p=new n(d+1),g=A(i[c-1],p,0);if(g>e){s=0;var w=0,y=g-e,m=1<<y;for(o.sort((function(t,n){return p[n.s]-p[t.s]||t.f-n.f}));s<a;++s){var b=o[s].s;if(!(p[b]>e))break;w+=m-(1<<g-p[b]),p[b]=e}for(w>>=y;w>0;){var M=o[s].s;p[M]<e?w-=1<<e-p[M]++-1:++s}for(;s>=0&&w;--s){var E=o[s].s;p[E]==e&&(--p[E],++w)}g=e}return{t:new t(p),l:g}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,s=t[0],a=1,o=function(t){e[i++]=t},h=1;h<=r;++h)if(t[h]==s&&h!=r)++a;else{if(!s&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(s),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(s);a=1,s=t[h]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e<n.length;++e)r+=t[e]*n[e];return r},k=function(t,n,r){var e=r.length,i=m(n+2);t[i]=255&e,t[i+1]=e>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var s=0;s<e;++s)t[i+s+4]=r[s];return 8*(i+4+e)},U=function(t,r,a,o,h,f,l,u,c,v,m){z(r,m++,a),++h[256];for(var b=x(h,15),M=b.t,E=b.l,A=x(f,15),U=A.t,C=A.l,F=D(M),I=F.c,S=F.n,L=D(U),O=L.c,j=L.n,q=new n(19),B=0;B<I.length;++B)++q[31&I[B]];for(B=0;B<O.length;++B)++q[31&O[B]];for(var G=x(q,7),H=G.t,J=G.l,K=19;K>4&&!H[s[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(h,p)+T(f,g)+l,X=T(h,M)+T(f,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X<W)),m+=2,X<W){N=d(M,E,0),P=M,Q=d(U,C,0),R=U;var Y=d(H,J,0);z(r,m,S-257),z(r,m+5,j-1),z(r,m+10,K-4),m+=14;for(B=0;B<K;++B)z(r,m+3*B,H[s[B]]);m+=3*K;for(var Z=[I,O],$=0;$<2;++$){var tt=Z[$];for(B=0;B<tt.length;++B){var nt=31&tt[B];z(r,m,Y[nt]),m+=H[nt],nt>15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=w,P=p,Q=y,R=g;for(B=0;B<u;++B){var rt=o[B];if(rt>255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e<n.length;++e)r=I[255&r^n[e]]^r>>>8;t=r},d:function(){return~t}}},L=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,s=0|r.length,a=0;a!=s;){for(var o=Math.min(a+2655,s);a<o;++a)i+=e+=r[a];e=(65535&e)+15*(e>>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},O=function(s,a,o,h,u){if(!u&&(u={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),v=new t(c.length+s.length);v.set(c),v.set(s,c.length),s=v,u.w=c.length}return function(s,a,o,h,u,c){var v=c.z||s.length,d=new t(h+v+5*(1+Math.ceil(v/7e3))+u),p=d.subarray(h,d.length-u),g=c.l,w=7&(c.r||0);if(a){w&&(p[0]=c.r>>3);for(var y=C[a-1],M=y>>13,E=8191&y,z=(1<<o)-1,_=c.p||new n(32768),x=c.h||new n(z+1),A=Math.ceil(o/3),D=2*A,T=function(t){return(s[t]^s[t+1]<<A^s[t+2]<<D)&z},F=new r(25e3),I=new n(288),S=new n(32),L=0,O=0,j=c.i||0,q=0,B=c.w||0,G=0;j+2<v;++j){var H=T(j),J=32767&j,K=x[H];if(_[J]=K,x[H]=J,B<=j){var N=v-j;if((L>7e3||q>24576)&&(N>423||!g)){w=U(s,p,0,F,I,S,O,q,G,j-G,w),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(s[j+Q]==s[j+Q-W]){for(var $=0;$<Z&&s[j+$]==s[j+$-W];++$);if($>Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;P<tt;++P){var rt=j-W+P&32767,et=rt-_[rt]&32767;et>nt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|f[Q]<<18|l[R];var it=31&f[Q],st=31&l[R];O+=e[it]+i[st],++I[257+it],++S[st],B=j+Q,++L}else F[q++]=s[j],++I[s[j]]}}for(j=Math.max(j,B);j<v;++j)F[q++]=s[j],++I[s[j]];w=U(s,p,g,F,I,S,O,q,G,j-G,w),g||(c.r=7&w|p[w/8|0]<<3,w-=7,c.h=x,c.p=_,c.i=j,c.w=B)}else{for(j=c.w||0;j<v+g;j+=65535){var at=j+65535;at>=v&&(p[w/8|0]=g,at=v),w=k(p,w+1,s.subarray(j,at))}c.i=v}return b(d,0,h+m(w)+u)}(s,null==a.level?6:a.level,null==a.mem?u.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):20:12+a.mem,o,h,u)},j=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},q=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&j(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}},B=function(t){return 10+(t.filename?t.filename.length+1:0)},G=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(O(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var s=this.b.length-this.s.z;this.b.set(n.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(s),32768),this.s.z=n.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n.prototype.flush=function(){this.ondata||E(5),this.s.l&&E(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},n}();var H=function(){function t(t,n){this.c=L(),this.v=1,G.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),G.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=O(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=L();i.p(n.dictionary),j(t,2,i.d())}}(r,this.o),this.v=0),n&&j(r,r.length-4,this.c.d()),this.ondata(r,n)},t.prototype.flush=function(){G.prototype.flush.call(this)},t}(),J="undefined"!=typeof TextEncoder&&new TextEncoder,K="undefined"!=typeof TextDecoder&&new TextDecoder;try{K.decode(F,{stream:!0})}catch(t){}var N=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(P(t),this.d=n||!1)},t}();function P(n,r){if(J)return J.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),s=0,a=function(t){i[s++]=t},o=0;o<e;++o){if(s+5>i.length){var h=new t(s+8+(e-o<<1));h.set(i),i=h}var f=n.charCodeAt(o);f<128||r?a(f):f<2048?(a(192|f>>6),a(128|63&f)):f>55295&&f<57344?(a(240|(f=65536+(1047552&f)|1023&n.charCodeAt(++o))>>18),a(128|f>>12&63),a(128|f>>6&63),a(128|63&f)):(a(224|f>>12),a(128|f>>6&63),a(128|63&f))}return b(i,0,s)}function Q(t){return function(t,n){n||(n={});var r=S(),e=t.length;r.p(t);var i=O(t,n,B(n),8),s=i.length;return q(i,n),j(i,s-8,r.d()),j(i,s-4,e),i}(P(t))}const R=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n<i;n++){const i=t[n];r.set(i,e),e+=i.length}return r}(this._deflatedData);return this._init(),t}_init(){this._hasEvents=!1,this._deflatedData=[],this.deflate=new H,this.deflate.ondata=(t,n)=>{this._deflatedData.push(t)},this.stream=new N(((t,n)=>{this.deflate.push(t,n)})),this.stream.push("[")}},V={clear:()=>{R.clear()},addEvent:t=>R.addEvent(t),finish:()=>R.finish(),compress:t=>Q(t)};addEventListener("message",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in V&&"function"==typeof V[n])try{const t=V[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});']);return URL.createObjectURL(e)}();return""}();if(!workerUrl)return;esm_DEBUG_BUILD&&esm_logger.info("Using compression worker"+(customWorkerUrl?` from ${customWorkerUrl}`:""));const worker=new Worker(workerUrl);return new EventBufferProxy(worker)}catch(error){esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to create compression worker")}}(customWorkerUrl);if(worker)return worker}return esm_DEBUG_BUILD&&esm_logger.info("Using simple buffer"),new EventBufferArray}function hasSessionStorage(){try{return"sessionStorage"in esm_WINDOW&&!!esm_WINDOW.sessionStorage}catch{return!1}}function clearSession(replay){!function(){if(!hasSessionStorage())return;try{esm_WINDOW.sessionStorage.removeItem("sentryReplaySession")}catch{}}(),replay.session=void 0}function isSampled(sampleRate){return void 0!==sampleRate&&Math.random()<sampleRate}function esm_makeSession(session){const now=Date.now();return{id:session.id||misc_uuid4(),started:session.started||now,lastActivity:session.lastActivity||now,segmentId:session.segmentId||0,sampled:session.sampled,previousSessionId:session.previousSessionId}}function saveSession(session){if(hasSessionStorage())try{esm_WINDOW.sessionStorage.setItem("sentryReplaySession",JSON.stringify(session))}catch{}}function createSession({sessionSampleRate:sessionSampleRate,allowBuffering:allowBuffering,stickySession:stickySession=!1},{previousSessionId:previousSessionId}={}){const sampled=function(sessionSampleRate,allowBuffering){return isSampled(sessionSampleRate)?"session":!!allowBuffering&&"buffer"}(sessionSampleRate,allowBuffering),session=esm_makeSession({sampled:sampled,previousSessionId:previousSessionId});return stickySession&&saveSession(session),session}function isExpired(initialTime,expiry,targetTime=+new Date){return null===initialTime||void 0===expiry||expiry<0||0!==expiry&&initialTime+expiry<=targetTime}function isSessionExpired(session,{maxReplayDuration:maxReplayDuration,sessionIdleExpire:sessionIdleExpire,targetTime:targetTime=Date.now()}){return isExpired(session.started,maxReplayDuration,targetTime)||isExpired(session.lastActivity,sessionIdleExpire,targetTime)}function shouldRefreshSession(session,{sessionIdleExpire:sessionIdleExpire,maxReplayDuration:maxReplayDuration}){return!!isSessionExpired(session,{sessionIdleExpire:sessionIdleExpire,maxReplayDuration:maxReplayDuration})&&("buffer"!==session.sampled||0!==session.segmentId)}function loadOrCreateSession({sessionIdleExpire:sessionIdleExpire,maxReplayDuration:maxReplayDuration,previousSessionId:previousSessionId},sessionOptions){const existingSession=sessionOptions.stickySession&&function(){if(!hasSessionStorage())return null;try{const sessionStringFromStorage=esm_WINDOW.sessionStorage.getItem("sentryReplaySession");if(!sessionStringFromStorage)return null;const sessionObj=JSON.parse(sessionStringFromStorage);return esm_DEBUG_BUILD&&esm_logger.infoTick("Loading existing session"),esm_makeSession(sessionObj)}catch{return null}}();return existingSession?shouldRefreshSession(existingSession,{sessionIdleExpire:sessionIdleExpire,maxReplayDuration:maxReplayDuration})?(esm_DEBUG_BUILD&&esm_logger.infoTick("Session in sessionStorage is expired, creating new one..."),createSession(sessionOptions,{previousSessionId:existingSession.id})):existingSession:(esm_DEBUG_BUILD&&esm_logger.infoTick("Creating new session"),createSession(sessionOptions,{previousSessionId:previousSessionId}))}function addEventSync(replay,event,isCheckout){return!!shouldAddEvent(replay,event)&&(_addEvent(replay,event,isCheckout),!0)}async function _addEvent(replay,event,isCheckout){const{eventBuffer:eventBuffer}=replay;if(!eventBuffer||eventBuffer.waitForCheckout&&!isCheckout)return null;const isBufferMode="buffer"===replay.recordingMode;try{isCheckout&&isBufferMode&&eventBuffer.clear(),isCheckout&&(eventBuffer.hasCheckout=!0,eventBuffer.waitForCheckout=!1);const eventAfterPossibleCallback=function(event,callback){try{if("function"==typeof callback&&function(event){return event.type===EventType.Custom}(event))return callback(event)}catch(error){return esm_DEBUG_BUILD&&esm_logger.exception(error,"An error occurred in the `beforeAddRecordingEvent` callback, skipping the event..."),null}return event}(event,replay.getOptions().beforeAddRecordingEvent);if(!eventAfterPossibleCallback)return;return await eventBuffer.addEvent(eventAfterPossibleCallback)}catch(error){const isExceeded=error&&error instanceof EventBufferSizeExceededError,reason=isExceeded?"addEventSizeExceeded":"addEvent";if(isExceeded&&isBufferMode)return eventBuffer.clear(),eventBuffer.waitForCheckout=!0,null;replay.handleException(error),await replay.stop({reason:reason});const client=currentScopes_getClient();client&&client.recordDroppedEvent("internal_sdk_error","replay")}}function shouldAddEvent(replay,event){if(!replay.eventBuffer||replay.isPaused()||!replay.isEnabled())return!1;const timestampInMs=timestampToMs(event.timestamp);return!(timestampInMs+replay.timeouts.sessionIdlePause<Date.now())&&(!(timestampInMs>replay.getContext().initialTimestamp+replay.getOptions().maxReplayDuration)||(esm_DEBUG_BUILD&&esm_logger.infoTick(`Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`),!1))}function esm_isErrorEvent(event){return!event.type}function isTransactionEvent(event){return"transaction"===event.type}function isFeedbackEvent(event){return"feedback"===event.type}function handleAfterSendEvent(replay){return(event,sendResponse)=>{if(!replay.isEnabled()||!esm_isErrorEvent(event)&&!isTransactionEvent(event))return;const statusCode=sendResponse?.statusCode;!statusCode||statusCode<200||statusCode>=300||(isTransactionEvent(event)?function(replay,event){const replayContext=replay.getContext();event.contexts?.trace?.trace_id&&replayContext.traceIds.size<100&&replayContext.traceIds.add(event.contexts.trace.trace_id)}(replay,event):function(replay,event){const replayContext=replay.getContext();event.event_id&&replayContext.errorIds.size<100&&replayContext.errorIds.add(event.event_id);if("buffer"!==replay.recordingMode||!event.tags||!event.tags.replayId)return;const{beforeErrorSampling:beforeErrorSampling}=replay.getOptions();if("function"==typeof beforeErrorSampling&&!beforeErrorSampling(event))return;getNativeImplementation_setTimeout((async()=>{try{await replay.sendBufferedReplayOrFlush()}catch(err){replay.handleException(err)}}))}(replay,event))}}function handleBeforeSendEvent(replay){return event=>{replay.isEnabled()&&esm_isErrorEvent(event)&&function(replay,event){const exceptionValue=event.exception?.values?.[0]?.value;if("string"!=typeof exceptionValue)return;if(exceptionValue.match(/(reactjs\.org\/docs\/error-decoder\.html\?invariant=|react\.dev\/errors\/)(418|419|422|423|425)/)||exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)){addBreadcrumbEvent(replay,createBreadcrumb({category:"replay.hydrate-error",data:{url:getLocationHref()}}))}}(replay,event)}}function handleBreadcrumbs(replay){const client=currentScopes_getClient();client&&client.on("beforeAddBreadcrumb",(breadcrumb=>function(replay,breadcrumb){if(!replay.isEnabled()||!isBreadcrumbWithCategory(breadcrumb))return;const result=function(breadcrumb){if(!isBreadcrumbWithCategory(breadcrumb)||["fetch","xhr","sentry.event","sentry.transaction"].includes(breadcrumb.category)||breadcrumb.category.startsWith("ui."))return null;if("console"===breadcrumb.category)return function(breadcrumb){const args=breadcrumb.data?.arguments;if(!Array.isArray(args)||0===args.length)return createBreadcrumb(breadcrumb);let isTruncated=!1;const normalizedArgs=args.map((arg=>{if(!arg)return arg;if("string"==typeof arg)return arg.length>5e3?(isTruncated=!0,`${arg.slice(0,5e3)}…`):arg;if("object"==typeof arg)try{const normalizedArg=normalize(arg,7);return JSON.stringify(normalizedArg).length>5e3?(isTruncated=!0,`${JSON.stringify(normalizedArg,null,2).slice(0,5e3)}…`):normalizedArg}catch{}return arg}));return createBreadcrumb({...breadcrumb,data:{...breadcrumb.data,arguments:normalizedArgs,...isTruncated?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{}}})}(breadcrumb);return createBreadcrumb(breadcrumb)}(breadcrumb);result&&addBreadcrumbEvent(replay,result)}(replay,breadcrumb)))}function isBreadcrumbWithCategory(breadcrumb){return!!breadcrumb.category}function resetReplayIdOnDynamicSamplingContext(){const dsc=currentScopes_getCurrentScope().getPropagationContext().dsc;dsc&&delete dsc.replay_id;const activeSpan=spanUtils_getActiveSpan();if(activeSpan){delete dynamicSamplingContext_getDynamicSamplingContextFromSpan(activeSpan).replay_id}}function handleGlobalEventListener(replay){return Object.assign(((event,hint)=>{if(!replay.isEnabled()||replay.isPaused())return event;if(function(event){return"replay_event"===event.type}(event))return delete event.breadcrumbs,event;if(!esm_isErrorEvent(event)&&!isTransactionEvent(event)&&!isFeedbackEvent(event))return event;if(!replay.checkAndHandleExpiredSession())return resetReplayIdOnDynamicSamplingContext(),event;if(isFeedbackEvent(event))return replay.flush(),event.contexts.feedback.replay_id=replay.getSessionId(),function(replay,event){replay.triggerUserActivity(),replay.addUpdate((()=>!event.timestamp||(replay.throttledAddEvent({type:EventType.Custom,timestamp:1e3*event.timestamp,data:{tag:"breadcrumb",payload:{timestamp:event.timestamp,type:"default",category:"sentry.feedback",data:{feedbackId:event.event_id}}}}),!1)))}(replay,event),event;if(function(event,hint){return!(event.type||!event.exception||!event.exception.values||!event.exception.values.length||!hint.originalException?.__rrweb__)}(event,hint)&&!replay.getOptions()._experiments.captureExceptions)return esm_DEBUG_BUILD&&esm_logger.log("Ignoring error from rrweb internals",event),null;const isErrorEventSampled=function(replay,event){return"buffer"===replay.recordingMode&&"Unable to send Replay"!==event.message&&!(!event.exception||event.type)&&isSampled(replay.getOptions().errorSampleRate)}(replay,event);return(isErrorEventSampled||"session"===replay.recordingMode)&&(event.tags={...event.tags,replayId:replay.getSessionId()}),event}),{id:"Replay"})}function createPerformanceSpans(replay,entries){return entries.map((({type:type,start:start,end:end,name:name,data:data})=>{const response=replay.throttledAddEvent({type:EventType.Custom,timestamp:start,data:{tag:"performanceSpan",payload:{op:type,description:name,startTimestamp:start,endTimestamp:end,data:data}}});return"string"==typeof response?Promise.resolve(null):response}))}function handleHistorySpanListener(replay){return handlerData=>{if(!replay.isEnabled())return;const result=function(handlerData){const{from:from,to:to}=handlerData,now=Date.now()/1e3;return{type:"navigation.push",start:now,end:now,name:to,data:{previous:from}}}(handlerData);null!==result&&(replay.getContext().urls.push(result.name),replay.triggerUserActivity(),replay.addUpdate((()=>(createPerformanceSpans(replay,[result]),!1))))}}function addNetworkBreadcrumb(replay,result){replay.isEnabled()&&null!==result&&(function(replay,url){return(!esm_DEBUG_BUILD||!replay.getOptions()._experiments.traceInternals)&&isSentryRequestUrl(url,currentScopes_getClient())}(replay,result.name)||replay.addUpdate((()=>(createPerformanceSpans(replay,[result]),!0))))}function getBodySize(body){if(!body)return;const textEncoder=new TextEncoder;try{if("string"==typeof body)return textEncoder.encode(body).length;if(body instanceof URLSearchParams)return textEncoder.encode(body.toString()).length;if(body instanceof FormData){const formDataStr=serializeFormData(body);return textEncoder.encode(formDataStr).length}if(body instanceof Blob)return body.size;if(body instanceof ArrayBuffer)return body.byteLength}catch{}}function parseContentLengthHeader(header){if(!header)return;const size=parseInt(header,10);return isNaN(size)?void 0:size}function mergeWarning(info,warning){if(!info)return{headers:{},size:void 0,_meta:{warnings:[warning]}};const newMeta={...info._meta},existingWarnings=newMeta.warnings||[];return newMeta.warnings=[...existingWarnings,warning],info._meta=newMeta,info}function makeNetworkReplayBreadcrumb(type,data){if(!data)return null;const{startTimestamp:startTimestamp,endTimestamp:endTimestamp,url:url,method:method,statusCode:statusCode,request:request,response:response}=data;return{type:type,start:startTimestamp/1e3,end:endTimestamp/1e3,name:url,data:{method:method,statusCode:statusCode,request:request,response:response}}}function buildSkippedNetworkRequestOrResponse(bodySize){return{headers:{},size:bodySize,_meta:{warnings:["URL_SKIPPED"]}}}function buildNetworkRequestOrResponse(headers,bodySize,body){if(!bodySize&&0===Object.keys(headers).length)return;if(!bodySize)return{headers:headers};if(!body)return{headers:headers,size:bodySize};const info={headers:headers,size:bodySize},{body:normalizedBody,warnings:warnings}=function(body){if(!body||"string"!=typeof body)return{body:body};const exceedsSizeLimit=body.length>15e4,isProbablyJson=function(str){const first=str[0],last=str[str.length-1];return"["===first&&"]"===last||"{"===first&&"}"===last}(body);if(exceedsSizeLimit){const truncatedBody=body.slice(0,15e4);return isProbablyJson?{body:truncatedBody,warnings:["MAYBE_JSON_TRUNCATED"]}:{body:`${truncatedBody}…`,warnings:["TEXT_TRUNCATED"]}}if(isProbablyJson)try{return{body:JSON.parse(body)}}catch{}return{body:body}}(body);return info.body=normalizedBody,warnings?.length&&(info._meta={warnings:warnings}),info}function getAllowedHeaders(headers,allowedHeaders){return Object.entries(headers).reduce(((filteredHeaders,[key,value])=>{const normalizedKey=key.toLowerCase();return allowedHeaders.includes(normalizedKey)&&headers[key]&&(filteredHeaders[normalizedKey]=value),filteredHeaders}),{})}function urlMatches(url,urls){const fullUrl=function(url,baseURI=esm_WINDOW.document.baseURI){if(url.startsWith("http://")||url.startsWith("https://")||url.startsWith(esm_WINDOW.location.origin))return url;const fixedUrl=new URL(url,baseURI);if(fixedUrl.origin!==new URL(baseURI).origin)return url;const fullUrl=fixedUrl.href;if(!url.endsWith("/")&&fullUrl.endsWith("/"))return fullUrl.slice(0,-1);return fullUrl}(url);return stringMatchesSomePattern(fullUrl,urls)}async function captureFetchBreadcrumbToReplay(breadcrumb,hint,options){try{const data=await async function(breadcrumb,hint,options){const now=Date.now(),{startTimestamp:startTimestamp=now,endTimestamp:endTimestamp=now}=hint,{url:url,method:method,status_code:statusCode=0,request_body_size:requestBodySize,response_body_size:responseBodySize}=breadcrumb.data,captureDetails=urlMatches(url,options.networkDetailAllowUrls)&&!urlMatches(url,options.networkDetailDenyUrls),request=captureDetails?function({networkCaptureBodies:networkCaptureBodies,networkRequestHeaders:networkRequestHeaders},input,requestBodySize){const headers=input?function(fetchArgs,allowedHeaders){if(1===fetchArgs.length&&"string"!=typeof fetchArgs[0])return getHeadersFromOptions(fetchArgs[0],allowedHeaders);if(2===fetchArgs.length)return getHeadersFromOptions(fetchArgs[1],allowedHeaders);return{}}(input,networkRequestHeaders):{};if(!networkCaptureBodies)return buildNetworkRequestOrResponse(headers,requestBodySize,void 0);const requestBody=getFetchRequestArgBody(input),[bodyStr,warning]=getBodyString(requestBody,esm_logger),data=buildNetworkRequestOrResponse(headers,requestBodySize,bodyStr);if(warning)return mergeWarning(data,warning);return data}(options,hint.input,requestBodySize):buildSkippedNetworkRequestOrResponse(requestBodySize),response=await async function(captureDetails,{networkCaptureBodies:networkCaptureBodies,networkResponseHeaders:networkResponseHeaders},response,responseBodySize){if(!captureDetails&&void 0!==responseBodySize)return buildSkippedNetworkRequestOrResponse(responseBodySize);const headers=response?getAllHeaders(response.headers,networkResponseHeaders):{};if(!response||!networkCaptureBodies&&void 0!==responseBodySize)return buildNetworkRequestOrResponse(headers,responseBodySize,void 0);const[bodyText,warning]=await async function(response){const res=function(response){try{return response.clone()}catch(error){esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to clone response body")}}(response);if(!res)return[void 0,"BODY_PARSE_ERROR"];try{const text=await function(response){return new Promise(((resolve,reject)=>{const timeout=getNativeImplementation_setTimeout((()=>reject(new Error("Timeout while trying to read response body"))),500);(async function(response){return await response.text()})(response).then((txt=>resolve(txt)),(reason=>reject(reason))).finally((()=>clearTimeout(timeout)))}))}(res);return[text]}catch(error){return error instanceof Error&&error.message.indexOf("Timeout")>-1?(esm_DEBUG_BUILD&&esm_logger.warn("Parsing text body from response timed out"),[void 0,"BODY_PARSE_TIMEOUT"]):(esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to get text body from response"),[void 0,"BODY_PARSE_ERROR"])}}(response),result=function(bodyText,{networkCaptureBodies:networkCaptureBodies,responseBodySize:responseBodySize,captureDetails:captureDetails,headers:headers}){try{const size=bodyText?.length&&void 0===responseBodySize?getBodySize(bodyText):responseBodySize;return captureDetails?buildNetworkRequestOrResponse(headers,size,networkCaptureBodies?bodyText:void 0):buildSkippedNetworkRequestOrResponse(size)}catch(error){return esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to serialize response body"),buildNetworkRequestOrResponse(headers,responseBodySize,void 0)}}(bodyText,{networkCaptureBodies:networkCaptureBodies,responseBodySize:responseBodySize,captureDetails:captureDetails,headers:headers});if(warning)return mergeWarning(result,warning);return result}(captureDetails,options,hint.response,responseBodySize);return{startTimestamp:startTimestamp,endTimestamp:endTimestamp,url:url,method:method,statusCode:statusCode,request:request,response:response}}(breadcrumb,hint,options),result=makeNetworkReplayBreadcrumb("resource.fetch",data);addNetworkBreadcrumb(options.replay,result)}catch(error){esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to capture fetch breadcrumb")}}function getAllHeaders(headers,allowedHeaders){const allHeaders={};return allowedHeaders.forEach((header=>{headers.get(header)&&(allHeaders[header]=headers.get(header))})),allHeaders}function getHeadersFromOptions(input,allowedHeaders){if(!input)return{};const headers=input.headers;return headers?headers instanceof Headers?getAllHeaders(headers,allowedHeaders):Array.isArray(headers)?{}:getAllowedHeaders(headers,allowedHeaders):{}}async function captureXhrBreadcrumbToReplay(breadcrumb,hint,options){try{const data=function(breadcrumb,hint,options){const now=Date.now(),{startTimestamp:startTimestamp=now,endTimestamp:endTimestamp=now,input:input,xhr:xhr}=hint,{url:url,method:method,status_code:statusCode=0,request_body_size:requestBodySize,response_body_size:responseBodySize}=breadcrumb.data;if(!url)return null;if(!xhr||!urlMatches(url,options.networkDetailAllowUrls)||urlMatches(url,options.networkDetailDenyUrls)){return{startTimestamp:startTimestamp,endTimestamp:endTimestamp,url:url,method:method,statusCode:statusCode,request:buildSkippedNetworkRequestOrResponse(requestBodySize),response:buildSkippedNetworkRequestOrResponse(responseBodySize)}}const xhrInfo=xhr.__sentry_xhr_v3__,networkRequestHeaders=xhrInfo?getAllowedHeaders(xhrInfo.request_headers,options.networkRequestHeaders):{},networkResponseHeaders=getAllowedHeaders(function(xhr){const headers=xhr.getAllResponseHeaders();if(!headers)return{};return headers.split("\r\n").reduce(((acc,line)=>{const[key,value]=line.split(": ");return value&&(acc[key.toLowerCase()]=value),acc}),{})}(xhr),options.networkResponseHeaders),[requestBody,requestWarning]=options.networkCaptureBodies?getBodyString(input,esm_logger):[void 0],[responseBody,responseWarning]=options.networkCaptureBodies?function(xhr){const errors=[];try{return[xhr.responseText]}catch(e){errors.push(e)}try{return function(body,responseType){try{if("string"==typeof body)return[body];if(body instanceof Document)return[body.body.outerHTML];if("json"===responseType&&body&&"object"==typeof body)return[JSON.stringify(body)];if(!body)return[void 0]}catch(error){return esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to serialize body",body),[void 0,"BODY_PARSE_ERROR"]}return esm_DEBUG_BUILD&&esm_logger.info("Skipping network body because of body type",body),[void 0,"UNPARSEABLE_BODY_TYPE"]}(xhr.response,xhr.responseType)}catch(e){errors.push(e)}return esm_DEBUG_BUILD&&esm_logger.warn("Failed to get xhr response body",...errors),[void 0]}(xhr):[void 0],request=buildNetworkRequestOrResponse(networkRequestHeaders,requestBodySize,requestBody),response=buildNetworkRequestOrResponse(networkResponseHeaders,responseBodySize,responseBody);return{startTimestamp:startTimestamp,endTimestamp:endTimestamp,url:url,method:method,statusCode:statusCode,request:requestWarning?mergeWarning(request,requestWarning):request,response:responseWarning?mergeWarning(response,responseWarning):response}}(breadcrumb,hint,options),result=makeNetworkReplayBreadcrumb("resource.xhr",data);addNetworkBreadcrumb(options.replay,result)}catch(error){esm_DEBUG_BUILD&&esm_logger.exception(error,"Failed to capture xhr breadcrumb")}}function enrichXhrBreadcrumb(breadcrumb,hint){const{xhr:xhr,input:input}=hint;if(!xhr)return;const reqSize=getBodySize(input),resSize=xhr.getResponseHeader("content-length")?parseContentLengthHeader(xhr.getResponseHeader("content-length")):function(body,responseType){try{return getBodySize("json"===responseType&&body&&"object"==typeof body?JSON.stringify(body):body)}catch{return}}(xhr.response,xhr.responseType);void 0!==reqSize&&(breadcrumb.data.request_body_size=reqSize),void 0!==resSize&&(breadcrumb.data.response_body_size=resSize)}function handleNetworkBreadcrumbs(replay){const client=currentScopes_getClient();try{const{networkDetailAllowUrls:networkDetailAllowUrls,networkDetailDenyUrls:networkDetailDenyUrls,networkCaptureBodies:networkCaptureBodies,networkRequestHeaders:networkRequestHeaders,networkResponseHeaders:networkResponseHeaders}=replay.getOptions(),options={replay:replay,networkDetailAllowUrls:networkDetailAllowUrls,networkDetailDenyUrls:networkDetailDenyUrls,networkCaptureBodies:networkCaptureBodies,networkRequestHeaders:networkRequestHeaders,networkResponseHeaders:networkResponseHeaders};client&&client.on("beforeAddBreadcrumb",((breadcrumb,hint)=>function(options,breadcrumb,hint){if(!breadcrumb.data)return;try{(function(breadcrumb){return"xhr"===breadcrumb.category})(breadcrumb)&&function(hint){return hint?.xhr}(hint)&&(enrichXhrBreadcrumb(breadcrumb,hint),captureXhrBreadcrumbToReplay(breadcrumb,hint,options)),function(breadcrumb){return"fetch"===breadcrumb.category}(breadcrumb)&&function(hint){return hint?.response}(hint)&&(!function(breadcrumb,hint){const{input:input,response:response}=hint,reqSize=getBodySize(input?getFetchRequestArgBody(input):void 0),resSize=response?parseContentLengthHeader(response.headers.get("content-length")):void 0;void 0!==reqSize&&(breadcrumb.data.request_body_size=reqSize),void 0!==resSize&&(breadcrumb.data.response_body_size=resSize)}(breadcrumb,hint),captureFetchBreadcrumbToReplay(breadcrumb,hint,options))}catch(e){esm_DEBUG_BUILD&&esm_logger.exception(e,"Error when enriching network breadcrumb")}}(options,breadcrumb,hint)))}catch{}}function addGlobalListeners(replay,{autoFlushOnFeedback:autoFlushOnFeedback}){const client=currentScopes_getClient();addClickKeypressInstrumentationHandler(handleDomListener(replay)),addHistoryInstrumentationHandler(handleHistorySpanListener(replay)),handleBreadcrumbs(replay),handleNetworkBreadcrumbs(replay);const eventProcessor=handleGlobalEventListener(replay);var callback;callback=eventProcessor,currentScopes_getIsolationScope().addEventProcessor(callback),client&&(client.on("beforeSendEvent",handleBeforeSendEvent(replay)),client.on("afterSendEvent",handleAfterSendEvent(replay)),client.on("createDsc",(dsc=>{const replayId=replay.getSessionId();if(replayId&&replay.isEnabled()&&"session"===replay.recordingMode){replay.checkAndHandleExpiredSession()&&(dsc.replay_id=replayId)}})),client.on("spanStart",(span=>{replay.lastActiveSpan=span})),client.on("spanEnd",(span=>{replay.lastActiveSpan=span})),client.on("beforeSendFeedback",(async(feedbackEvent,options)=>{const replayId=replay.getSessionId();options?.includeReplay&&replay.isEnabled()&&replayId&&feedbackEvent.contexts?.feedback&&("api"===feedbackEvent.contexts.feedback.source&&autoFlushOnFeedback&&await replay.flush(),feedbackEvent.contexts.feedback.replay_id=replayId)})),autoFlushOnFeedback&&client.on("openFeedbackWidget",(async()=>{await replay.flush()})))}function createMemoryEntry(memoryEntry){const{jsHeapSizeLimit:jsHeapSizeLimit,totalJSHeapSize:totalJSHeapSize,usedJSHeapSize:usedJSHeapSize}=memoryEntry,time=Date.now()/1e3;return{type:"memory",name:"memory",start:time,end:time,data:{memory:{jsHeapSizeLimit:jsHeapSizeLimit,totalJSHeapSize:totalJSHeapSize,usedJSHeapSize:usedJSHeapSize}}}}const NAVIGATOR=worldwide_GLOBAL_OBJ.navigator;function getHandleRecordingEmit(replay){let hadFirstEvent=!1;return(event,_isCheckout)=>{if(!replay.checkAndHandleExpiredSession())return void(esm_DEBUG_BUILD&&esm_logger.warn("Received replay event after session expired."));const isCheckout=_isCheckout||!hadFirstEvent;hadFirstEvent=!0,replay.clickDetector&&updateClickDetectorForRecordingEvent(replay.clickDetector,event),replay.addUpdate((()=>{if("buffer"===replay.recordingMode&&isCheckout&&replay.setInitialState(),!addEventSync(replay,event,isCheckout))return!0;if(!isCheckout)return!1;const session=replay.session;if(function(replay,isCheckout){if(!isCheckout||!replay.session||0!==replay.session.segmentId)return;addEventSync(replay,function(replay){const options=replay.getOptions();return{type:EventType.Custom,timestamp:Date.now(),data:{tag:"options",payload:{shouldRecordCanvas:replay.isRecordingCanvas(),sessionSampleRate:options.sessionSampleRate,errorSampleRate:options.errorSampleRate,useCompressionOption:options.useCompression,blockAllMedia:options.blockAllMedia,maskAllText:options.maskAllText,maskAllInputs:options.maskAllInputs,useCompression:!!replay.eventBuffer&&"worker"===replay.eventBuffer.type,networkDetailHasUrls:options.networkDetailAllowUrls.length>0,networkCaptureBodies:options.networkCaptureBodies,networkRequestHasHeaders:options.networkRequestHeaders.length>0,networkResponseHasHeaders:options.networkResponseHeaders.length>0}}}}(replay),!1)}(replay,isCheckout),"buffer"===replay.recordingMode&&session&&replay.eventBuffer){const earliestEvent=replay.eventBuffer.getEarliestTimestamp();earliestEvent&&(esm_DEBUG_BUILD&&esm_logger.info(`Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`),session.started=earliestEvent,replay.getOptions().stickySession&&saveSession(session))}return session?.previousSessionId||"session"===replay.recordingMode&&replay.flush(),!0}))}}async function sendReplayRequest({recordingData:recordingData,replayId:replayId,segmentId:segment_id,eventContext:eventContext,timestamp:timestamp,session:session}){const preparedRecordingData=function({recordingData:recordingData,headers:headers}){let payloadWithSequence;const replayHeaders=`${JSON.stringify(headers)}\n`;if("string"==typeof recordingData)payloadWithSequence=`${replayHeaders}${recordingData}`;else{const sequence=(new TextEncoder).encode(replayHeaders);payloadWithSequence=new Uint8Array(sequence.length+recordingData.length),payloadWithSequence.set(sequence),payloadWithSequence.set(recordingData,sequence.length)}return payloadWithSequence}({recordingData:recordingData,headers:{segment_id:segment_id}}),{urls:urls,errorIds:errorIds,traceIds:traceIds,initialTimestamp:initialTimestamp}=eventContext,client=currentScopes_getClient(),scope=currentScopes_getCurrentScope(),transport=client?.getTransport(),dsn=client?.getDsn();if(!(client&&transport&&dsn&&session.sampled))return resolvedSyncPromise({});const baseEvent={type:"replay_event",replay_start_timestamp:initialTimestamp/1e3,timestamp:timestamp/1e3,error_ids:errorIds,trace_ids:traceIds,urls:urls,replay_id:replayId,segment_id:segment_id,replay_type:session.sampled},replayEvent=await async function({client:client,scope:scope,replayId:event_id,event:event}){const eventHint={event_id:event_id,integrations:"object"!=typeof client._integrations||null===client._integrations||Array.isArray(client._integrations)?void 0:Object.keys(client._integrations)};client.emit("preprocessEvent",event,eventHint);const preparedEvent=await prepareEvent(client.getOptions(),event,eventHint,scope,client,currentScopes_getIsolationScope());if(!preparedEvent)return null;client.emit("postprocessEvent",preparedEvent,eventHint),preparedEvent.platform=preparedEvent.platform||"javascript";const metadata=client.getSdkMetadata(),{name:name,version:version}=metadata?.sdk||{};return preparedEvent.sdk={...preparedEvent.sdk,name:name||"sentry.javascript.unknown",version:version||"0.0.0"},preparedEvent}({scope:scope,client:client,replayId:replayId,event:baseEvent});if(!replayEvent)return client.recordDroppedEvent("event_processor","replay"),esm_DEBUG_BUILD&&esm_logger.info("An event processor returned `null`, will not send event."),resolvedSyncPromise({});delete replayEvent.sdkProcessingMetadata;const envelope=function(replayEvent,recordingData,dsn,tunnel){return createEnvelope(createEventEnvelopeHeaders(replayEvent,getSdkMetadataForEnvelopeHeader(replayEvent),tunnel,dsn),[[{type:"replay_event"},replayEvent],[{type:"replay_recording",length:"string"==typeof recordingData?(new TextEncoder).encode(recordingData).length:recordingData.length},recordingData]])}(replayEvent,preparedRecordingData,dsn,client.getOptions().tunnel);let response;try{response=await transport.send(envelope)}catch(err){const error=new Error("Unable to send Replay");try{error.cause=err}catch{}throw error}if("number"==typeof response.statusCode&&(response.statusCode<200||response.statusCode>=300))throw new TransportStatusCodeError(response.statusCode);const rateLimits=updateRateLimits({},response);if(isRateLimited(rateLimits,"replay"))throw new RateLimitError(rateLimits);return response}class TransportStatusCodeError extends Error{constructor(statusCode){super(`Transport returned status code ${statusCode}`)}}class RateLimitError extends Error{constructor(rateLimits){super("Rate limit hit"),this.rateLimits=rateLimits}}async function sendReplay(replayData,retryConfig={count:0,interval:5e3}){const{recordingData:recordingData,onError:onError}=replayData;var name,context;if(recordingData.length)try{return await sendReplayRequest(replayData),!0}catch(err){if(err instanceof TransportStatusCodeError||err instanceof RateLimitError)throw err;if(name="Replays",context={_retryCount:retryConfig.count},currentScopes_getIsolationScope().setContext(name,context),onError&&onError(err),retryConfig.count>=3){const error=new Error("Unable to send Replay - max retries exceeded");try{error.cause=err}catch{}throw error}return retryConfig.interval*=++retryConfig.count,new Promise(((resolve,reject)=>{getNativeImplementation_setTimeout((async()=>{try{await sendReplay(replayData,retryConfig),resolve(!0)}catch(err){reject(err)}}),retryConfig.interval)}))}}function throttle(fn,maxCount,durationSeconds){const counter=new Map;let isThrottled=!1;return(...rest)=>{const now=Math.floor(Date.now()/1e3);if((now=>{const threshold=now-durationSeconds;counter.forEach(((_value,key)=>{key<threshold&&counter.delete(key)}))})(now),[...counter.values()].reduce(((a,b)=>a+b),0)>=maxCount){const wasThrottled=isThrottled;return isThrottled=!0,wasThrottled?"__SKIPPED":"__THROTTLED"}isThrottled=!1;const count=counter.get(now)||0;return counter.set(now,count+1),fn(...rest)}}class ReplayContainer{constructor({options:options,recordingOptions:recordingOptions}){this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:3e5,sessionIdleExpire:9e5},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._requiresManualStart=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=recordingOptions,this._options=options,this._debouncedFlush=function(func,wait,options){let callbackReturnValue,timerId,maxTimerId;const maxWait=options?.maxWait?Math.max(options.maxWait,wait):0;function invokeFunc(){return cancelTimers(),callbackReturnValue=func(),callbackReturnValue}function cancelTimers(){void 0!==timerId&&clearTimeout(timerId),void 0!==maxTimerId&&clearTimeout(maxTimerId),timerId=maxTimerId=void 0}function debounced(){return timerId&&clearTimeout(timerId),timerId=getNativeImplementation_setTimeout(invokeFunc,wait),maxWait&&void 0===maxTimerId&&(maxTimerId=getNativeImplementation_setTimeout(invokeFunc,maxWait)),callbackReturnValue}return debounced.cancel=cancelTimers,debounced.flush=function(){return void 0!==timerId||void 0!==maxTimerId?invokeFunc():callbackReturnValue},debounced}((()=>this._flush()),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=throttle(((event,isCheckout)=>function(replay,event,isCheckout){return shouldAddEvent(replay,event)?_addEvent(replay,event,isCheckout):Promise.resolve(null)}(this,event,isCheckout)),300,5);const{slowClickTimeout:slowClickTimeout,slowClickIgnoreSelectors:slowClickIgnoreSelectors}=this.getOptions(),slowClickConfig=slowClickTimeout?{threshold:Math.min(3e3,slowClickTimeout),timeout:slowClickTimeout,scrollTimeout:300,ignoreSelector:slowClickIgnoreSelectors?slowClickIgnoreSelectors.join(","):""}:void 0;if(slowClickConfig&&(this.clickDetector=new ClickDetector(this,slowClickConfig)),esm_DEBUG_BUILD){const experiments=options._experiments;esm_logger.setConfig({captureExceptions:!!experiments.captureExceptions,traceInternals:!!experiments.traceInternals})}this._handleVisibilityChange=()=>{"visible"===esm_WINDOW.document.visibilityState?this._doChangeToForegroundTasks():this._doChangeToBackgroundTasks()},this._handleWindowBlur=()=>{const breadcrumb=createBreadcrumb({category:"ui.blur"});this._doChangeToBackgroundTasks(breadcrumb)},this._handleWindowFocus=()=>{const breadcrumb=createBreadcrumb({category:"ui.focus"});this._doChangeToForegroundTasks(breadcrumb)},this._handleKeyboardEvent=event=>{handleKeyboardEvent(this,event)}}getContext(){return this._context}isEnabled(){return this._isEnabled}isPaused(){return this._isPaused}isRecordingCanvas(){return Boolean(this._canvas)}getOptions(){return this._options}handleException(error){esm_DEBUG_BUILD&&esm_logger.exception(error),this._options.onError&&this._options.onError(error)}initializeSampling(previousSessionId){const{errorSampleRate:errorSampleRate,sessionSampleRate:sessionSampleRate}=this._options,requiresManualStart=errorSampleRate<=0&&sessionSampleRate<=0;this._requiresManualStart=requiresManualStart,requiresManualStart||(this._initializeSessionForSampling(previousSessionId),this.session?!1!==this.session.sampled&&(this.recordingMode="buffer"===this.session.sampled&&0===this.session.segmentId?"buffer":"session",esm_DEBUG_BUILD&&esm_logger.infoTick(`Starting replay in ${this.recordingMode} mode`),this._initializeRecording()):esm_DEBUG_BUILD&&esm_logger.exception(new Error("Unable to initialize and create session")))}start(){if(this._isEnabled&&"session"===this.recordingMode)return void(esm_DEBUG_BUILD&&esm_logger.info("Recording is already in progress"));if(this._isEnabled&&"buffer"===this.recordingMode)return void(esm_DEBUG_BUILD&&esm_logger.info("Buffering is in progress, call `flush()` to save the replay"));esm_DEBUG_BUILD&&esm_logger.infoTick("Starting replay in session mode"),this._updateUserActivity();const session=loadOrCreateSession({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=session,this._initializeRecording()}startBuffering(){if(this._isEnabled)return void(esm_DEBUG_BUILD&&esm_logger.info("Buffering is in progress, call `flush()` to save the replay"));esm_DEBUG_BUILD&&esm_logger.infoTick("Starting replay in buffer mode");const session=loadOrCreateSession({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=session,this.recordingMode="buffer",this._initializeRecording()}startRecording(){try{const canvasOptions=this._canvas;this._stopRecording=record({...this._recordingOptions,..."buffer"===this.recordingMode?{checkoutEveryNms:6e4}:this._options._experiments.continuousCheckout&&{checkoutEveryNms:Math.max(36e4,this._options._experiments.continuousCheckout)},emit:getHandleRecordingEmit(this),.../iPhone|iPad|iPod/i.test(NAVIGATOR?.userAgent??"")||/Macintosh/i.test(NAVIGATOR?.userAgent??"")&&NAVIGATOR?.maxTouchPoints&&NAVIGATOR?.maxTouchPoints>1?{sampling:{mousemove:!1}}:{},onMutation:this._onMutationHandler.bind(this),...canvasOptions?{recordCanvas:canvasOptions.recordCanvas,getCanvasManager:canvasOptions.getCanvasManager,sampling:canvasOptions.sampling,dataURLOptions:canvasOptions.dataURLOptions}:{}})}catch(err){this.handleException(err)}}stopRecording(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(err){return this.handleException(err),!1}}async stop({forceFlush:forceFlush=!1,reason:reason}={}){if(this._isEnabled){this._isEnabled=!1;try{esm_DEBUG_BUILD&&esm_logger.info("Stopping Replay"+(reason?` triggered by ${reason}`:"")),resetReplayIdOnDynamicSamplingContext(),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),forceFlush&&await this._flush({force:!0}),this.eventBuffer?.destroy(),this.eventBuffer=null,clearSession(this)}catch(err){this.handleException(err)}}}pause(){this._isPaused||(this._isPaused=!0,this.stopRecording(),esm_DEBUG_BUILD&&esm_logger.info("Pausing replay"))}resume(){this._isPaused&&this._checkSession()&&(this._isPaused=!1,this.startRecording(),esm_DEBUG_BUILD&&esm_logger.info("Resuming replay"))}async sendBufferedReplayOrFlush({continueRecording:continueRecording=!0}={}){if("session"===this.recordingMode)return this.flushImmediate();const activityTime=Date.now();esm_DEBUG_BUILD&&esm_logger.info("Converting buffer to session"),await this.flushImmediate();const hasStoppedRecording=this.stopRecording();continueRecording&&hasStoppedRecording&&"session"!==this.recordingMode&&(this.recordingMode="session",this.session&&(this._updateUserActivity(activityTime),this._updateSessionActivity(activityTime),this._maybeSaveSession()),this.startRecording())}addUpdate(cb){const cbResult=cb();"buffer"!==this.recordingMode&&!0!==cbResult&&this._debouncedFlush()}triggerUserActivity(){if(this._updateUserActivity(),this._stopRecording)this.checkAndHandleExpiredSession(),this._updateSessionActivity();else{if(!this._checkSession())return;this.resume()}}updateUserActivity(){this._updateUserActivity(),this._updateSessionActivity()}conditionalFlush(){return"buffer"===this.recordingMode?Promise.resolve():this.flushImmediate()}flush(){return this._debouncedFlush()}flushImmediate(){return this._debouncedFlush(),this._debouncedFlush.flush()}cancelFlush(){this._debouncedFlush.cancel()}getSessionId(){return this.session?.id}checkAndHandleExpiredSession(){if(!(this._lastActivity&&isExpired(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&"session"===this.session.sampled))return!!this._checkSession();this.pause()}setInitialState(){const urlPath=`${esm_WINDOW.location.pathname}${esm_WINDOW.location.hash}${esm_WINDOW.location.search}`,url=`${esm_WINDOW.location.origin}${urlPath}`;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=url,this._context.initialTimestamp=Date.now(),this._context.urls.push(url)}throttledAddEvent(event,isCheckout){const res=this._throttledAddEvent(event,isCheckout);if("__THROTTLED"===res){const breadcrumb=createBreadcrumb({category:"replay.throttled"});this.addUpdate((()=>!addEventSync(this,{type:5,timestamp:breadcrumb.timestamp||0,data:{tag:"breadcrumb",payload:breadcrumb,metric:!0}})))}return res}getCurrentRoute(){const lastActiveSpan=this.lastActiveSpan||spanUtils_getActiveSpan(),lastRootSpan=lastActiveSpan&&spanUtils_getRootSpan(lastActiveSpan),source=(lastRootSpan&&spanUtils_spanToJSON(lastRootSpan).data||{})["sentry.source"];if(lastRootSpan&&source&&["route","custom"].includes(source))return spanUtils_spanToJSON(lastRootSpan).description}_initializeRecording(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=createEventBuffer({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.startRecording()}_initializeSessionForSampling(previousSessionId){const allowBuffering=this._options.errorSampleRate>0,session=loadOrCreateSession({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,previousSessionId:previousSessionId},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:allowBuffering});this.session=session}_checkSession(){if(!this.session)return!1;const currentSession=this.session;return!shouldRefreshSession(currentSession,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})||(this._refreshSession(currentSession),!1)}async _refreshSession(session){this._isEnabled&&(await this.stop({reason:"refresh session"}),this.initializeSampling(session.id))}_addListeners(){try{esm_WINDOW.document.addEventListener("visibilitychange",this._handleVisibilityChange),esm_WINDOW.addEventListener("blur",this._handleWindowBlur),esm_WINDOW.addEventListener("focus",this._handleWindowFocus),esm_WINDOW.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(addGlobalListeners(this,{autoFlushOnFeedback:this._options._experiments.autoFlushOnFeedback}),this._hasInitializedCoreListeners=!0)}catch(err){this.handleException(err)}this._performanceCleanupCallback=setupPerformanceObserver(this)}_removeListeners(){try{esm_WINDOW.document.removeEventListener("visibilitychange",this._handleVisibilityChange),esm_WINDOW.removeEventListener("blur",this._handleWindowBlur),esm_WINDOW.removeEventListener("focus",this._handleWindowFocus),esm_WINDOW.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(err){this.handleException(err)}}_doChangeToBackgroundTasks(breadcrumb){if(!this.session)return;isSessionExpired(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})||(breadcrumb&&this._createCustomBreadcrumb(breadcrumb),this.conditionalFlush())}_doChangeToForegroundTasks(breadcrumb){if(!this.session)return;this.checkAndHandleExpiredSession()?breadcrumb&&this._createCustomBreadcrumb(breadcrumb):esm_DEBUG_BUILD&&esm_logger.info("Document has become active, but session has expired")}_updateUserActivity(_lastActivity=Date.now()){this._lastActivity=_lastActivity}_updateSessionActivity(_lastActivity=Date.now()){this.session&&(this.session.lastActivity=_lastActivity,this._maybeSaveSession())}_createCustomBreadcrumb(breadcrumb){this.addUpdate((()=>{this.throttledAddEvent({type:EventType.Custom,timestamp:breadcrumb.timestamp||0,data:{tag:"breadcrumb",payload:breadcrumb}})}))}_addPerformanceEntries(){let performanceEntries=(entries=this.performanceEntries,entries.map(createPerformanceEntry).filter(Boolean)).concat(this.replayPerformanceEntries);var entries;if(this.performanceEntries=[],this.replayPerformanceEntries=[],this._requiresManualStart){const initialTimestampInSeconds=this._context.initialTimestamp/1e3;performanceEntries=performanceEntries.filter((entry=>entry.start>=initialTimestampInSeconds))}return Promise.all(createPerformanceSpans(this,performanceEntries))}_clearContext(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]}_updateInitialTimestampFromEventBuffer(){const{session:session,eventBuffer:eventBuffer}=this;if(!session||!eventBuffer||this._requiresManualStart)return;if(session.segmentId)return;const earliestEvent=eventBuffer.getEarliestTimestamp();earliestEvent&&earliestEvent<this._context.initialTimestamp&&(this._context.initialTimestamp=earliestEvent)}_popEventContext(){const _context={initialTimestamp:this._context.initialTimestamp,initialUrl:this._context.initialUrl,errorIds:Array.from(this._context.errorIds),traceIds:Array.from(this._context.traceIds),urls:this._context.urls};return this._clearContext(),_context}async _runFlush(){const replayId=this.getSessionId();if(this.session&&this.eventBuffer&&replayId){if(await this._addPerformanceEntries(),this.eventBuffer?.hasEvents&&(await async function(replay){try{return Promise.all(createPerformanceSpans(replay,[createMemoryEntry(esm_WINDOW.performance.memory)]))}catch(error){return[]}}(this),this.eventBuffer&&replayId===this.getSessionId()))try{this._updateInitialTimestampFromEventBuffer();const timestamp=Date.now();if(timestamp-this._context.initialTimestamp>this._options.maxReplayDuration+3e4)throw new Error("Session is too long, not sending replay");const eventContext=this._popEventContext(),segmentId=this.session.segmentId++;this._maybeSaveSession();const recordingData=await this.eventBuffer.finish();await sendReplay({replayId:replayId,recordingData:recordingData,segmentId:segmentId,eventContext:eventContext,session:this.session,timestamp:timestamp,onError:err=>this.handleException(err)})}catch(err){this.handleException(err),this.stop({reason:"sendReplay"});const client=currentScopes_getClient();if(client){const dropReason=err instanceof RateLimitError?"ratelimit_backoff":"send_error";client.recordDroppedEvent(dropReason,"replay")}}}else esm_DEBUG_BUILD&&esm_logger.error("No session or eventBuffer found to flush.")}async _flush({force:force=!1}={}){if(!this._isEnabled&&!force)return;if(!this.checkAndHandleExpiredSession())return void(esm_DEBUG_BUILD&&esm_logger.error("Attempting to finish replay event after session expired."));if(!this.session)return;const start=this.session.started,duration=Date.now()-start;this._debouncedFlush.cancel();const tooShort=duration<this._options.minReplayDuration,tooLong=duration>this._options.maxReplayDuration+5e3;if(tooShort||tooLong)return esm_DEBUG_BUILD&&esm_logger.info(`Session duration (${Math.floor(duration/1e3)}s) is too ${tooShort?"short":"long"}, not sending replay.`),void(tooShort&&this._debouncedFlush());const eventBuffer=this.eventBuffer;eventBuffer&&0===this.session.segmentId&&!eventBuffer.hasCheckout&&esm_DEBUG_BUILD&&esm_logger.info("Flushing initial segment without checkout.");const _flushInProgress=!!this._flushLock;this._flushLock||(this._flushLock=this._runFlush());try{await this._flushLock}catch(err){this.handleException(err)}finally{this._flushLock=void 0,_flushInProgress&&this._debouncedFlush()}}_maybeSaveSession(){this.session&&this._options.stickySession&&saveSession(this.session)}_onMutationHandler(mutations){const count=mutations.length,mutationLimit=this._options.mutationLimit,overMutationLimit=mutationLimit&&count>mutationLimit;if(count>this._options.mutationBreadcrumbLimit||overMutationLimit){const breadcrumb=createBreadcrumb({category:"replay.mutations",data:{count:count,limit:overMutationLimit}});this._createCustomBreadcrumb(breadcrumb)}return!overMutationLimit||(this.stop({reason:"mutationLimit",forceFlush:"session"===this.recordingMode}),!1)}}function getOption(selectors,defaultSelectors){return[...selectors,...defaultSelectors].join(",")}const MEDIA_SELECTORS='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',DEFAULT_NETWORK_HEADERS=["content-length","content-type","accept"];let _initialized=!1;class Replay{constructor({flushMinDelay:flushMinDelay=5e3,flushMaxDelay:flushMaxDelay=5500,minReplayDuration:minReplayDuration=4999,maxReplayDuration:maxReplayDuration=36e5,stickySession:stickySession=!0,useCompression:useCompression=!0,workerUrl:workerUrl,_experiments:_experiments={},maskAllText:maskAllText=!0,maskAllInputs:maskAllInputs=!0,blockAllMedia:blockAllMedia=!0,mutationBreadcrumbLimit:mutationBreadcrumbLimit=750,mutationLimit:mutationLimit=1e4,slowClickTimeout:slowClickTimeout=7e3,slowClickIgnoreSelectors:slowClickIgnoreSelectors=[],networkDetailAllowUrls:networkDetailAllowUrls=[],networkDetailDenyUrls:networkDetailDenyUrls=[],networkCaptureBodies:networkCaptureBodies=!0,networkRequestHeaders:networkRequestHeaders=[],networkResponseHeaders:networkResponseHeaders=[],mask:mask=[],maskAttributes:maskAttributes=["title","placeholder"],unmask:unmask=[],block:block=[],unblock:unblock=[],ignore:ignore=[],maskFn:maskFn,beforeAddRecordingEvent:beforeAddRecordingEvent,beforeErrorSampling:beforeErrorSampling,onError:onError}={}){this.name="Replay";const privacyOptions=function({mask:mask,unmask:unmask,block:block,unblock:unblock,ignore:ignore}){return{maskTextSelector:getOption(mask,[".sentry-mask","[data-sentry-mask]"]),unmaskTextSelector:getOption(unmask,[]),blockSelector:getOption(block,[".sentry-block","[data-sentry-block]","base","iframe[srcdoc]:not([src])"]),unblockSelector:getOption(unblock,[]),ignoreSelector:getOption(ignore,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'])}}({mask:mask,unmask:unmask,block:block,unblock:unblock,ignore:ignore});if(this._recordingOptions={maskAllInputs:maskAllInputs,maskAllText:maskAllText,maskInputOptions:{password:!0},maskTextFn:maskFn,maskInputFn:maskFn,maskAttributeFn:(key,value,el)=>function({el:el,key:key,maskAttributes:maskAttributes,maskAllText:maskAllText,privacyOptions:privacyOptions,value:value}){return maskAllText?privacyOptions.unmaskTextSelector&&el.matches(privacyOptions.unmaskTextSelector)?value:maskAttributes.includes(key)||"value"===key&&"INPUT"===el.tagName&&["submit","button"].includes(el.getAttribute("type")||"")?value.replace(/[\S]/g,"*"):value:value}({maskAttributes:maskAttributes,maskAllText:maskAllText,privacyOptions:privacyOptions,key:key,value:value,el:el}),...privacyOptions,slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:err=>{try{err.__rrweb__=!0}catch(error){}},recordCrossOriginIframes:Boolean(_experiments.recordCrossOriginIframes)},this._initialOptions={flushMinDelay:flushMinDelay,flushMaxDelay:flushMaxDelay,minReplayDuration:Math.min(minReplayDuration,15e3),maxReplayDuration:Math.min(maxReplayDuration,36e5),stickySession:stickySession,useCompression:useCompression,workerUrl:workerUrl,blockAllMedia:blockAllMedia,maskAllInputs:maskAllInputs,maskAllText:maskAllText,mutationBreadcrumbLimit:mutationBreadcrumbLimit,mutationLimit:mutationLimit,slowClickTimeout:slowClickTimeout,slowClickIgnoreSelectors:slowClickIgnoreSelectors,networkDetailAllowUrls:networkDetailAllowUrls,networkDetailDenyUrls:networkDetailDenyUrls,networkCaptureBodies:networkCaptureBodies,networkRequestHeaders:_getMergedNetworkHeaders(networkRequestHeaders),networkResponseHeaders:_getMergedNetworkHeaders(networkResponseHeaders),beforeAddRecordingEvent:beforeAddRecordingEvent,beforeErrorSampling:beforeErrorSampling,onError:onError,_experiments:_experiments},this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?`${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`:MEDIA_SELECTORS),this._isInitialized&&isBrowser())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}get _isInitialized(){return _initialized}set _isInitialized(value){_initialized=value}afterAllSetup(client){isBrowser()&&!this._replay&&(this._setup(client),this._initialize(client))}start(){this._replay&&this._replay.start()}startBuffering(){this._replay&&this._replay.startBuffering()}stop(){return this._replay?this._replay.stop({forceFlush:"session"===this._replay.recordingMode}):Promise.resolve()}flush(options){return this._replay?this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(options):(this._replay.start(),Promise.resolve()):Promise.resolve()}getReplayId(){if(this._replay?.isEnabled())return this._replay.getSessionId()}getRecordingMode(){if(this._replay?.isEnabled())return this._replay.recordingMode}_initialize(client){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(client),this._replay.initializeSampling())}_setup(client){const finalOptions=function(initialOptions,client){const opt=client.getOptions(),finalOptions={sessionSampleRate:0,errorSampleRate:0,...initialOptions},replaysSessionSampleRate=parseSampleRate(opt.replaysSessionSampleRate),replaysOnErrorSampleRate=parseSampleRate(opt.replaysOnErrorSampleRate);null==replaysSessionSampleRate&&null==replaysOnErrorSampleRate&&consoleSandbox((()=>{console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")}));null!=replaysSessionSampleRate&&(finalOptions.sessionSampleRate=replaysSessionSampleRate);null!=replaysOnErrorSampleRate&&(finalOptions.errorSampleRate=replaysOnErrorSampleRate);return finalOptions}(this._initialOptions,client);this._replay=new ReplayContainer({options:finalOptions,recordingOptions:this._recordingOptions})}_maybeLoadFromReplayCanvasIntegration(client){try{const canvasIntegration=client.getIntegrationByName("ReplayCanvas");if(!canvasIntegration)return;this._replay._canvas=canvasIntegration.getOptions()}catch{}}}function _getMergedNetworkHeaders(headers){return[...DEFAULT_NETWORK_HEADERS,...headers.map((header=>header.toLowerCase()))]}const installedIntegrations=[];function getIntegrationsToSetup(options){const defaultIntegrations=options.defaultIntegrations||[],userIntegrations=options.integrations;let integrations;if(defaultIntegrations.forEach((integration=>{integration.isDefaultInstance=!0})),Array.isArray(userIntegrations))integrations=[...defaultIntegrations,...userIntegrations];else if("function"==typeof userIntegrations){const resolvedUserIntegrations=userIntegrations(defaultIntegrations);integrations=Array.isArray(resolvedUserIntegrations)?resolvedUserIntegrations:[resolvedUserIntegrations]}else integrations=defaultIntegrations;return function(integrations){const integrationsByName={};return integrations.forEach((currentInstance=>{const{name:name}=currentInstance,existingInstance=integrationsByName[name];existingInstance&&!existingInstance.isDefaultInstance&¤tInstance.isDefaultInstance||(integrationsByName[name]=currentInstance)})),Object.values(integrationsByName)}(integrations)}function afterSetupIntegrations(client,integrations){for(const integration of integrations)integration?.afterAllSetup&&integration.afterAllSetup(client)}function setupIntegration(client,integration,integrationIndex){if(integrationIndex[integration.name])esm_debug_build_DEBUG_BUILD&&logger_logger.log(`Integration skipped because it was already installed: ${integration.name}`);else{if(integrationIndex[integration.name]=integration,-1===installedIntegrations.indexOf(integration.name)&&"function"==typeof integration.setupOnce&&(integration.setupOnce(),installedIntegrations.push(integration.name)),integration.setup&&"function"==typeof integration.setup&&integration.setup(client),"function"==typeof integration.preprocessEvent){const callback=integration.preprocessEvent.bind(integration);client.on("preprocessEvent",((event,hint)=>callback(event,hint,client)))}if("function"==typeof integration.processEvent){const callback=integration.processEvent.bind(integration),processor=Object.assign(((event,hint)=>callback(event,hint,client)),{id:integration.name});client.addEventProcessor(processor)}esm_debug_build_DEBUG_BUILD&&logger_logger.log(`Integration installed: ${integration.name}`)}}function getPossibleEventMessages(event){const possibleMessages=[];event.message&&possibleMessages.push(event.message);try{const lastException=event.exception.values[event.exception.values.length-1];lastException?.value&&(possibleMessages.push(lastException.value),lastException.type&&possibleMessages.push(`${lastException.type}: ${lastException.value}`))}catch(e){}return possibleMessages}const 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\.[A-Z]'\)$/,'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$/],eventFiltersIntegration=(options={})=>{let mergedOptions;return{name:"EventFilters",setup(client){const clientOptions=client.getOptions();mergedOptions=_mergeOptions(options,clientOptions)},processEvent(event,_hint,client){if(!mergedOptions){const clientOptions=client.getOptions();mergedOptions=_mergeOptions(options,clientOptions)}return function(event,options){if(event.type){if("transaction"===event.type&&function(event,ignoreTransactions){if(!ignoreTransactions?.length)return!1;const name=event.transaction;return!!name&&stringMatchesSomePattern(name,ignoreTransactions)}(event,options.ignoreTransactions))return esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${getEventDescription(event)}`),!0}else{if(function(event,ignoreErrors){if(!ignoreErrors?.length)return!1;return getPossibleEventMessages(event).some((message=>stringMatchesSomePattern(message,ignoreErrors)))}(event,options.ignoreErrors))return esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${getEventDescription(event)}`),!0;if(function(event){if(!event.exception?.values?.length)return!1;return!event.message&&!event.exception.values.some((value=>value.stacktrace||value.type&&"Error"!==value.type||value.value))}(event))return esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Event dropped due to not having an error message, error type or stacktrace.\nEvent: ${getEventDescription(event)}`),!0;if(function(event,denyUrls){if(!denyUrls?.length)return!1;const url=_getEventFilterUrl(event);return!!url&&stringMatchesSomePattern(url,denyUrls)}(event,options.denyUrls))return esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${getEventDescription(event)}.\nUrl: ${_getEventFilterUrl(event)}`),!0;if(!function(event,allowUrls){if(!allowUrls?.length)return!0;const url=_getEventFilterUrl(event);return!url||stringMatchesSomePattern(url,allowUrls)}(event,options.allowUrls))return esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${getEventDescription(event)}.\nUrl: ${_getEventFilterUrl(event)}`),!0}return!1}(event,mergedOptions)?null:event}}},inboundFiltersIntegration=(options={})=>({...eventFiltersIntegration(options),name:"InboundFilters"});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||[]]}}function _getEventFilterUrl(event){try{const rootException=[...event.exception?.values??[]].reverse().find((value=>void 0===value.mechanism?.parent_id&&value.stacktrace?.frames?.length)),frames=rootException?.stacktrace?.frames;return frames?function(frames=[]){for(let i=frames.length-1;i>=0;i--){const frame=frames[i];if(frame&&"<anonymous>"!==frame.filename&&"[native code]"!==frame.filename)return frame.filename||null}return null}(frames):null}catch(oO){return esm_debug_build_DEBUG_BUILD&&logger_logger.error(`Cannot extract url for event ${getEventDescription(event)}`),null}}let originalFunctionToString;const SETUP_CLIENTS=new WeakMap,functionToStringIntegration=()=>({name:"FunctionToString",setupOnce(){originalFunctionToString=Function.prototype.toString;try{Function.prototype.toString=function(...args){const originalFunction=getOriginalFunction(this),context=SETUP_CLIENTS.has(currentScopes_getClient())&&void 0!==originalFunction?originalFunction:this;return originalFunctionToString.apply(context,args)}}catch{}},setup(client){SETUP_CLIENTS.set(client,!0)}}),dedupeIntegration=()=>{let previousEvent;return{name:"Dedupe",processEvent(currentEvent){if(currentEvent.type)return currentEvent;try{if(function(currentEvent,previousEvent){if(!previousEvent)return!1;if(function(currentEvent,previousEvent){const currentMessage=currentEvent.message,previousMessage=previousEvent.message;if(!currentMessage&&!previousMessage)return!1;if(currentMessage&&!previousMessage||!currentMessage&&previousMessage)return!1;if(currentMessage!==previousMessage)return!1;if(!_isSameFingerprint(currentEvent,previousEvent))return!1;if(!_isSameStacktrace(currentEvent,previousEvent))return!1;return!0}(currentEvent,previousEvent))return!0;if(function(currentEvent,previousEvent){const previousException=_getExceptionFromEvent(previousEvent),currentException=_getExceptionFromEvent(currentEvent);if(!previousException||!currentException)return!1;if(previousException.type!==currentException.type||previousException.value!==currentException.value)return!1;if(!_isSameFingerprint(currentEvent,previousEvent))return!1;if(!_isSameStacktrace(currentEvent,previousEvent))return!1;return!0}(currentEvent,previousEvent))return!0;return!1}(currentEvent,previousEvent))return esm_debug_build_DEBUG_BUILD&&logger_logger.warn("Event dropped due to being a duplicate of previously captured event."),null}catch(_oO){}return previousEvent=currentEvent}}};function _isSameStacktrace(currentEvent,previousEvent){let currentFrames=getFramesFromEvent(currentEvent),previousFrames=getFramesFromEvent(previousEvent);if(!currentFrames&&!previousFrames)return!0;if(currentFrames&&!previousFrames||!currentFrames&&previousFrames)return!1;if(previousFrames.length!==currentFrames.length)return!1;for(let i=0;i<previousFrames.length;i++){const frameA=previousFrames[i],frameB=currentFrames[i];if(frameA.filename!==frameB.filename||frameA.lineno!==frameB.lineno||frameA.colno!==frameB.colno||frameA.function!==frameB.function)return!1}return!0}function _isSameFingerprint(currentEvent,previousEvent){let currentFingerprint=currentEvent.fingerprint,previousFingerprint=previousEvent.fingerprint;if(!currentFingerprint&&!previousFingerprint)return!0;if(currentFingerprint&&!previousFingerprint||!currentFingerprint&&previousFingerprint)return!1;try{return!(currentFingerprint.join("")!==previousFingerprint.join(""))}catch(_oO){return!1}}function _getExceptionFromEvent(event){return event.exception?.values&&event.exception.values[0]}function initAndBind(clientClass,options){!0===options.debug&&(esm_debug_build_DEBUG_BUILD?logger_logger.enable():consoleSandbox((()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")})));currentScopes_getCurrentScope().update(options.initialScope);const client=new clientClass(options);return function(client){currentScopes_getCurrentScope().setClient(client)}(client),client.init(),client}function getBaseApiEndpoint(dsn){const protocol=dsn.protocol?`${dsn.protocol}:`:"",port=dsn.port?`:${dsn.port}`:"";return`${protocol}//${dsn.host}${port}${dsn.path?`/${dsn.path}`:""}/api/`}function getEnvelopeEndpointWithUrlEncodedAuth(dsn,tunnel,sdkInfo){return tunnel||`${function(dsn){return`${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`}(dsn)}?${function(dsn,sdkInfo){const params={sentry_version:"7"};return dsn.publicKey&&(params.sentry_key=dsn.publicKey),sdkInfo&&(params.sentry_client=`${sdkInfo.name}/${sdkInfo.version}`),new URLSearchParams(params).toString()}(dsn,sdkInfo)}`}const ALREADY_SEEN_ERROR="Not capturing exception because it's already been captured.",INTERNAL_ERROR_SYMBOL=Symbol.for("SentryInternalError"),DO_NOT_SEND_EVENT_SYMBOL=Symbol.for("SentryDoNotSendEventError");function _makeInternalError(message){return{message:message,[INTERNAL_ERROR_SYMBOL]:!0}}function _makeDoNotSendEventError(message){return{message:message,[DO_NOT_SEND_EVENT_SYMBOL]:!0}}function _isInternalError(error){return!!error&&"object"==typeof error&&INTERNAL_ERROR_SYMBOL in error}function _isDoNotSendEventError(error){return!!error&&"object"==typeof error&&DO_NOT_SEND_EVENT_SYMBOL in error}class Client{constructor(options){if(this._options=options,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],options.dsn?this._dsn=dsn_makeDsn(options.dsn):esm_debug_build_DEBUG_BUILD&&logger_logger.warn("No DSN provided, client will not send events."),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:url})}}captureException(exception,hint,scope){const eventId=misc_uuid4();if(checkOrSetAlreadyCaught(exception))return esm_debug_build_DEBUG_BUILD&&logger_logger.log(ALREADY_SEEN_ERROR),eventId;const hintWithEventId={event_id:eventId,...hint};return this._process(this.eventFromException(exception,hintWithEventId).then((event=>this._captureEvent(event,hintWithEventId,scope)))),hintWithEventId.event_id}captureMessage(message,level,hint,currentScope){const hintWithEventId={event_id:misc_uuid4(),...hint},eventMessage=is_isParameterizedString(message)?message:String(message),promisedEvent=is_isPrimitive(message)?this.eventFromMessage(eventMessage,level,hintWithEventId):this.eventFromException(message,hintWithEventId);return this._process(promisedEvent.then((event=>this._captureEvent(event,hintWithEventId,currentScope)))),hintWithEventId.event_id}captureEvent(event,hint,currentScope){const eventId=misc_uuid4();if(hint?.originalException&&checkOrSetAlreadyCaught(hint.originalException))return esm_debug_build_DEBUG_BUILD&&logger_logger.log(ALREADY_SEEN_ERROR),eventId;const hintWithEventId={event_id:eventId,...hint},sdkProcessingMetadata=event.sdkProcessingMetadata||{},capturedSpanScope=sdkProcessingMetadata.capturedSpanScope,capturedSpanIsolationScope=sdkProcessingMetadata.capturedSpanIsolationScope;return this._process(this._captureEvent(event,hintWithEventId,capturedSpanScope||currentScope,capturedSpanIsolationScope)),hintWithEventId.event_id}captureSession(session){this.sendSession(session),updateSession(session,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(timeout){const transport=this._transport;return transport?(this.emit("flush"),this._isClientDoneProcessing(timeout).then((clientFinished=>transport.flush(timeout).then((transportFlushed=>clientFinished&&transportFlushed))))):resolvedSyncPromise(!0)}close(timeout){return this.flush(timeout).then((result=>(this.getOptions().enabled=!1,this.emit("close"),result)))}getEventProcessors(){return this._eventProcessors}addEventProcessor(eventProcessor){this._eventProcessors.push(eventProcessor)}init(){(this._isEnabled()||this._options.integrations.some((({name:name})=>name.startsWith("Spotlight"))))&&this._setupIntegrations()}getIntegrationByName(integrationName){return this._integrations[integrationName]}addIntegration(integration){const isAlreadyInstalled=this._integrations[integration.name];setupIntegration(this,integration,this._integrations),isAlreadyInstalled||afterSetupIntegrations(this,[integration])}sendEvent(event,hint={}){this.emit("beforeSendEvent",event,hint);let env=function(event,dsn,metadata,tunnel){const sdkInfo=getSdkMetadataForEnvelopeHeader(metadata),eventType=event.type&&"replay_event"!==event.type?event.type:"event";!function(event,sdkInfo){sdkInfo&&(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||[]])}(event,metadata?.sdk);const envelopeHeaders=createEventEnvelopeHeaders(event,sdkInfo,tunnel,dsn);return delete event.sdkProcessingMetadata,createEnvelope(envelopeHeaders,[[{type:eventType},event]])}(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);promise&&promise.then((sendResponse=>this.emit("afterSendEvent",event,sendResponse)),null)}sendSession(session){const{release:clientReleaseOption,environment:clientEnvironmentOption=DEFAULT_ENVIRONMENT}=this._options;if("aggregates"in session){const sessionAttrs=session.attrs||{};if(!sessionAttrs.release&&!clientReleaseOption)return void(esm_debug_build_DEBUG_BUILD&&logger_logger.warn("Discarded session because of missing or non-string release"));sessionAttrs.release=sessionAttrs.release||clientReleaseOption,sessionAttrs.environment=sessionAttrs.environment||clientEnvironmentOption,session.attrs=sessionAttrs}else{if(!session.release&&!clientReleaseOption)return void(esm_debug_build_DEBUG_BUILD&&logger_logger.warn("Discarded session because of missing or non-string release"));session.release=session.release||clientReleaseOption,session.environment=session.environment||clientEnvironmentOption}this.emit("beforeSendSession",session);const env=function(session,dsn,metadata,tunnel){const sdkInfo=getSdkMetadataForEnvelopeHeader(metadata);return createEnvelope({sent_at:(new Date).toISOString(),...sdkInfo&&{sdk:sdkInfo},...!!tunnel&&dsn&&{dsn:dsn_dsnToString(dsn)}},["aggregates"in session?[{type:"sessions"},session]:[{type:"session"},session.toJSON()]])}(session,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(env)}recordDroppedEvent(reason,category,count=1){if(this._options.sendClientReports){const key=`${reason}:${category}`;esm_debug_build_DEBUG_BUILD&&logger_logger.log(`Recording outcome: "${key}"${count>1?` (${count} times)`:""}`),this._outcomes[key]=(this._outcomes[key]||0)+count}}on(hook,callback){const hooks=this._hooks[hook]=this._hooks[hook]||[];return hooks.push(callback),()=>{const cbIndex=hooks.indexOf(callback);cbIndex>-1&&hooks.splice(cbIndex,1)}}emit(hook,...rest){const callbacks=this._hooks[hook];callbacks&&callbacks.forEach((callback=>callback(...rest)))}sendEnvelope(envelope){return this.emit("beforeEnvelope",envelope),this._isEnabled()&&this._transport?this._transport.send(envelope).then(null,(reason=>(esm_debug_build_DEBUG_BUILD&&logger_logger.error("Error while sending envelope:",reason),reason))):(esm_debug_build_DEBUG_BUILD&&logger_logger.error("Transport disabled"),resolvedSyncPromise({}))}_setupIntegrations(){const{integrations:integrations}=this._options;this._integrations=function(client,integrations){const integrationIndex={};return integrations.forEach((integration=>{integration&&setupIntegration(client,integration,integrationIndex)})),integrationIndex}(this,integrations),afterSetupIntegrations(this,integrations)}_updateSessionFromEvent(session,event){let crashed="fatal"===event.level,errored=!1;const exceptions=event.exception?.values;if(exceptions){errored=!0;for(const ex of exceptions){const mechanism=ex.mechanism;if(!1===mechanism?.handled){crashed=!0;break}}}const sessionNonTerminal="ok"===session.status;(sessionNonTerminal&&0===session.errors||sessionNonTerminal&&crashed)&&(updateSession(session,{...crashed&&{status:"crashed"},errors:session.errors||Number(errored||crashed)}),this.captureSession(session))}_isClientDoneProcessing(timeout){return new SyncPromise((resolve=>{let ticked=0;const interval=setInterval((()=>{0==this._numProcessing?(clearInterval(interval),resolve(!0)):(ticked+=1,timeout&&ticked>=timeout&&(clearInterval(interval),resolve(!1)))}),1)}))}_isEnabled(){return!1!==this.getOptions().enabled&&void 0!==this._transport}_prepareEvent(event,hint,currentScope,isolationScope){const options=this.getOptions(),integrations=Object.keys(this._integrations);return!hint.integrations&&integrations?.length&&(hint.integrations=integrations),this.emit("preprocessEvent",event,hint),event.type||isolationScope.setLastEventId(event.event_id||hint.event_id),prepareEvent(options,event,hint,currentScope,this,isolationScope).then((evt=>{if(null===evt)return evt;this.emit("postprocessEvent",evt,hint),evt.contexts={trace:currentScopes_getTraceContextFromScope(currentScope),...evt.contexts};const dynamicSamplingContext=function(client,scope){const propagationContext=scope.getPropagationContext();return propagationContext.dsc||getDynamicSamplingContextFromClient(propagationContext.traceId,client)}(this,currentScope);return evt.sdkProcessingMetadata={dynamicSamplingContext:dynamicSamplingContext,...evt.sdkProcessingMetadata},evt}))}_captureEvent(event,hint={},currentScope=currentScopes_getCurrentScope(),isolationScope=currentScopes_getIsolationScope()){return esm_debug_build_DEBUG_BUILD&&client_isErrorEvent(event)&&logger_logger.log(`Captured error event \`${getPossibleEventMessages(event)[0]||"<unknown>"}\``),this._processEvent(event,hint,currentScope,isolationScope).then((finalEvent=>finalEvent.event_id),(reason=>{esm_debug_build_DEBUG_BUILD&&(_isDoNotSendEventError(reason)?logger_logger.log(reason.message):_isInternalError(reason)?logger_logger.warn(reason.message):logger_logger.warn(reason))}))}_processEvent(event,hint,currentScope,isolationScope){const options=this.getOptions(),{sampleRate:sampleRate}=options,isTransaction=client_isTransactionEvent(event),isError=client_isErrorEvent(event),eventType=event.type||"error",beforeSendLabel=`before send for type \`${eventType}\``,parsedSampleRate=void 0===sampleRate?void 0:parseSampleRate(sampleRate);if(isError&&"number"==typeof parsedSampleRate&&Math.random()>parsedSampleRate)return this.recordDroppedEvent("sample_rate","error"),rejectedSyncPromise(_makeDoNotSendEventError(`Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`));const dataCategory="replay_event"===eventType?"replay":eventType;return this._prepareEvent(event,hint,currentScope,isolationScope).then((prepared=>{if(null===prepared)throw this.recordDroppedEvent("event_processor",dataCategory),_makeDoNotSendEventError("An event processor returned `null`, will not send event.");if(hint.data&&!0===hint.data.__sentry__)return prepared;const result=function(client,options,event,hint){const{beforeSend:beforeSend,beforeSendTransaction:beforeSendTransaction,beforeSendSpan:beforeSendSpan}=options;let processedEvent=event;if(client_isErrorEvent(processedEvent)&&beforeSend)return beforeSend(processedEvent,hint);if(client_isTransactionEvent(processedEvent)){if(beforeSendSpan){const processedRootSpanJson=beforeSendSpan(function(event){const{trace_id:trace_id,parent_span_id:parent_span_id,span_id:span_id,status:status,origin:origin,data:data,op:op}=event.contexts?.trace??{};return{data:data??{},description:event.transaction,op:op,parent_span_id:parent_span_id,span_id:span_id??"",start_timestamp:event.start_timestamp??0,status:status,timestamp:event.timestamp,trace_id:trace_id??"",origin:origin,profile_id:data?.["sentry.profile_id"],exclusive_time:data?.["sentry.exclusive_time"],measurements:event.measurements,is_segment:!0}}(processedEvent));if(processedRootSpanJson?processedEvent=merge(event,{type:"transaction",timestamp:(span=processedRootSpanJson).timestamp,start_timestamp:span.start_timestamp,transaction:span.description,contexts:{trace:{trace_id:span.trace_id,span_id:span.span_id,parent_span_id:span.parent_span_id,op:span.op,status:span.status,origin:span.origin,data:{...span.data,...span.profile_id&&{[SEMANTIC_ATTRIBUTE_PROFILE_ID]:span.profile_id},...span.exclusive_time&&{[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]:span.exclusive_time}}}},measurements:span.measurements}):showSpanDropWarning(),processedEvent.spans){const processedSpans=[];for(const span of processedEvent.spans){const processedSpan=beforeSendSpan(span);processedSpan?processedSpans.push(processedSpan):(showSpanDropWarning(),processedSpans.push(span))}processedEvent.spans=processedSpans}}if(beforeSendTransaction){if(processedEvent.spans){const spanCountBefore=processedEvent.spans.length;processedEvent.sdkProcessingMetadata={...event.sdkProcessingMetadata,spanCountBeforeProcessing:spanCountBefore}}return beforeSendTransaction(processedEvent,hint)}}var span;return processedEvent}(0,options,prepared,hint);return function(beforeSendResult,beforeSendLabel){const invalidValueError=`${beforeSendLabel} must return \`null\` or a valid event.`;if(is_isThenable(beforeSendResult))return beforeSendResult.then((event=>{if(!isPlainObject(event)&&null!==event)throw _makeInternalError(invalidValueError);return event}),(e=>{throw _makeInternalError(`${beforeSendLabel} rejected with ${e}`)}));if(!isPlainObject(beforeSendResult)&&null!==beforeSendResult)throw _makeInternalError(invalidValueError);return beforeSendResult}(result,beforeSendLabel)})).then((processedEvent=>{if(null===processedEvent){if(this.recordDroppedEvent("before_send",dataCategory),isTransaction){const spanCount=1+(event.spans||[]).length;this.recordDroppedEvent("before_send","span",spanCount)}throw _makeDoNotSendEventError(`${beforeSendLabel} returned \`null\`, will not send event.`)}const session=currentScope.getSession()||isolationScope.getSession();if(isError&&session&&this._updateSessionFromEvent(session,processedEvent),isTransaction){const droppedSpanCount=(processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing||0)-(processedEvent.spans?processedEvent.spans.length:0);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:source}}return this.sendEvent(processedEvent,hint),processedEvent})).then(null,(reason=>{if(_isDoNotSendEventError(reason)||_isInternalError(reason))throw reason;throw this.captureException(reason,{data:{__sentry__:!0},originalException:reason}),_makeInternalError(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`)}))}_process(promise){this._numProcessing++,promise.then((value=>(this._numProcessing--,value)),(reason=>(this._numProcessing--,reason)))}_clearOutcomes(){const outcomes=this._outcomes;return this._outcomes={},Object.entries(outcomes).map((([key,quantity])=>{const[reason,category]=key.split(":");return{reason:reason,category:category,quantity:quantity}}))}_flushOutcomes(){esm_debug_build_DEBUG_BUILD&&logger_logger.log("Flushing outcomes...");const outcomes=this._clearOutcomes();if(0===outcomes.length)return void(esm_debug_build_DEBUG_BUILD&&logger_logger.log("No outcomes to send"));if(!this._dsn)return void(esm_debug_build_DEBUG_BUILD&&logger_logger.log("No dsn provided, will not send outcomes"));esm_debug_build_DEBUG_BUILD&&logger_logger.log("Sending outcomes:",outcomes);const envelope=(discarded_events=outcomes,createEnvelope((dsn=this._options.tunnel&&dsn_dsnToString(this._dsn))?{dsn:dsn}:{},[[{type:"client_report"},{timestamp:timestamp||dateTimestampInSeconds(),discarded_events:discarded_events}]]));var discarded_events,dsn,timestamp;this.sendEnvelope(envelope)}}function client_isErrorEvent(event){return void 0===event.type}function client_isTransactionEvent(event){return"transaction"===event.type}function applySdkMetadata(options,name,names=[name],source="npm"){const metadata=options._metadata||{};metadata.sdk||(metadata.sdk={name:`sentry.javascript.${name}`,packages:names.map((name=>({name:`${source}:@sentry/${name}`,version:"9.13.0"}))),version:"9.13.0"}),options._metadata=metadata}function createOtelLogEnvelopeItem(log){return[{type:"otel_log"},log]}const CLIENT_TO_LOG_BUFFER_MAP=new WeakMap;function _INTERNAL_flushLogsBuffer(client,maybeLogBuffer){const logBuffer=maybeLogBuffer??CLIENT_TO_LOG_BUFFER_MAP.get(client)??[];if(0===logBuffer.length)return;const clientOptions=client.getOptions(),envelope=function(logs,metadata,tunnel,dsn){const headers={};return metadata?.sdk&&(headers.sdk={name:metadata.sdk.name,version:metadata.sdk.version}),tunnel&&dsn&&(headers.dsn=dsn_dsnToString(dsn)),createEnvelope(headers,logs.map(createOtelLogEnvelopeItem))}(logBuffer,clientOptions._metadata,clientOptions.tunnel,client.getDsn());logBuffer.length=0,client.emit("flushLogs"),client.sendEnvelope(envelope)}function addAutoIpAddressToUser(objWithMaybeUser){void 0===objWithMaybeUser.user?.ip_address&&(objWithMaybeUser.user={...objWithMaybeUser.user,ip_address:"{{auto}}"})}function addAutoIpAddressToSession(session){"aggregates"in session?void 0===session.attrs?.ip_address&&(session.attrs={...session.attrs,ip_address:"{{auto}}"}):void 0===session.ipAddress&&(session.ipAddress="{{auto}}")}function exceptionFromError(stackParser,ex){const frames=parseStackFrames(stackParser,ex),exception={type:extractType(ex),value:extractMessage(ex)};return frames.length&&(exception.stacktrace={frames:frames}),void 0===exception.type&&""===exception.value&&(exception.value="Unrecoverable error caught"),exception}function eventFromPlainObject(stackParser,exception,syntheticException,isUnhandledRejection){const client=currentScopes_getClient(),normalizeDepth=client?.getOptions().normalizeDepth,errorFromProp=function(obj){for(const prop in obj)if(Object.prototype.hasOwnProperty.call(obj,prop)){const value=obj[prop];if(value instanceof Error)return value}return}(exception),extra={__serialized__:normalizeToSize(exception,normalizeDepth)};if(errorFromProp)return{exception:{values:[exceptionFromError(stackParser,errorFromProp)]},extra:extra};const event={exception:{values:[{type:isEvent(exception)?exception.constructor.name:isUnhandledRejection?"UnhandledRejection":"Error",value:getNonErrorObjectExceptionValue(exception,{isUnhandledRejection:isUnhandledRejection})}]},extra:extra};if(syntheticException){const frames=parseStackFrames(stackParser,syntheticException);frames.length&&(event.exception.values[0].stacktrace={frames:frames})}return event}function eventFromError(stackParser,ex){return{exception:{values:[exceptionFromError(stackParser,ex)]}}}function parseStackFrames(stackParser,ex){const stacktrace=ex.stacktrace||ex.stack||"",skipLines=function(ex){if(ex&&reactMinifiedRegexp.test(ex.message))return 1;return 0}(ex),framesToPop=function(ex){if("number"==typeof ex.framesToPop)return ex.framesToPop;return 0}(ex);try{return stackParser(stacktrace,skipLines,framesToPop)}catch(e){}return[]}const reactMinifiedRegexp=/Minified React error #\d+;/i;function isWebAssemblyException(exception){return"undefined"!=typeof WebAssembly&&void 0!==WebAssembly.Exception&&exception instanceof WebAssembly.Exception}function extractType(ex){const name=ex?.name;if(!name&&isWebAssemblyException(ex)){return ex.message&&Array.isArray(ex.message)&&2==ex.message.length?ex.message[0]:"WebAssembly.Exception"}return name}function extractMessage(ex){const message=ex?.message;return isWebAssemblyException(ex)?Array.isArray(ex.message)&&2==ex.message.length?ex.message[1]:"wasm exception":message?message.error&&"string"==typeof message.error.message?message.error.message:message:"No error message"}function eventFromUnknownInput(stackParser,exception,syntheticException,attachStacktrace,isUnhandledRejection){let event;if(isErrorEvent(exception)&&exception.error){return eventFromError(stackParser,exception.error)}if(isDOMError(exception)||isBuiltin(exception,"DOMException")){const domException=exception;if("stack"in exception)event=eventFromError(stackParser,exception);else{const name=domException.name||(isDOMError(domException)?"DOMError":"DOMException"),message=domException.message?`${name}: ${domException.message}`:name;event=eventFromString(stackParser,message,syntheticException,attachStacktrace),addExceptionTypeValue(event,message)}return"code"in domException&&(event.tags={...event.tags,"DOMException.code":`${domException.code}`}),event}if(isError(exception))return eventFromError(stackParser,exception);if(isPlainObject(exception)||isEvent(exception)){return event=eventFromPlainObject(stackParser,exception,syntheticException,isUnhandledRejection),addExceptionMechanism(event,{synthetic:!0}),event}return event=eventFromString(stackParser,exception,syntheticException,attachStacktrace),addExceptionTypeValue(event,`${exception}`,void 0),addExceptionMechanism(event,{synthetic:!0}),event}function eventFromString(stackParser,message,syntheticException,attachStacktrace){const event={};if(attachStacktrace&&syntheticException){const frames=parseStackFrames(stackParser,syntheticException);frames.length&&(event.exception={values:[{value:message,stacktrace:{frames:frames}}]}),addExceptionMechanism(event,{synthetic:!0})}if(is_isParameterizedString(message)){const{__sentry_template_string__:__sentry_template_string__,__sentry_template_values__:__sentry_template_values__}=message;return event.logentry={message:__sentry_template_string__,params:__sentry_template_values__},event}return event.message=message,event}function getNonErrorObjectExceptionValue(exception,{isUnhandledRejection:isUnhandledRejection}){const keys=function(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))return includedKeys===keys.length?serialized:truncate(serialized,maxLength)}return""}(exception),captureType=isUnhandledRejection?"promise rejection":"exception";if(isErrorEvent(exception))return`Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``;if(isEvent(exception)){return`Event \`${function(obj){try{const prototype=Object.getPrototypeOf(obj);return prototype?prototype.constructor.name:void 0}catch(e){}}(exception)}\` (type=${exception.type}) captured as ${captureType}`}return`Object captured as ${captureType} with keys: ${keys}`}const helpers_WINDOW=worldwide_GLOBAL_OBJ;let ignoreOnError=0;function shouldIgnoreOnError(){return ignoreOnError>0}function wrap(fn,options={}){if(!function(fn){return"function"==typeof fn}(fn))return fn;try{const wrapper=fn.__sentry_wrapped__;if(wrapper)return"function"==typeof wrapper?wrapper: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){throw ignoreOnError++,setTimeout((()=>{ignoreOnError--})),currentScopes_withScope((scope=>{scope.addEventProcessor((event=>(options.mechanism&&(addExceptionTypeValue(event,void 0,void 0),addExceptionMechanism(event,options.mechanism)),event.extra={...event.extra,arguments:args},event))),captureException(ex)})),ex}};try{for(const property in fn)Object.prototype.hasOwnProperty.call(fn,property)&&(sentryWrapped[property]=fn[property])}catch{}markFunctionWrapped(sentryWrapped,fn),addNonEnumerableProperty(fn,"__sentry_wrapped__",sentryWrapped);try{Object.getOwnPropertyDescriptor(sentryWrapped,"name").configurable&&Object.defineProperty(sentryWrapped,"name",{get(){return fn.name}})}catch{}return sentryWrapped}class BrowserClient extends Client{constructor(options){const opts={parentSpanIsAlwaysRootSpan:!0,...options};applySdkMetadata(opts,"browser",["browser"],helpers_WINDOW.SENTRY_SDK_SOURCE||"npm"),super(opts);const client=this,{sendDefaultPii:sendDefaultPii,_experiments:_experiments}=client._options,enableLogs=_experiments?.enableLogs;opts.sendClientReports&&helpers_WINDOW.document&&helpers_WINDOW.document.addEventListener("visibilitychange",(()=>{"hidden"===helpers_WINDOW.document.visibilityState&&(this._flushOutcomes(),enableLogs&&_INTERNAL_flushLogsBuffer(client))})),enableLogs&&(client.on("flush",(()=>{_INTERNAL_flushLogsBuffer(client)})),client.on("afterCaptureLog",(()=>{client._logFlushIdleTimeout&&clearTimeout(client._logFlushIdleTimeout),client._logFlushIdleTimeout=setTimeout((()=>{_INTERNAL_flushLogsBuffer(client)}),5e3)}))),sendDefaultPii&&(client.on("postprocessEvent",addAutoIpAddressToUser),client.on("beforeSendSession",addAutoIpAddressToSession))}eventFromException(exception,hint){return function(stackParser,exception,hint,attachStacktrace){const event=eventFromUnknownInput(stackParser,exception,hint?.syntheticException||void 0,attachStacktrace);return addExceptionMechanism(event),event.level="error",hint?.event_id&&(event.event_id=hint.event_id),resolvedSyncPromise(event)}(this._options.stackParser,exception,hint,this._options.attachStacktrace)}eventFromMessage(message,level="info",hint){return function(stackParser,message,level="info",hint,attachStacktrace){const event=eventFromString(stackParser,message,hint?.syntheticException||void 0,attachStacktrace);return event.level=level,hint?.event_id&&(event.event_id=hint.event_id),resolvedSyncPromise(event)}(this._options.stackParser,message,level,hint,this._options.attachStacktrace)}_prepareEvent(event,hint,currentScope,isolationScope){return event.platform=event.platform||"javascript",super._prepareEvent(event,hint,currentScope,isolationScope)}}const npm_esm_debug_build_DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__;function instrumentConsole(){"console"in worldwide_GLOBAL_OBJ&&CONSOLE_LEVELS.forEach((function(level){level in worldwide_GLOBAL_OBJ.console&&fill(worldwide_GLOBAL_OBJ.console,level,(function(originalConsoleMethod){return originalConsoleMethods[level]=originalConsoleMethod,function(...args){handlers_triggerHandlers("console",{args:args,level:level});const log=originalConsoleMethods[level];log?.apply(worldwide_GLOBAL_OBJ.console,args)}}))}))}function instrumentFetch(onFetchResolved,skipNativeFetchCheck=!1){skipNativeFetchCheck&&!function(){if("string"==typeof EdgeRuntime)return!0;if(!supportsFetch())return!1;if(isNativeFunction(supports_WINDOW.fetch))return!0;let result=!1;const doc=supports_WINDOW.document;if(doc&&"function"==typeof doc.createElement)try{const sandbox=doc.createElement("iframe");sandbox.hidden=!0,doc.head.appendChild(sandbox),sandbox.contentWindow?.fetch&&(result=isNativeFunction(sandbox.contentWindow.fetch)),doc.head.removeChild(sandbox)}catch(err){debug_build_DEBUG_BUILD&&logger_logger.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",err)}return result}()||fill(worldwide_GLOBAL_OBJ,"fetch",(function(originalFetch){return function(...args){const virtualError=new Error,{method:method,url:url}=function(fetchArgs){if(0===fetchArgs.length)return{method:"GET",url:""};if(2===fetchArgs.length){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"}}(args),handlerData={args:args,fetchData:{method:method,url:url},startTimestamp:1e3*time_timestampInSeconds(),virtualError:virtualError,headers:getHeadersFromFetchArgs(args)};return onFetchResolved||handlers_triggerHandlers("fetch",{...handlerData}),originalFetch.apply(worldwide_GLOBAL_OBJ,args).then((async response=>(onFetchResolved?onFetchResolved(response):handlers_triggerHandlers("fetch",{...handlerData,endTimestamp:1e3*time_timestampInSeconds(),response:response}),response)),(error=>{if(handlers_triggerHandlers("fetch",{...handlerData,endTimestamp:1e3*time_timestampInSeconds(),error:error}),isError(error)&&void 0===error.stack&&(error.stack=virtualError.stack,addNonEnumerableProperty(error,"framesToPop",1)),error instanceof TypeError&&("Failed to fetch"===error.message||"Load failed"===error.message||"NetworkError when attempting to fetch resource."===error.message))try{const url=new URL(handlerData.fetchData.url);error.message=`${error.message} (${url.host})`}catch{}throw error}))}}))}function hasProp(obj,prop){return!!obj&&"object"==typeof obj&&!!obj[prop]}function getUrlFromResource(resource){return"string"==typeof resource?resource:resource?hasProp(resource,"url")?resource.url:resource.toString?resource.toString():"":""}function getHeadersFromFetchArgs(fetchArgs){const[requestArgument,optionsArgument]=fetchArgs;try{if("object"==typeof optionsArgument&&null!==optionsArgument&&"headers"in optionsArgument&&optionsArgument.headers)return new Headers(optionsArgument.headers);if(request=requestArgument,"undefined"!=typeof Request&&isInstanceOf(request,Request))return new Headers(requestArgument.headers)}catch{}var request}function getBreadcrumbLogLevelFromHttpStatusCode(statusCode){return void 0===statusCode?void 0:statusCode>=400&&statusCode<500?"warning":statusCode>=500?"error":void 0}function parseUrl(url){if(!url)return{};const match=url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!match)return{};const query=match[6]||"",fragment=match[8]||"";return{host:match[4],path:match[5],protocol:match[2],search:query,hash:fragment,relative:match[5]+query+fragment}}const breadcrumbsIntegration=(options={})=>{const _options={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...options};return{name:"Breadcrumbs",setup(client){var handler;_options.console&&(handler=function(client){return function(handlerData){if(currentScopes_getClient()!==client)return;const breadcrumb={category:"console",data:{arguments:handlerData.args,logger:"console"},level:severityLevelFromString(handlerData.level),message:safeJoin(handlerData.args," ")};if("assert"===handlerData.level){if(!1!==handlerData.args[0])return;breadcrumb.message=`Assertion failed: ${safeJoin(handlerData.args.slice(1)," ")||"console.assert"}`,breadcrumb.data.arguments=handlerData.args.slice(1)}addBreadcrumb(breadcrumb,{input:handlerData.args,level:handlerData.level})}}(client),handlers_addHandler("console",handler),handlers_maybeInstrument("console",instrumentConsole)),_options.dom&&addClickKeypressInstrumentationHandler(function(client,dom){return function(handlerData){if(currentScopes_getClient()!==client)return;let target,componentName,keyAttrs="object"==typeof dom?dom.serializeAttribute:void 0,maxStringLength="object"==typeof dom&&"number"==typeof dom.maxStringLength?dom.maxStringLength:void 0;maxStringLength&&maxStringLength>1024&&(npm_esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`\`dom.maxStringLength\` cannot exceed 1024, but a value of ${maxStringLength} was configured. Sentry will use 1024 instead.`),maxStringLength=1024),"string"==typeof keyAttrs&&(keyAttrs=[keyAttrs]);try{const event=handlerData.event,element=function(event){return!!event&&!!event.target}(event)?event.target:event;target=htmlTreeAsString(element,{keyAttrs:keyAttrs,maxStringLength:maxStringLength}),componentName=function(elem){if(!browser_WINDOW.HTMLElement)return null;let currentElem=elem;for(let i=0;i<5;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}(element)}catch(e){target="<unknown>"}if(0===target.length)return;const breadcrumb={category:`ui.${handlerData.name}`,message:target};componentName&&(breadcrumb.data={"ui.component_name":componentName}),addBreadcrumb(breadcrumb,{event:handlerData.event,name:handlerData.name,global:handlerData.global})}}(client,_options.dom)),_options.xhr&&function(handler){handlers_addHandler("xhr",handler),handlers_maybeInstrument("xhr",instrumentXHR)}(function(client){return function(handlerData){if(currentScopes_getClient()!==client)return;const{startTimestamp:startTimestamp,endTimestamp:endTimestamp}=handlerData,sentryXhrData=handlerData.xhr.__sentry_xhr_v3__;if(!startTimestamp||!endTimestamp||!sentryXhrData)return;const{method:method,url:url,status_code:status_code,body:body}=sentryXhrData,data={method:method,url:url,status_code:status_code},hint={xhr:handlerData.xhr,input:body,startTimestamp:startTimestamp,endTimestamp:endTimestamp},breadcrumb={category:"xhr",data:data,type:"http",level:getBreadcrumbLogLevelFromHttpStatusCode(status_code)};client.emit("beforeOutgoingRequestBreadcrumb",breadcrumb,hint),addBreadcrumb(breadcrumb,hint)}}(client)),_options.fetch&&function(handler,skipNativeFetchCheck){handlers_addHandler("fetch",handler),handlers_maybeInstrument("fetch",(()=>instrumentFetch(void 0,skipNativeFetchCheck)))}(function(client){return function(handlerData){if(currentScopes_getClient()!==client)return;const{startTimestamp:startTimestamp,endTimestamp:endTimestamp}=handlerData;if(endTimestamp&&(!handlerData.fetchData.url.match(/sentry_key/)||"POST"!==handlerData.fetchData.method))if(handlerData.fetchData.method,handlerData.fetchData.url,handlerData.error){const data=handlerData.fetchData,hint={data:handlerData.error,input:handlerData.args,startTimestamp:startTimestamp,endTimestamp:endTimestamp},breadcrumb={category:"fetch",data:data,level:"error",type:"http"};client.emit("beforeOutgoingRequestBreadcrumb",breadcrumb,hint),addBreadcrumb(breadcrumb,hint)}else{const response=handlerData.response,data={...handlerData.fetchData,status_code:response?.status};handlerData.fetchData.request_body_size,handlerData.fetchData.response_body_size;const hint={input:handlerData.args,response:response,startTimestamp:startTimestamp,endTimestamp:endTimestamp},breadcrumb={category:"fetch",data:data,type:"http",level:getBreadcrumbLogLevelFromHttpStatusCode(data.status_code)};client.emit("beforeOutgoingRequestBreadcrumb",breadcrumb,hint),addBreadcrumb(breadcrumb,hint)}}}(client)),_options.history&&addHistoryInstrumentationHandler(function(client){return function(handlerData){if(currentScopes_getClient()!==client)return;let from=handlerData.from,to=handlerData.to;const parsedLoc=parseUrl(helpers_WINDOW.location.href);let parsedFrom=from?parseUrl(from):void 0;const parsedTo=parseUrl(to);parsedFrom?.path||(parsedFrom=parsedLoc),parsedLoc.protocol===parsedTo.protocol&&parsedLoc.host===parsedTo.host&&(to=parsedTo.relative),parsedLoc.protocol===parsedFrom.protocol&&parsedLoc.host===parsedFrom.host&&(from=parsedFrom.relative),addBreadcrumb({category:"navigation",data:{from:from,to:to}})}}(client)),_options.sentry&&client.on("beforeSendEvent",function(client){return function(event){currentScopes_getClient()===client&&addBreadcrumb({category:"sentry."+("transaction"===event.type?"transaction":"event"),event_id:event.event_id,level:event.level,message:getEventDescription(event)},{event:event})}}(client))}}};const DEFAULT_EVENT_TARGET=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],browserApiErrorsIntegration=(options={})=>{const _options={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...options};return{name:"BrowserApiErrors",setupOnce(){_options.setTimeout&&fill(helpers_WINDOW,"setTimeout",_wrapTimeFunction),_options.setInterval&&fill(helpers_WINDOW,"setInterval",_wrapTimeFunction),_options.requestAnimationFrame&&fill(helpers_WINDOW,"requestAnimationFrame",_wrapRAF),_options.XMLHttpRequest&&"XMLHttpRequest"in helpers_WINDOW&&fill(XMLHttpRequest.prototype,"send",_wrapXHR);const eventTargetOption=_options.eventTarget;if(eventTargetOption){(Array.isArray(eventTargetOption)?eventTargetOption:DEFAULT_EVENT_TARGET).forEach(_wrapEventTarget)}}}};function _wrapTimeFunction(original){return function(...args){const originalCallback=args[0];return args[0]=wrap(originalCallback,{mechanism:{data:{function:getFunctionName(original)},handled:!1,type:"instrument"}}),original.apply(this,args)}}function _wrapRAF(original){return function(callback){return original.apply(this,[wrap(callback,{mechanism:{data:{function:"requestAnimationFrame",handler:getFunctionName(original)},handled:!1,type:"instrument"}})])}}function _wrapXHR(originalSend){return function(...args){const xhr=this;return["onload","onerror","onprogress","onreadystatechange"].forEach((prop=>{prop in xhr&&"function"==typeof xhr[prop]&&fill(xhr,prop,(function(original){const wrapOptions={mechanism:{data:{function:prop,handler:getFunctionName(original)},handled:!1,type:"instrument"}},originalFunction=getOriginalFunction(original);return originalFunction&&(wrapOptions.mechanism.data.handler=getFunctionName(originalFunction)),wrap(original,wrapOptions)}))})),originalSend.apply(this,args)}}function _wrapEventTarget(target){const globalObject=helpers_WINDOW,proto=globalObject[target]?.prototype;proto?.hasOwnProperty?.("addEventListener")&&(fill(proto,"addEventListener",(function(original){return function(eventName,fn,options){try{"function"==typeof fn.handleEvent&&(fn.handleEvent=wrap(fn.handleEvent,{mechanism:{data:{function:"handleEvent",handler:getFunctionName(fn),target:target},handled:!1,type:"instrument"}}))}catch{}return original.apply(this,[eventName,wrap(fn,{mechanism:{data:{function:"addEventListener",handler:getFunctionName(fn),target:target},handled:!1,type:"instrument"}}),options])}})),fill(proto,"removeEventListener",(function(originalRemoveEventListener){return function(eventName,fn,options){try{const originalEventHandler=fn.__sentry_wrapped__;originalEventHandler&&originalRemoveEventListener.call(this,eventName,originalEventHandler,options)}catch(e){}return originalRemoveEventListener.call(this,eventName,fn,options)}})))}const browserSessionIntegration=()=>({name:"BrowserSession",setupOnce(){void 0!==helpers_WINDOW.document?(startSession({ignoreDuration:!0}),captureSession(),addHistoryInstrumentationHandler((({from:from,to:to})=>{void 0!==from&&from!==to&&(startSession({ignoreDuration:!0}),captureSession())}))):npm_esm_debug_build_DEBUG_BUILD&&logger_logger.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.")}});let _oldOnErrorHandler=null;function instrumentError(){_oldOnErrorHandler=worldwide_GLOBAL_OBJ.onerror,worldwide_GLOBAL_OBJ.onerror=function(msg,url,line,column,error){return handlers_triggerHandlers("error",{column:column,error:error,line:line,msg:msg,url:url}),!!_oldOnErrorHandler&&_oldOnErrorHandler.apply(this,arguments)},worldwide_GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__=!0}let _oldOnUnhandledRejectionHandler=null;function instrumentUnhandledRejection(){_oldOnUnhandledRejectionHandler=worldwide_GLOBAL_OBJ.onunhandledrejection,worldwide_GLOBAL_OBJ.onunhandledrejection=function(e){return handlers_triggerHandlers("unhandledrejection",e),!_oldOnUnhandledRejectionHandler||_oldOnUnhandledRejectionHandler.apply(this,arguments)},worldwide_GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}const globalHandlersIntegration=(options={})=>{const _options={onerror:!0,onunhandledrejection:!0,...options};return{name:"GlobalHandlers",setupOnce(){Error.stackTraceLimit=50},setup(client){_options.onerror&&(!function(client){handler=data=>{const{stackParser:stackParser,attachStacktrace:attachStacktrace}=getOptions();if(currentScopes_getClient()!==client||shouldIgnoreOnError())return;const{msg:msg,url:url,line:line,column:column,error:error}=data,event=function(event,url,line,column){const e=event.exception=event.exception||{},ev=e.values=e.values||[],ev0=ev[0]=ev[0]||{},ev0s=ev0.stacktrace=ev0.stacktrace||{},ev0sf=ev0s.frames=ev0s.frames||[],colno=column,lineno=line,filename=isString(url)&&url.length>0?url:getLocationHref();return 0===ev0sf.length&&ev0sf.push({colno:colno,filename:filename,function:"?",in_app:!0,lineno:lineno}),event}(eventFromUnknownInput(stackParser,error||msg,void 0,attachStacktrace,!1),url,line,column);event.level="error",captureEvent(event,{originalException:error,mechanism:{handled:!1,type:"onerror"}})},handlers_addHandler("error",handler),handlers_maybeInstrument("error",instrumentError);var handler}(client),globalHandlerLog("onerror")),_options.onunhandledrejection&&(!function(client){!function(handler){const type="unhandledrejection";handlers_addHandler(type,handler),handlers_maybeInstrument(type,instrumentUnhandledRejection)}((e=>{const{stackParser:stackParser,attachStacktrace:attachStacktrace}=getOptions();if(currentScopes_getClient()!==client||shouldIgnoreOnError())return;const error=function(error){if(is_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{}return error}(e),event=is_isPrimitive(error)?{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(error)}`}]}}:eventFromUnknownInput(stackParser,error,void 0,attachStacktrace,!0);event.level="error",captureEvent(event,{originalException:error,mechanism:{handled:!1,type:"onunhandledrejection"}})}))}(client),globalHandlerLog("onunhandledrejection"))}}};function globalHandlerLog(type){npm_esm_debug_build_DEBUG_BUILD&&logger_logger.log(`Global Handler attached: ${type}`)}function getOptions(){const client=currentScopes_getClient();return client?.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}const httpContextIntegration=()=>({name:"HttpContext",preprocessEvent(event){if(!helpers_WINDOW.navigator&&!helpers_WINDOW.location&&!helpers_WINDOW.document)return;const url=event.request?.url||getLocationHref(),{referrer:referrer}=helpers_WINDOW.document||{},{userAgent:userAgent}=helpers_WINDOW.navigator||{},headers={...event.request?.headers,...referrer&&{Referer:referrer},...userAgent&&{"User-Agent":userAgent}},request={...event.request,...url&&{url:url},headers:headers};event.request=request}});function applyAggregateErrorsToEvent(exceptionFromErrorImplementation,parser,key,limit,event,hint){if(!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;originalException&&(event.exception.values=aggregateExceptionsFromError(exceptionFromErrorImplementation,parser,limit,hint.originalException,key,event.exception.values,originalException,0))}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]),newExceptionId=newExceptions.length;applyExceptionGroupFieldsForChildException(newException,key,newExceptionId,exceptionId),newExceptions=aggregateExceptionsFromError(exceptionFromErrorImplementation,parser,limit,error[key],key,[newException,...newExceptions],newException,newExceptionId)}return Array.isArray(error.errors)&&error.errors.forEach(((childError,i)=>{if(isInstanceOf(childError,Error)){applyExceptionGroupFieldsForParentException(exception,exceptionId);const newException=exceptionFromErrorImplementation(parser,childError),newExceptionId=newExceptions.length;applyExceptionGroupFieldsForChildException(newException,`errors[${i}]`,newExceptionId,exceptionId),newExceptions=aggregateExceptionsFromError(exceptionFromErrorImplementation,parser,limit,childError,key,[newException,...newExceptions],newException,newExceptionId)}})),newExceptions}function applyExceptionGroupFieldsForParentException(exception,exceptionId){exception.mechanism=exception.mechanism||{type:"generic",handled:!0},exception.mechanism={...exception.mechanism,..."AggregateError"===exception.type&&{is_exception_group:!0},exception_id:exceptionId}}function applyExceptionGroupFieldsForChildException(exception,source,exceptionId,parentId){exception.mechanism=exception.mechanism||{type:"generic",handled:!0},exception.mechanism={...exception.mechanism,type:"chained",source:source,exception_id:exceptionId,parent_id:parentId}}const linkedErrorsIntegration=(options={})=>{const limit=options.limit||5,key=options.key||"cause";return{name:"LinkedErrors",preprocessEvent(event,hint,client){applyAggregateErrorsToEvent(exceptionFromError,client.getOptions().stackParser,key,limit,event,hint)}}};function createFrame(filename,func,lineno,colno){const frame={filename:filename,function:"<anonymous>"===func?"?":func,in_app:!0};return void 0!==lineno&&(frame.lineno=lineno),void 0!==colno&&(frame.colno=colno),frame}const chromeRegexNoFnName=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,chromeRegex=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,chromeEvalRegex=/\((\S*)(?::(\d+))(?::(\d+))\)/,geckoREgex=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,geckoEvalRegex=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,defaultStackParser=createStackParser(...[[30,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]&&0===parts[2].indexOf("eval")){const subMatch=chromeEvalRegex.exec(parts[2]);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)}}],[50,line=>{const parts=geckoREgex.exec(line);if(parts){if(parts[3]&&parts[3].indexOf(" > eval")>-1){const subMatch=geckoEvalRegex.exec(parts[3]);subMatch&&(parts[1]=parts[1]||"eval",parts[3]=subMatch[1],parts[4]=subMatch[2],parts[5]="")}let filename=parts[3],func=parts[1]||"?";return[func,filename]=extractSafariExtensionDetails(func,filename),createFrame(filename,func,parts[4]?+parts[4]:void 0,parts[5]?+parts[5]:void 0)}}]]),extractSafariExtensionDetails=(func,filename)=>{const isSafariExtension=-1!==func.indexOf("safari-extension"),isSafariWebExtension=-1!==func.indexOf("safari-web-extension");return isSafariExtension||isSafariWebExtension?[-1!==func.indexOf("@")?func.split("@")[0]:"?",isSafariExtension?`safari-extension:${filename}`:`safari-web-extension:${filename}`]:[func,filename]},SENTRY_BUFFER_FULL_ERROR=Symbol.for("SentryBufferFullError");function makePromiseBuffer(limit){const buffer=[];function remove(task){return buffer.splice(buffer.indexOf(task),1)[0]||Promise.resolve(void 0)}return{$:buffer,add:function(taskProducer){if(!(void 0===limit||buffer.length<limit))return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR);const task=taskProducer();return-1===buffer.indexOf(task)&&buffer.push(task),task.then((()=>remove(task))).then(null,(()=>remove(task).then(null,(()=>{})))),task},drain:function(timeout){return new SyncPromise(((resolve,reject)=>{let counter=buffer.length;if(!counter)return resolve(!0);const capturedSetTimeout=setTimeout((()=>{timeout&&timeout>0&&resolve(!1)}),timeout);buffer.forEach((item=>{resolvedSyncPromise(item).then((()=>{--counter||(clearTimeout(capturedSetTimeout),resolve(!0))}),reject)}))}))}}}function makeFetchTransport(options,nativeFetch=getNativeImplementation("fetch")){let pendingBodySize=0,pendingCount=0;return function(options,makeRequest,buffer=makePromiseBuffer(options.bufferSize||64)){let rateLimits={};return{send:function(envelope){const filteredEnvelopeItems=[];if(forEachEnvelopeItem(envelope,((item,type)=>{const dataCategory=envelopeItemTypeToDataCategory(type);isRateLimited(rateLimits,dataCategory)?options.recordDroppedEvent("ratelimit_backoff",dataCategory):filteredEnvelopeItems.push(item)})),0===filteredEnvelopeItems.length)return resolvedSyncPromise({});const filteredEnvelope=createEnvelope(envelope[0],filteredEnvelopeItems),recordEnvelopeLoss=reason=>{forEachEnvelopeItem(filteredEnvelope,((item,type)=>{options.recordDroppedEvent(reason,envelopeItemTypeToDataCategory(type))}))};return buffer.add((()=>makeRequest({body:serializeEnvelope(filteredEnvelope)}).then((response=>(void 0!==response.statusCode&&(response.statusCode<200||response.statusCode>=300)&&esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`),rateLimits=updateRateLimits(rateLimits,response),response)),(error=>{throw recordEnvelopeLoss("network_error"),esm_debug_build_DEBUG_BUILD&&logger_logger.error("Encountered error running transport request:",error),error})))).then((result=>result),(error=>{if(error===SENTRY_BUFFER_FULL_ERROR)return esm_debug_build_DEBUG_BUILD&&logger_logger.error("Skipped sending event because buffer is full."),recordEnvelopeLoss("queue_overflow"),resolvedSyncPromise({});throw error}))},flush:timeout=>buffer.drain(timeout)}}(options,(function(request){const requestSize=request.body.length;pendingBodySize+=requestSize,pendingCount++;const requestOptions={body:request.body,method:"POST",referrerPolicy:"strict-origin",headers:options.headers,keepalive:pendingBodySize<=6e4&&pendingCount<15,...options.fetchOptions};if(!nativeFetch)return clearCachedImplementation("fetch"),rejectedSyncPromise("No fetch implementation available");try{return nativeFetch(options.url,requestOptions).then((response=>(pendingBodySize-=requestSize,pendingCount--,{statusCode:response.status,headers:{"x-sentry-rate-limits":response.headers.get("X-Sentry-Rate-Limits"),"retry-after":response.headers.get("Retry-After")}})))}catch(e){return clearCachedImplementation("fetch"),pendingBodySize-=requestSize,pendingCount--,rejectedSyncPromise(e)}}))}function getDefaultIntegrations(_options){return[inboundFiltersIntegration(),functionToStringIntegration(),browserApiErrorsIntegration(),breadcrumbsIntegration(),globalHandlersIntegration(),linkedErrorsIntegration(),dedupeIntegration(),httpContextIntegration(),browserSessionIntegration()]}function dropTopLevelUndefinedKeys(obj){const mutatetedObj={};for(const k of Object.getOwnPropertyNames(obj)){const key=k;void 0!==obj[key]&&(mutatetedObj[key]=obj[key])}return mutatetedObj}function init(browserOptions={}){const options=function(optionsArg={}){return{defaultIntegrations:getDefaultIntegrations(),release:"string"==typeof __SENTRY_RELEASE__?__SENTRY_RELEASE__:helpers_WINDOW.SENTRY_RELEASE?.id,sendClientReports:!0,...dropTopLevelUndefinedKeys(optionsArg)}}(browserOptions);if(!options.skipBrowserExtensionCheck&&function(){const windowWithMaybeExtension=void 0!==helpers_WINDOW.window&&helpers_WINDOW;if(!windowWithMaybeExtension)return!1;const extensionObject=windowWithMaybeExtension[windowWithMaybeExtension.chrome?"chrome":"browser"],runtimeId=extensionObject?.runtime?.id,href=getLocationHref()||"",isDedicatedExtensionPage=!!runtimeId&&helpers_WINDOW===helpers_WINDOW.top&&["chrome-extension:","moz-extension:","ms-browser-extension:","safari-web-extension:"].some((protocol=>href.startsWith(`${protocol}//`))),isNWjs=void 0!==windowWithMaybeExtension.nw;return!!runtimeId&&!isDedicatedExtensionPage&&!isNWjs}())return void(npm_esm_debug_build_DEBUG_BUILD&&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/")})));npm_esm_debug_build_DEBUG_BUILD&&!supportsFetch()&&logger_logger.warn("No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill.");const clientOptions={...options,stackParser:(stackParser=options.stackParser||defaultStackParser,Array.isArray(stackParser)?createStackParser(...stackParser):stackParser),integrations:getIntegrationsToSetup(options),transport:options.transport||makeFetchTransport};var stackParser;return initAndBind(BrowserClient,clientOptions)}const DEFAULT_HOOKS=["activate","mount"],vue_build_esm_debug_build_DEBUG_BUILD="undefined"==typeof __SENTRY_DEBUG__||__SENTRY_DEBUG__,classifyRE=/(?:^|[-_])(\w)/g,formatComponentName=(vm,includeFile)=>{if(!vm)return"<Anonymous>";if(vm.$root===vm)return"<Root>";if(!vm.$options)return"<Anonymous>";const options=vm.$options;let name=options.name||options._componentTag||options.__name;const file=options.__file;if(!name&&file){const match=file.match(/([^/\\]+)\.vue$/);match&&(name=match[1])}return(name?`<${str=name,str.replace(classifyRE,(c=>c.toUpperCase())).replace(/[-_]/g,"")}>`:"<Anonymous>")+(file&&!1!==includeFile?` at ${file}`:"");var str},attachErrorHandler=(app,options)=>{const{errorHandler:originalErrorHandler}=app.config;app.config.errorHandler=(error,vm,lifecycleHook)=>{const componentName=formatComponentName(vm,!1),trace=vm?(vm=>{if(vm&&(vm._isVue||vm.__isVue)&&vm.$parent){const tree=[];let currentRecursiveSequence=0;for(;vm;){if(tree.length>0){const last=tree[tree.length-1];if(last.constructor===vm.constructor){currentRecursiveSequence++,vm=vm.$parent;continue}currentRecursiveSequence>0&&(tree[tree.length-1]=[last,currentRecursiveSequence],currentRecursiveSequence=0)}tree.push(vm),vm=vm.$parent}const formattedTree=tree.map(((vm,i)=>`${(0===i?"---\x3e ":((str,n)=>" ".repeat(n))(0,5+2*i))+(Array.isArray(vm)?`${formatComponentName(vm[0])}... (${vm[1]} recursive calls)`:formatComponentName(vm))}`)).join("\n");return`\n\nfound in\n\n${formattedTree}`}return`\n\n(found in ${formatComponentName(vm)})`})(vm):"",metadata={componentName:componentName,lifecycleHook:lifecycleHook,trace:trace};if(options.attachProps&&vm&&(vm.$options?.propsData?metadata.propsData=vm.$options.propsData:vm.$props&&(metadata.propsData=vm.$props)),setTimeout((()=>{captureException(error,{captureContext:{contexts:{vue:metadata}},mechanism:{handled:!!originalErrorHandler,type:"vue"}})})),"function"!=typeof originalErrorHandler||!app.config.errorHandler)throw error;originalErrorHandler.call(app,error,vm,lifecycleHook)}};class sentryNonRecordingSpan_SentryNonRecordingSpan{constructor(spanContext={}){this._traceId=spanContext.traceId||propagationContext_generateTraceId(),this._spanId=spanContext.spanId||generateSpanId()}spanContext(){return{spanId:this._spanId,traceId:this._traceId,traceFlags:0}}end(_timestamp){}setAttribute(_key,_value){return this}setAttributes(_values){return this}setStatus(_status){return this}updateName(_name){return this}isRecording(){return!1}addEvent(_name,_attributesOrStartTime,_startTime){return this}addLink(_link){return this}addLinks(_links){return this}recordException(_exception,_time){}}function timedEventsToMeasurements(events){if(!events||0===events.length)return;const measurements={};return events.forEach((event=>{const attributes=event.attributes||{},unit=attributes["sentry.measurement_unit"],value=attributes["sentry.measurement_value"];"string"==typeof unit&&"number"==typeof value&&(measurements[event.name]={value:value,unit:unit})})),measurements}class SentrySpan{constructor(spanContext={}){this._traceId=spanContext.traceId||propagationContext_generateTraceId(),this._spanId=spanContext.spanId||generateSpanId(),this._startTime=spanContext.startTimestamp||time_timestampInSeconds(),this._links=spanContext.links,this._attributes={},this.setAttributes({[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"manual",[SEMANTIC_ATTRIBUTE_SENTRY_OP]:spanContext.op,...spanContext.attributes}),this._name=spanContext.name,spanContext.parentSpanId&&(this._parentSpanId=spanContext.parentSpanId),"sampled"in spanContext&&(this._sampled=spanContext.sampled),spanContext.endTimestamp&&(this._endTime=spanContext.endTimestamp),this._events=[],this._isStandaloneSpan=spanContext.isStandalone,this._endTime&&this._onSpanEnded()}addLink(link){return this._links?this._links.push(link):this._links=[link],this}addLinks(links){return this._links?this._links.push(...links):this._links=links,this}recordException(_exception,_time){}spanContext(){const{_spanId:spanId,_traceId:traceId,_sampled:sampled}=this;return{spanId:spanId,traceId:traceId,traceFlags:sampled?1:0}}setAttribute(key,value){return void 0===value?delete this._attributes[key]:this._attributes[key]=value,this}setAttributes(attributes){return Object.keys(attributes).forEach((key=>this.setAttribute(key,attributes[key]))),this}updateStartTime(timeInput){this._startTime=spanTimeInputToSeconds(timeInput)}setStatus(value){return this._status=value,this}updateName(name){return this._name=name,this.setAttribute("sentry.source","custom"),this}end(endTimestamp){this._endTime||(this._endTime=spanTimeInputToSeconds(endTimestamp),function(span){if(!esm_debug_build_DEBUG_BUILD)return;const{description:description="< unknown name >",op:op="< unknown op >"}=spanUtils_spanToJSON(span),{spanId:spanId}=span.spanContext(),msg=`[Tracing] Finishing "${op}" ${spanUtils_getRootSpan(span)===span?"root ":""}span "${description}" with ID ${spanId}`;logger_logger.log(msg)}(this),this._onSpanEnded())}getSpanJSON(){return{data:this._attributes,description:this._name,op:this._attributes["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["sentry.origin"],profile_id:this._attributes["sentry.profile_id"],exclusive_time:this._attributes["sentry.exclusive_time"],measurements:timedEventsToMeasurements(this._events),is_segment:this._isStandaloneSpan&&spanUtils_getRootSpan(this)===this||void 0,segment_id:this._isStandaloneSpan?spanUtils_getRootSpan(this).spanContext().spanId:void 0,links:convertSpanLinksForEnvelope(this._links)}}isRecording(){return!this._endTime&&!!this._sampled}addEvent(name,attributesOrStartTime,startTime){esm_debug_build_DEBUG_BUILD&&logger_logger.log("[Tracing] Adding an event to span:",name);const time=isSpanTimeInput(attributesOrStartTime)?attributesOrStartTime:startTime||time_timestampInSeconds(),attributes=isSpanTimeInput(attributesOrStartTime)?{}:attributesOrStartTime||{},event={name:name,time:spanTimeInputToSeconds(time),attributes:attributes};return this._events.push(event),this}isStandaloneSpan(){return!!this._isStandaloneSpan}_onSpanEnded(){const client=currentScopes_getClient();client&&client.emit("spanEnd",this);if(!(this._isStandaloneSpan||this===spanUtils_getRootSpan(this)))return;if(this._isStandaloneSpan)return void(this._sampled?function(envelope){const client=currentScopes_getClient();if(!client)return;const spanItems=envelope[1];if(!spanItems||0===spanItems.length)return void client.recordDroppedEvent("before_send","span");client.sendEnvelope(envelope)}(function(spans,client){const dsc=dynamicSamplingContext_getDynamicSamplingContextFromSpan(spans[0]),dsn=client?.getDsn(),tunnel=client?.getOptions().tunnel,headers={sent_at:(new Date).toISOString(),...function(dsc){return!!dsc.trace_id&&!!dsc.public_key}(dsc)&&{trace:dsc},...!!tunnel&&dsn&&{dsn:dsn_dsnToString(dsn)}},beforeSendSpan=client?.getOptions().beforeSendSpan,convertToSpanJSON=beforeSendSpan?span=>{const spanJson=spanUtils_spanToJSON(span);return beforeSendSpan(spanJson)||(showSpanDropWarning(),spanJson)}:spanUtils_spanToJSON,items=[];for(const span of spans){const spanJson=convertToSpanJSON(span);spanJson&&items.push(createSpanEnvelopeItem(spanJson))}return createEnvelope(headers,items)}([this],client)):(esm_debug_build_DEBUG_BUILD&&logger_logger.log("[Tracing] Discarding standalone span because its trace was not chosen to be sampled."),client&&client.recordDroppedEvent("sample_rate","span")));const transactionEvent=this._convertSpanToTransaction();if(transactionEvent){(getCapturedScopesOnSpan(this).scope||currentScopes_getCurrentScope()).captureEvent(transactionEvent)}}_convertSpanToTransaction(){if(!isFullFinishedSpan(spanUtils_spanToJSON(this)))return;this._name||(esm_debug_build_DEBUG_BUILD&&logger_logger.warn("Transaction has no name, falling back to `<unlabeled transaction>`."),this._name="<unlabeled transaction>");const{scope:capturedSpanScope,isolationScope:capturedSpanIsolationScope}=getCapturedScopesOnSpan(this);if(!0!==this._sampled)return;const spans=function(span){const resultSet=new Set;return function addSpanChildren(span){if(!resultSet.has(span)&&spanIsSampled(span)){resultSet.add(span);const childSpans=span._sentryChildSpans?Array.from(span._sentryChildSpans):[];for(const childSpan of childSpans)addSpanChildren(childSpan)}}(span),Array.from(resultSet)}(this).filter((span=>span!==this&&!function(span){return span instanceof SentrySpan&&span.isStandaloneSpan()}(span))).map((span=>spanUtils_spanToJSON(span))).filter(isFullFinishedSpan),source=this._attributes["sentry.source"];delete this._attributes["sentry.custom_span_name"],spans.forEach((span=>{delete span.data["sentry.custom_span_name"]}));const transaction={contexts:{trace:spanToTransactionTraceContext(this)},spans:spans.length>1e3?spans.sort(((a,b)=>a.start_timestamp-b.start_timestamp)).slice(0,1e3):spans,start_timestamp:this._startTime,timestamp:this._endTime,transaction:this._name,type:"transaction",sdkProcessingMetadata:{capturedSpanScope:capturedSpanScope,capturedSpanIsolationScope:capturedSpanIsolationScope,dynamicSamplingContext:dynamicSamplingContext_getDynamicSamplingContextFromSpan(this)},...source&&{transaction_info:{source:source}}},measurements=timedEventsToMeasurements(this._events);return measurements&&Object.keys(measurements).length&&(esm_debug_build_DEBUG_BUILD&&logger_logger.log("[Measurements] Adding measurements to transaction event",JSON.stringify(measurements,void 0,2)),transaction.measurements=measurements),transaction}}function isSpanTimeInput(value){return value&&"number"==typeof value||value instanceof Date||Array.isArray(value)}function isFullFinishedSpan(input){return!!(input.start_timestamp&&input.timestamp&&input.span_id&&input.trace_id)}function startInactiveSpan(options){const acs=getAcs();if(acs.startInactiveSpan)return acs.startInactiveSpan(options);const spanArguments=parseSentrySpanArguments(options),{forceTransaction:forceTransaction,parentSpan:customParentSpan}=options;return(options.scope?callback=>currentScopes_withScope(options.scope,callback):void 0!==customParentSpan?callback=>withActiveSpan(customParentSpan,callback):callback=>callback())((()=>{const scope=currentScopes_getCurrentScope(),parentSpan=getParentSpan(scope);return options.onlyIfParent&&!parentSpan?new sentryNonRecordingSpan_SentryNonRecordingSpan:createChildOrRootSpan({parentSpan:parentSpan,spanArguments:spanArguments,forceTransaction:forceTransaction,scope:scope})}))}function withActiveSpan(span,callback){const acs=getAcs();return acs.withActiveSpan?acs.withActiveSpan(span,callback):currentScopes_withScope((scope=>(spanOnScope_setSpanForScope(scope,span||void 0),callback(scope))))}function createChildOrRootSpan({parentSpan:parentSpan,spanArguments:spanArguments,forceTransaction:forceTransaction,scope:scope}){if(!hasSpansEnabled()){const span=new sentryNonRecordingSpan_SentryNonRecordingSpan;if(forceTransaction||!parentSpan){freezeDscOnSpan(span,{sampled:"false",sample_rate:"0",transaction:spanArguments.name,...dynamicSamplingContext_getDynamicSamplingContextFromSpan(span)})}return span}const isolationScope=currentScopes_getIsolationScope();let span;if(parentSpan&&!forceTransaction)span=function(parentSpan,scope,spanArguments){const{spanId:spanId,traceId:traceId}=parentSpan.spanContext(),sampled=!scope.getScopeData().sdkProcessingMetadata.__SENTRY_SUPPRESS_TRACING__&&spanIsSampled(parentSpan),childSpan=sampled?new SentrySpan({...spanArguments,parentSpanId:spanId,traceId:traceId,sampled:sampled}):new sentryNonRecordingSpan_SentryNonRecordingSpan({traceId:traceId});addChildSpanToSpan(parentSpan,childSpan);const client=currentScopes_getClient();client&&(client.emit("spanStart",childSpan),spanArguments.endTimestamp&&client.emit("spanEnd",childSpan));return childSpan}(parentSpan,scope,spanArguments),addChildSpanToSpan(parentSpan,span);else if(parentSpan){const dsc=dynamicSamplingContext_getDynamicSamplingContextFromSpan(parentSpan),{traceId:traceId,spanId:parentSpanId}=parentSpan.spanContext(),parentSampled=spanIsSampled(parentSpan);span=_startRootSpan({traceId:traceId,parentSpanId:parentSpanId,...spanArguments},scope,parentSampled),freezeDscOnSpan(span,dsc)}else{const{traceId:traceId,dsc:dsc,parentSpanId:parentSpanId,sampled:parentSampled}={...isolationScope.getPropagationContext(),...scope.getPropagationContext()};span=_startRootSpan({traceId:traceId,parentSpanId:parentSpanId,...spanArguments},scope,parentSampled),dsc&&freezeDscOnSpan(span,dsc)}return function(span){if(!esm_debug_build_DEBUG_BUILD)return;const{description:description="< unknown name >",op:op="< unknown op >",parent_span_id:parentSpanId}=spanUtils_spanToJSON(span),{spanId:spanId}=span.spanContext(),sampled=spanIsSampled(span),rootSpan=spanUtils_getRootSpan(span),isRootSpan=rootSpan===span,header=`[Tracing] Starting ${sampled?"sampled":"unsampled"} ${isRootSpan?"root ":""}span`,infoParts=[`op: ${op}`,`name: ${description}`,`ID: ${spanId}`];if(parentSpanId&&infoParts.push(`parent ID: ${parentSpanId}`),!isRootSpan){const{op:op,description:description}=spanUtils_spanToJSON(rootSpan);infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`),op&&infoParts.push(`root op: ${op}`),description&&infoParts.push(`root description: ${description}`)}logger_logger.log(`${header}\n ${infoParts.join("\n ")}`)}(span),function(span,scope,isolationScope){span&&(addNonEnumerableProperty(span,"_sentryIsolationScope",isolationScope),addNonEnumerableProperty(span,"_sentryScope",scope))}(span,scope,isolationScope),span}function parseSentrySpanArguments(options){const initialCtx={isStandalone:(options.experimental||{}).standalone,...options};if(options.startTime){const ctx={...initialCtx};return ctx.startTimestamp=spanTimeInputToSeconds(options.startTime),delete ctx.startTime,ctx}return initialCtx}function getAcs(){return asyncContext_getAsyncContextStrategy(carrier_getMainCarrier())}function _startRootSpan(spanArguments,scope,parentSampled){const client=currentScopes_getClient(),options=client?.getOptions()||{},{name:name="",attributes:attributes}=spanArguments,currentPropagationContext=scope.getPropagationContext(),[sampled,sampleRate,localSampleRateWasApplied]=scope.getScopeData().sdkProcessingMetadata.__SENTRY_SUPPRESS_TRACING__?[!1]:function(options,samplingContext,sampleRand){if(!hasSpansEnabled(options))return[!1];let localSampleRateWasApplied,sampleRate;"function"==typeof options.tracesSampler?(sampleRate=options.tracesSampler({...samplingContext,inheritOrSampleWith:fallbackSampleRate=>"number"==typeof samplingContext.parentSampleRate?samplingContext.parentSampleRate:"boolean"==typeof samplingContext.parentSampled?Number(samplingContext.parentSampled):fallbackSampleRate}),localSampleRateWasApplied=!0):void 0!==samplingContext.parentSampled?sampleRate=samplingContext.parentSampled:void 0!==options.tracesSampleRate&&(sampleRate=options.tracesSampleRate,localSampleRateWasApplied=!0);const parsedSampleRate=parseSampleRate(sampleRate);if(void 0===parsedSampleRate)return esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(sampleRate)} of type ${JSON.stringify(typeof sampleRate)}.`),[!1];if(!parsedSampleRate)return esm_debug_build_DEBUG_BUILD&&logger_logger.log("[Tracing] Discarding transaction because "+("function"==typeof options.tracesSampler?"tracesSampler returned 0 or false":"a negative sampling decision was inherited or tracesSampleRate is set to 0")),[!1,parsedSampleRate,localSampleRateWasApplied];const shouldSample=sampleRand<parsedSampleRate;return shouldSample||esm_debug_build_DEBUG_BUILD&&logger_logger.log(`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(sampleRate)})`),[shouldSample,parsedSampleRate,localSampleRateWasApplied]}(options,{name:name,parentSampled:parentSampled,attributes:attributes,parentSampleRate:parseSampleRate(currentPropagationContext.dsc?.sample_rate)},currentPropagationContext.sampleRand),rootSpan=new SentrySpan({...spanArguments,attributes:{[semanticAttributes_SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]:"custom",[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:void 0!==sampleRate&&localSampleRateWasApplied?sampleRate:void 0,...spanArguments.attributes},sampled:sampled});return!sampled&&client&&(esm_debug_build_DEBUG_BUILD&&logger_logger.log("[Tracing] Discarding root span because its trace was not chosen to be sampled."),client.recordDroppedEvent("sample_rate","transaction")),client&&client.emit("spanStart",rootSpan),rootSpan}function getParentSpan(scope){const span=spanOnScope_getSpanForScope(scope);if(!span)return;const client=currentScopes_getClient();return(client?client.getOptions():{}).parentSpanIsAlwaysRootSpan?spanUtils_getRootSpan(span):span}const HOOKS={activate:["activated","deactivated"],create:["beforeCreate","created"],unmount:["beforeUnmount","unmounted"],destroy:["beforeDestroy","destroyed"],mount:["beforeMount","mounted"],update:["beforeUpdate","updated"]};function findTrackComponent(trackComponents,formattedName){function extractComponentName(name){return name.replace(/^<([^\s]*)>(?: at [^\s]*)?$/,"$1")}return trackComponents.some((compo=>extractComponentName(formattedName)===extractComponentName(compo)))}const createTracingMixins=(options={})=>{const hooks=(options.hooks||[]).concat(DEFAULT_HOOKS).filter(((value,index,self)=>self.indexOf(value)===index)),mixins={};for(const operation of hooks){const internalHooks=HOOKS[operation];if(internalHooks)for(const internalHook of internalHooks)mixins[internalHook]=function(){const isRoot=this.$root===this;isRoot&&(this.$_sentryRootSpan=this.$_sentryRootSpan||startInactiveSpan({name:"Application Render",op:"ui.vue.render",attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.vue"},onlyIfParent:!0}));const name=formatComponentName(this,!1),shouldTrack=Array.isArray(options.trackComponents)?findTrackComponent(options.trackComponents,name):options.trackComponents;var vm,timestamp,timeout;if(isRoot||shouldTrack)if(this.$_sentrySpans=this.$_sentrySpans||{},internalHook==internalHooks[0]){if(this.$root?.$_sentryRootSpan||spanUtils_getActiveSpan()){const oldSpan=this.$_sentrySpans[operation];oldSpan&&oldSpan.end(),this.$_sentrySpans[operation]=startInactiveSpan({name:`Vue ${name}`,op:`ui.vue.${operation}`,attributes:{[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]:"auto.ui.vue"},onlyIfParent:!0})}}else{const span=this.$_sentrySpans[operation];if(!span)return;span.end(),vm=this,timestamp=time_timestampInSeconds(),timeout=options.timeout||2e3,vm.$_sentryRootSpanTimer&&clearTimeout(vm.$_sentryRootSpanTimer),vm.$_sentryRootSpanTimer=setTimeout((()=>{vm.$root?.$_sentryRootSpan&&(vm.$root.$_sentryRootSpan.end(timestamp),vm.$root.$_sentryRootSpan=void 0)}),timeout)}};else vue_build_esm_debug_build_DEBUG_BUILD&&logger_logger.warn(`Unknown hook: ${operation}`)}return mixins},DEFAULT_CONFIG={Vue:worldwide_GLOBAL_OBJ.Vue,attachProps:!0,attachErrorHandler:!0,tracingOptions:{hooks:DEFAULT_HOOKS,timeout:2e3,trackComponents:!1}},vueIntegration=(integrationOptions={})=>({name:"Vue",setup(client){const options={...DEFAULT_CONFIG,...client.getOptions(),...integrationOptions};if(options.Vue||options.app)if(options.app){(Array.isArray(options.app)?options.app:[options.app]).forEach((app=>vueInit(app,options)))}else options.Vue&&vueInit(options.Vue,options);else 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).")}))}}),vueInit=(app,options)=>{if(vue_build_esm_debug_build_DEBUG_BUILD){const appWithInstance=app,isMounted=appWithInstance._instance?.isMounted;!0===isMounted&&consoleSandbox((()=>{console.warn("[@sentry/vue]: Misconfigured SDK. Vue app is already mounted. Make sure to call `app.mount()` after `Sentry.init()`.")}))}options.attachErrorHandler&&attachErrorHandler(app,options),hasSpansEnabled(options)&&app.mixin(createTracingMixins(options.tracingOptions))};var external_kolibriCoreAppGlobal_namespaceObject=kolibriCoreAppGlobal,external_kolibriCoreAppGlobal_default=__webpack_require__.n(external_kolibriCoreAppGlobal_namespaceObject);const template=document.querySelector('template[data-plugin="kolibri_sentry_plugin.main"]');var src=template?JSON.parse(template.innerHTML.trim()):{},external_kolibriCoreAppGlobal_vue_namespaceObject=kolibriCoreAppGlobal.vue,external_kolibriCoreAppGlobal_vue_default=__webpack_require__.n(external_kolibriCoreAppGlobal_vue_namespaceObject),store_namespaceObject=kolibriCoreAppGlobal["kolibri/store"],store_default=__webpack_require__.n(store_namespaceObject),i18n_namespaceObject=kolibriCoreAppGlobal["kolibri/utils/i18n"];if(src.sentryDSN){const initOptions={Vue:external_kolibriCoreAppGlobal_vue_default(),dsn:src.sentryDSN,environment:src.sentryEnv,release:external_kolibriCoreAppGlobal_default().version,integrations:[]};src.sentryReplayEnabled&&(initOptions.replaysSessionSampleRate=.1,initOptions.replaysOnErrorSampleRate=1,initOptions.integrations.push(new Replay({maskAllText:!1,maskAllInputs:!1,blockAllMedia:!1}))),function(options={}){const opts={defaultIntegrations:[...getDefaultIntegrations(),vueIntegration()],...options};applySdkMetadata(opts,"vue"),init(opts)}(initOptions),setTag("lang",i18n_namespaceObject.currentLanguage),setTag("host",window.location.hostname),store_default().watch((state=>state.error),(errorString=>{errorString&&captureException(errorString)})),store_default().watch((state=>state.session),(session=>{var user;user={id:session.user_id,full_name:session.full_name,username:session.username,facility_id:session.facility_id,type:JSON.stringify(session.kind)},currentScopes_getIsolationScope().setUser(user)}))}}()}();
|
2
|
+
//# sourceMappingURL=kolibri_sentry_plugin.main-0.2.0.js.map
|