@tracescout/browser 2.4.0 → 2.4.1
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.
package/dist/tracescout.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(S,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define("tracescout",["exports"],b):b((S="undefined"!=typeof globalThis?globalThis:S||self).TraceScout={})}(this,function(S){"use strict";function generateId(){return Math.random().toString(36).substr(2,9)+Date.now().toString(36)}function parseUrl(S,b=("undefined"!=typeof location?location.origin:void 0)){try{const I=new URL(S,b);return{hostname:I.hostname,pathname:I.pathname,search:I.search,protocol:I.protocol,origin:I.origin,hash:I.hash}}catch(S){return{hostname:"",pathname:"",search:"",protocol:"",origin:"",hash:""}}}const b={get(S){try{const b=localStorage.getItem(S);return b?JSON.parse(b):null}catch(S){return null}},set(S,b){try{return localStorage.setItem(S,JSON.stringify(b)),!0}catch(S){return!1}},remove(S){try{return localStorage.removeItem(S),!0}catch(S){return!1}},getItem(S){return this.get(S)},setItem(S,b){return this.set(S,b)},removeItem(S){return this.remove(S)}},I={getItem(S){try{return sessionStorage.getItem(S)}catch(S){return null}},setItem(S,b){try{return sessionStorage.setItem(S,b),!0}catch(S){return!1}},removeItem(S){try{return sessionStorage.removeItem(S),!0}catch(S){return!1}}},x={isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isString:S=>"string"==typeof S,isFunction:S=>"function"==typeof S,isEmpty:S=>null==S||""===S||Array.isArray(S)&&0===S.length,get:(S,b,I)=>{if(!S)return I;const x=b.split(".");let R=S;for(const S of x){if(!R||"object"!=typeof R||!(S in R))return I;R=R[S]}return R}};function debounce(S,b){let I;return function executedFunction(...x){clearTimeout(I),I=setTimeout(()=>{clearTimeout(I),S(...x)},b)}}function throttle$1(S,b){let I;return function(...x){I||(S.apply(this,x),I=!0,setTimeout(()=>I=!1,b))}}function safeStringify(S,b=10,I=1e4){const x=new WeakSet;let R=0;const A=JSON.stringify(S,function(S,I){if("object"==typeof I&&null!==I&&(R++,R>b))return"[Max Depth Exceeded]";if("object"==typeof I&&null!==I){if(x.has(I))return"[Circular Reference]";x.add(I)}return"function"==typeof I?`[Function: ${I.name||"anonymous"}]`:I instanceof Error?{__type:"Error",name:I.name,message:I.message,stack:I.stack}:I instanceof RegExp?`[RegExp: ${I.toString()}]`:I instanceof Date?`[Date: ${I.toISOString()}]`:"symbol"==typeof I?`[Symbol: ${I.toString()}]`:"bigint"==typeof I?`[BigInt: ${I.toString()}]`:"undefined"!=typeof HTMLElement&&I instanceof HTMLElement?`[HTMLElement: <${I.tagName.toLowerCase()}${I.id?' id="'+I.id+'"':""}>]`:"undefined"!=typeof Window&&I instanceof Window?"[Window]":"undefined"!=typeof Document&&I instanceof Document?"[Document]":I});return A&&A.length>I?A.substring(0,I)+"... [truncated]":A}function safeParseConsoleArgs(S,b=5e3,I=1e4){if(!Array.isArray(S))return[];const x=[];let R=0;for(let A=0;A<S.length;A++){if(R>=I){x.push(`[${S.length-A} more arguments truncated]`);break}const _=S[A];let D;try{D=null===_?"null":void 0===_?"undefined":"string"==typeof _?_.length>b?_.substring(0,b)+"... [truncated]":_:"number"==typeof _||"boolean"==typeof _?String(_):"object"==typeof _?safeStringify(_,5,b):String(_)}catch(S){D=`[Unserializable: ${typeof _}]`}const L="string"==typeof D?D.length:0;if(R+L>I){const S=I-R;if(!(S>50&&"string"==typeof D)){x.push("[Remaining arguments truncated]");break}D=D.substring(0,S)+"... [truncated]"}x.push(D),R+=L}return x}const R={get:(S,b,I)=>{const x=b.split(".");let R=S;for(const S of x){if(null==R)return I;R=R[S]}return void 0!==R?R:I},set:(S,b,I)=>{const x=b.split("."),R=x.pop();let A=S;for(const S of x)S in A&&"object"==typeof A[S]||(A[S]={}),A=A[S];return A[R]=I,S},has:(S,b)=>{const I=b.split(".");let x=S;for(const S of I){if(null==x||!(S in x))return!1;x=x[S]}return!0},isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isArray:S=>Array.isArray(S),isString:S=>"string"==typeof S,isNumber:S=>"number"==typeof S&&!isNaN(S),isBoolean:S=>"boolean"==typeof S,isFunction:S=>"function"==typeof S,isNull:S=>null===S,isUndefined:S=>void 0===S,isEmpty:S=>null==S||("string"==typeof S||Array.isArray(S)?0===S.length:"object"==typeof S&&0===Object.keys(S).length),toLower:S=>String(S).toLowerCase(),toUpper:S=>String(S).toUpperCase(),trim:S=>String(S).trim(),startsWith:(S,b)=>String(S).startsWith(b),endsWith:(S,b)=>String(S).endsWith(b),includes:(S,b)=>String(S).includes(b),filter:(S,b)=>Array.isArray(S)?S.filter(b):[],map:(S,b)=>Array.isArray(S)?S.map(b):[],find:(S,b)=>{if(Array.isArray(S))return S.find(b)},sortBy:(S,b)=>Array.isArray(S)?[...S].sort((S,I)=>{const x="function"==typeof b?b(S):S[b],R="function"==typeof b?b(I):I[b];return x<R?-1:x>R?1:0}):[],keys:S=>Object.keys(S||{}),values:S=>Object.values(S||{}),entries:S=>Object.entries(S||{}),assign:(S,...b)=>Object.assign({},S,...b),cloneDeep:S=>{if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>R.cloneDeep(S));if("object"==typeof S){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=R.cloneDeep(S[I]));return b}return S},merge:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&(R.isObject(S[b])&&R.isObject(I[b])?I[b]=R.merge(I[b],S[b]):I[b]=S[b]);return I},defaults:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&void 0===I[b]&&(I[b]=S[b]);return I},min:(...S)=>Math.min(...S),max:(...S)=>Math.max(...S),round:(S,b=0)=>{const I=Math.pow(10,b);return Math.round(S*I)/I},noop:()=>{},identity:S=>S,isEqual:(S,b)=>{if(S===b)return!0;if(null===S||null===b)return!1;if(typeof S!=typeof b)return!1;if("object"!=typeof S)return!1;const I=Object.keys(S),x=Object.keys(b);if(I.length!==x.length)return!1;for(const A of I){if(!x.includes(A))return!1;if(!R.isEqual(S[A],b[A]))return!1}return!0}},A={RETRY_INTERVAL_MS:3e4,DEDUPLICATION_WINDOW_MS:6e4,MAX_QUEUE_SIZE:1e3,MAX_RETRIES:3,BATCH_SIZE:10,DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS:[]};class LoggingManager{constructor(){this.globalConfig={enabled:!1,level:"info",showTimestamps:!0,showServiceIcons:!0},this.serviceConfig={TraceScoutMonitoringCore:{enabled:!1,level:"info"},ConfigManager:{enabled:!1,level:"info"},EventManager:{enabled:!1,level:"info"},ServiceManager:{enabled:!1,level:"info"},UserProfileManager:{enabled:!1,level:"info"},PerformanceMonitor:{enabled:!1,level:"info"},FetchInterceptor:{enabled:!1,level:"info"},XHRInterceptor:{enabled:!1,level:"info"},ResourceInterceptor:{enabled:!1,level:"info"},PostMessageInterceptor:{enabled:!1,level:"info"},CoreWebVitalsMonitor:{enabled:!1,level:"info"},Recorder:{enabled:!1,level:"info"},SessionStorage:{enabled:!1,level:"info"},UploadQueue:{enabled:!1,level:"info"},"CDN-Loader":{enabled:!1,level:"info"},Replayer:{enabled:!1,level:"info"},Validation:{enabled:!1,level:"info"},BaseService:{enabled:!1,level:"info"}},this.logLevels={error:0,warn:1,info:2,debug:3},this.serviceStyles={TraceScoutMonitoringCore:{icon:"🎯",color:"#009688"},ConfigManager:{icon:"⚙️",color:"#607D8B"},EventManager:{icon:"📝",color:"#4CAF50"},ServiceManager:{icon:"🌐",color:"#9C27B0"},UserProfileManager:{icon:"👤",color:"#FF9800"},PerformanceMonitor:{icon:"⚡",color:"#795548"},FetchInterceptor:{icon:"🔌",color:"#8BC34A"},XHRInterceptor:{icon:"📡",color:"#FFC107"},ResourceInterceptor:{icon:"📦",color:"#E91E63"},PostMessageInterceptor:{icon:"💬",color:"#3F51B5"},CoreWebVitalsMonitor:{icon:"📊",color:"#2196F3"},Recorder:{icon:"🎬",color:"#FF5722"},SessionStorage:{icon:"💾",color:"#673AB7"},UploadQueue:{icon:"📤",color:"#FF9800"},"CDN-Loader":{icon:"📥",color:"#4CAF50"},Replayer:{icon:"▶️",color:"#9C27B0"},Validation:{icon:"✅",color:"#4CAF50"},BaseService:{icon:"🔧",color:"#607D8B"},default:{icon:"🔍",color:"#666"}}}configure(S={}){this.globalConfig={...this.globalConfig,...S},S.services&&Object.keys(S.services).forEach(b=>{this.serviceConfig[b]&&(this.serviceConfig[b]={...this.serviceConfig[b],...S.services[b]})})}enableServices(S,b="info"){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!0,this.serviceConfig[S].level=b)}),this.globalConfig.enabled=!0}disableServices(S){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!1)})}enableAll(S="info"){Object.keys(this.serviceConfig).forEach(b=>{this.serviceConfig[b].enabled=!0,this.serviceConfig[b].level=S}),this.globalConfig.enabled=!0}disableAll(){Object.keys(this.serviceConfig).forEach(S=>{this.serviceConfig[S].enabled=!1}),this.globalConfig.enabled=!1}getConfig(){return{global:{...this.globalConfig},services:{...this.serviceConfig}}}getEnabledServices(){return Object.keys(this.serviceConfig).filter(S=>this.serviceConfig[S].enabled)}isEnabled(S,b="info"){if(!this.globalConfig.enabled)return!1;const I=this.serviceConfig[S];if(!I||!I.enabled)return!1;const x=this.logLevels[I.level]||this.logLevels.info;return(this.logLevels[b]||this.logLevels.info)<=x}createLogger(S){return new ServiceLogger(S,this)}formatMessage(S,b,I){const x=this.serviceStyles[S]||this.serviceStyles.default;return{prefix:`%c${`${this.globalConfig.showTimestamps?`[${(new Date).toLocaleTimeString()}]`:""}[TraceScout][${S}]${this.globalConfig.showServiceIcons?x.icon:""}`}`,style:`color: ${x.color}; font-weight: bold;`,args:I}}}class ServiceLogger{constructor(S,b){this.serviceName=S,this.loggingManager=b}log(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.log(b.prefix,b.style,...b.args)}}info(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.info(b.prefix,b.style,...b.args)}}warn(...S){if(this.loggingManager.isEnabled(this.serviceName,"warn")){const b=this.loggingManager.formatMessage(this.serviceName,"warn",S);console.warn(b.prefix,"color: #FF5722; font-weight: bold;",...b.args)}}error(...S){const b=this.loggingManager.formatMessage(this.serviceName,"error",S);console.error(b.prefix,"color: #F44336; font-weight: bold;",...b.args)}debug(...S){if(this.loggingManager.isEnabled(this.serviceName,"debug")){const b=this.loggingManager.formatMessage(this.serviceName,"debug",S);console.debug(b.prefix,"color: #9E9E9E; font-weight: bold;",...b.args)}}session(...S){this.log("🎬",...S)}performance(...S){this.log("⚡",...S)}network(...S){this.log("🌐",...S)}storage(...S){this.log("💾",...S)}updateDebugMode(S){S?this.loggingManager.enableServices(this.serviceName):this.loggingManager.disableServices(this.serviceName)}}const _=new LoggingManager;function createLogger(S){return _.createLogger(S)}class Logger{constructor(S="",b=!1){this.serviceName=S.replace(/^\[|\]$/g,""),this.serviceLogger=_.createLogger(this.serviceName),b&&_.enableServices(this.serviceName),this.prefix=S,this.debug=Boolean(b)}updateDebugMode(S){this.debug=Boolean(S),this.serviceLogger.updateDebugMode(S)}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.serviceLogger.debug(...S)}success(...S){this.serviceLogger.log("✅",...S)}important(...S){this.serviceLogger.log("⚠️",...S)}session(...S){this.serviceLogger.session(...S)}performance(...S){this.serviceLogger.performance(...S)}interceptor(...S){this.serviceLogger.network(...S)}service(...S){this.serviceLogger.network(...S)}monitor(...S){this.serviceLogger.log("📊",...S)}}function validateEndpoints(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateDomains(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateService(S){return S&&"object"==typeof S&&"function"==typeof S.send}class ConfigManager{constructor(S={}){this.defaultConfig=S,this.config={},this.logger=new Logger("[ConfigManager]",S.debug)}validate(S={}){const b=[];try{const I=validateEndpoints(S.endpoints),x=validateDomains(S.domainsToTrack);I||x||b.push("Either endpoints or domainsToTrack must be provided"),S.service&&!validateService(S.service)&&b.push("Invalid service: must be an object with send() method");const R={retryIntervalMs:{min:1e3,max:3e5},deduplicationWindowMs:{min:100,max:36e5},maxQueueSize:{min:10,max:1e4},maxRetries:{min:1,max:10},batchSize:{min:1,max:100}};if(Object.entries(R).forEach(([I,{min:x,max:R}])=>{const A=S[I];void 0!==A&&("number"!=typeof A||A<x||A>R)&&b.push(`${I} must be a number between ${x} and ${R}`)}),void 0!==S.monitorPostMessages)if("object"!=typeof S.monitorPostMessages||null===S.monitorPostMessages)b.push("monitorPostMessages must be an object");else{const I=S.monitorPostMessages;void 0!==I.postMessageOriginWhitelist&&(Array.isArray(I.postMessageOriginWhitelist)?I.postMessageOriginWhitelist.every(S=>"string"==typeof S)||b.push("postMessageOriginWhitelist must contain only strings"):b.push("postMessageOriginWhitelist must be an array")),void 0===I.excludePostMessagesEvents||Array.isArray(I.excludePostMessagesEvents)||b.push("excludePostMessagesEvents must be an array"),void 0===I.monitorSpecificPostMessagesEvents||Array.isArray(I.monitorSpecificPostMessagesEvents)||b.push("monitorSpecificPostMessagesEvents must be an array")}if(void 0!==S.monitorPerformance&&"boolean"!=typeof S.monitorPerformance&&b.push("monitorPerformance must be a boolean"),void 0!==S.slowRequestThreshold&&("number"!=typeof S.slowRequestThreshold||S.slowRequestThreshold<100||S.slowRequestThreshold>3e4)&&b.push("slowRequestThreshold must be a number between 100 and 30000 milliseconds"),void 0!==S.averageAlertThreshold&&("number"!=typeof S.averageAlertThreshold||S.averageAlertThreshold<100||S.averageAlertThreshold>3e4)&&b.push("averageAlertThreshold must be a number between 100 and 30000 milliseconds"),b.length>0)throw new Error(`Configuration validation failed: ${b.join(", ")}`);return!0}catch(S){throw S}}apply(S={}){this.logger.log("Applying configuration options"),this.validate(S);try{this.config=R.merge({},this.defaultConfig,S,{debug:"boolean"==typeof R.get(S,"debug")?R.get(S,"debug"):Boolean(R.get(S,"debug")),retryIntervalMs:Math.max(1e3,R.get(S,"retryIntervalMs",this.defaultConfig.retryIntervalMs)),deduplicationWindowMs:Math.max(100,R.get(S,"deduplicationWindowMs",this.defaultConfig.deduplicationWindowMs)),maxQueueSize:Math.max(10,R.get(S,"maxQueueSize",this.defaultConfig.maxQueueSize)),maxRetries:Math.max(1,Math.min(10,R.get(S,"maxRetries",this.defaultConfig.maxRetries))),batchSize:Math.max(1,Math.min(100,R.get(S,"batchSize",this.defaultConfig.batchSize)))}),S.service&&(this.config.service=S.service),S.endpoints&&(this.config.endpoints=S.endpoints),S.domainsToTrack&&(this.config.domainsToTrack=S.domainsToTrack),S.monitorPostMessages&&(this.config.monitorPostMessages={postMessageOriginWhitelist:S.monitorPostMessages.postMessageOriginWhitelist||[],excludePostMessagesEvents:S.monitorPostMessages.excludePostMessagesEvents||[],monitorSpecificPostMessagesEvents:S.monitorPostMessages.monitorSpecificPostMessagesEvents||[]}),void 0!==S.monitorPerformance&&(this.config.monitorPerformance=S.monitorPerformance),void 0!==S.slowRequestThreshold&&(this.config.slowRequestThreshold=Math.max(100,Math.min(3e4,S.slowRequestThreshold))),void 0!==S.averageAlertThreshold&&(this.config.averageAlertThreshold=Math.max(100,Math.min(3e4,S.averageAlertThreshold)));return["appName","appVersion","environment","userId","sessionId","logPreflight","logResourceErrors","enableSessionRecording","sessionRecordingOptions","coreWebVitalsConfig"].forEach(b=>{void 0!==S[b]&&(this.config[b]=S[b])}),this.logger.log("Configuration applied successfully"),this.config}catch(S){throw this.logger.error("Failed to apply configuration:",S),S}}get(S,b=void 0){return R.get(this.config,S,b)}getAll(){return{...this.config}}update(S,b){return"string"==typeof S?this.config[S]=b:"object"==typeof S&&(this.config={...this.config,...S}),this.config}reset(){return this.config={...this.defaultConfig},this.config}}var D,L,B,U,$,j=-1,o=function(S){addEventListener("pageshow",function(b){b.persisted&&(j=b.timeStamp,S(b))},!0)},c=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},u=function(){var S=c();return S&&S.activationStart||0},f=function(S,b){var I=c(),x="navigate";return j>=0?x="back-forward-cache":I&&(document.prerendering||u()>0?x="prerender":document.wasDiscarded?x="restore":I.type&&(x=I.type.replace(/_/g,"-"))),{name:S,value:void 0===b?-1:b,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:x}},s=function(S,b,I){try{if(PerformanceObserver.supportedEntryTypes.includes(S)){var x=new PerformanceObserver(function(S){Promise.resolve().then(function(){b(S.getEntries())})});return x.observe(Object.assign({type:S,buffered:!0},I||{})),x}}catch(S){}},d=function(S,b,I,x){var R,A;return function(_){b.value>=0&&(_||x)&&((A=b.value-(R||0))||void 0===R)&&(R=b.value,b.delta=A,b.rating=function(S,b){return S>b[1]?"poor":S>b[0]?"needs-improvement":"good"}(b.value,I),S(b))}},l=function(S){requestAnimationFrame(function(){return requestAnimationFrame(function(){return S()})})},p=function(S){var n=function(b){"pagehide"!==b.type&&"hidden"!==document.visibilityState||S(b)};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},v=function(S){var b=!1;return function(I){b||(S(I),b=!0)}},W=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},g=function(S){"hidden"===document.visibilityState&&W>-1&&(W="visibilitychange"===S.type?S.timeStamp:0,T())},y=function(){addEventListener("visibilitychange",g,!0),addEventListener("prerenderingchange",g,!0)},T=function(){removeEventListener("visibilitychange",g,!0),removeEventListener("prerenderingchange",g,!0)},E=function(){return W<0&&(W=h(),y(),o(function(){setTimeout(function(){W=h(),y()},0)})),{get firstHiddenTime(){return W}}},C=function(S){document.prerendering?addEventListener("prerenderingchange",function(){return S()},!0):S()},H=[1800,3e3],w=function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FCP"),A=s("paint",function(S){S.forEach(function(S){"first-contentful-paint"===S.name&&(A.disconnect(),S.startTime<x.firstHiddenTime&&(R.value=Math.max(S.startTime-u(),0),R.entries.push(S),I(!0)))})});A&&(I=d(S,R,H,b.reportAllChanges),o(function(x){R=f("FCP"),I=d(S,R,H,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,I(!0)})}))})},V=[.1,.25],Q={passive:!0,capture:!0},G=new Date,P=function(S,b){D||(D=b,L=S,B=new Date,k(removeEventListener),F())},F=function(){if(L>=0&&L<B-G){var S={entryType:"first-input",name:D.type,target:D.target,cancelable:D.cancelable,startTime:D.timeStamp,processingStart:D.timeStamp+L};U.forEach(function(b){b(S)}),U=[]}},M=function(S){if(S.cancelable){var b=(S.timeStamp>1e12?new Date:performance.now())-S.timeStamp;"pointerdown"==S.type?function(S,b){var t=function(){P(S,b),r()},i=function(){r()},r=function(){removeEventListener("pointerup",t,Q),removeEventListener("pointercancel",i,Q)};addEventListener("pointerup",t,Q),addEventListener("pointercancel",i,Q)}(b,S):P(b,S)}},k=function(S){["mousedown","keydown","touchstart","pointerdown"].forEach(function(b){return S(b,M,Q)})},J=[100,300],X=0,Y=1/0,ee=0,N=function(S){S.forEach(function(S){S.interactionId&&(Y=Math.min(Y,S.interactionId),ee=Math.max(ee,S.interactionId),X=ee?(ee-Y)/7+1:0)})},O=function(){return $?X:performance.interactionCount||0},q=function(){"interactionCount"in performance||$||($=s("event",N,{type:"event",buffered:!0,durationThreshold:0}))},te=[200,500],se=0,z=function(){return O()-se},re=[],ne={},K=function(S){var b=re[re.length-1],I=ne[S.interactionId];if(I||re.length<10||S.duration>b.latency){if(I)I.entries.push(S),I.latency=Math.max(I.latency,S.duration);else{var x={id:S.interactionId,latency:S.duration,entries:[S]};ne[x.id]=x,re.push(x)}re.sort(function(S,b){return b.latency-S.latency}),re.splice(10).forEach(function(S){delete ne[S.id]})}},ie=[2500,4e3],oe={},ae=[800,1800],le=function e(S){document.prerendering?C(function(){return e(S)}):"complete"!==document.readyState?addEventListener("load",function(){return e(S)},!0):setTimeout(S,0)},Z=function(S,b){b=b||{};var I=f("TTFB"),x=d(S,I,ae,b.reportAllChanges);le(function(){var R=c();if(R){var A=R.responseStart;if(A<=0||A>performance.now())return;I.value=Math.max(A-u(),0),I.entries=[R],x(!0),o(function(){I=f("TTFB",0),(x=d(S,I,ae,b.reportAllChanges))(!0)})}})};class CoreWebVitalsMonitor{constructor(S={}){this.config=S,this.logger=new Logger("[CoreWebVitalsMonitor]",S.debug),this.enabled=!1!==S.enabled,this.metrics=new Map,this.observers=[],this.callbacks=[],this.useWebVitalsLibrary=!1!==S.useWebVitalsLibrary,this.thresholds={lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3},...S.thresholds},this.collectMetrics={lcp:!1!==S.collectLCP,fid:!1!==S.collectFID,cls:!1!==S.collectCLS,inp:!1!==S.collectINP,ttfb:!1!==S.collectTTFB,fcp:!1!==S.collectFCP},this.reportingEnabled=!1!==S.reportingEnabled,this.reportThreshold=S.reportThreshold||"needsImprovement",this.enabled&&"undefined"!=typeof window&&this.init()}init(){if(this.logger.log("Initializing Core Web Vitals monitoring..."),this.useWebVitalsLibrary)try{return this.initWithWebVitalsLibrary(),void this.logger.log("Core Web Vitals monitoring initialized with web-vitals library")}catch(S){this.logger.warn("web-vitals library subscription failed, falling back to custom implementation:",S)}this.initCustomImplementation(),this.logger.log("Core Web Vitals monitoring initialized with custom implementation")}initWithWebVitalsLibrary(){this.collectMetrics.lcp&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("LCP"),a=function(S){var b=S[S.length-1];b&&b.startTime<x.firstHiddenTime&&(R.value=Math.max(b.startTime-u(),0),R.entries=[b],I())},A=s("largest-contentful-paint",a);if(A){I=d(S,R,ie,b.reportAllChanges);var _=v(function(){oe[R.id]||(a(A.takeRecords()),A.disconnect(),oe[R.id]=!0,I(!0))});["keydown","click"].forEach(function(S){addEventListener(S,function(){return setTimeout(_,0)},!0)}),p(_),o(function(x){R=f("LCP"),I=d(S,R,ie,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,oe[R.id]=!0,I(!0)})})}})}(S=>this.handleWebVitalsMetric("lcp",S)),this.collectMetrics.fid&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FID"),l=function(S){S.startTime<x.firstHiddenTime&&(R.value=S.processingStart-S.startTime,R.entries.push(S),I(!0))},m=function(S){S.forEach(l)},A=s("first-input",m);I=d(S,R,J,b.reportAllChanges),A&&p(v(function(){m(A.takeRecords()),A.disconnect()})),A&&o(function(){var x;R=f("FID"),I=d(S,R,J,b.reportAllChanges),U=[],L=-1,D=null,k(addEventListener),x=l,U.push(x),F()})})}(S=>this.handleWebVitalsMetric("fid",S)),this.collectMetrics.cls&&function(S,b){b=b||{},w(v(function(){var I,x=f("CLS",0),R=0,A=[],c=function(S){S.forEach(function(S){if(!S.hadRecentInput){var b=A[0],I=A[A.length-1];R&&S.startTime-I.startTime<1e3&&S.startTime-b.startTime<5e3?(R+=S.value,A.push(S)):(R=S.value,A=[S])}}),R>x.value&&(x.value=R,x.entries=A,I())},_=s("layout-shift",c);_&&(I=d(S,x,V,b.reportAllChanges),p(function(){c(_.takeRecords()),I(!0)}),o(function(){R=0,x=f("CLS",0),I=d(S,x,V,b.reportAllChanges),l(function(){return I()})}),setTimeout(I,0))}))}(S=>this.handleWebVitalsMetric("cls",S)),this.collectMetrics.inp&&function(S,b){b=b||{},C(function(){var I;q();var x,R=f("INP"),a=function(S){S.forEach(function(S){S.interactionId&&K(S),"first-input"===S.entryType&&!re.some(function(b){return b.entries.some(function(b){return S.duration===b.duration&&S.startTime===b.startTime})})&&K(S)});var b,I=(b=Math.min(re.length-1,Math.floor(z()/50)),re[b]);I&&I.latency!==R.value&&(R.value=I.latency,R.entries=I.entries,x())},A=s("event",a,{durationThreshold:null!==(I=b.durationThreshold)&&void 0!==I?I:40});x=d(S,R,te,b.reportAllChanges),A&&("PerformanceEventTiming"in window&&"interactionId"in PerformanceEventTiming.prototype&&A.observe({type:"first-input",buffered:!0}),p(function(){a(A.takeRecords()),R.value<0&&z()>0&&(R.value=0,R.entries=[]),x(!0)}),o(function(){re=[],se=O(),R=f("INP"),x=d(S,R,te,b.reportAllChanges)}))})}(S=>this.handleWebVitalsMetric("inp",S)),this.collectMetrics.ttfb&&Z(S=>this.handleWebVitalsMetric("ttfb",S)),this.collectMetrics.fcp&&w(S=>this.handleWebVitalsMetric("fcp",S)),this.setupVisibilityChangeHandler()}handleWebVitalsMetric(S,b){const I={type:S,value:b.value,id:b.id,timestamp:Date.now(),rating:this.getRating(S,b.value),threshold:this.thresholds[S],libRating:"string"==typeof b.rating?b.rating:null,navigationType:"string"==typeof b.navigationType?b.navigationType:null};this.metrics.set(S,I),this.logger.log(`Web Vital metric captured: ${S} = ${b.value}ms (${I.rating})`),this.reportingEnabled&&this.shouldReport(I)&&this.reportMetric(I),this.triggerCallbacks(S,I)}initCustomImplementation(){this.logger.log("Initializing custom Core Web Vitals implementation..."),this.collectMetrics.fcp&&this.trackFCP(),this.collectMetrics.lcp&&this.trackLCP(),this.collectMetrics.fid&&this.trackFID(),this.collectMetrics.cls&&this.trackCLS(),this.collectMetrics.ttfb&&this.trackTTFB(),this.setupVisibilityChangeHandler()}trackFCP(){try{const S=new PerformanceObserver(b=>{for(const I of b.getEntries())"first-contentful-paint"===I.name&&(this.handleWebVitalsMetric("fcp",{value:I.startTime,id:`fcp-${Date.now()}`,name:"FCP"}),S.disconnect())});S.observe({type:"paint",buffered:!0})}catch(S){this.logger.warn("Failed to track FCP:",S)}}trackLCP(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.size>S&&(S=I.size,this.handleWebVitalsMetric("lcp",{value:I.startTime,id:`lcp-${Date.now()}`,name:"LCP"}))});b.observe({type:"largest-contentful-paint",buffered:!0})}catch(S){this.logger.warn("Failed to track LCP:",S)}}trackFID(){let S=!1;const handleInput=b=>{if(S)return;S=!0;const I=b.timeStamp-b.timeStamp;this.handleWebVitalsMetric("fid",{value:I,id:`fid-${Date.now()}`,name:"FID"}),["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.removeEventListener(S,handleInput)})};["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.addEventListener(S,handleInput,{once:!0,passive:!0})})}trackCLS(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.hadRecentInput||(S+=I.value,this.handleWebVitalsMetric("cls",{value:S,id:`cls-${Date.now()}`,name:"CLS"}))});b.observe({type:"layout-shift",buffered:!0})}catch(S){this.logger.warn("Failed to track CLS:",S)}}trackTTFB(){try{if(window.performance&&window.performance.timing){const S=window.performance.timing,b=S.responseStart-S.navigationStart;b>0&&this.handleWebVitalsMetric("ttfb",{value:b,id:`ttfb-${Date.now()}`,name:"TTFB"})}}catch(S){this.logger.warn("Failed to track TTFB:",S)}}getRating(S,b){const I=this.thresholds[S];return I?b<=I.good?"good":b<=I.needsImprovement?"needsImprovement":"poor":"unknown"}shouldReport(S){return"good"===this.reportThreshold?"good"===S.rating:"needsImprovement"!==this.reportThreshold||("good"===S.rating||"needsImprovement"===S.rating)}reportMetric(S){const b={type:"core_web_vital",context:{forceLog:!0,isMonitored:!0,metricType:S.type,metricValue:S.value,metricRating:S.rating,threshold:S.threshold},data:S};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}triggerCallbacks(S,b){this.callbacks.forEach(I=>{try{I(S,b)}catch(S){this.logger.error("Error in metric callback:",S)}})}setupVisibilityChangeHandler(){document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.reportFinalMetrics()})}reportFinalMetrics(){if(!this.reportingEnabled)return;const S=Array.from(this.metrics.values());if(0===S.length)return;this.logger.log("Reporting final Core Web Vitals metrics:",S);const b={type:"core_web_vitals_final_report",context:{forceLog:!0,isMonitored:!0,timestamp:Date.now(),pageUrl:window.location.href},data:{metrics:S,summary:this.generateSummary(S)}};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}generateSummary(S){const b={total:S.length,byRating:{good:0,needsImprovement:0,poor:0},average:0,worst:null};let I=0,x=null;return S.forEach(S=>{b.byRating[S.rating]++,I+=S.value,(!x||"poor"===S.rating||"needsImprovement"===S.rating&&"poor"!==x.rating)&&(x=S)}),b.average=I/S.length,b.worst=x,b}addCallback(S){"function"==typeof S&&this.callbacks.push(S)}removeCallback(S){const b=this.callbacks.indexOf(S);b>-1&&this.callbacks.splice(b,1)}getMetrics(){return Array.from(this.metrics.values())}getMetric(S){return this.metrics.get(S)}updateThresholds(S){this.thresholds={...this.thresholds,...S},this.logger.log("Core Web Vitals thresholds updated:",this.thresholds)}destroy(){this.observers.forEach(S=>{S&&"function"==typeof S.disconnect&&S.disconnect()}),this.observers=[],this.callbacks=[],this.metrics.clear(),this.logger=null}}const ce="0123456789abcdef";function generateSessionId(){return`ts_${Date.now()}_${function randomHexSuffix(S=12){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const b=new Uint8Array(Math.ceil(S/2));crypto.getRandomValues(b);let I="";for(let S=0;S<b.length;S++)I+=ce[b[S]>>4]+ce[15&b[S]];return I.slice(0,S)}let b="";for(let I=0;I<S;I++)b+=ce[Math.floor(16*Math.random())];return b}(12)}`}class SDKContext{static#e=null;static initialize(S){return this.#e?(console.warn("[SDKContext] Already initialized, returning existing instance"),this.#e):(this.#e=new SDKContext(S),this.#e)}static updateSessionId(S){this.#e&&(this.#e.sessionId=S,this.#e.sessionStartTime=Date.now(),console.log("[SDKContext] ✅ Session ID updated:",S))}static getInstance(){return this.#e}static resetForTests(){if("undefined"!=typeof process)throw new Error("resetForTests() only allowed in test environment");this.#e=null}constructor({projectId:S,workspaceId:b,environment:I,userId:x,sessionId:R,sessionManager:A}){this.#t({projectId:S}),this.projectId=S,this.workspaceId=null,this.environment=I||"production",this.userId=x||null,this.userEmail=null,this.userAttributes={},this.sessionManager=A||null,this.pageviewManager=null,this.sessionId=R||this.#s(),this.sessionStartTime=Date.now(),this.device={userAgent:navigator.userAgent,viewport:this.#r(),platform:navigator.platform,language:navigator.language,timezone:this.#n(),screen:{width:window.screen.width,height:window.screen.height,colorDepth:window.screen.colorDepth}},this.uaInfo=function parseUserAgent(S){const b={browserName:null,browserVersion:null,osName:null,osVersion:null,deviceType:null};if(!S||"string"!=typeof S)return b;let I;return/iPad|Tablet|PlayBook|Silk/i.test(S)||/Android/i.test(S)&&!/Mobile/i.test(S)?b.deviceType="tablet":/Mobi|iPhone|iPod|Android.*Mobile|Windows Phone|BlackBerry/i.test(S)?b.deviceType="mobile":/Mozilla|Chrome|Safari|Firefox|Edg|Opera|OPR/i.test(S)&&(b.deviceType="desktop"),(I=S.match(/Edg(?:e|A|iOS)?\/([\d.]+)/))?(b.browserName="Edge",b.browserVersion=I[1]):(I=S.match(/(?:OPR|Opera)\/([\d.]+)/))?(b.browserName="Opera",b.browserVersion=I[1]):(I=S.match(/SamsungBrowser\/([\d.]+)/))?(b.browserName="Samsung Internet",b.browserVersion=I[1]):(I=S.match(/(?:FxiOS|Firefox)\/([\d.]+)/))?(b.browserName="Firefox",b.browserVersion=I[1]):(I=S.match(/(?:CriOS|Chrome)\/([\d.]+)/))?(b.browserName="Chrome",b.browserVersion=I[1]):/Safari\//.test(S)&&(I=S.match(/Version\/([\d.]+)/))&&(b.browserName="Safari",b.browserVersion=I[1]),(I=S.match(/Windows NT ([\d.]+)/))?(b.osName="Windows",b.osVersion={"10.0":"10/11",6.3:"8.1",6.2:"8",6.1:"7"}[I[1]]||I[1]):(I=S.match(/iPhone OS ([\d_]+)|iPad; CPU OS ([\d_]+)/))?(b.osName="iOS",b.osVersion=(I[1]||I[2]||"").replace(/_/g,".")||null):(I=S.match(/Mac OS X ([\d_.]+)/))?(b.osName="macOS",b.osVersion=I[1].replace(/_/g,".")):(I=S.match(/Android ([\d.]+)/))?(b.osName="Android",b.osVersion=I[1]):/Android/i.test(S)?b.osName="Android":/CrOS/.test(S)?b.osName="ChromeOS":/Linux/.test(S)&&(b.osName="Linux"),b}(navigator.userAgent),this.errorCount=0,this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] ✅ Initialized successfully"),console.log(` Project ID: ${S}`),console.log(` Session ID: ${this.sessionId}`),console.log(` Environment: ${this.environment}`)}setWorkspaceId(S){this.workspaceId=S,console.log("[SDKContext] ✅ Workspace ID updated:",S)}#t(S){const b=[];if(S.projectId?this.#i(S.projectId)||b.push("projectId must be a valid UUID"):b.push("projectId is required"),b.length>0){const S=new Error(`TraceScout.init() validation failed:\n - ${b.join("\n - ")}`);throw S.name="ValidationError",S.validationErrors=b,S}}#i(S){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(S)}#s(){return generateSessionId()}#r(){return{width:window.innerWidth,height:window.innerHeight}}#n(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}enrichEvent(S){return{...S,sessionId:this.sessionId,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,relativeTime:S.timestamp?S.timestamp-this.sessionStartTime:0,browser:{...this.device,url:window.location.href,referrer:document.referrer,title:document.title},userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0}}enrichChunk(S){return{...S,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,metadata:{...S.metadata,metaSchema:2,sdkVersion:"2.4.0",projectId:this.projectId,workspaceId:this.workspaceId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,userName:this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??void 0:void 0,userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0,userTraits:this.userAttributes,browser:this.uaInfo.browserName?{name:this.uaInfo.browserName,version:this.uaInfo.browserVersion||void 0}:void 0,os:this.uaInfo.osName?{name:this.uaInfo.osName,version:this.uaInfo.osVersion||void 0}:void 0,deviceType:this.uaInfo.deviceType||void 0,userAgent:this.device.userAgent,viewport:this.device.viewport,platform:this.device.platform,language:this.device.language,timezone:this.device.timezone,screen:this.device.screen,errorCount:this.errorCount,url:window.location.href,referrer:document.referrer,title:document.title}}}recordError(){this.errorCount++}setUser(S,b={}){this.userId=S,this.userEmail=b.email||this.userEmail,this.userAttributes=b,console.log("[SDKContext] User updated:",S)}clearUser(){this.userId=null,this.userEmail=null,this.userAttributes={},console.log("[SDKContext] User cleared")}updatePageContext(){this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] Page context updated:",this.page.url)}getContext(){return{workspace:{id:this.workspaceId},project:{id:this.projectId,environment:this.environment},session:{id:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime},user:{id:this.userId,email:this.userEmail,attributes:this.userAttributes},device:this.device,page:{url:window.location.href,referrer:document.referrer,title:document.title}}}getEventContext(S={}){const b=this.sessionManager?.currentSession?.anonymousId??null,I=this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??null:null,x="function"==typeof this.pageviewManager?.getCurrentPageviewId?this.pageviewManager.getCurrentPageviewId():null;return{projectId:this.projectId,sessionId:this.sessionId,anonymousId:b,environment:this.environment,sdkVersion:S.sdkVersion??"1.0.0",workspaceId:this.workspaceId,userId:this.userId,userEmail:this.userEmail,userName:I,release:S.release??null,sourceName:S.sourceName??null,url:"undefined"!=typeof window?window.location.href:null,pageviewId:x}}setPageviewManager(S){this.pageviewManager=S||null}getSessionInfo(){return{sessionId:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId}}}const ue={CHANNEL_NAME:"ts_session",HEARTBEAT_INTERVAL:5e3,TAB_TIMEOUT:1e4,AWAY_THRESHOLD:12e4};class TabCoordinator{constructor(S={}){this.tabId=`tab_${Date.now()}_${Math.random().toString(36).substr(2,6)}`,this.awayAt=null,this.lastHeartbeat=Date.now(),this.knownTabs=new Map,this.channel=null,this.heartbeatTimer=null,this.channelName=S.channelName||ue.CHANNEL_NAME,this.heartbeatInterval=S.heartbeatInterval||ue.HEARTBEAT_INTERVAL,this.tabTimeout=S.tabTimeout||ue.TAB_TIMEOUT,this.awayThreshold=S.awayThreshold||ue.AWAY_THRESHOLD,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onActivity=S.onActivity||(()=>{}),this.debug=S.debug||!1,this._initBroadcastChannel(),this._initVisibilityTracking(),this._startHeartbeat(),this.debug&&console.log(`[TabCoordinator] Initialized tab: ${this.tabId}`)}_initBroadcastChannel(){if("undefined"!=typeof BroadcastChannel)try{this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=S=>this._handleMessage(S.data),this._broadcast({type:"hb",tabId:this.tabId,timestamp:Date.now()}),this.debug&&console.log("[TabCoordinator] BroadcastChannel connected")}catch(S){console.warn("[TabCoordinator] Failed to create BroadcastChannel:",S)}else console.warn("[TabCoordinator] BroadcastChannel not supported - single-tab mode")}_initVisibilityTracking(){document.addEventListener("visibilitychange",()=>{document.hidden?this._markAway():this._markVisible()}),window.addEventListener("pagehide",()=>{this._markAway(),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt})}),window.addEventListener("beforeunload",()=>{this._markAway()})}_startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.lastHeartbeat=Date.now(),this._broadcast({type:"hb",tabId:this.tabId,timestamp:this.lastHeartbeat,awayAt:this.awayAt}),this._pruneDeadTabs(),this._checkAwayRule()},this.heartbeatInterval)}_broadcast(S){if(this.channel)try{this.channel.postMessage(S)}catch(S){this.debug&&console.warn("[TabCoordinator] Broadcast failed:",S)}}_handleMessage(S){if(S.tabId!==this.tabId)switch(S.type){case"hb":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt}),this.debug&&console.log(`[TabCoordinator] Heartbeat from ${S.tabId}, away: ${S.awayAt?"yes":"no"}`);break;case"activity":this.onActivity(S.timestamp);break;case"away":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt});break;case"visible":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:null});break;case"new_session":this.debug&&console.log("[TabCoordinator] New session broadcast received")}}_markAway(){this.awayAt||(this.awayAt=Date.now(),this.debug&&console.log("[TabCoordinator] Tab marked AWAY"),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt}))}_markVisible(){if(this.awayAt){const S=Date.now()-this.awayAt;this.debug&&console.log(`[TabCoordinator] Tab back VISIBLE after ${Math.round(S/1e3)}s`),this.awayAt=null,this._broadcast({type:"visible",tabId:this.tabId,timestamp:Date.now()})}}_pruneDeadTabs(){const S=Date.now();for(const[b,I]of this.knownTabs.entries())S-I.lastSeen>this.tabTimeout&&(this.debug&&console.log(`[TabCoordinator] Pruning dead tab: ${b}`),this.knownTabs.delete(b))}_checkAwayRule(){const S=Date.now(),b=this.awayAt&&S-this.awayAt>this.awayThreshold;if(this.awayAt){for(const[b,I]of this.knownTabs.entries())if(!I.awayAt||S-I.awayAt<this.awayThreshold)return;b&&(console.log("[TabCoordinator] ALL tabs away >2min - session should end"),this.onSessionEnd("away_rule"))}}reportActivity(){const S=Date.now();this._broadcast({type:"activity",tabId:this.tabId,timestamp:S})}broadcastNewSession(S){this._broadcast({type:"new_session",tabId:this.tabId,sessionId:S,timestamp:Date.now()})}hasActiveTab(){if(!this.awayAt)return!0;for(const[S,b]of this.knownTabs.entries())if(!b.awayAt)return!0;return!1}getTabCount(){return this.knownTabs.size+1}getTabId(){return this.tabId}isAway(){return null!==this.awayAt}getAwayDuration(){return this.awayAt?Date.now()-this.awayAt:0}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.channel&&(this.channel.close(),this.channel=null),this.knownTabs.clear(),this.debug&&console.log(`[TabCoordinator] Destroyed tab: ${this.tabId}`)}}function uuidv4(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID()}catch{}const S=new Uint8Array(16);let b=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(S),b=!0)}catch{}if(!b)for(let b=0;b<16;b++)S[b]=Math.floor(256*Math.random());S[6]=15&S[6]|64,S[8]=63&S[8]|128;const I=Array.from(S,S=>S.toString(16).padStart(2,"0")).join("");return I.slice(0,8)+"-"+I.slice(8,12)+"-"+I.slice(12,16)+"-"+I.slice(16,20)+"-"+I.slice(20)}const he="__ts_aid";let de=null;function readCookie(S){if("undefined"==typeof document||"string"!=typeof document.cookie)return null;const b=document.cookie.split("; ");for(const I of b){const b=I.indexOf("=");if(!(b<0)&&I.slice(0,b)===S)try{return decodeURIComponent(I.slice(b+1))}catch{return I.slice(b+1)}}return null}function peekAnonymousId(){const S=readCookie(he);return S||de}function getOrCreateAnonymousId(){const S=peekAnonymousId();if(S)return S;const b=uuidv4();return function writeCookie(S,b,I){if("undefined"==typeof document)return!1;let x=`${S}=${encodeURIComponent(b)}; max-age=${I}; path=/; SameSite=Lax`;"undefined"!=typeof window&&window.location&&"https:"===window.location.protocol&&(x+="; Secure");try{document.cookie=x}catch{return!1}return readCookie(S)===b}(he,b,63072e3)||(de=b),b}const ge={INACTIVITY_TIMEOUT:18e5,ACTIVITY_THROTTLE:1e3,MAX_SESSION_DURATION:144e5};class SessionManager{constructor(S={}){this.sessionIdCookie=S.sessionIdCookie||"__ts_sid",this.lastActivityCookie=S.lastActivityCookie||"__ts_ts",this.sessionStartCookie=S.sessionStartCookie||"__ts_start",this.storageKey=S.storageKey||"__tracescout_session_stats__",this.inactivityTimeout=S.inactivityTimeout||ge.INACTIVITY_TIMEOUT,this.maxSessionDuration=S.maxSessionDuration||ge.MAX_SESSION_DURATION,this.activityThrottle=S.activityThrottle||ge.ACTIVITY_THROTTLE,this.cookieDomain=S.cookieDomain||window.location.hostname,this.cookiePath=S.cookiePath||"/",this.cookieSameSite=S.cookieSameSite||"Lax",this.debug=S.debug||!1,this.onLifecycleEnd="function"==typeof S.onLifecycleEnd?S.onLifecycleEnd:null,this.currentSession=null,this._lastActivityUpdate=0,this._boundActivityHandler=this._handleActivity.bind(this),this._trackingStarted=!1,this.tabCoordinator=new TabCoordinator({onSessionEnd:S=>this._handleSessionEnd(S),onActivity:S=>this._handleRemoteActivity(S),debug:this.debug,awayThreshold:S.awayThreshold,heartbeatInterval:S.heartbeatInterval,tabTimeout:S.tabTimeout})}getOrCreateSession(S={}){const b=this._getStoredSession();if(b&&this._isSessionValid(b))return console.log("[SessionManager] ✅ Continuing session:",b.sessionId),console.log(" Duration:",Math.round((Date.now()-b.startTime)/1e3/60),"min"),console.log(" Pages so far:",b.pageCount),this.currentSession=b,this.currentSession.pageCount++,this._updateActivity(),this._startActivityTracking(),b.sessionId;const I=generateSessionId(),x=getOrCreateAnonymousId();this.currentSession={sessionId:I,anonymousId:x,startTime:Date.now(),lastActivityTime:Date.now(),pageCount:1,eventCount:0,chunkCount:0,lastChunkSequence:0,projectId:S.projectId,workspaceId:S.workspaceId,environment:S.environment,userId:S.userId||null,userEmail:null,userAttributes:{},lifecycle:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}},this._saveSession(),this._startActivityTracking();const R=b?.expiredReason||(b?"Previous session invalid":"No previous session found");return console.log("[SessionManager] 🆕 Created new session:",I),console.log(" Reason:",R),this.tabCoordinator.broadcastNewSession(I),I}_isSessionValid(S){if(!S?.sessionId)return!1;const b=Date.now(),I=b-(S.lastActivityTime||0),x=b-(S.startTime||0),R=this.tabCoordinator?.awayThreshold||12e4;return I>R?(console.log("[SessionManager] ⏰ Session expired: away rule (all tabs closed)"),console.log(" Away for:",Math.round(I/1e3),"seconds"),console.log(" Threshold:",Math.round(R/1e3),"seconds"),S.expiredReason="away_rule",!1):I>this.inactivityTimeout?(console.log("[SessionManager] ⏰ Session expired: inactivity"),console.log(" Inactive for:",Math.round(I/1e3/60),"min"),S.expiredReason="inactivity",!1):!(x>this.maxSessionDuration)||(console.log("[SessionManager] ⏰ Session expired: max duration"),console.log(" Duration:",Math.round(x/1e3/60),"min"),S.expiredReason="max_duration",!1)}_getStoredSession(){try{const S=this._getCookie(this.sessionIdCookie);if(!S)return null;const b=getOrCreateAnonymousId(),I=parseInt(this._getCookie(this.sessionStartCookie))||Date.now(),x=parseInt(this._getCookie(this.lastActivityCookie))||Date.now();let R={};try{const S=localStorage.getItem(this.storageKey);S&&(R=JSON.parse(S))}catch(S){console.warn("[SessionManager] Failed to load stats from localStorage:",S)}if(R.anonymousId&&R.anonymousId!==b)return console.log("[SessionManager] 🔄 Storage cleared detected (anonymousId mismatch)"),console.log(" Cookie anonymousId:",b),console.log(" localStorage anonymousId:",R.anonymousId),this._clearSession(),null;if("number"==typeof R.schemaVersion&&5!==R.schemaVersion)return console.log("[SessionManager] 🔄 Stats schemaVersion mismatch — dropping cached session"),console.log(" cached schemaVersion:",R.schemaVersion),console.log(" required schemaVersion: 5"),this._clearSession(),null;return{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x,pageCount:R.pageCount||1,eventCount:R.eventCount||0,chunkCount:R.chunkCount||0,lastChunkSequence:R.lastChunkSequence||0,projectId:R.projectId,workspaceId:R.workspaceId,environment:R.environment,userId:R.userId,userEmail:R.userEmail,userAttributes:R.userAttributes||{},lifecycle:R.lifecycle&&"object"==typeof R.lifecycle?{sessionStartEmitted:!0===R.lifecycle.sessionStartEmitted,sessionEndEmitted:!0===R.lifecycle.sessionEndEmitted,startedAt:"number"==typeof R.lifecycle.startedAt?R.lifecycle.startedAt:null,endedAt:"number"==typeof R.lifecycle.endedAt?R.lifecycle.endedAt:null,endReason:"string"==typeof R.lifecycle.endReason?R.lifecycle.endReason:null}:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}}}catch(S){return console.warn("[SessionManager] Failed to load stored session:",S),this._clearSession(),null}}_saveSession(){if(this.currentSession)try{const{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x}=this.currentSession,R=this.maxSessionDuration;this._setCookie(this.sessionIdCookie,S,R),this._setCookie(this.sessionStartCookie,I.toString(),R),this._setCookie(this.lastActivityCookie,x.toString(),R);const A={schemaVersion:5,anonymousId:b,pageCount:this.currentSession.pageCount,eventCount:this.currentSession.eventCount,chunkCount:this.currentSession.chunkCount,lastChunkSequence:this.currentSession.lastChunkSequence,projectId:this.currentSession.projectId,workspaceId:this.currentSession.workspaceId,environment:this.currentSession.environment,userId:this.currentSession.userId,userEmail:this.currentSession.userEmail,userAttributes:this.currentSession.userAttributes||{},lifecycle:this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}};localStorage.setItem(this.storageKey,JSON.stringify(A))}catch(S){console.warn("[SessionManager] Failed to save session:",S)}}_handleActivity(){const S=Date.now();S-this._lastActivityUpdate<this.activityThrottle||(this._lastActivityUpdate=S,this._updateActivity(),this.tabCoordinator.reportActivity())}_handleRemoteActivity(S){this.currentSession&&(this.currentSession.lastActivityTime=S,this._setCookie(this.lastActivityCookie,S.toString(),this.maxSessionDuration))}_updateActivity(){this.currentSession&&(this.currentSession.lastActivityTime=Date.now(),this._saveSession())}_startActivityTracking(){if(this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.addEventListener(S,this._boundActivityHandler,{passive:!0})}),this._trackingStarted=!0,this.debug&&console.log("[SessionManager] ✅ Activity tracking started (mousemove/click/scroll)")}_stopActivityTracking(){if(!this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.removeEventListener(S,this._boundActivityHandler)}),this._trackingStarted=!1}_handleSessionEnd(S){if(console.log("[SessionManager] 🛑 Session ended by TabCoordinator:",S),"away_rule"===S&&"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"allTabsClosed"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}}getLifecycleGuard(){if(!this.currentSession)return null;const S=this.currentSession.lifecycle;return S&&"object"==typeof S?{sessionStartEmitted:!0===S.sessionStartEmitted,sessionEndEmitted:!0===S.sessionEndEmitted,startedAt:"number"==typeof S.startedAt?S.startedAt:null,endedAt:"number"==typeof S.endedAt?S.endedAt:null,endReason:"string"==typeof S.endReason?S.endReason:null}:null}setLifecycleGuard(S){if(!this.currentSession)return;if(!S||"object"!=typeof S)return;const b=this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null};!0===S.sessionStartEmitted&&(b.sessionStartEmitted=!0),!0===S.sessionEndEmitted&&(b.sessionEndEmitted=!0),"number"==typeof S.startedAt&&(b.startedAt=S.startedAt),"number"==typeof S.endedAt&&(b.endedAt=S.endedAt),"string"==typeof S.endReason&&(b.endReason=S.endReason),this.currentSession.lifecycle=b,this._saveSession()}_getCookie(S){return document.cookie.split("; ").reduce((S,b)=>{const[I,x]=b.split("=");return I&&(S[I]=decodeURIComponent(x||"")),S},{})[S]||null}_setCookie(S,b,I){const x=Math.floor(I/1e3);let R=`${S}=${encodeURIComponent(b)}`;R+=`; max-age=${x}`,R+=`; path=${this.cookiePath}`,R+=`; SameSite=${this.cookieSameSite}`,"undefined"!=typeof window&&"https:"===window.location.protocol&&(R+="; Secure"),this.cookieDomain&&!this.cookieDomain.includes("localhost")&&(R+=`; domain=${this.cookieDomain}`),document.cookie=R}_deleteCookie(S){document.cookie=`${S}=; max-age=0; path=${this.cookiePath}`}_clearSession(){this._deleteCookie(this.sessionIdCookie),this._deleteCookie(this.lastActivityCookie),this._deleteCookie(this.sessionStartCookie);try{localStorage.removeItem(this.storageKey)}catch(S){console.warn("[SessionManager] Failed to clear localStorage:",S)}}getSessionInfo(){if(!this.currentSession)return null;const S=Date.now(),b=S-this.currentSession.startTime,I=S-this.currentSession.lastActivityTime;return{...this.currentSession,duration:b,durationMinutes:Math.round(b/1e3/60),timeSinceActivity:I,timeSinceActivityMinutes:Math.round(I/1e3/60),isValid:this._isSessionValid(this.currentSession),willExpireIn:this.inactivityTimeout-I,willExpireInMinutes:Math.round((this.inactivityTimeout-I)/1e3/60),tabCount:this.tabCoordinator.getTabCount(),tabId:this.tabCoordinator.getTabId(),isAway:this.tabCoordinator.isAway()}}incrementEventCount(S=1){this.currentSession&&(this.currentSession.eventCount+=S,this._updateActivity())}incrementPageCount(){this.currentSession&&(this.currentSession.pageCount++,this._updateActivity(),this.debug&&console.log("[SessionManager] 📄 Page navigation, count:",this.currentSession.pageCount))}incrementChunkCount(){this.currentSession&&(this.currentSession.chunkCount++,this._saveSession())}updateLastChunkSequence(S){this.currentSession&&(this.currentSession.lastChunkSequence=S,this._saveSession(),this.debug&&console.log(`[SessionManager] Updated lastChunkSequence to ${S}`))}getLastChunkSequence(){return this.currentSession?.lastChunkSequence||0}getResumeInfo(){const S=this._getStoredSession();return S&&this._isSessionValid(S)&&(S.pageCount||1)>1?{sessionId:S.sessionId,lastChunkSequence:S.lastChunkSequence||0,lastActivityTime:S.lastActivityTime,isResumed:!0,pageCount:S.pageCount||1,eventCount:S.eventCount||0,chunkCount:S.chunkCount||0}:{sessionId:null,lastChunkSequence:0,lastActivityTime:null,isResumed:!1,pageCount:0,eventCount:0,chunkCount:0}}isResumedSession(){return!!this.currentSession&&(this.currentSession.pageCount||1)>1}updateUser(S,b){this.updateUserMetadata(S,{email:b})}updateUserMetadata(S,b={}){this.currentSession&&(this.currentSession.userId=S,this.currentSession.userEmail=b.email||this.currentSession.userEmail,this.currentSession.userAttributes=b,this._saveSession(),console.log("[SessionManager] 👤 User metadata updated"))}clearUserMetadata(){this.currentSession&&(this.currentSession.userId=null,this.currentSession.userEmail=null,this.currentSession.userAttributes={},this._saveSession(),console.log("[SessionManager] 👤 User metadata cleared"))}endSession(){if(!this.currentSession)return;const S=Date.now()-this.currentSession.startTime;if(console.log("[SessionManager] 🛑 Ending session:",this.currentSession.sessionId),console.log(" Duration:",Math.round(S/1e3),"s"),console.log(" Events:",this.currentSession.eventCount),console.log(" Pages:",this.currentSession.pageCount),console.log(" Chunks:",this.currentSession.chunkCount),"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"manual"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}this._stopActivityTracking(),this._clearSession(),this.currentSession=null}forceNewSession(S="manual"){console.log("[SessionManager] 🔄 Force new session, reason:",S),this.currentSession&&console.log(" Ending:",this.currentSession.sessionId),this.endSession()}destroy(){this._stopActivityTracking(),this.tabCoordinator.destroy()}}class EventManager{constructor(S={},b={}){this.config=S,this.storageKeys=b,this.logger=new Logger("[EventManager]",S.debug),this.eventQueue=[],this.eventOccurrenceTracker=new Map,this.debouncedSave=debounce(this.saveToLocal.bind(this),100),this._cleanupInterval=null,this._startCleanupTimer()}_startCleanupTimer(){const S=this.config.memoryCleanupIntervalMs||6e4;this._cleanupInterval=setInterval(()=>{this._cleanupOccurrenceTracker()},S)}_stopCleanupTimer(){this._cleanupInterval&&(clearInterval(this._cleanupInterval),this._cleanupInterval=null)}_cleanupOccurrenceTracker(){const S=Date.now(),b=this.config.deduplicationWindowMs||6e4,I=this.config.maxOccurrenceTrackerSize||5e3;let x=0;for(const[I,R]of this.eventOccurrenceTracker.entries())S-R>b&&(this.eventOccurrenceTracker.delete(I),x++);if(this.eventOccurrenceTracker.size>I){const S=Array.from(this.eventOccurrenceTracker.entries()).sort((S,b)=>b[1]-S[1]);this.eventOccurrenceTracker.clear();const b=S.slice(0,I);for(const[S,I]of b)this.eventOccurrenceTracker.set(S,I);const R=S.length-I;this.config.debug&&this.logger.log(`[Memory] Force-cleaned ${R} entries (exceeded max size ${I})`),x+=R}x>0&&this.config.debug&&this.logger.log(`[Memory] Cleaned up ${x} stale entries from occurrence tracker (size: ${this.eventOccurrenceTracker.size})`)}destroy(){this._stopCleanupTimer(),this.eventOccurrenceTracker.clear(),this.eventQueue=[]}addEvent(S){try{return!!this.shouldLogEvent(S)&&(!!this.deduplicateEvent(S)&&(this.eventQueue.length>=this.config.maxQueueSize&&(this.eventQueue.shift(),this.logger.warn("Queue size limit reached, removing oldest event")),this.eventQueue.push(S),this.debouncedSave(),this.logger.log("Event added:",S.type),!0))}catch(S){return this.logger.error("Failed to add event:",S),!1}}getEvents(){try{return R.sortBy(R.cloneDeep(this.eventQueue),"timestamp")}catch(S){return this.logger.error("Failed to get events:",S),[]}}removeEvents(S){try{const b=new Set(S);this.eventQueue=R.filter(this.eventQueue,S=>!b.has(S.id)),this.debouncedSave()}catch(S){this.logger.error("Failed to remove events:",S)}}clearEvents(){try{this.eventQueue.length=0,this.eventOccurrenceTracker.clear(),this.clearLocal(),this.logger.log("All events cleared")}catch(S){this.logger.error("Failed to clear events:",S)}}getQueueSize(){return this.eventQueue.length}shouldLogEvent(S){try{const b=S.context?.isMonitored,I=S.context?.forceLog;if(!(b||I))return!1;return!(this.config.ignoreEventTypes||[]).includes(S.type)}catch(S){return this.logger.error("Error in shouldLogEvent:",S),!1}}deduplicateEvent(S){try{const b=this.generateDedupeKey(S),I=Date.now(),x=this.eventOccurrenceTracker.get(b);return!(x&&I-x<this.config.deduplicationWindowMs)&&(this.eventOccurrenceTracker.set(b,I),!0)}catch(S){return this.logger.error("Error in deduplicateEvent:",S),!0}}generateDedupeKey(S){try{return`${S.type}_${S.context?.url||"unknown"}_${S.context?.method||"unknown"}`}catch(b){return this.logger.error("Error generating dedupe key:",b),`${S.type}_${Date.now()}`}}saveToLocal(){try{const S={events:this.eventQueue,timestamp:Date.now()};b.set(this.storageKeys.EVENTS||"__api_reporter_events__",S)}catch(S){this.logger.error("Failed to save events to local storage:",S)}}loadFromLocal(){try{const S=b.get(this.storageKeys.EVENTS||"__api_reporter_events__");S&&S.events&&(this.eventQueue=S.events,this.logger.log(`Loaded ${this.eventQueue.length} events from local storage`))}catch(S){this.logger.error("Failed to load events from local storage:",S)}}clearLocal(){try{b.remove(this.storageKeys.EVENTS||"__api_reporter_events__")}catch(S){this.logger.error("Failed to clear local storage:",S)}}getEventById(S){try{return this.eventQueue.find(b=>b.id===S)}catch(S){return this.logger.error("Failed to get event by ID:",S),null}}getEventsByType(S){try{return this.eventQueue.filter(b=>b.type===S)}catch(S){return this.logger.error("Failed to get events by type:",S),[]}}getEventsByTimeRange(S,b){try{return this.eventQueue.filter(I=>{const x=I.timestamp;return x>=S&&x<=b})}catch(S){return this.logger.error("Failed to get events by time range:",S),[]}}getEventStats(){try{const S={total:this.eventQueue.length,byType:{},byStatus:{}};return this.eventQueue.forEach(b=>{S.byType[b.type]=(S.byType[b.type]||0)+1;const I=b.context?.status||"unknown";S.byStatus[I]=(S.byStatus[I]||0)+1}),S}catch(S){return this.logger.error("Failed to get event stats:",S),{total:0,byType:{},byStatus:{}}}}cleanupOldEvents(S=864e5){try{const b=Date.now()-S,I=this.eventQueue.length;this.eventQueue=this.eventQueue.filter(S=>S.timestamp>b);const x=I-this.eventQueue.length;x>0&&(this.logger.log(`Cleaned up ${x} old events`),this.debouncedSave())}catch(S){this.logger.error("Failed to cleanup old events:",S)}}}class ServiceManager{constructor(S={},b=null){this.config=S,this.logger=b||new Logger("[ServiceManager]",S.debug),this.service=null,this.isSending=!1,this.retryCount=0,this.maxRetries=R.get(S,"maxRetries",3),this.initializeService()}initializeService(){if(!R.get(this.config,"service"))throw new Error("Service configuration is required");this.setService(R.get(this.config,"service"),R.get(this.config,"serviceOptions",{}))}setService(S,b={}){if(!R.isObject(S)||!R.isFunction(R.get(S,"send")))throw new Error("Invalid service: must be an object with send() method");this.service=S,this.logger.log(`Service initialized: ${this.getServiceName()}`)}async sendEvents(S){if(this.isSending||R.isEmpty(S)||!this.service)return this.logger.warn("Cannot send events:",{isSending:this.isSending,isEmpty:R.isEmpty(S),noService:!this.service}),R.map(S||[],S=>({event:S,success:!1,error:new Error("Service unavailable")}));this.isSending=!0;try{const b=[];for(const I of S)try{await this.sendSingleEvent(I),b.push({event:I,success:!0}),this.logger.log(`Event sent successfully: ${I.type}`)}catch(S){this.logger.error(`Event failed: ${I.type}`,S),b.push({event:I,success:!1,error:S})}return this.retryCount=0,b}catch(b){return this.logger.error("Failed to send events:",b),this.retryCount++,R.map(S,S=>({event:S,success:!1,error:b}))}finally{this.isSending=!1}}async sendSingleEvent(S){let b;for(let I=1;I<=this.maxRetries;I++)try{return void await this.service.send(S)}catch(x){b=x,this.logger.warn(`Attempt ${I}/${this.maxRetries} failed for event ${S.id}:`,x.message),I<this.maxRetries&&await this.delay(this.getRetryDelay(I))}throw b}getRetryDelay(S){return Math.min(1e3*Math.pow(2,S-1),3e4)}async delay(S){return new Promise(b=>setTimeout(b,S))}getServiceName(){return R.isString(this.config.service)?this.config.service:this.service.constructor.name}isServiceAvailable(){return null!==this.service}getServiceStatus(){return{available:this.isServiceAvailable(),name:this.getServiceName(),isSending:this.isSending,retryCount:this.retryCount}}resetRetryCount(){this.retryCount=0}destroy(){this.service=null,this.isSending=!1,this.retryCount=0}}class UserProfileManager{constructor(S,b=[],I=!1){this.storageKey=S,this.fieldsToExtract=b,this.logger=new Logger("[UserProfileManager]",I)}getProfile(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.warn("Failed to read user profile:",S),{}}}setProfile(S={}){if(!R.isObject(S))return this.logger.warn("Invalid profile object provided"),!1;try{const b=this.getProfile(),I=R.merge(b,S);return localStorage.setItem(this.storageKey,JSON.stringify(I)),this.logger.log("User profile updated:",I),!0}catch(S){return"QuotaExceededError"===S.name?this.logger.warn("Storage quota exceeded for user profile"):this.logger.error("Failed to save user profile:",S),!1}}ensureProfile(){try{const S=this.getProfile();if(R.isEmpty(R.get(S,"uniqId"))){const b=R.merge(S,{uniqId:generateId(),createdAt:(new Date).toISOString()});this.setProfile(b),this.logger.log("Generated new user profile:",R.get(b,"uniqId"))}}catch(S){this.logger.error("Failed to ensure user profile:",S)}}extractContextFromData({data:S,source:b="response",url:I=""}){const x={};try{if(!R.isObject(S)||!R.isArray(this.fieldsToExtract))return x;const A=R.toLower(I);return this.fieldsToExtract.forEach(_=>{try{const D=R.toLower(R.get(_,"api","")),L=R.get(_,"source",""),B="*"===D||A.includes(D);if(!B||!("*"===L||L===b))return;const U=R.get(_,"fields",[]);R.isArray(U)?U.forEach(R=>{try{this.recursiveFieldMatch({context:x,matchRule:R,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with pattern "${R}":`,S)}}):R.isObject(U)&&R.entries(U).forEach(([R,A])=>{try{this.recursiveFieldMatchWithMapping({context:x,newKey:R,matchRule:A,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with mapping "${R}": "${A}":`,S)}})}catch(S){this.logger.warn("Failed to process extraction rule:",S)}}),x}catch(S){return this.logger.error("Failed to extract context from data:",S),x}}updateFromContext({url:S,source:b,data:I}){try{const x=this.extractContextFromData({url:S,source:b,data:I});if(Object.keys(x).length>0){const S=this.getProfile(),b={...S,...x};if(JSON.stringify(S)!==JSON.stringify(b))return this.setProfile(b),!0}return!1}catch(S){return this.logger.warn("Failed to update user profile context:",S),!1}}recursiveFieldMatch({context:S,matchRule:b,data:I,source:x,url:A}){try{if(!R.isObject(I))return;if(R.isString(b)){const x=R.get(I,b);if(void 0!==x)return S[b]=x,void this.logger.log(`Found field by path: ${b} = ${JSON.stringify(x)}`);const A=R.find(R.entries(I),([S])=>R.toLower(S)===R.toLower(b));if(A){const[b,I]=A;return S[b]=I,void this.logger.log(`Found field by name: ${b} = ${JSON.stringify(I)}`)}}if(b instanceof RegExp){const x=R.find(R.entries(I),([S,I])=>R.isString(I)&&b.test(I));if(x){const[b,I]=x;return S[b]=I,void this.logger.log(`Found field by value pattern: ${b} = ${I}`)}}R.values(I).forEach(I=>{R.isObject(I)&&!R.isNull(I)&&this.recursiveFieldMatch({context:S,matchRule:b,data:I,source:x,url:A})})}catch(S){this.logger.warn("Error in recursive field matching:",S)}}recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:x,source:A,url:_}){try{if(!R.isObject(x))return;if(R.isString(I)){const A=R.get(x,I);if(void 0!==A)return S[b]=A,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(A)}`);const _=R.find(R.entries(x),([S])=>R.toLower(S)===R.toLower(I));if(_){const[I,x]=_;return S[b]=x,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(x)}`)}}if(I instanceof RegExp){const A=R.find(R.entries(x),([S,b])=>R.isString(b)&&I.test(b));if(A){const[I,x]=A;return S[b]=x,void this.logger.log(`Found field by pattern with mapping: ${I} -> ${b} = ${x}`)}}R.values(x).forEach(x=>{R.isObject(x)&&!R.isNull(x)&&this.recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:x,source:A,url:_})})}catch(S){this.logger.warn("Error in recursive field matching with mapping:",S)}}validateFieldValue(S,b){try{if(R.isString(b)){const I=R.get(DEFAULT_FIELD_PATTERNS,b);return I&&I.test(S)}if(R.isFunction(b))return b(S);if(R.isObject(b)){const{type:I,min:x,max:R,pattern:A}=b;return(!I||typeof S===I)&&(!(void 0!==x&&S<x)&&(!(void 0!==R&&S>R)&&!(A&&!A.test(S))))}return!0}catch(S){return this.logger.warn("Validation error:",S),!1}}transformFieldValue(S,b){try{if(R.isFunction(b))return b(S);if(R.isString(b))switch(b){case"toLowerCase":return R.toLower(S);case"toUpperCase":return R.toUpper(S);case"trim":return R.trim(S);case"toString":return String(S);case"toNumber":return Number(S);default:return S}return S}catch(b){return this.logger.warn("Transform error:",b),S}}clearProfile(){try{return localStorage.removeItem(this.storageKey),this.logger.log("User profile cleared"),!0}catch(S){return this.logger.error("Failed to clear user profile:",S),!1}}getProfileField(S){try{const b=this.getProfile();return R.get(b,S)}catch(S){return void this.logger.error("Failed to get profile field:",S)}}setProfileField(S,b){try{const I=this.getProfile();return I[S]=b,this.setProfile(I)}catch(S){return this.logger.error("Failed to set profile field:",S),!1}}hasProfile(){try{const S=this.getProfile();return!R.isEmpty(S)}catch(S){return this.logger.error("Failed to check profile existence:",S),!1}}getProfileSize(){try{const S=this.getProfile();return Object.keys(S).length}catch(S){return this.logger.error("Failed to get profile size:",S),0}}}class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=new Logger("[PerformanceMonitor]",this.debug),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function resolveApiBaseUrl(S={}){if(S&&"string"==typeof S.apiBaseUrl&&S.apiBaseUrl)return S.apiBaseUrl;if(S&&"string"==typeof S.backendUrl&&S.backendUrl)return S.backendUrl;if("undefined"!=typeof window&&window.location&&window.location.hostname){const S=window.location.hostname;if("localhost"===S||"127.0.0.1"===S)return"http://localhost:3001"}return"https://api.tracescout.com"}const pe=["/chunks","/logs/batch","/telemetry","/sdk-config"];function isInternalSdkEndpoint(S){if("string"!=typeof S||!S)return!1;if(!S.includes("/api/"))return!1;for(const b of pe)if(S.includes(b)){if(S.includes("/api/projects/")||S.includes("/api/sdk-config"))return!0;if("/sdk-config"===b&&S.includes("/sdk-config"))return!0}return!1}class InitializationPipeline{#o=null;#a=null;constructor(S){this.#o=S}async run(S){this.#a=S;try{this.#l();const S=this.#c(),b=this.#u(S),I=this.#h(b),x=this.#d(I,b);x&&(I.service=x);const R=this.#g(I);return{success:!0,sessionManager:S,sdkContext:b,remoteConfigService:null,serverConfig:this.#p(),config:I,managers:R}}catch(S){throw this.#o?.error("Initialization pipeline failed:",S),S}}#l(){const S=this.#a;if(!R.isObject(S))throw new Error("InitializationPipeline.run(options): options must be an object");if(!S.projectId)throw new Error("InitializationPipeline.run(options): projectId missing");S.debug&&console.log("[TraceScout] ✓ Required fields validated")}#c(){const S=this.#a;S.debug&&console.log("[TraceScout] 📅 Initializing session manager...");const b=new SessionManager({inactivityTimeout:18e5,maxSessionDuration:144e5,activityThrottle:1e3,awayThreshold:12e4,heartbeatInterval:5e3,tabTimeout:1e4,debug:S.debug||!1}),I=b.getOrCreateSession({projectId:S.projectId,environment:S.environment});return S.debug&&console.log("[TraceScout] ✓ Session manager initialized"),{sessionManager:b,sessionId:I}}#u(S){const b=this.#a,{sessionManager:I,sessionId:x}=S;try{const S=SDKContext.initialize({projectId:b.projectId,environment:b.environment||"production",userId:void 0,sessionId:x,sessionManager:I});if(I&&I.currentSession){const x=I.currentSession;x.userId&&x.userAttributes&&(S.setUser(x.userId,x.userAttributes),b.debug&&console.log("[TraceScout] ✓ Restored user metadata from session"))}return b.debug&&(console.log("[TraceScout] ✓ SDK Context initialized"),console.log(` Session ID: ${S.sessionId}`),console.log(` Project: ${S.projectId}`),console.log(` Environment: ${S.environment}`)),S}catch(S){throw console.error("[TraceScout] ❌ Failed to initialize SDKContext:",S),S}}#h(S){const b=this.#a,I={projectId:S.projectId,environment:S.environment,release:b.release,sourceName:b.sourceName,debug:b.debug||!1,apiBaseUrl:resolveApiBaseUrl(b),sampleRate:1,sessionChunkDuration:3e4,sessionMaxChunkSize:5e5,privacy:{maskAllInputs:!1,maskTextClass:"ts-mask",blockClass:"ts-block",ignoreClass:"ts-ignore",blockSelectors:[],maskImages:!1},network:(x=b.network,{isEnabled:!0,captureRequestHeaders:!0,captureResponseHeaders:!0,captureRequestBody:!0,captureResponseBody:!0,excludeEndpoints:[],maxBodyBytes:10240,requestSanitizer:null,responseSanitizer:null,sensitiveFields:[],...x&&"object"==typeof x&&!Array.isArray(x)?x:{}})};var x;return b.debug&&console.log("[TraceScout] ✓ Configuration built (SDK defaults)"),I}#p(){return{workspace:{name:"Unknown",id:null},project:{name:"Unknown"},configVersion:"sdk-defaults",features:{sessionRecording:{enabled:!0,sampleRate:1,captureNetwork:!0,captureConsole:!0,captureErrors:!0,networkSettings:{captureHeaders:!0,captureRequestBody:!0,captureResponseBody:!0},chunkDuration:3e4,maxChunkSize:5e5,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},performanceMonitoring:{enabled:!0,coreWebVitals:!0},logging:{enabled:!0,captureConsole:!0,minLevel:"debug",maxBufferSize:1e3,flushInterval:5e3,sampleRate:1}},telemetry:{}}}#d(S,b){const I=`${resolveApiBaseUrl(S)}/api/projects/${b.projectId}/telemetry`;return{send:async S=>{const x=Array.isArray(S)?S:[S];try{const S=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:x,context:{projectId:b.projectId,sessionId:b.sessionId,environment:b.environment}})});if(!S.ok)throw new Error(`Telemetry send failed: ${S.status}`);return await S.json()}catch(S){throw console.error("[TraceScout][TelemetryService] Send failed:",S),S}}}}#g(S){const b=new EventManager(S),I=new ServiceManager(S,this.#o),x=new UserProfileManager(S),R=new PerformanceMonitor(S);return S.debug&&console.log("[TraceScout] ✓ Core managers initialized"),{eventManager:b,serviceManager:I,userProfileManager:x,performanceMonitor:R}}}var fe={environment:{type:"string",minLength:1,maxLength:64,default:"production"},release:{type:"string",minLength:1,maxLength:255},debug:{type:"boolean",default:!1},sourceName:{type:"string",minLength:1,maxLength:100,pattern:"^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$",default:"web-client",description:"S-2d.2 (step B): optional browser-source attribution. Defaults to 'web-client' when omitted. Emitted on every SDK v1 common envelope as `sourceName`. Pattern matches the API's envelope.schema.json SOURCE_NAME_PATTERN union. NOT named `source` to avoid collision with the existing js_error leaf `source` field (stack-frame URL, up to 2048 chars)."}};const me=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ye=new Set(["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody","maxBodyBytes","excludeEndpoints","requestSanitizer","responseSanitizer","sensitiveFields"]),ve=["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody"];const Se=/^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$/,we=new Set(Object.keys(fe));function validateConfig(S,b){if(null!==S&&"object"==typeof S&&!Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_FIRST_ARG"};if(null==S||""===S||"string"!=typeof S)return{ok:!1,code:"CONFIG_PROJECT_ID_REQUIRED"};if(!me.test(S))return{ok:!1,code:"CONFIG_PROJECT_ID_INVALID"};const I=b??{};if("object"!=typeof I||Array.isArray(I)||null===I)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:["(options must be a plain object)"]};const x=[];for(const S of Object.keys(I))"network"!==S&&(we.has(S)||x.push(S));if(x.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:x};if(void 0!==I.network){const S=function validateNetworkOptions(S){if("object"!=typeof S||null===S||Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["(network must be a plain object)"]};const b=[];for(const I of Object.keys(S))ye.has(I)||b.push(`network.${I}`);if(b.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:b};for(const b of ve)if(void 0!==S[b]&&"boolean"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};if(void 0!==S.maxBodyBytes){const b=S.maxBodyBytes;if("number"!=typeof b||!Number.isFinite(b)||b<0)return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.maxBodyBytes"]}}if(void 0!==S.excludeEndpoints){if(!Array.isArray(S.excludeEndpoints))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]};for(const b of S.excludeEndpoints)if("string"!=typeof b&&!(b instanceof RegExp))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]}}if(void 0!==S.sensitiveFields&&(!Array.isArray(S.sensitiveFields)||S.sensitiveFields.some(S=>"string"!=typeof S)))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.sensitiveFields"]};for(const b of["requestSanitizer","responseSanitizer"])if(void 0!==S[b]&&"function"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};return{ok:!0}}(I.network);if(!S.ok)return S}return void 0!==I.sourceName&&("string"!=typeof I.sourceName||I.sourceName.length<1||I.sourceName.length>100||!Se.test(I.sourceName))?{ok:!1,code:"CONFIG_INVALID_SOURCE_NAME"}:{ok:!0,projectId:S,options:I}}function shouldSampleSession(S,b={}){const I=b.anonymousId??null,x=b.randomFn??Math.random;return null==S||"number"!=typeof S||(!!Number.isNaN(S)||(S>=1||!(S<=0)&&("string"==typeof I&&I.length>0?function hashToUnitInterval(S){let b=2166136261;for(let I=0;I<S.length;I++)b^=S.charCodeAt(I),b=Math.imul(b,16777619);return(b>>>0)/4294967296}(I)<S:x()<S)))}const be="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ulid(S=Date.now()){return function encodeTimestamp(S){let b="",I=S;for(let S=9;S>=0;S--)b=be[I%32]+b,I=Math.floor(I/32);return b}(S)+function encodeRandom(){let S="";const b=new Uint8Array(10);let I=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(b),I=!0)}catch{}if(!I)for(let S=0;S<b.length;S++)b[S]=Math.floor(256*Math.random());let x=0,R=0;for(let I=0;I<b.length;I++)for(x=x<<8|b[I],R+=8;R>=5;)R-=5,S+=be[x>>R&31];return S}()}const Ce=Object.freeze(["session_start","session_end","replay_chunk","page_view","route_change","network_request","console_event","js_error","performance_metric","custom_event","user_identified"]),ke=new Set(Ce);function wrapInEnvelope(S,b,I){if(!ke.has(S))throw new Error(`wrapInEnvelope: unknown eventType "${S}"`);if(null===I||"object"!=typeof I)throw new Error("wrapInEnvelope: context is required");const x={eventId:ulid(),eventType:S,timestamp:Date.now(),contractVersion:"1.0.0",projectId:I.projectId,sessionId:I.sessionId,anonymousId:I.anonymousId,environment:I.environment,sdkVersion:I.sdkVersion};return isNonEmptyString$3(I.workspaceId)&&(x.workspaceId=I.workspaceId),isNonEmptyString$3(I.userId)&&(x.userId=I.userId),isNonEmptyString$3(I.userEmail)&&(x.userEmail=I.userEmail),isNonEmptyString$3(I.userName)&&(x.userName=I.userName),isNonEmptyString$3(I.release)&&(x.release=I.release),isNonEmptyString$3(I.sourceName)&&(x.sourceName=I.sourceName),isNonEmptyString$3(I.pageviewId)&&(x.pageviewId=I.pageviewId),isNonEmptyString$3(I.url)&&(x.url=I.url),isNonEmptyString$3(I.traceId)&&(x.traceId=I.traceId),isNonEmptyString$3(I.spanId)&&(x.spanId=I.spanId),{...x,...b}}function isNonEmptyString$3(S){return"string"==typeof S&&S.length>0}function mapInternalEndReason(S){switch(S){case"max_inactivity":case"inactivity":return"inactivity";case"max_duration":case"maxDuration":return"maxDuration";case"away_rule":case"allTabsClosed":return"allTabsClosed";case"manual":return"manual";default:return null}}function detectDeviceType$1(S){const b=(S&&"string"==typeof S.userAgent?S.userAgent:"")||("undefined"!=typeof navigator&&navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"");return b?/iPad|Tablet|PlayBook|Silk/i.test(b)||/Android/i.test(b)&&!/Mobile/i.test(b)?"tablet":/Mobi|iPhone|iPod|Android/i.test(b)?"mobile":"desktop":"desktop"}function buildDeviceField(){const S="undefined"!=typeof navigator?navigator:{},b="undefined"!=typeof window?window:{},I=b.screen||{};let x="UTC";try{x=Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch(S){}return{type:detectDeviceType$1(S),userAgent:"string"==typeof S.userAgent?S.userAgent:"",platform:"string"==typeof S.platform?S.platform:"",language:"string"==typeof S.language?S.language:"",timezone:x,viewport:{width:"number"==typeof b.innerWidth?b.innerWidth:0,height:"number"==typeof b.innerHeight?b.innerHeight:0},screen:{width:"number"==typeof I.width?I.width:0,height:"number"==typeof I.height?I.height:0,colorDepth:"number"==typeof I.colorDepth?I.colorDepth:0}}}function isNonEmptyString$2(S){return"string"==typeof S&&S.length>0}class SessionLifecycleEmitter{#f=!1;#m=!1;#y;#v;#S;#w;#b;#C;constructor(S){if(!S||"object"!=typeof S)throw new Error("SessionLifecycleEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("SessionLifecycleEmitter: addCustomEvent callback is required");if("function"!=typeof S.getContext)throw new Error("SessionLifecycleEmitter: getContext callback is required");if("function"!=typeof S.readGuard||"function"!=typeof S.writeGuard)throw new Error("SessionLifecycleEmitter: readGuard/writeGuard callbacks are required");this.#v=S.addCustomEvent,this.#C=S.getContext,this.#S=S.readGuard,this.#w=S.writeGuard,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{}}emitStart(S={}){if(this.#f)return!1;let b=null;try{b=this.#S()}catch(S){b=null}if(b&&!0===b.sessionStartEmitted)return this.#f=!0,!1;b||this.#b("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const I=this.#C(),x="undefined"!=typeof window?window:{},R="undefined"!=typeof document?document:{},A=isNonEmptyString$2(S.landingUrl)?S.landingUrl:"string"==typeof x.location?.href?x.location.href:"";if(!isNonEmptyString$2(A))return this.#b("[SDK lifecycle] session_start skipped — landingUrl unavailable"),!1;const _={device:buildDeviceField(),landingUrl:A},D=void 0!==S.referrer?S.referrer:"string"==typeof R.referrer?R.referrer:"";isNonEmptyString$2(D)&&(_.referrer=D);const L=void 0!==S.landingTitle?S.landingTitle:"string"==typeof R.title?R.title:"";let B;isNonEmptyString$2(L)&&(_.landingTitle=L),function isPlainObjectWithKeys(S){if(!S||"object"!=typeof S)return!1;for(const b in S)return!0;return!1}(S.userTraits)&&(_.userTraits=S.userTraits);try{B=this.#y("session_start",_,I)}catch(S){return this.#b("[SDK lifecycle] session_start envelope wrap failed:",S),!1}try{this.#v("tracescout.session_start",B)}catch(S){return this.#b("[SDK lifecycle] session_start addCustomEvent failed:",S),!1}this.#f=!0;try{this.#w({sessionStartEmitted:!0,startedAt:"number"==typeof B.timestamp?B.timestamp:Date.now()})}catch(S){}return!0}emitEnd(S){if(!S||"object"!=typeof S)return!1;if(this.#m)return!1;const b=mapInternalEndReason(S.reason);if(!b)return this.#b("[SDK lifecycle] session_end refused for non-logical reason:",S.reason),!1;let I=null;try{I=this.#S()}catch(S){I=null}if(I&&!0===I.sessionEndEmitted)return this.#m=!0,!1;I||this.#b("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const x=this.#C(),R=Date.now(),A=I&&"number"==typeof I.startedAt?I.startedAt:"number"==typeof x.sessionStartTime?x.sessionStartTime:R,_={endedAt:R,durationMs:Math.max(0,R-A),reason:b};let D;Number.isFinite(S.totalChunks)&&S.totalChunks>=0&&(_.totalChunks=Math.trunc(S.totalChunks)),Number.isFinite(S.totalEvents)&&S.totalEvents>=0&&(_.totalEvents=Math.trunc(S.totalEvents));try{D=this.#y("session_end",_,x)}catch(S){return this.#b("[SDK lifecycle] session_end envelope wrap failed:",S),!1}try{this.#v("tracescout.session_end",D)}catch(S){return this.#b("[SDK lifecycle] session_end addCustomEvent failed:",S),!1}this.#m=!0;try{this.#w({sessionEndEmitted:!0,endedAt:R,endReason:b})}catch(S){}return!0}get startEmitted(){return this.#f}get endEmitted(){return this.#m}}function isNonEmptyString$1(S){return"string"==typeof S&&S.length>0}function urlParts(S){if("string"!=typeof S||0===S.length)return{path:null,query:null,hash:null};try{const b=new URL(S);return{path:b.pathname,query:b.search||null,hash:b.hash||null}}catch(S){return{path:null,query:null,hash:null}}}class PageviewManager{#k;#I=!1;#E=null;#v;#x;#y;#b;constructor(S){if(!S||"object"!=typeof S)throw new Error("PageviewManager: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("PageviewManager: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("PageviewManager: getBaseContext callback is required");this.#v=S.addCustomEvent,this.#x=S.getBaseContext,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{},this.#k=uuidv4()}getCurrentPageviewId(){return this.#k}emitInitialPageView(S={}){if(this.#I)return!1;const b="undefined"!=typeof window?window:{},I="undefined"!=typeof document?document:{},x="string"==typeof b.location?.href?b.location.href:"";if(!isNonEmptyString$1(x))return this.#b("[SDK pageview] initial page_view skipped — url unavailable"),!1;const R=urlParts(x);if(!isNonEmptyString$1(R.path))return this.#b("[SDK pageview] initial page_view skipped — could not derive path"),!1;const A={url:x,path:R.path,isInitial:!0!==S.isResumed};isNonEmptyString$1(R.query)&&(A.query=R.query),isNonEmptyString$1(R.hash)&&(A.hash=R.hash),isNonEmptyString$1(I.title)&&(A.title=I.title),isNonEmptyString$1(I.referrer)&&(A.referrer=I.referrer);const _=this.#M(this.#k);let D;try{D=this.#y("page_view",A,_)}catch(S){return this.#b("[SDK pageview] initial page_view envelope wrap failed:",S),!1}try{this.#v("tracescout.page_view",D)}catch(S){return this.#b("[SDK pageview] initial page_view addCustomEvent failed:",S),!1}return this.#I=!0,this.#E=x,!0}recordNavigation(S,b,I){if(!isNonEmptyString$1(I))return this.#b("[SDK pageview] navigation skipped — toUrl unavailable"),!1;if(null!==this.#E&&this.#E===I)return!1;if(!["pushState","replaceState","popstate","hashchange"].includes(S))return this.#b("[SDK pageview] navigation skipped — unknown method:",S),!1;const x=isNonEmptyString$1(b)?b:I,R=urlParts(x),A=urlParts(I);if(!isNonEmptyString$1(A.path))return this.#b("[SDK pageview] navigation skipped — could not derive toPath"),!1;const _=this.#k,D=uuidv4(),L={fromUrl:x,toUrl:I,method:S,nextPageviewId:D};let B;isNonEmptyString$1(R.path)&&(L.fromPath=R.path),isNonEmptyString$1(A.path)&&(L.toPath=A.path);try{B=this.#y("route_change",L,this.#M(_))}catch(S){return this.#b("[SDK pageview] route_change envelope wrap failed:",S),!1}try{this.#v("tracescout.route_change",B)}catch(S){return this.#b("[SDK pageview] route_change addCustomEvent failed:",S),!1}this.#k=D,this.#E=I;const U="undefined"!=typeof document?document:{},$={url:I,path:A.path,isInitial:!1};let j;isNonEmptyString$1(A.query)&&($.query=A.query),isNonEmptyString$1(A.hash)&&($.hash=A.hash),isNonEmptyString$1(U.title)&&($.title=U.title),isNonEmptyString$1(x)&&($.referrer=x);try{j=this.#y("page_view",$,this.#M(D))}catch(S){return this.#b("[SDK pageview] post-nav page_view envelope wrap failed:",S),!1}try{this.#v("tracescout.page_view",j)}catch(S){return this.#b("[SDK pageview] post-nav page_view addCustomEvent failed:",S),!1}return!0}#M(S){const b=this.#x()||{};return Object.assign({},b,{pageviewId:S})}get initialEmitted(){return this.#I}get lastUrl(){return this.#E}}function normalizeRating(S){if("string"!=typeof S)return null;switch(S){case"good":return"good";case"needs-improvement":case"needsImprovement":return"needs-improvement";case"poor":return"poor";default:return null}}const Ie=new Set(["navigate","reload","back-forward","prerender","back-forward-cache","restore"]);function isNonEmptyString(S){return"string"==typeof S&&S.length>0}class WebVitalsEmitter{#R;#T;#A=new Set;#v;#x;#y;#b;constructor(S){if(!S||"object"!=typeof S)throw new Error("WebVitalsEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("WebVitalsEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("WebVitalsEmitter: getBaseContext callback is required");if(!isNonEmptyString(S.initialPageviewId))throw new Error("WebVitalsEmitter: initialPageviewId is required");if(!isNonEmptyString(S.initialUrl))throw new Error("WebVitalsEmitter: initialUrl is required");this.#v=S.addCustomEvent,this.#x=S.getBaseContext,this.#R=S.initialPageviewId,this.#T=S.initialUrl,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{}}emit(S,b){if(!b||"object"!=typeof b)return!1;const I=function normalizeMetricType(S){switch((S||"").toString().toLowerCase()){case"lcp":return"LCP";case"fid":return"FID";case"cls":return"CLS";case"inp":return"INP";case"ttfb":return"TTFB";case"fcp":return"FCP";default:return null}}(S);if(!I)return this.#b("[SDK web-vitals] emit refused — unknown metric type:",S),!1;if(this.#A.has(I))return!1;if(!function isPositiveFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)&&S>=0}(b.value))return this.#b("[SDK web-vitals] emit refused — invalid value for",I,b.value),!1;const x=normalizeRating(b.libRating)??normalizeRating(b.rating);if(!x)return this.#b("[SDK web-vitals] emit refused — invalid rating for",I,b.libRating,b.rating),!1;const R={metric:I,value:b.value,unit:(A=I,"CLS"===A?"score":"ms"),rating:x};var A;"string"==typeof b.navigationType&&Ie.has(b.navigationType)&&(R.navigationType=b.navigationType);const _=this.#x()||{},D=Object.assign({},_,{pageviewId:this.#R,url:this.#T});let L;try{L=this.#y("performance_metric",R,D)}catch(S){return this.#b("[SDK web-vitals] envelope wrap failed:",S),!1}try{this.#v("tracescout.performance_metric",L)}catch(S){return this.#b("[SDK web-vitals] addCustomEvent failed:",S),!1}return this.#A.add(I),!0}get emittedMetrics(){return new Set(this.#A)}get initialPageviewId(){return this.#R}get initialUrl(){return this.#T}}const Ee=/^[a-zA-Z][a-zA-Z0-9_.-]*$/,xe=["_ts_","internal","system"],Me=["password","token","authorization","cookie","ssn","creditcard","secret","apikey"],Re=new Set(["__proto__","constructor","prototype"]);function isValidUserId(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isValidEmail(S){if("string"!=typeof S)return!1;if(0===S.length||S.length>320)return!1;if(/\s/.test(S))return!1;const b=S.indexOf("@");if(b<1||b!==S.lastIndexOf("@"))return!1;const I=S.slice(0,b),x=S.slice(b+1);if(0===I.length||x.length<3)return!1;if(I.startsWith(".")||I.endsWith("."))return!1;if(!x.includes("."))return!1;if(x.startsWith(".")||x.endsWith("."))return!1;if(x.includes("..")||I.includes(".."))return!1;const R=x.lastIndexOf("."),A=x.slice(R+1);return!(A.length<2||!/^[a-zA-Z]+$/.test(A))}function isValidUserName(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)}function sanitizeScalarBag(S,b){const I={};if(!S||"object"!=typeof S||Array.isArray(S))return I;const x="function"==typeof b?b:()=>{};let R=0;for(const b of Object.keys(S)){if(R>=50){x("too-many-keys",b);continue}if("string"!=typeof b||0===b.length){x("invalid-key",String(b));continue}if(b.length>64){x("key-too-long",b);continue}if(Re.has(b)){x("pollution-key",b);continue}if(xe.some(S=>b.startsWith(S))){x("reserved-key",b);continue}const A=b.toLowerCase();if(Me.some(S=>A.includes(S))){x("sensitive-key",b);continue}const _=S[b];if(null===_){I[b]=null,R++;continue}const D=typeof _;if("string"!==D)if("number"!==D)"boolean"!==D?x(`invalid-type:${Array.isArray(_)?"array":D}`,b):(I[b]=_,R++);else{if(!isFiniteNumber(_)){x("non-finite-number",b);continue}I[b]=_,R++}else{if(_.length>1024){x("string-too-long",b);continue}I[b]=_,R++}}return I}class TrackIdentifyEmitter{#v;#x;#y;#b;constructor(S){if(!S||"object"!=typeof S)throw new Error("TrackIdentifyEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("TrackIdentifyEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("TrackIdentifyEmitter: getBaseContext callback is required");this.#v=S.addCustomEvent,this.#x=S.getBaseContext,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{}}emitCustomEvent(S,b){if(!function isValidEventName(S){return"string"==typeof S&&S.length>=1&&S.length<=128&&Ee.test(S)}(S))return this.#b("[SDK track] emit refused — invalid event name:",S),!1;const I=[],x=sanitizeScalarBag(b,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#b("[SDK track] properties keys dropped:",I);const R={name:S};Object.keys(x).length>0&&(R.properties=x);const A=this.#x()||{};let _;try{_=this.#y("custom_event",R,A)}catch(S){return this.#b("[SDK track] envelope wrap failed:",S),!1}try{this.#v("tracescout.custom_event",_)}catch(S){return this.#b("[SDK track] addCustomEvent failed:",S),!1}return!0}emitUserIdentified(S){if(!S||"object"!=typeof S)return!1;if(!isValidUserId(S.userId))return this.#b("[SDK identify] emit refused — invalid userId"),!1;const b="set"===S.mode?"set":"merge",I=[],x=sanitizeScalarBag(S.traits,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#b("[SDK identify] traits keys dropped:",I);const R={mode:b};Object.keys(x).length>0&&(R.traits=x);const A=this.#x()||{},_=Object.assign({},A,{userId:S.userId});let D;isValidEmail(S.userEmail)&&(_.userEmail=S.userEmail),isValidUserName(S.userName)&&(_.userName=S.userName);try{D=this.#y("user_identified",R,_)}catch(S){return this.#b("[SDK identify] envelope wrap failed:",S),!1}try{this.#v("tracescout.user_identified",D)}catch(S){return this.#b("[SDK identify] addCustomEvent failed:",S),!1}return!0}}class SessionRecordingFeature{#o=null;#_=null;#O=null;#a=null;#D=null;#F=null;#N=null;#L=null;#P=!1;#B=!1;#z=null;#U=0;#$=null;#j=null;#q=null;#W=null;constructor({logger:S,sdkContext:b,config:I,options:x}){this.#o=S,this.#_=b,this.#O=I,this.#a=x}async initialize(S,b){try{console.log("[TraceScout] Loading recording module..."),this.#D=await Promise.resolve().then(function(){return Mc});const{SessionStorage:I,UploadQueue:x,Recorder:R}=this.#D;return this.#N=new I({storageKey:"__tracescout_sessions_v2__",maxStorageSize:2097152,maxSessions:5,logger:this.#o}),console.log("[TraceScout] ✓ Session storage initialized"),this.#L=this.#H(x,S,b),console.log("[TraceScout] ✓ Upload queue initialized"),console.log(` Endpoint: /api/projects/${this.#_.projectId}/sessions/${this.#_.sessionId}/chunks`),this.#F=this.#V(R,S),console.log("[TraceScout] ✓ Session recorder initialized"),await this.#F.start(),console.log("[TraceScout] ✓ Session recording started"),this.#a.onSessionStart&&this.#a.onSessionStart(this.#_.sessionId),this.#P=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize session recording:",S),!1}}#H(S,b,I){return new S({sdkContext:this.#_,baseUrl:I?.baseUrl,batchSize:b.telemetry?.batchSize||5,maxRetries:3,retryDelay:2e3,enableCompression:!1!==b.telemetry?.enableCompression,enableOfflineQueue:!0,logger:this.#o,onUploadSuccess:(S,b)=>{this.#o?.log(`✅ Chunk ${S.chunkIndex} uploaded successfully`),this.#a.onChunkUploaded&&this.#a.onChunkUploaded(S,b)},onUploadError:(S,b)=>{if(b&&"QUOTA_EXCEEDED"===b.code)return console.error("[TraceScout] ⛔ QUOTA EXCEEDED - Stopping recording"),void this.#q?.(b);this.#o?.error(`❌ Chunk ${S?.chunkIndex} upload failed:`,b?.message)},onNetworkChange:S=>{this.#o?.log("Network status: "+(S?"online":"offline"))}})}#V(S,b){const I=b.features.sessionRecording;return new S({sdkContext:this.#_,serverSettings:I,emit:S=>this.#Q(S),onChunk:S=>{this.#K(S),this.#L&&this.#L.enqueue(S,"normal")},onSessionEnd:S=>{console.log(`[TraceScout] 🛑 Session ended: ${S.reason}`),console.log(` Session ID: ${S.sessionId}`),console.log(` Duration: ${Math.round(S.duration/6e4)}min`),console.log(` Total events: ${S.totalEvents}`),this.#B=!0,this.#z=S.reason,this.#a.onSessionEnd&&this.#a.onSessionEnd(S),this.#j?.(S)},chunkDuration:I.chunkDuration||3e4,maxChunkSize:I.maxChunkSize||5e5,blockClass:I.blockClass||"ts-block",ignoreClass:I.ignoreClass||"ts-ignore",maskTextClass:I.maskTextClass||"ts-mask",maskAllInputs:I.maskAllInputs||!1,recordCanvas:I.recordCanvas||!1,collectFonts:I.collectFonts||!1,inactivityTimeout:I.inactivityTimeout||3e5,maxInactivityDuration:I.maxInactivityDuration||18e5,maxSessionDuration:I.maxSessionDuration||36e5,enableInactivityDetection:!0,enableSampling:I.enableSampling||!1,enableDeduplication:I.enableDeduplication||!1,mousemoveSampling:I.mousemoveSampling||1,scrollSampling:I.scrollSampling||1,enableStorage:!0,enableCompression:!0,debug:this.#O.debug||!1,onSpaNavigation:(S,b,I)=>{"function"==typeof this.#W&&this.#W(S,b,I)}})}#Q(S){}#K(S){const b=Date.now();if(b-this.#U>=1e4){const I="number"==typeof S.size?S.size:S.compressedSize||0;this.#o?.log(`Session chunk created: ${S.chunkId} (${S.eventCount} events, ${I} bytes)`),this.#U=b}this.#N&&this.#N.storeChunk(S.sessionId,S),this.#$?.(S)}setCallbacks({onChunkCreated:S,onSessionEnd:b,onQuotaExceeded:I,onSpaNavigation:x}){this.#$=S,this.#j=b,this.#q=I,this.#W=x||null}get isAvailable(){return this.#P&&null!=this.#F}get isRecording(){return this.#F?.isRecording||!1}get sessionEnded(){return this.#B}get sessionEndReason(){return this.#z}get recorder(){return this.#F}get uploadQueue(){return this.#L}get sessionStorage(){return this.#N}async start(S={}){if(!this.#F)return this.#o?.warn("Session recording not enabled"),null;try{const b=this.#F.start(S),I=this.#F.getSessionId();return this.#o?.info("Session recording started:",I),{sessionId:I,startTime:Date.now(),status:"recording",stop:b}}catch(S){return this.#o?.error("Failed to start session recording:",S),null}}stop(){if(!this.#F)return this.#o?.warn("Session recording not enabled"),null;try{this.#F.stop();const S=this.#F.getEvents(),b=this.#F.getSessionId();return this.#o?.info("Session recording stopped:",b),{sessionId:b,startTime:this.#F.recordingStartTime,duration:Date.now()-this.#F.recordingStartTime,totalEvents:S.length,events:S,status:"stopped"}}catch(S){return this.#o?.error("Failed to stop session recording:",S),null}}addCustomEvent(S,b){if(!this.#F)return!1;try{return this.#F.addCustomEvent(S,b)}catch(S){return!1}}getStatus(){return this.#F?{available:!0,isRecording:this.#F.isRecording,sessionId:this.#F.getSessionId(),eventCount:this.#F.getEvents().length,startTime:this.#F.recordingStartTime}:{available:!1,error:"Session recording not enabled"}}getEvents(){return this.#F?.getEvents()||[]}getChunks(){return this.#F?.getChunks?.()||[]}getMetadata(){return this.#F?.getMetadata?.()||{}}getSessionId(){return this.#F?.getSessionId()}updateSessionId(S){this.#F&&(this.#F.sessionId=S),this.#B=!1,this.#z=null}updateUploadEndpoint(S){this.#L&&(this.#L.config.endpoint=S)}destroy(){if(this.#F){try{this.#F.stop()}catch(S){}this.#F=null}this.#N=null,this.#L=null,this.#D=null,this.#P=!1}}class LogManager{#o=null;#O=null;#_=null;#G=[];#J={};#X="debug";#Y=1e3;#Z=new Map;#ee=5e3;#te=null;#se=!0;static LOG_LEVELS={debug:0,info:1,warn:2,error:3,fatal:4};constructor(S={},b=null,I=null){this.#O=S,this.#_=b,this.#te=I,this.#o=new Logger("[LogManager]",S.debug),this.#se=!1!==S.logs?.enabled,this.#X=S.logs?.minLevel||"debug",this.#Y=S.logs?.maxBufferSize||1e3,this.#o.log("LogManager initialized",{enabled:this.#se,minLevel:this.#X,maxBufferSize:this.#Y})}log(S,b,I={}){if(!this.#se)return!1;if(!this.#re(S))return!1;try{const x=this.#ne(S,b,I);return!this.#ie(x)&&(this.#G.push(x),this.#G.length>=this.#Y&&this.flush(),"error"!==S&&"fatal"!==S||setTimeout(()=>this.flush(),0),!0)}catch(S){return this.#o.error("Failed to log message:",S),!1}}debug(S,b={}){return this.log("debug",S,b)}info(S,b={}){return this.log("info",S,b)}warn(S,b={}){return this.log("warn",S,b)}error(S,b={}){return this.log("error",S,b)}fatal(S,b={}){return this.log("fatal",S,b)}attachContext(S,b){"string"==typeof S?this.#J[S]=b:"object"==typeof S&&Object.assign(this.#J,S),this.#o.log("Context attached:",S)}clearContext(){this.#J={},this.#o.log("Context cleared")}setLogLevel(S){LogManager.LOG_LEVELS.hasOwnProperty(S)?(this.#X=S,this.#o.log("Log level set to:",S)):this.#o.warn("Invalid log level:",S)}getLogLevel(){return this.#X}setEnabled(S){this.#se=S,this.#o.log("Logging",S?"enabled":"disabled")}isEnabled(){return this.#se}flush(){if(0===this.#G.length)return[];const S=[...this.#G];if(this.#G=[],this.#o.log(`Flushing ${S.length} logs`),this.#te)try{this.#te(S)}catch(S){this.#o.error("Error in flush callback:",S)}return S}getQueueSize(){return this.#G.length}getQueue(){return[...this.#G]}clearQueue(){const S=this.#G.length;this.#G=[],this.#o.log(`Cleared ${S} logs from queue`)}getStats(){const S={queueSize:this.#G.length,byLevel:{},enabled:this.#se,minLevel:this.#X};return this.#G.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}#ne(S,b,I={}){const x=Date.now(),R=`log_${x}_${generateId()}`,A={source:"undefined"!=typeof process&&process.versions&&process.versions.node?"server":"client",timestamp:x,...this.#oe(),...this.#J};this.#_&&(A.sessionId=this.#_.sessionId,A.projectId=this.#_.projectId,A.environment=this.#_.environment,this.#_.userId&&(A.userId=this.#_.userId));const _=this.#ae(I);return"error"!==S&&"fatal"!==S||!1===this.#O.logs?.attachStackTrace||_.stack||(_.stack=this.#le()),{logId:R,timestamp:x,level:S,message:String(b),metadata:_,context:A}}#oe(){const S={};return"undefined"!=typeof window?(S.url=window.location?.href,S.userAgent=navigator?.userAgent,S.platform=navigator?.platform):"undefined"!=typeof process&&(S.platform=process.platform,S.nodeVersion=process.version,S.pid=process.pid),S}#ae(S){if(!S||"object"!=typeof S)return{};const b={};for(const[I,x]of Object.entries(S))if(x instanceof Error)b[I]={name:x.name,message:x.message,stack:x.stack,...x};else if("object"==typeof x&&null!==x)try{JSON.stringify(x),b[I]=x}catch(S){b[I]="[Circular Reference]"}else b[I]=x;return b}#le(){try{const S=(new Error).stack||"";return S.split("\n").slice(3).join("\n")}catch(S){return"Stack trace unavailable"}}#re(S){const b=LogManager.LOG_LEVELS[S],I=LogManager.LOG_LEVELS[this.#X];return void 0===b||void 0===I||b>=I}#ie(S){const b=`${S.level}:${S.message}`,I=Date.now(),x=this.#Z.get(b);return!!(x&&I-x<this.#ee)||(this.#Z.set(b,I),this.#Z.size>1e3&&this.#ce(),!1)}#ce(){const S=Date.now();for(const[b,I]of this.#Z.entries())S-I>this.#ee&&this.#Z.delete(b)}destroy(){this.flush(),this.#G=[],this.#J={},this.#Z.clear(),this.#te=null,this.#o.log("LogManager destroyed")}}class LogBuffer{#o=null;#O=null;#_=null;#ue=[];#he=null;#de=5e3;#ge=100;#pe=!1;#fe=null;#me=!0;#ye=0;static MAX_CONSECUTIVE_FAILURES=5;constructor(S={},b=null,I=null){this.#O=S,this.#_=b,this.#fe=I,this.#o=new Logger("[LogBuffer]",S.debug),this.#de=S.logs?.flushInterval||5e3,this.#ge=S.logs?.maxBatchSize||100,this.#me=!1!==S.telemetry?.enableCompression,this.#ve(),this.#o.log("LogBuffer initialized",{flushInterval:this.#de,maxBatchSize:this.#ge,compressionEnabled:this.#me})}add(S){Array.isArray(S)||(S=[S]),this.#ue.push(...S),this.#o.log(`Added ${S.length} logs to buffer. Buffer size: ${this.#ue.length}`),this.#ue.length>=this.#ge&&(this.#o.log("Buffer size threshold reached, flushing..."),this.flush())}async flush(){if(0===this.#ue.length)return{success:!0,sent:0};if(this.#pe)return this.#o.log("Already sending, skipping flush"),{success:!1,reason:"Already sending"};const S=this.#ue.splice(0,this.#ge);if(0===S.length)return{success:!0,sent:0};this.#o.log(`Flushing ${S.length} logs`);try{this.#pe=!0;const b=this.#Se(S);let I=b,x=!1;if(this.#me&&"function"==typeof this.#we)try{I=await this.#we(b),x=!0,this.#o.log(`Compressed batch from ${JSON.stringify(b).length} to ${I.length} bytes`)}catch(S){this.#o.warn("Compression failed, sending uncompressed:",S)}return this.#fe&&await this.#fe(I,x),this.#o.log(`Successfully sent batch with ${S.length} logs`),this.#ye=0,{success:!0,sent:S.length}}catch(b){return this.#ye++,this.#o.error(`Failed to flush logs (consecutive failures: ${this.#ye}):`,b),this.#ye>LogBuffer.MAX_CONSECUTIVE_FAILURES?(this.#o.warn(`Dropping batch of ${S.length} logs after ${this.#ye} consecutive failures`),{success:!1,dropped:S.length,error:b.message}):(this.#ue.unshift(...S),{success:!1,error:b.message})}finally{this.#pe=!1}}getConsecutiveFailures(){return this.#ye}async forceFlush(){this.#be();try{await this.flush()}finally{this.#ve()}}getBufferSize(){return this.#ue.length}getStats(){const S={bufferSize:this.#ue.length,isSending:this.#pe,flushInterval:this.#de,maxBatchSize:this.#ge,byLevel:{}};return this.#ue.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}clear(){const S=this.#ue.length;this.#ue=[],this.#o.log(`Cleared ${S} logs from buffer`)}destroy(){this.#be(),this.flush().catch(S=>{this.#o.error("Error during final flush:",S)}),this.clear(),this.#o.log("LogBuffer destroyed")}#Se(S){return{batchId:`batch_${Date.now()}_${generateId()}`,timestamp:Date.now(),projectId:this.#_?.projectId,count:S.length,logs:S}}async#we(S){const b=JSON.stringify(S);if("undefined"!=typeof CompressionStream)try{const S=new Blob([b]).stream().pipeThrough(new CompressionStream("gzip")),I=await new Response(S).blob(),x=await I.arrayBuffer();return Array.from(new Uint8Array(x))}catch(S){throw this.#o.warn("Browser compression failed:",S),S}throw new Error("Compression not available - CompressionStream not supported")}#ve(){this.#he||(this.#he=setInterval(()=>{this.#ue.length>0&&this.flush().catch(S=>{this.#o.error("Auto-flush failed:",S)})},this.#de),this.#o.log("Auto-flush started"))}#be(){this.#he&&(clearInterval(this.#he),this.#he=null,this.#o.log("Auto-flush stopped"))}}class LoggingFeature{#o=null;#_=null;#O=null;#Ce=null;#ke=null;#P=!1;constructor({logger:S,sdkContext:b,config:I}){this.#o=S,this.#_=b,this.#O=I}initialize(S){console.log("[TraceScout] Initializing logging system...");try{return this.#Ce=new LogManager(this.#O,this.#_,S=>{this.#ke&&this.#ke.add(S)}),this.#ke=new LogBuffer(this.#O,this.#_,async(S,b)=>this.#Ie(S,b)),console.log("[TraceScout] ✓ Logging system initialized"),this.#P=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize logging:",S),!1}}configure(S){try{const b={enabled:S.debug||!1,level:S.logLevel||"info",showTimestamps:!1!==S.showLogTimestamps,showServiceIcons:!1!==S.showServiceIcons};S.logging&&"object"==typeof S.logging&&(b.services=S.logging),_.configure(b),S.enabledLogServices&&Array.isArray(S.enabledLogServices)?_.enableServices(S.enabledLogServices,S.logLevel||"info"):S.debug&&_.enableServices(["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager"],S.logLevel||"info"),this.#o?.log("Logging system configured successfully")}catch(S){this.#o?.error("Failed to configure logging system:",S)}}async#Ie(S,b){if(!this.#_)throw new Error("SDK not initialized");const I=this.#_.projectId,x=`${resolveApiBaseUrl(this.#O)}/api/projects/${I}/logs/batch`;try{const I={};b?(I["Content-Type"]="application/octet-stream",I["Content-Encoding"]="gzip"):I["Content-Type"]="application/json";const R=await fetch(x,{method:"POST",headers:I,body:b?new Blob([new Uint8Array(S)]):JSON.stringify(S)});if(!R.ok)throw new Error(`HTTP ${R.status}: ${R.statusText}`);const A=await R.json();return this.#o?.log("Log batch sent successfully"),A}catch(S){throw this.#o?.error("Failed to send log batch:",S),S}}get isAvailable(){return this.#P&&null!=this.#Ce}get logManager(){return this.#Ce}get logBuffer(){return this.#ke}log(S,b,I={}){return!!this.#Ce&&this.#Ce.log(S,b,I)}debug(S,b={}){return this.#Ce?.debug(S,b)||!1}info(S,b={}){return this.#Ce?.info(S,b)||!1}warn(S,b={}){return this.#Ce?.warn(S,b)||!1}error(S,b={}){return this.#Ce?.error(S,b)||!1}fatal(S,b={}){return this.#Ce?.fatal(S,b)||!1}setContext(S,b){return!!this.#Ce&&(this.#Ce.attachContext(S,b),!0)}clearContext(){return!!this.#Ce&&(this.#Ce.clearContext(),!0)}setLogLevel(S){return!!this.#Ce&&(this.#Ce.setLogLevel(S),!0)}getStats(){return this.#Ce?{manager:this.#Ce.getStats(),buffer:this.#ke?this.#ke.getStats():null}:null}async flush(){if(!this.#ke)return!1;try{return await this.#ke.forceFlush(),!0}catch(S){return this.#o?.error("Failed to flush logs:",S),!1}}enableServices(S,b="info"){try{return _.enableServices(S,b),!0}catch(S){return this.#o?.error("Failed to enable logging:",S),!1}}disableServices(S){try{return _.disableServices(S),!0}catch(S){return this.#o?.error("Failed to disable logging:",S),!1}}enableAll(S="info"){try{return _.enableAll(S),!0}catch(S){return this.#o?.error("Failed to enable all logging:",S),!1}}disableAll(){try{return _.disableAll(),!0}catch(S){return this.#o?.error("Failed to disable all logging:",S),!1}}getConfig(){try{return _.getConfig()}catch(S){return this.#o?.error("Failed to get logging config:",S),null}}getEnabledServices(){try{return _.getEnabledServices()}catch(S){return[]}}getAvailableServices(){return["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager","UserProfileManager","PerformanceMonitor","FetchInterceptor","XHRInterceptor","ResourceInterceptor","PostMessageInterceptor","CoreWebVitalsMonitor","Recorder","SessionStorage","UploadQueue","CDN-Loader","Replayer","Validation","BaseService"]}destroy(){this.#ke&&(this.#ke.destroy(),this.#ke=null),this.#Ce&&(this.#Ce.destroy(),this.#Ce=null),this.#P=!1}}class ConsoleInterceptor{constructor(S,b={},I=null){this.eventManager=S,this.reporter=I,this.logManager=null,this.config={captureLog:!1!==b.captureLog,captureWarn:!1!==b.captureWarn,captureError:!1!==b.captureError,captureInfo:!1!==b.captureInfo,captureDebug:!1!==b.captureDebug,captureTrace:!1!==b.captureTrace,maxMessageLength:b.maxMessageLength||5e3,maxArgSize:b.maxArgSize||2e3,maxTotalArgsSize:b.maxTotalArgsSize||1e4,...b},this.logger=createLogger("ConsoleInterceptor"),this.originalMethods={},this.installed=!1}setLogManager(S){this.logManager=S,this.logger.debug("LogManager attached to ConsoleInterceptor")}install(){if(this.installed)return;const S=[];this.config.captureLog&&S.push("log"),this.config.captureWarn&&S.push("warn"),this.config.captureError&&S.push("error"),this.config.captureInfo&&S.push("info"),this.config.captureDebug&&S.push("debug"),this.config.captureTrace&&S.push("trace"),S.forEach(S=>{this.originalMethods[S]=console[S],console[S]=this.createInterceptor(S)}),this.installed=!0,this.logger.debug("Console interceptor installed")}uninstall(){this.installed&&(Object.keys(this.originalMethods).forEach(S=>{console[S]=this.originalMethods[S]}),this.originalMethods={},this.installed=!1,this.logger.debug("Console interceptor uninstalled"))}createInterceptor(S){const b=this;return function(...I){b.originalMethods[S].apply(console,I);const x=I[0];if("string"!=typeof x||!(x.includes("[TraceScout]")||x.includes("[Recorder]")||x.includes("[SDK]")||x.includes("[ConsoleInterceptor]")||x.includes("[NetworkInterceptor]")||x.includes("[FetchInterceptor]")||x.includes("[XHRInterceptor]")||x.includes("[SessionManager]")||x.includes("[UploadQueue]")||x.includes("[ErrorHandler]")||x.includes("TraceScoutMonitoringCore")))try{const x=b.formatMessage(I),R=Date.now(),A=b.getLevel(S),_=b.processArgs(I),D={method:S,args:_,source:"console"};if("error"!==S&&"trace"!==S||(D.stack=b.captureStackTrace()),b.logManager&&"function"==typeof b.logManager.log)try{const I=b.truncateMessage(x),R=b.mapToLogLevel(S);b.logManager.log(R,I,D)}catch(S){}const L={type:"console",category:"console",method:S,message:b.truncateMessage(x),timestamp:R,level:A,args:_};if("error"!==S&&"trace"!==S||(L.stack=b.captureStackTrace()),b.eventManager&&"function"==typeof b.eventManager.logEvent&&b.eventManager.logEvent("console",L),b.reporter&&b.reporter.addSessionCustomEvent&&"function"==typeof b.reporter.addSessionCustomEvent)try{b.reporter.addSessionCustomEvent("console",{method:S,message:L.message,args:L.args,level:L.level,stack:L.stack,timestamp:L.timestamp})}catch(S){}}catch(S){}}}formatMessage(S){return S.map(S=>{if(null===S)return"null";if(void 0===S)return"undefined";if("object"==typeof S)try{return safeStringify(S,5,this.config.maxArgSize)}catch{return"[Unserializable Object]"}return"string"==typeof S&&S.length>this.config.maxArgSize?S.substring(0,this.config.maxArgSize)+"... [truncated]":String(S)}).join(" ")}processArgs(S){if(this.config.captureArgs)return safeParseConsoleArgs(S,this.config.maxArgSize,this.config.maxTotalArgsSize)}truncateMessage(S){return S.length>this.config.maxMessageLength?S.substring(0,this.config.maxMessageLength)+"...":S}getLevel(S){return{log:"log",info:"info",warn:"warn",error:"error",debug:"debug",trace:"trace"}[S]||"log"}mapToLogLevel(S){return{log:"info",info:"info",warn:"warn",error:"error",debug:"debug",trace:"debug"}[S]||"info"}captureStackTrace(){return(new Error).stack||""}}const Te=["authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-csrf-token","x-xsrf-token","api-key","apikey","x-amz-security-token","x-ms-client-principal","proxy-authorization","www-authenticate"],Ae="[REDACTED]";function filterSensitiveHeaders(S,b=[]){if(!S)return{};const I={},x=new Set([...Te,...b.map(S=>S.toLowerCase())]);if(S instanceof Headers||S.forEach&&"function"==typeof S.forEach)S.forEach((S,b)=>{const R=b.toLowerCase();I[b]=x.has(R)?Ae:S});else if("object"==typeof S)for(const[b,R]of Object.entries(S)){const S=b.toLowerCase();I[b]=x.has(S)?Ae:R}return I}const _e=[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".woff",".woff2",".ttf",".eot",".ico",".webp",".avif"],Oe=["text/css","text/javascript","application/javascript","image/","font/","application/font","application/x-font"],De=[/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|ico|webp|avif)(\?|$)/i,/\/static\//i,/\/assets\//i,/\/images\//i,/\/fonts\//i,/\/_next\/static\//i,/\/webpack\//i,/\/node_modules\//i];function isStaticResource(S,b=""){if(!S)return!1;if(_e.some(b=>S.toLowerCase().includes(b)))return!0;const I=Oe.some(S=>b.toLowerCase().startsWith(S));return!!I||De.some(b=>b.test(S))}function getResourceType(S,b=""){const I=S.toLowerCase(),x=b.toLowerCase();return I.includes(".js")||x.includes("javascript")?"script":I.includes(".css")||x.includes("text/css")?"stylesheet":/\.(woff2?|ttf|eot|otf)(\?|$)/i.test(S)||x.includes("font")?"font":/\.(png|jpg|jpeg|gif|svg|ico|webp|avif)(\?|$)/i.test(S)||x.includes("image")?"image":"other"}const Fe=1e4;function parseFormData(S){try{const b=new URLSearchParams(S),I={};for(const[S,x]of b)I[S]=x;return I}catch(S){return null}}function createTruncatedBody(S,b,I="body"){return{_truncated:!0,_originalSize:S.length,_message:`${I} body truncated (${S.length} bytes, limit ${b} bytes)`,_preview:S.substring(0,b)+"...",_tip:"Enable full body capture in project settings if needed"}}function handleRequestBody(S,b={}){const{maxSize:I=Fe,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Request");try{const S=JSON.parse(b),x=JSON.stringify(S);return x.length>I?createTruncatedBody(x,I,"Request"):S}catch{const S=parseFormData(b);return S||b}}else{if(b instanceof FormData){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if(b instanceof URLSearchParams){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Request"):b}}}catch(S){x("Failed to parse request data:",S)}return null}function handleResponseBody(S,b={}){const{maxSize:I=Fe,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Response");try{b=JSON.parse(b)}catch{return b}}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Response"):b}return b}catch(S){x("Failed to parse response data:",S)}return null}const Ne="[REDACTED]",Le=10240,Pe=65536,Be=["password","passwd","pwd","secret","token","access_token","refresh_token","id_token","authorization","auth","api_key","apikey","x-api-key","cookie","session","sessionid","session_id","sid","jwt","bearer","credential","credentials","private_key","client_secret","card","cardnumber","card_number","cvv","cvc","pin","ssn","social_security","dob","date_of_birth","email","phone","address"];function utf8Bytes(S){return"string"!=typeof S||0===S.length?0:(new TextEncoder).encode(S).length}function truncateToBytes(S,b){const I=new TextEncoder,x=I.encode(S),R=x.length;if(R<=b)return{text:S,truncated:!1,capturedBytes:R,originalBytes:R};if(b<=0)return{text:"",truncated:!0,capturedBytes:0,originalBytes:R};const A=x.subarray(0,b);let _=new TextDecoder("utf-8",{fatal:!1}).decode(A);_.length&&65533===_.charCodeAt(_.length-1)&&(_=_.slice(0,-1));return{text:_,truncated:!0,capturedBytes:I.encode(_).length,originalBytes:R}}function safeMime(S){if(!S||"string"!=typeof S)return null;const b=S.split(";")[0].trim().toLowerCase();return b&&/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(b)?b.length>128?b.slice(0,128):b:null}function classifyMime(S){return S?"application/json"===S||"application/ld+json"===S||"application/graphql"===S||"application/graphql+json"===S||S.endsWith("+json")?"json":"application/x-www-form-urlencoded"===S?"form":"image/svg+xml"===S||"application/xml"===S||"text/xml"===S||"application/xhtml+xml"===S||"application/javascript"===S||"application/x-javascript"===S||"text/javascript"===S||S.startsWith("text/")?"text":S.startsWith("image/")||S.startsWith("audio/")||S.startsWith("video/")||S.startsWith("font/")||"application/octet-stream"===S||"application/zip"===S||"application/gzip"===S||"application/pdf"===S||"application/x-protobuf"===S||"application/protobuf"===S||S.startsWith("multipart/")?"binary":"unknown":"unknown"}function isTextualContentType(S){const b=classifyMime(safeMime(S));return"json"===b||"form"===b||"text"===b}function buildFieldDenylist(S=[]){const b=new Set(Be);if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.add(I.toLowerCase());return b}function isSensitiveField(S,b){const I=String(S).toLowerCase();for(const S of b)if(I.includes(S))return!0;return!1}function redactObject(S,b){let I=!1;const walk=S=>{if(Array.isArray(S))return S.map(walk);if(S&&"object"==typeof S){const x={};for(const R of Object.keys(S))isSensitiveField(R,b)?(x[R]=Ne,I=!0):x[R]=walk(S[R]);return x}return S};return{value:walk(S),redacted:I}}function redactFormUrlEncoded(S,b){let I;try{I=new URLSearchParams(S)}catch{return{text:S,redacted:!1}}let x=!1;const R=[];for(const S of I.keys())R.push(S);const A=new Set;for(const S of R){if(A.has(S))continue;if(A.add(S),!isSensitiveField(S,b))continue;const R=I.getAll(S).length;I.delete(S);for(let b=0;b<R;b++)I.append(S,Ne);x=!0}return{text:I.toString(),redacted:x}}function rawBodyBinarySize(S){return"undefined"!=typeof Blob&&S instanceof Blob&&"number"==typeof S.size?S.size:"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(S)?S.byteLength:null}function makeResult({state:S,contentType:b=null,originalBytes:I=null,redacted:x=!1}){return{text:null,state:S,redacted:!!x,truncated:!1,originalBytes:"number"==typeof I&&I>=0?I:null,capturedBytes:null,contentType:b||null}}function runSanitizer(S,b){try{return{threw:!1,value:S(b)}}catch{return{threw:!0}}}function safeToString(S){try{return"string"==typeof S?S:JSON.stringify(S)}catch{return String(S)}}function finalizeText(S,{mime:b,maxBytes:I,redacted:x}){const{text:R,truncated:A,capturedBytes:_,originalBytes:D}=truncateToBytes(S,I);let L;return L=A?"truncated":x?"redacted":"captured",{text:R,state:L,redacted:!!x,truncated:A,originalBytes:D,capturedBytes:_,contentType:b||null}}function finalizeStructured(S,{redacted:b,mime:I,maxBytes:x,sanitizer:R}){let A,_=S;if(R){const x=runSanitizer(R,S);if(x.threw)return makeResult({state:"failed",contentType:I,redacted:b});if(null===x.value||void 0===x.value)return makeResult({state:"excluded",contentType:I});_=x.value}try{A=JSON.stringify(_)}catch{return makeResult({state:"failed",contentType:I,redacted:b})}return void 0===A&&(A=""),finalizeText(A,{mime:I,maxBytes:x,redacted:b})}function captureText(S,{mime:b,maxBytes:I,sanitizer:x}){let R=S;if(x){const I=runSanitizer(x,S);if(I.threw)return makeResult({state:"failed",contentType:b});if(null===I.value||void 0===I.value)return makeResult({state:"excluded",contentType:b});R="string"==typeof I.value?I.value:safeToString(I.value)}return finalizeText(R,{mime:b,maxBytes:I,redacted:!1})}function captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const{text:A,redacted:_}=redactFormUrlEncoded(S,x);let D=A;if(R){const S=runSanitizer(R,D);if(S.threw)return makeResult({state:"failed",contentType:b,redacted:_});if(null===S.value||void 0===S.value)return makeResult({state:"excluded",contentType:b});D="string"==typeof S.value?S.value:safeToString(S.value)}return finalizeText(D,{mime:b,maxBytes:I,redacted:_})}function captureStringByMime(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const A=classifyMime(b);if("binary"===A||"unknown"===A)return makeResult({state:"binary",contentType:b,originalBytes:utf8Bytes(S)});if("form"===A)return captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R});if("json"===A){let A;try{A=JSON.parse(S)}catch{return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}const{value:_,redacted:D}=redactObject(A,x);return finalizeStructured(_,{redacted:D,mime:b,maxBytes:I,sanitizer:R})}return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}function normalizeOpts(S){let b="number"==typeof S.maxBytes&&S.maxBytes>=0?S.maxBytes:Le;return b>Pe&&(b=Pe),{maxBytes:b,denylist:S.denylist instanceof Set?S.denylist:buildFieldDenylist(S.sensitiveFields),sanitizer:"function"==typeof S.sanitizer?S.sanitizer:null,captureEnabled:!1!==S.captureEnabled,excluded:!0===S.excluded}}function captureRequestBody(S,b={}){const I=safeMime(b.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(null==S||""===S)return makeResult({state:"unavailable",contentType:I});try{if("undefined"!=typeof FormData&&S instanceof FormData){const{obj:b,redacted:_}=function sanitizeFormData(S,b){let I=!1;const x={};for(const[R,A]of S.entries()){let S;"undefined"!=typeof File&&A instanceof File||"undefined"!=typeof Blob&&A instanceof Blob?S={_type:"file",mime:safeMime(A.type)||null,bytes:"number"==typeof A.size?A.size:null}:isSensitiveField(R,b)?(S=Ne,I=!0):S=String(A),Object.prototype.hasOwnProperty.call(x,R)?Array.isArray(x[R])?x[R].push(S):x[R]=[x[R],S]:x[R]=S}return{obj:x,redacted:I}}(S,R);return finalizeStructured(b,{redacted:_,mime:I||"multipart/form-data",maxBytes:x,sanitizer:A})}if("undefined"!=typeof URLSearchParams&&S instanceof URLSearchParams)return captureFormString(S.toString(),{mime:I||"application/x-www-form-urlencoded",maxBytes:x,denylist:R,sanitizer:A});if(function isBinaryRawBody(S){return"undefined"!=typeof Blob&&S instanceof Blob||"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||!("undefined"==typeof ArrayBuffer||!ArrayBuffer.isView||!ArrayBuffer.isView(S))||"undefined"!=typeof ReadableStream&&S instanceof ReadableStream}(S))return makeResult({state:"binary",contentType:I||(L=S,"undefined"!=typeof Blob&&L instanceof Blob&&L.type?safeMime(L.type):null),originalBytes:rawBodyBinarySize(S)});if("string"==typeof S)return captureStringByMime(S,{mime:I,maxBytes:x,denylist:R,sanitizer:A});if("object"==typeof S){const{value:b,redacted:_}=redactObject(S,R);return finalizeStructured(b,{redacted:_,mime:I||"application/json",maxBytes:x,sanitizer:A})}return captureStringByMime(String(S),{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}var L}function captureResponseBody(S={},b={}){const I=safeMime(S.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(S.opaque)return makeResult({state:"inaccessible",contentType:I});if(S.readError)return makeResult({state:"failed",contentType:I});if(S.binary){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}const L=classifyMime(I);if("binary"===L||"unknown"===L){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}if(S.empty||null===S.text||void 0===S.text||""===S.text)return makeResult({state:"unavailable",contentType:I});try{return captureStringByMime(S.text,{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}}const ze="[REDACTED]",Ue=["token","access_token","refresh_token","id_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","ssid","password","passwd","pwd","secret","jwt","bearer","credential","credentials","private_token","private_key","client_secret","pin","cvv","cvc","ssn","email"];function buildTokens(S=[]){const b=[...Ue];if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.push(I.toLowerCase());return b}function isSensitiveParam(S,b){const I=String(S).toLowerCase();return b.some(S=>I.includes(S))}function scrubSearchParams(S,b,I){let x=!1;const R=[];for(const b of S.keys())R.push(b);const A=new Set;for(const _ of R)if(!A.has(_)&&(A.add(_),isSensitiveParam(_,b)))if(x=!0,"delete"===I)S.delete(_);else{const b=S.getAll(_).length;S.delete(_);for(let I=0;I<b;I++)S.append(_,ze)}return x}function splitSanitizedUrl(S,b={}){const{extraParams:I=[],mode:x="redact"}=b;if(!S)return{url:"",path:"",query:""};const R=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);scrubSearchParams(I.searchParams,R,x);const A=I.searchParams.toString();return{url:I.toString(),path:I.pathname||"",query:A}}catch{const I=function sanitizeUrl$1(S,b={}){const{extraParams:I=[],mode:x="redact",stripHash:R=!1}=b;if(!S)return S||"";const A=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);return scrubSearchParams(I.searchParams,A,x),R&&(I.hash=""),I.toString()}catch{let b=S.replace(/([?&][^=&]*(?:token|key|secret|password|passwd|pwd|auth|jwt|bearer|session|sid|credential|pin|cvv|cvc|ssn|email)[^=&]*=)[^&#]*/gi,`$1${ze}`);return b.length>2048&&(b=b.substring(0,2048)),b}}(S,b),x=I.indexOf("?");return-1===x?{url:I,path:I,query:""}:{url:I,path:I.substring(0,x),query:I.substring(x+1).split("#")[0]}}}class InterceptorLogger{constructor(S,b=!1){let I=S.replace(/^\[|\]$/g,"").replace(":","");I="xhrinterceptor"===I.toLowerCase()?"XHRInterceptor":I.charAt(0).toUpperCase()+I.slice(1),this.serviceLogger=createLogger(I),this.prefix=S,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class BaseInterceptor{constructor(S,b){this.reporter=S,this.interceptorName=b,this.logger=new InterceptorLogger(`[${this.interceptorName}Interceptor]`,this.reporter.config?.debug||!1)}updateDebugMode(S){this.logger.updateDebugMode(S)}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!1}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isStaticResource(S,b=""){return isStaticResource(S,b)}isResourceUrl(S,b=""){return isStaticResource(S,b)}getResourceType(S,b=""){return getResourceType(S,b)}extractRequestDetails(S,b,I,x,R){const A=parseUrl(S);return{method:b.toUpperCase(),url:S,domain:A.hostname,path:A.pathname,status:I,statusText:x,response:R,interceptor:this.interceptorName}}logEvent(S){const b=S?.url||S?.request?.url;if(b&&isInternalSdkEndpoint(b))return;if(this.reporter?._sessionRecorder?.isRecording||this.reporter?.sessionRecording?.isRecording)return;const I={id:generateId(),timestamp:Date.now(),...S};this.reporter.logEvent&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(I)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("string"==typeof S&&0===S.indexOf("network")){const S=this.reporter.config&&this.reporter.config.network;if(S&&!1===S.isEnabled)return!1}const I=b?.url||b?.request?.url;if(I&&isInternalSdkEndpoint(I))return!1;if(!this.reporter.addSessionCustomEvent)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateUserProfileFromContext({url:S,source:b,data:I}){try{if(this.reporter.extractUserContextFromBody&&"function"==typeof this.reporter.extractUserContextFromBody){const x=this.reporter.extractUserContextFromBody({url:S,source:b,data:I});if(Object.keys(x).length>0){let S={};this.reporter._getUserProfile&&"function"==typeof this.reporter._getUserProfile?S=this.reporter._getUserProfile():this.reporter.getUserProfile&&"function"==typeof this.reporter.getUserProfile&&(S=this.reporter.getUserProfile());const b={...S,...x};JSON.stringify(S)!==JSON.stringify(b)&&this.reporter.setUserProfile&&"function"==typeof this.reporter.setUserProfile&&this.reporter.setUserProfile(b)}}}catch(S){this.logger.warn("Failed to update user profile context:",S)}}getNetworkConfig(){const S=this.reporter&&this.reporter.config&&this.reporter.config.network||{};let b="number"==typeof S.maxBodyBytes?S.maxBodyBytes:Le;b>=0||(b=Le),b>Pe&&(b=Pe);const I=Array.isArray(S.sensitiveFields)?S.sensitiveFields:[];return{isEnabled:!1!==S.isEnabled,captureRequestHeaders:!1!==S.captureRequestHeaders,captureResponseHeaders:!1!==S.captureResponseHeaders,captureRequestBody:!1!==S.captureRequestBody,captureResponseBody:!1!==S.captureResponseBody,maxBodyBytes:b,excludeEndpoints:Array.isArray(S.excludeEndpoints)?S.excludeEndpoints:[],requestSanitizer:"function"==typeof S.requestSanitizer?S.requestSanitizer:null,responseSanitizer:"function"==typeof S.responseSanitizer?S.responseSanitizer:null,sensitiveFields:I,_denylist:buildFieldDenylist(I)}}isEndpointExcluded(S,b){const I=b&&b.excludeEndpoints||[],x=String(S||"");for(const S of I)try{if(S instanceof RegExp){if(S.test(x))return!0}else if("string"==typeof S&&S&&x.includes(S))return!0}catch{}return!1}sanitizeRequestUrlFields(S,b){try{return splitSanitizedUrl(S,{extraParams:b&&b.sensitiveFields||[]})}catch{return{url:String(S||""),path:"",query:""}}}mapCaptureToFields(S,b){const I={};return I[`${b}Body`]="string"==typeof S.text?S.text:null,I[`${b}BodyState`]=S.state,I[`${b}BodyRedacted`]=!!S.redacted,I[`${b}BodyTruncated`]=!!S.truncated,"number"==typeof S.originalBytes&&(I[`${b}BodySize`]=S.originalBytes),"number"==typeof S.capturedBytes&&(I[`${b}BodyCapturedBytes`]=S.capturedBytes),S.contentType&&(I[`${b}BodyContentType`]=S.contentType),I}buildRequestBodyFields(S,b,I,x){const R=captureRequestBody(S,{contentTypeHeader:b,maxBytes:I.maxBodyBytes,denylist:I._denylist,sanitizer:I.requestSanitizer,captureEnabled:I.captureRequestBody,excluded:x});return this.mapCaptureToFields(R,"request")}buildResponseBodyFields(S,b,I){const x=captureResponseBody(S,{maxBytes:b.maxBodyBytes,denylist:b._denylist,sanitizer:b.responseSanitizer,captureEnabled:b.captureResponseBody,excluded:I});return this.mapCaptureToFields(x,"response")}handleRequestData(S,b){return handleRequestBody(b,{maxSize:Fe,onWarn:(...S)=>this.logger.warn(...S)})}handleResponseData(S,b){return handleResponseBody(b,{maxSize:Fe,onWarn:(...S)=>this.logger.warn(...S)})}createEvent(S,b,I,x,R,A=null,_=null,D={}){const L={type:S,context:{url:b,method:I.toUpperCase(),status:x,statusText:R,requestData:this.handleRequestData(b,A),responseData:this.handleResponseData(b,_),isMonitored:this.shouldMonitor(b),...D}};return this.shouldExtractFields(b,"response")&&_&&this.updateUserProfileFromContext({url:b,source:"response",data:_}),L}logErrorEvent(S,b,I,x,R=null,A=null,_={}){const D={type:_.errorType||`${this.interceptorName}_http_error`,request:this.extractRequestDetails(S,b,I,x,A),extraData:_,context:{isMonitored:this.shouldMonitor(S),forceLog:I>=400,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}handleSilentLoginFailure(S,b,I,x,R,A){S.toLowerCase().includes("/myava/login")&&(I>=200&&I<300)&&null==R?.LoginToken&&this.logEvent({type:A,request:this.extractRequestDetails(S,b,I,x,R),extraData:R})}logCustomApiError(S,b,I,x,R,A,_={}){const D={type:"custom_api_error",request:this.extractRequestDetails(S,b,I,x,R),extraData:{errorCondition:A,..._},context:{isMonitored:this.shouldMonitor(S),forceLog:!0,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}logUnknownError(S,b,I,x={}){const R={type:"unknown_error",request:{method:b||"UNKNOWN",url:S||"unknown",domain:S?this.extractDomain(S):"unknown",path:S?this.extractPath(S):"unknown",status:0,statusText:"Unknown Error",response:{error:I?.message||"Unknown error occurred",stack:I?.stack||""},interceptor:this.interceptorName},extraData:{errorType:I?.name||"UnknownError",errorMessage:I?.message||"Unknown error",...x},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logEvent(R)}extractDomain(S){try{return new URL(S,window.location.origin).hostname}catch{return"unknown"}}extractPath(S){try{return new URL(S,window.location.origin).pathname}catch{return"unknown"}}destroy(){this.reporter=null,this.logger=null}}function getHeader(S,b){if(!S)return null;const I=b.toLowerCase();if(S instanceof Headers)return S.get(I);for(const b in S)if(b.toLowerCase()===I)return S[b];return null}function setHeader(S,b,I){if(!S)return;if(S instanceof Headers)return void S.set(b,I);const x=b.toLowerCase();for(const b in S)b.toLowerCase()===x&&delete S[b];S[b]=I}function hasHeader(S,b){if(!S)return!1;const I=b.toLowerCase();if(S instanceof Headers)return S.has(I);for(const b in S)if(b.toLowerCase()===I)return!0;return!1}const $e=/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/,je=/^0+$/;function readTraceContextFromHeaders(S){return function parseTraceparent(S){if("string"!=typeof S)return null;const b=S.match($e);if(!b)return null;const I=b[1],x=b[2];return je.test(I)||je.test(x)?null:{traceId:I,spanId:x}}(function readTraceparentFromHeaders(S){if(!S)return null;if("undefined"!=typeof Headers&&S instanceof Headers){const b=S.get("traceparent");return"string"==typeof b?b:null}if("object"==typeof S)for(const b of Object.keys(S))if("traceparent"===b.toLowerCase()){const I=S[b];return"string"==typeof I?I:null}return null}(S))}function isSameOrigin(S,b,I){const x=function resolveOrigin(S,b){try{const I=b||"undefined"!=typeof window&&window.location&&window.location.href||void 0;return new URL(S,I).origin}catch{return null}}(S,I),R=function currentOrigin(S){return S||("undefined"!=typeof window&&window.location?window.location.origin:null)}(b);return null!==x&&null!==R&&x===R}function tracePropagationDecision(S,b={}){const{pageOrigin:I,pageHref:x}=b;return"string"==typeof S&&isInternalSdkEndpoint(S)?{traceparent:!1,baggage:!1,reason:"sdk_ingest_excluded"}:isSameOrigin(S,I,x)?{traceparent:!0,baggage:!0,reason:"same_origin"}:{traceparent:!1,baggage:!1,reason:"third_party"}}const qe="undefined"!=typeof window&&window.fetch?window.fetch.bind(window):void 0;class FetchInterceptor extends BaseInterceptor{constructor(S){super(S,"fetch"),this.originalFetch=qe}setup(){this.logger.log("Initializing Fetch interceptor...");const S=this;window._apiReporter_originalFetch||(window._apiReporter_originalFetch=this.originalFetch),window.fetch=async function(...b){const I=(b=S.injectCorrelationHeaders(b))[0]instanceof Request?b[0].url:String(b[0]),x=b[1]||{},R=x.method||(b[0]instanceof Request?b[0].method:"GET"),A=x.body;let _={};b[0]instanceof Request?b[0].headers.forEach((S,b)=>{_[b]=S}):x.headers&&(x.headers instanceof Headers?x.headers.forEach((S,b)=>{_[b]=S}):Object.assign(_,x.headers));const D=filterSensitiveHeaders(_),L=S.shouldMonitor(I),B=S.isStaticResource(I);let U=null;L&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&(U=S.reporter.performanceMonitor.generateRequestId(),S.reporter.performanceMonitor.startTracking(U,I,R));const $=Date.now();if(!B){const b=S.getNetworkConfig(),x=S.isEndpointExcluded(I,b),L=S.sanitizeRequestUrlFields(I,b),B=getHeader(_,"content-type"),U=S.buildRequestBodyFields(A,B,b,x),j={interceptor:"fetch",method:R,url:L.url,requestHeaders:b.captureRequestHeaders?D:{},timestamp:$,...U};L.path&&(j.requestPath=L.path),L.query&&(j.requestQuery=L.query);const W=readTraceContextFromHeaders(_);W&&(j.traceId=W.traceId,j.spanId=W.spanId),S.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing API request:",{url:L.url,hasHeaders:!!D&&Object.keys(D).length>0,bodyState:U.requestBodyState}),S.addToSessionReplay("network_request",j)}try{const x=await S.originalFetch.apply(window,b);let A=null;return U&&(A=S.reporter.performanceMonitor.endTracking(U,x.status)),await S.handleResponse(x,I,R,A),x}catch(b){throw U&&S.reporter.performanceMonitor.endTracking(U,0),S.handleNetworkError(I,R,b,"fetch_network_error"),b}},this.logger.log("Fetch interceptor setup complete")}async handleResponse(S,b,I,x){const R=this.getNetworkConfig(),A=this.isEndpointExcluded(b,R);let _=null,D=!1;try{_=S.clone()}catch{D=!0}const L="opaque"===S.type,B=_&&_.headers&&_.headers.get("content-type")||"",U={};_&&_.headers&&_.headers.forEach((S,b)=>{U[b]=S});const $=R.captureResponseHeaders?filterSensitiveHeaders(U):{},j=_&&_.headers?_.headers.get("content-length"):null,W=j?parseInt(j,10):null;let H=null,V=!1,Q=null;const G=!L&&!D&&isTextualContentType(B);if(G){try{H=await _.text()}catch{V=!0}if(!V&&null!=H){const S=safeMime(B);if(S&&"json"===classifyMime(S))try{Q=JSON.parse(H)}catch{Q=H}else Q=H}}else D&&!L&&(V=!0);const J=this.buildResponseBodyFields({opaque:L,readError:V,text:G?H:null,contentTypeHeader:B,knownSize:W},R,A),X=this.isStaticResource(b,B);!X&&x?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,Q,x),x?.performanceAlert&&this.logPerformanceAlert(x.metrics),X?this.handleStaticResource(b,I,S.status,S.statusText,B,x,_||S):this.handleApiResponse(b,I,S.status,S.statusText,Q,x,$,J,R)}handleStaticResource(S,b,I,x,R,A,_){const D=_.headers?.get("content-length"),L=D?parseInt(D,10):null,B={interceptor:"fetch",method:b,url:S,status:I,statusText:x,resourceType:this.getResourceType(S,R),size:L,duration:A?.duration||null,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing static resource:",{url:S,status:I,resourceType:B.resourceType,size:L}),this.addToSessionReplay("network_resource",B),I>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(S,b,I,x,null,null,{errorType:"resource_load_error",contentType:R,resourceType:B.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"fetch",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing response:",{url:U.url,status:I,hasHeaders:!!_&&Object.keys(_).length>0,bodyState:$.responseBodyState}),this.addToSessionReplay("network_response",$),I>=400?this.logErrorEvent(S,b,I,x,null,R,{errorType:"fetch_http_error",performanceData:A}):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"fetch_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"fetch_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logger.log(`Slow request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"fetch",method:b,url:R.url,status:0,statusText:"Network Error",errorMessage:I.message||"Network request failed",errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,"Network Error",null,null,{errorType:x,errorMessage:I.message||"Network request failed",errorStack:I.stack})}destroy(){window._apiReporter_originalFetch&&(window.fetch=window._apiReporter_originalFetch,delete window._apiReporter_originalFetch),super.destroy()}injectCorrelationHeaders(S){const b=SDKContext.getInstance();if(!b||!b.sessionId)return S;const I=tracePropagationDecision(S[0]instanceof Request?S[0].url:String(S[0]));if(!I.traceparent&&!I.baggage)return S;const x=[];if(I.baggage&&(b.sessionId&&x.push(`sessionId=${encodeURIComponent(b.sessionId)}`),b.userId&&x.push(`userId=${encodeURIComponent(b.userId)}`),b.projectId&&x.push(`projectId=${encodeURIComponent(b.projectId)}`)),S[0]instanceof Request){const b=S[0],R=S[1]||{},A=new Headers(b.headers);if(R.headers)if(R.headers instanceof Headers)R.headers.forEach((S,b)=>A.set(b,S));else for(const S in R.headers)A.set(S,R.headers[S]);const _=hasHeader(A,"traceparent");I.baggage&&x.length>0&&!getHeader(A,"baggage")&&setHeader(A,"baggage",x.join(",")),I.traceparent&&!_&&setHeader(A,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`);const D={...R};delete D.headers;return[new Request(b,{...D,headers:A})]}const R=S[0],A=S[1]||{};if(A.headers=A.headers||{},A.headers instanceof Headers){const S={};A.headers.forEach((b,I)=>{S[I]=b}),A.headers=S}const _=hasHeader(A.headers,"traceparent");return I.baggage&&x.length>0&&!getHeader(A.headers,"baggage")&&setHeader(A.headers,"baggage",x.join(",")),I.traceparent&&!_&&setHeader(A.headers,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`),[R,A]}generateW3CTraceId(){const S=new Uint8Array(16);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=new Uint8Array(8);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}}class XHRInterceptor extends BaseInterceptor{constructor(S){super(S,"xhr"),this.originalOpen=XMLHttpRequest.prototype.open,this.originalSend=XMLHttpRequest.prototype.send}setup(){this.logger.log("Initializing XHR interceptor...");const S=this;XMLHttpRequest.prototype.open=function(b,I,...x){return this._apiReporterUrl=I,this._apiReporterMethod=b.toUpperCase(),this._apiReporterRequestHeaders={},this._apiReporterUserSetHeaders=new Set,this._apiReporterHeadersInjected=!1,S.originalOpen.call(this,b,I,...x)};const b=XMLHttpRequest.prototype.setRequestHeader;XMLHttpRequest.prototype.setRequestHeader=function(S,I){return this._apiReporterRequestHeaders||(this._apiReporterRequestHeaders={}),this._apiReporterUserSetHeaders||(this._apiReporterUserSetHeaders=new Set),this._apiReporterUserSetHeaders.add(S.toLowerCase()),setHeader(this._apiReporterRequestHeaders,S,I),b.call(this,S,I)},XMLHttpRequest.prototype.send=function(...b){const I=this;if(!I._apiReporterHeadersInjected){const b=I._apiReporterUserSetHeaders?.has("traceparent");S.injectXHRCorrelationHeaders(I,b),I._apiReporterHeadersInjected=!0}const{_apiReporterUrl:x,_apiReporterMethod:R,_apiReporterRequestHeaders:A}=I,_=filterSensitiveHeaders(A||{}),D=S.shouldMonitor(x),L=S.isStaticResource(x),B=b[0],U=Date.now();I._apiReporterStartTime=U,S.logger.log(`XHR Request: ${R} ${x}, shouldMonitor: ${D}, isResource: ${L}`);let $=null;if(D&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&($=S.reporter.performanceMonitor.generateRequestId(),I._apiReporterRequestId=$,S.reporter.performanceMonitor.startTracking($,x,R)),!L){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(x,b),D=S.sanitizeRequestUrlFields(x,b),L=getHeader(A||{},"content-type"),$=S.buildRequestBodyFields(B,L,b,I),j={interceptor:"xhr",method:R,url:D.url,requestHeaders:b.captureRequestHeaders&&_||{},timestamp:U,...$};D.path&&(j.requestPath=D.path),D.query&&(j.requestQuery=D.query);const W=readTraceContextFromHeaders(A);W&&(j.traceId=W.traceId,j.spanId=W.spanId),S.addToSessionReplay("network_request",j)}return I.addEventListener("load",()=>S.handleXHRLoad(I,x,R,L)),I.addEventListener("error",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Network error"),"xhr_network_error")}),I.addEventListener("timeout",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request timed out"),"xhr_timeout_error")}),I.addEventListener("abort",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request aborted"),"xhr_aborted_error")}),S.originalSend.apply(I,b)},this.logger.log("XHR interceptor setup complete")}handleXHRLoad(S,b,I,x){let R=null;S._apiReporterRequestId&&(R=this.reporter.performanceMonitor.endTracking(S._apiReporterRequestId,S.status));const A=S.getResponseHeader("content-type")||"",_=R?.duration||(S._apiReporterStartTime?Date.now()-S._apiReporterStartTime:null);if(x)return void this.handleStaticResource(S,b,I,A,_);const D=this.getNetworkConfig(),L=this.isEndpointExcluded(b,D);let B=null,U=null;try{const b=S.responseType;if(""===b||"text"===b){const b=S.responseText||null;if(B={text:b,contentTypeHeader:A},b){const S=safeMime(A);if(S&&"json"===classifyMime(S))try{U=JSON.parse(b)}catch{U=b}else U=b}}else if("json"===b){const b=S.response;U=b;let I=null;try{I=null==b?null:JSON.stringify(b)}catch{I=null}B={text:I,contentTypeHeader:A||"application/json"}}else{const I=S.getResponseHeader("content-length");B={binary:!0,contentTypeHeader:A,knownSize:I?parseInt(I,10):null},U=`[${String(b).toUpperCase()} data]`}}catch(S){this.logger.warn(`Failed to read XHR response for ${b}`),B={readError:!0,contentTypeHeader:A},U={error:"Failed to read response",originalError:S.message}}const $=this.parseXHRResponseHeaders(S.getAllResponseHeaders?.()),j=D.captureResponseHeaders?filterSensitiveHeaders($):{},W=this.buildResponseBodyFields(B,D,L);R?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,U,R),R?.performanceAlert&&this.logPerformanceAlert(R.metrics),this.handleApiResponse(b,I,S.status,S.statusText,U,R,j,W,D)}parseXHRResponseHeaders(S){const b={};if(!S||"string"!=typeof S)return b;for(const I of S.trim().split(/[\r\n]+/)){const S=I.indexOf(":");if(-1===S)continue;const x=I.slice(0,S).trim(),R=I.slice(S+1).trim();x&&(b[x]=R)}return b}handleStaticResource(S,b,I,x,R){const A=S.getResponseHeader("content-length"),_=A?parseInt(A,10):null,D={interceptor:"xhr",method:I,url:b,status:S.status,statusText:S.statusText,resourceType:this.getResourceType(b,x),size:_,duration:R,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[XHRInterceptor] Capturing static resource:",{url:b,status:S.status,resourceType:D.resourceType,size:_}),this.addToSessionReplay("network_resource",D),S.status>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(b,I,S.status,S.statusText,null,null,{errorType:"resource_load_error",contentType:x,resourceType:D.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){this.logger.log(`Handling API response: ${b} ${S}, status: ${I}`);const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"xhr",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.addToSessionReplay("network_response",$),I>=400?(this.logger.log(`Logging error event for: ${S} with status ${I}`),this.logErrorEvent(S,b,I,x,null,R,{errorType:"xhr_http_error",performanceData:A})):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"xhr_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"xhr_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logger.log(`Slow XHR request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"xhr",method:b,url:R.url,status:0,statusText:I.message||"Network Error",errorMessage:I.message,errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,I.message,null,null,{errorType:x,errorMessage:I.message,errorStack:I.stack})}destroy(){XMLHttpRequest.prototype.open=this.originalOpen,XMLHttpRequest.prototype.send=this.originalSend,super.destroy()}injectXHRCorrelationHeaders(S,b){const I=SDKContext.getInstance();if(!I||!I.sessionId)return;const x=tracePropagationDecision(String(S._apiReporterUrl||""));if(x.traceparent||x.baggage){if(x.baggage&&!getHeader(S._apiReporterRequestHeaders,"baggage")){const b=[];I.sessionId&&b.push(`sessionId=${encodeURIComponent(I.sessionId)}`),I.userId&&b.push(`userId=${encodeURIComponent(I.userId)}`),I.projectId&&b.push(`projectId=${encodeURIComponent(I.projectId)}`),b.length>0&&S.setRequestHeader("baggage",b.join(","))}if(x.traceparent&&!b){const b=`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`;S.setRequestHeader("traceparent",b)}}}generateW3CTraceId(){const S=new Uint8Array(16);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=new Uint8Array(8);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}}const We=["token","access_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","password","pwd","secret","email","jwt","bearer","refresh_token","id_token"];class LRUDedupeCache{constructor(S=5e3){this.maxSize=S,this.cache=new Map}has(S){if(this.cache.has(S)){const b=this.cache.get(S);return this.cache.delete(S),this.cache.set(S,b),!0}return!1}add(S){if(this.cache.has(S))this.cache.delete(S);else if(this.cache.size>=this.maxSize){const S=this.cache.keys().next().value;this.cache.delete(S)}this.cache.set(S,!0)}clear(){this.cache.clear()}get size(){return this.cache.size}}class PerformanceResourceObserver{constructor(S,b={}){this.reporter=S,this.logger=createLogger("PerformanceResourceObserver"),this.config={captureResources:!1!==b.captureResources,captureNavigation:!1!==b.captureNavigation,maxDedupeEntries:b.maxDedupeEntries||5e3,filterOtherInitiator:!1!==b.filterOtherInitiator,debug:b.debug||this.reporter?.config?.debug||!1,maxResourceEntriesPerSession:b.maxResourceEntriesPerSession||2e3,resourceAllowlist:b.resourceAllowlist||null,resourceBlocklist:b.resourceBlocklist||null},this.allowlistRegexes=this.compilePatterns(this.config.resourceAllowlist),this.blocklistRegexes=this.compilePatterns(this.config.resourceBlocklist),this.resourceObserver=null,this.navigationObserver=null,this.processedEntries=new LRUDedupeCache(this.config.maxDedupeEntries),this.isDestroyed=!1,this.sessionResourceCount=0,this.sessionCapReached=!1,this.eventCount=0,this.eventCountResetTime=Date.now(),this.maxEventsPerMinute=this.reporter?.config?.maxEventsPerMinute||500}compilePatterns(S){if(!S||!Array.isArray(S)||0===S.length)return null;try{return S.map(S=>new RegExp(S,"i"))}catch(S){return this.logger?.warn?.("Invalid regex pattern in allowlist/blocklist:",S.message),null}}passesUrlFilters(S){if(this.blocklistRegexes)for(const b of this.blocklistRegexes)if(b.test(S))return!1;if(this.allowlistRegexes){for(const b of this.allowlistRegexes)if(b.test(S))return!0;return!1}return!0}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed PerformanceResourceObserver"):"undefined"!=typeof PerformanceObserver?(this.config.captureResources&&this.setupResourceObserver(),this.config.captureNavigation&&this.setupNavigationObserver(),this.logger.log("PerformanceResourceObserver setup complete",{captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation})):this.logger.warn("PerformanceObserver not supported in this browser")}setupResourceObserver(){try{this.resourceObserver=new PerformanceObserver(S=>{for(const b of S.getEntries())this.processResourceEntry(b)}),this.resourceObserver.observe({type:"resource",buffered:!0}),this.logger.log("Resource observer initialized")}catch(S){this.logger.warn("Failed to setup resource observer:",S.message)}}setupNavigationObserver(){try{this.navigationObserver=new PerformanceObserver(S=>{for(const b of S.getEntries())this.processNavigationEntry(b)}),this.navigationObserver.observe({type:"navigation",buffered:!0}),this.logger.log("Navigation observer initialized")}catch(S){this.logger.warn("Failed to setup navigation observer:",S.message)}}processResourceEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(this.sessionResourceCount>=this.config.maxResourceEntriesPerSession)return void(this.sessionCapReached||(this.sessionCapReached=!0,this.logger.warn(`Session resource cap reached (${this.config.maxResourceEntriesPerSession}). Stopping resource capture.`)));if(!this.checkRateLimit())return;const b=S.initiatorType;if("fetch"===b||"xmlhttprequest"===b)return;if(this.config.filterOtherInitiator&&"other"===b){const b=(S.transferSize||S.encodedBodySize||S.decodedBodySize)>0,I=S.duration>10;if(!b&&!I)return}if(!this.passesUrlFilters(S.name))return;const I=`${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(I))return;this.processedEntries.add(I);const x=this.sanitizeUrl(S.name),R=this.mapInitiatorType(b,S.name),A=this.extractTimingPhases(S),_={interceptor:"performance",method:"GET",url:x,status:this.getResponseStatus(S),resourceType:R,initiatorType:b,duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:A,timestamp:Math.round(performance.timeOrigin+S.startTime)};this.addToSessionReplay("network_resource",_)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured resource:",{url:x.substring(0,80),type:R,duration:_.duration,cached:_.cached,sessionCount:this.sessionResourceCount})}processNavigationEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(!this.checkRateLimit())return;const b=`nav-${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(b))return;this.processedEntries.add(b);const I=this.sanitizeUrl(S.name),x=this.extractTimingPhases(S),R={dns:x.dns,tcp:x.tcp,ssl:x.ssl,ttfb:Math.round(S.responseStart-S.requestStart),download:Math.round(S.responseEnd-S.responseStart),domInteractive:Math.round(S.domInteractive-S.responseEnd),domContentLoaded:Math.round(S.domContentLoadedEventEnd-S.responseEnd),loadComplete:Math.round(S.loadEventEnd-S.startTime)},A={interceptor:"performance",method:"GET",url:I,status:this.getResponseStatus(S),resourceType:"document",initiatorType:"navigation",duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:R,navigationType:S.type,timestamp:Math.round(performance.timeOrigin+S.startTime)};this.addToSessionReplay("network_resource",A)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured navigation:",{url:I.substring(0,80),type:S.type,loadTime:R.loadComplete,sessionCount:this.sessionResourceCount})}sanitizeUrl(S){if(!S)return S;try{const b=new URL(S);for(const S of We){b.searchParams.has(S)&&b.searchParams.delete(S);for(const[I]of b.searchParams.entries())I.toLowerCase()===S.toLowerCase()&&b.searchParams.delete(I)}return b.hash="",b.toString()}catch(b){return S.length>500?S.substring(0,500):S}}mapInitiatorType(S,b=""){const I={script:"script",link:"stylesheet",css:"stylesheet",img:"image",image:"image",font:"font",video:"media",audio:"media",iframe:"document",navigation:"document",beacon:"beacon"};if(I[S]){if("link"===S){const S=b.toLowerCase();return S.includes(".css")?"stylesheet":S.includes(".woff")||S.includes(".ttf")||S.includes(".eot")?"font":"stylesheet"}return I[S]}return getResourceType(b,"")}extractTimingPhases(S){return{dns:Math.max(0,Math.round(S.domainLookupEnd-S.domainLookupStart)),tcp:Math.max(0,Math.round(S.connectEnd-S.connectStart)),ssl:S.secureConnectionStart>0?Math.max(0,Math.round(S.connectEnd-S.secureConnectionStart)):0,ttfb:Math.max(0,Math.round(S.responseStart-S.requestStart)),download:Math.max(0,Math.round(S.responseEnd-S.responseStart)),total:Math.round(S.duration)}}getResponseStatus(S){return"number"==typeof S.responseStatus?S.responseStatus:0===S.duration&&0===S.transferSize&&0===S.decodedBodySize?0:200}isCached(S){return 0===S.transferSize&&S.decodedBodySize>0||S.domainLookupEnd===S.domainLookupStart&&S.connectEnd===S.connectStart&&S.requestStart>0}checkRateLimit(){const S=Date.now();return S-this.eventCountResetTime>6e4&&(this.eventCount=0,this.eventCountResetTime=S),!(this.eventCount>=this.maxEventsPerMinute)&&(this.eventCount++,!0)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}updateConfig(S){void 0!==S.captureResources&&S.captureResources!==this.config.captureResources&&(this.config.captureResources=S.captureResources,S.captureResources&&!this.resourceObserver?this.setupResourceObserver():!S.captureResources&&this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null)),void 0!==S.captureNavigation&&S.captureNavigation!==this.config.captureNavigation&&(this.config.captureNavigation=S.captureNavigation,S.captureNavigation&&!this.navigationObserver?this.setupNavigationObserver():!S.captureNavigation&&this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null)),void 0!==S.debug&&(this.config.debug=S.debug),void 0!==S.maxDedupeEntries&&(this.config.maxDedupeEntries=S.maxDedupeEntries),void 0!==S.filterOtherInitiator&&(this.config.filterOtherInitiator=S.filterOtherInitiator)}getStats(){return{dedupeEntriesCount:this.processedEntries.size,maxDedupeEntries:this.config.maxDedupeEntries,eventsThisMinute:this.eventCount,maxEventsPerMinute:this.maxEventsPerMinute,captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation,resourceObserverActive:!!this.resourceObserver,navigationObserverActive:!!this.navigationObserver,sessionResourceCount:this.sessionResourceCount,maxResourceEntriesPerSession:this.config.maxResourceEntriesPerSession,sessionCapReached:this.sessionCapReached,hasAllowlist:!!this.allowlistRegexes,hasBlocklist:!!this.blocklistRegexes}}destroy(){this.isDestroyed?this.logger.warn("PerformanceResourceObserver already destroyed"):(this.isDestroyed=!0,this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null),this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null),this.processedEntries.clear(),this.reporter=null,this.logger.log("PerformanceResourceObserver destroyed"))}}class ErrorFingerprint{constructor(S={}){this.maxUniqueErrors=S.maxUniqueErrors||100,this.throttleWindow=S.throttleWindow||6e4,this.maxPerFingerprint=S.maxPerFingerprint||5,this.seenFingerprints=new Map,this.cleanupInterval=null,this.startCleanup()}generateFingerprint(S){if(!S)return"unknown_error";return`${this.getErrorName(S)}::${this.normalizeMessage(this.getErrorMessage(S))}::${this.getFirstMeaningfulStackLine(S.stack)}`}getErrorName(S){return S.name?S.name:S.constructor&&S.constructor.name?S.constructor.name:S.type?S.type:"Error"}getErrorMessage(S){return"string"==typeof S?S:S.message?S.message:S.reason?String(S.reason):String(S)}normalizeMessage(S){return S&&"string"==typeof S?S.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"[UUID]").replace(/\b(0x)?[0-9a-f]{8,}\b/gi,"[HEX]").replace(/\b\d+\b/g,"[N]").replace(/https?:\/\/[^\s'"]+/gi,"[URL]").replace(/\/[\w./-]+\.(js|ts|jsx|tsx|mjs|cjs)/gi,"[PATH]").replace(/"[^"]*"/g,"[STR]").replace(/'[^']*'/g,"[STR]").replace(/[\w.+-]+@[\w.-]+\.\w+/gi,"[EMAIL]").replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,"[IP]").replace(/\s+/g," ").substring(0,200).trim():""}getFirstMeaningfulStackLine(S){if(!S||"string"!=typeof S)return"unknown";const b=[/tracescout/i,/rrweb/i,/node_modules/,/<anonymous>/,/native code/i,/eval at/i,/^\s*at\s*$/],I=S.split("\n");for(const S of I){if(!S.trim()||S.match(/^[\w]*Error:/))continue;if(b.some(b=>b.test(S)))continue;const I=S.match(/(?:at\s+)?(?:[\w.<>[\]]+\s+\()?([^()\s]+):(\d+):(\d+)\)?/);if(I){const[,S,b,x]=I;return`${S.split("/").pop().split("\\").pop()}:${b}:${x}`}const x=S.match(/@([^@]+):(\d+):(\d+)/);if(x){const[,S,b,I]=x;return`${S.split("/").pop().split("\\").pop()}:${b}:${I}`}}return"unknown"}shouldCapture(S){const b=Date.now(),I=this.seenFingerprints.get(S);if(!I)return this.seenFingerprints.set(S,{count:1,firstSeen:b,lastSeen:b,windowStart:b}),this.seenFingerprints.size>this.maxUniqueErrors&&this.evictOldest(),{shouldCapture:!0,count:1,isFirst:!0};if(b-I.windowStart>this.throttleWindow)return I.count=1,I.windowStart=b,I.lastSeen=b,{shouldCapture:!0,count:1,isFirst:!1};I.count++,I.lastSeen=b;const x=I.count<=this.maxPerFingerprint;return{shouldCapture:x,count:I.count,isFirst:!1,throttled:!x}}getStats(S){return this.seenFingerprints.get(S)||null}getAllStats(){const S=[];return this.seenFingerprints.forEach((b,I)=>{S.push({fingerprint:I,...b})}),S.sort((S,b)=>b.count-S.count)}evictOldest(){let S=null,b=1/0;this.seenFingerprints.forEach((I,x)=>{I.lastSeen<b&&(b=I.lastSeen,S=x)}),S&&this.seenFingerprints.delete(S)}startCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanup()},3e5)}cleanup(){const S=Date.now(),b=2*this.throttleWindow;this.seenFingerprints.forEach((I,x)=>{S-I.lastSeen>b&&this.seenFingerprints.delete(x)})}reset(){this.seenFingerprints.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.seenFingerprints.clear()}}class ErrorHandler{constructor(S,b={},I=null){this.eventManager=S,this.reporter=I,this.config={captureErrors:!1!==b.captureErrors,captureUnhandledRejections:!1!==b.captureUnhandledRejections,maxStackTraceLength:b.maxStackTraceLength||5e3,filterErrors:b.filterErrors||[],enableFingerprinting:!1!==b.enableFingerprinting,maxUniqueErrors:b.maxUniqueErrors||100,throttleWindow:b.throttleWindow||6e4,maxPerFingerprint:b.maxPerFingerprint||5,...b},this.logger=createLogger("ErrorHandler"),this.originalHandlers={},this.installed=!1,this.config.enableFingerprinting&&(this.fingerprinter=new ErrorFingerprint({maxUniqueErrors:this.config.maxUniqueErrors,throttleWindow:this.config.throttleWindow,maxPerFingerprint:this.config.maxPerFingerprint}))}install(){this.installed||(this.config.captureErrors&&(this.originalHandlers.onerror=window.onerror,window.onerror=this.handleError.bind(this)),this.config.captureUnhandledRejections&&(this.originalHandlers.onunhandledrejection=window.onunhandledrejection,window.addEventListener("unhandledrejection",this.handleUnhandledRejection.bind(this))),this.installed=!0,this.logger.debug("Error handler installed"))}uninstall(){this.installed&&(this.originalHandlers.onerror&&(window.onerror=this.originalHandlers.onerror),this.originalHandlers.onunhandledrejection&&(window.removeEventListener("unhandledrejection",this.handleUnhandledRejection),this.originalHandlers.onunhandledrejection&&(window.onunhandledrejection=this.originalHandlers.onunhandledrejection)),this.fingerprinter&&this.fingerprinter.destroy(),this.originalHandlers={},this.installed=!1,this.logger.debug("Error handler uninstalled"))}handleError(S,b,I,x,R){try{if(this.shouldFilterError(S,R))return;let A=null,_=null;if(this.fingerprinter&&(A=this.fingerprinter.generateFingerprint(R||{message:S,stack:`at ${b}:${I}:${x}`}),_=this.fingerprinter.shouldCapture(A),!_.shouldCapture))return _.count===this.config.maxPerFingerprint+1&&this.logger.debug(`Error throttled: "${S.substring(0,50)}..." (${_.count} occurrences)`),this.originalHandlers.onerror?this.originalHandlers.onerror(S,b,I,x,R):void 0;SDKContext.getInstance()?.recordError();const D={type:"error",category:"error",message:String(S),source:b,lineno:I,colno:x,stack:this.getStackTrace(R),timestamp:Date.now(),userAgent:navigator.userAgent,url:window.location.href,fingerprint:A,occurrenceCount:_?.count||1,isFirstOccurrence:_?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",D),console.log("[TraceScout][ErrorHandler] Checking reporter:",{hasReporter:!!this.reporter,hasMethod:!(!this.reporter||!this.reporter.addSessionCustomEvent),isFunction:!(!this.reporter||"function"!=typeof this.reporter.addSessionCustomEvent)}),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{console.log("[TraceScout][ErrorHandler] Adding error to session replay:",D.message),this.reporter.addSessionCustomEvent("error",{message:D.message,stack:D.stack,fingerprint:D.fingerprint,source:D.source,lineno:D.lineno,colno:D.colno,timestamp:D.timestamp,url:D.url,userAgent:D.userAgent,occurrenceCount:D.occurrenceCount,isFirstOccurrence:D.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture error:",S)}if(this.originalHandlers.onerror)return this.originalHandlers.onerror(S,b,I,x,R)}handleUnhandledRejection(S){try{const b=S.reason;let I=null,x=null;if(this.fingerprinter&&(I=this.fingerprinter.generateFingerprint(b||{message:"Unhandled Promise Rejection"}),x=this.fingerprinter.shouldCapture(I),!x.shouldCapture)){if(x.count===this.config.maxPerFingerprint+1){const S=b?String(b).substring(0,50):"Promise rejection";this.logger.debug(`Promise rejection throttled: "${S}..." (${x.count} occurrences)`)}return void(this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S))}SDKContext.getInstance()?.recordError();const R={type:"unhandledRejection",category:"error",message:b?String(b):"Unhandled Promise Rejection",stack:this.getStackTrace(b),promiseState:"rejected",timestamp:Date.now(),userAgent:navigator.userAgent,url:window.location.href,fingerprint:I,occurrenceCount:x?.count||1,isFirstOccurrence:x?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",R),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{this.reporter.addSessionCustomEvent("unhandledRejection",{message:R.message,stack:R.stack,fingerprint:R.fingerprint,timestamp:R.timestamp,url:R.url,userAgent:R.userAgent,occurrenceCount:R.occurrenceCount,isFirstOccurrence:R.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture unhandled rejection:",S)}this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S)}shouldFilterError(S,b){return this.config.filterErrors.some(I=>"string"==typeof I?S.includes(I):I instanceof RegExp?I.test(S):"function"==typeof I&&I(S,b))}getStackTrace(S){if(!S)return"";let b="";return S.stack?b=S.stack:S instanceof Error&&(b=S.toString()),b.length>this.config.maxStackTraceLength&&(b=b.substring(0,this.config.maxStackTraceLength)+"..."),b}getErrorStats(){return this.fingerprinter?this.fingerprinter.getAllStats():[]}resetErrorTracking(){this.fingerprinter&&this.fingerprinter.reset()}}class PostMessageInterceptor{constructor(S){this.reporter=S,this.logger=createLogger("PostMessageInterceptor"),this.originalPostMessage=window.postMessage,this.boundMessageHandler=this.handleMessage.bind(this),this.messageCounter=0,this.suspiciousOrigins=[],this.errorCount=0,this.isDestroyed=!1,this.config=null,this.whitelist=[]}setup(){if(this.isDestroyed)return void this.logger.warn("Attempted to setup destroyed PostMessageMonitor");this.logger.log("Initializing PostMessage monitor...");const S=this;this.config=this.reporter.config?.monitorPostMessages||{},this.whitelist=this.config.postMessageOriginWhitelist||[],window.postMessage=function(b,I,...x){const R=window.location.origin;if(S.shouldMonitor(I,"outgoing",b)){const x=S.getEventType(b);S.logger.log(`Outgoing PostMessage [${x}]: ${R} -> ${I}`),S.logPostMessage({direction:"outgoing",message:b,targetOrigin:I,sourceOrigin:R,eventType:x})}return S.originalPostMessage.call(this,b,I,...x)},window.addEventListener("message",this.boundMessageHandler),this.logger.log("PostMessage monitor setup complete")}handleMessage(S){if(!this.isDestroyed)try{if(this.shouldMonitor(S.origin,"incoming",S.data)){const b=this.getEventType(S.data);this.logger.log(`Incoming PostMessage [${b}]: ${S.origin} -> ${window.location.origin}`),this.logPostMessage({direction:"incoming",message:S.data,sourceOrigin:S.origin,targetOrigin:window.location.origin,source:this.getSourceInfo(S.source),eventType:b}),this.shouldExtractFields("postmessage","message")&&this.extractUserData(S.origin,S.data)}}catch(b){this.logger.error("Error handling message:",b),this.logPostMessageError(S,b)}}shouldMonitor(S,b,I){if(!this.config||"object"!=typeof this.config)return!1;if(this.whitelist.length>0&&!this.isOriginWhitelisted(S))return!1;const x=this.getEventType(I),R=(this.config.excludePostMessagesEvents||[]).includes(x),A=this.config.monitorSpecificPostMessagesEvents||[];return!R&&(0===A.length||A.includes(x))}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isOriginWhitelisted(S){if(this.whitelist.includes("*"))return!0;if("null"===S&&this.whitelist.includes("null"))return!0;try{const b=new URL(S).hostname.toLowerCase();return this.whitelist.some(I=>{const x=I.toLowerCase();return x.includes("://")?S.toLowerCase()===x:b===x||b.endsWith(`.${x}`)})}catch{return this.whitelist.includes(S)}}getEventType(S){if(null==S)return"null_message";let b=S;if("string"==typeof S)try{b=JSON.parse(S)}catch{return"string_message"}if("object"!=typeof b)return typeof b+"_message";const I=["event_type","type","action","event","command","method"];for(const S of I)if(b[S])return String(b[S]);return!0===b.init?"init":!0===b.ready?"ready":b.resize?"resize":void 0!==b.height?"height_update":"object_message"}getSourceInfo(S){try{return S===window?"same-window":S===window.parent?"parent-window":S===window.opener?"opener-window":S===window.top?"top-window":S instanceof Window?"other-window":S instanceof MessagePort?"message-port":S instanceof ServiceWorker?"service-worker":"unknown-source"}catch{return"unknown-source"}}logPostMessage(S){const b=this.parseMessage(S.message),I=S.sourceOrigin!==S.targetOrigin,x=this.getSize(S.message),R=x>1e4,A=this.isSuspiciousOrigin(S.sourceOrigin);let _="postmessage_communication";I&&(_="postmessage_cross_origin"),R&&(_="postmessage_large_payload"),A&&(_="postmessage_suspicious_origin",this.trackSuspiciousOrigin(S.sourceOrigin));const D={type:_,request:{method:"POSTMESSAGE",url:"outgoing"===S.direction?S.targetOrigin:S.sourceOrigin,domain:this.getDomain("outgoing"===S.direction?S.targetOrigin:S.sourceOrigin),path:null,status:null,statusText:null,response:b,interceptor:"postMessage"},extraData:{messageId:`pm_${S.direction}_${Date.now()}_${++this.messageCounter}`,direction:S.direction,sourceOrigin:S.sourceOrigin,targetOrigin:S.targetOrigin,messageSize:x,messageType:typeof S.message,detectedEventType:S.eventType,source:S.source||"unknown",isCrossOrigin:I,isLargePayload:R,isSuspicious:A,hasTransferables:S.transferables?.length>0||!1},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(D)}logPostMessageError(S,b){const I={type:"postmessage_error",request:{method:"POSTMESSAGE",url:S?.origin||"unknown",domain:this.getDomain(S?.origin||"unknown"),path:null,status:0,statusText:"PostMessage Error",response:{error:b.message,stack:b.stack},interceptor:"postMessage"},extraData:{errorCount:++this.errorCount,sourceOrigin:S?.origin||"unknown",targetOrigin:window.location.origin,errorType:b.name||"Error",errorMessage:b.message,errorStack:b.stack},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(I)}logEvent(S){this.reporter&&this.reporter.logEvent?this.reporter.logEvent(S):this.logger.error("Could not log event - reporter.logEvent not available")}parseMessage(S){if("string"==typeof S)try{return JSON.parse(S)}catch{return S.length>1e3?S.substring(0,1e3)+"...":S}try{return JSON.stringify(S),S}catch{return"[Circular or Complex Object]"}}getSize(S){try{return"string"==typeof S?S.length:JSON.stringify(S).length}catch{return-1}}getDomain(S){try{return"*"===S||"null"===S||"file://"===S?S:new URL(S).hostname}catch{return"unknown"}}isSuspiciousOrigin(S){if(!S||"null"===S||"file://"===S)return!0;if(this.whitelist.length>0&&!this.whitelist.includes("*")&&!this.isOriginWhitelisted(S))return!0;if("https:"===window.location.protocol&&"https://localhost"!==S&&!S.startsWith("https://"))return!0;const b=this.suspiciousOrigins.filter(b=>b===S).length;return b>100}trackSuspiciousOrigin(S){this.suspiciousOrigins.push(S),this.suspiciousOrigins.length>1e3&&(this.suspiciousOrigins=this.suspiciousOrigins.slice(-1e3))}extractUserData(S,b){try{const I=this.parseMessage(b);I&&"object"==typeof I&&this.reporter.updateUserProfileFromContext&&this.reporter.updateUserProfileFromContext({url:`postmessage://${S}`,source:"message",data:I})}catch(S){this.logger.warn("Failed to extract user data:",S)}}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}destroy(){this.isDestroyed?this.logger.warn("PostMessageMonitor already destroyed"):(this.isDestroyed=!0,this.originalPostMessage&&(window.postMessage=this.originalPostMessage),window.removeEventListener("message",this.boundMessageHandler),this.reporter=null,this.boundMessageHandler=null,this.suspiciousOrigins=[],this.logger.log("PostMessage monitor destroyed"))}}class InterceptorFeature{#o=null;#O=null;#Ee=null;#xe=null;#Me=null;#P=!1;constructor({logger:S,config:b,monitoringCore:I,eventManager:x}){this.#o=S,this.#O=b,this.#Ee=I,this.#xe=x}initialize(S,b=null){try{this.#Me={};return S&&S.isRecording?(console.log("[TraceScout] 🔌 Setting up session recording interceptors bundle..."),this.#Re(),this.#Te(),this.#Ae(),this.#_e(b),this.#Oe(),this.#De(),console.log("[TraceScout] ✅ Session recording bundle complete (DOM + Network + Console + Errors)"),this.#o?.log("Interceptors setup complete"),this.#P=!0,!0):(console.log("[TraceScout] ⏭️ Interceptors skipped (bundled with session recording - not active)"),!1)}catch(S){return this.#o?.error("Failed to setup interceptors:",S),!1}}#Re(){console.log("[TraceScout] 📡 Setting up FetchInterceptor..."),this.#Me.fetch=new FetchInterceptor(this.#Ee),this.#Me.fetch.setup?.()||this.#Me.fetch.install?.(),console.log("[TraceScout] ✅ FetchInterceptor active")}#Te(){console.log("[TraceScout] 📡 Setting up XHRInterceptor..."),this.#Me.xhr=new XHRInterceptor(this.#Ee),this.#Me.xhr.setup?.()||this.#Me.xhr.install?.(),console.log("[TraceScout] ✅ XHRInterceptor active")}#Ae(){const S=!1!==this.#O?.captureResources,b=!1!==this.#O?.captureNavigation;if(S||b)try{console.log("[TraceScout] 📊 Setting up PerformanceResourceObserver...",{captureResources:S,captureNavigation:b,maxResourceEntriesPerSession:this.#O?.maxResourceEntriesPerSession||2e3}),this.#Me.performanceResource=new PerformanceResourceObserver(this.#Ee,{captureResources:S,captureNavigation:b,debug:this.#O?.debug||!1,maxDedupeEntries:this.#O?.maxDedupeEntries||5e3,filterOtherInitiator:!1!==this.#O?.filterOtherInitiator,maxResourceEntriesPerSession:this.#O?.maxResourceEntriesPerSession||2e3,resourceAllowlist:this.#O?.resourceAllowlist||null,resourceBlocklist:this.#O?.resourceBlocklist||null}),this.#Me.performanceResource.setup(),console.log("[TraceScout] ✅ PerformanceResourceObserver active")}catch(S){console.warn("[TraceScout] ⚠️ PerformanceResourceObserver setup failed:",S.message)}else console.log("[TraceScout] ⏭️ PerformanceResourceObserver disabled via config")}#_e(S){console.log("[TraceScout] 💬 Setting up ConsoleInterceptor..."),this.#Me.console=new ConsoleInterceptor(this.#xe,this.#O,this.#Ee),S&&this.#Me.console.setLogManager(S),this.#Me.console.install?.(),console.log("[TraceScout] ✅ ConsoleInterceptor active")}#Oe(){try{console.log("[TraceScout] 🚨 Setting up ErrorHandler..."),this.#Me.errors=new ErrorHandler(this.#xe,this.#O,this.#Ee),console.log("[TraceScout] ErrorHandler created, installing...",{hasInstall:"function"==typeof this.#Me.errors?.install,hasReporter:!!this.#Ee}),this.#Me.errors.install?.(),console.log("[TraceScout] ✅ ErrorHandler active")}catch(S){console.error("[TraceScout] ❌ ErrorHandler setup failed:",S)}}#De(){this.#O?.monitorPostMessages&&"object"==typeof this.#O.monitorPostMessages&&(this.#Me.postMessage=new PostMessageInterceptor(this.#Ee),this.#Me.postMessage.setup?.()||this.#Me.postMessage.install?.())}get isInitialized(){return this.#P}get interceptors(){return this.#Me}getInterceptor(S){return this.#Me?.[S]||null}updateDebugMode(S){this.#Me&&Object.values(this.#Me).forEach(b=>{b&&b.updateDebugMode&&b.updateDebugMode(S)})}destroy(){this.#Me&&(Object.values(this.#Me).forEach(S=>{S?.destroy?.()||S?.uninstall?.()}),this.#Me=null),this.#P=!1}}class EventLifecycleFeature{#o=null;#O=null;#Fe=null;#Ne=null;#Le=null;#Pe=null;#Be=null;#ze=null;#Ue=null;#$e=null;#P=!1;#je=!1;constructor({logger:S,config:b}){this.#o=S,this.#O=b}setCallbacks({onCustomApiError:S,onBeforeUnload:b,onUserActivity:I,onVisibilityChange:x}){this.#Be=S,this.#ze=b,this.#Ue=I,this.#$e=x}initialize(){try{return this.#Fe=this.#qe.bind(this),this.#Ne=this.#We.bind(this),this.#Le=this.#He.bind(this),this.#Pe=this.#Ve.bind(this),document.addEventListener("custom-api-error",this.#Fe),window.addEventListener("beforeunload",this.#Ne),document.addEventListener("click",this.#Le,{passive:!0,capture:!0}),document.addEventListener("keydown",this.#Le,{passive:!0,capture:!0}),document.addEventListener("scroll",this.#Le,{passive:!0,capture:!0}),document.addEventListener("visibilitychange",this.#Pe),this.#o?.log("Event listeners setup complete"),this.#P=!0,!0}catch(S){return this.#o?.error("Failed to setup event listeners:",S),!1}}#qe(S){this.#Be?.(S)}#We(S){this.#ze?.(S)}#He(){this.#je||this.#Ue?.()}#Ve(){this.#je||("visible"===document.visibilityState?this.#$e?.("visible"):this.#$e?.("hidden"))}get isInitialized(){return this.#P}setQuotaExceeded(S){this.#je=S,S&&this.#Qe()}#Qe(){this.#Le&&(document.removeEventListener("click",this.#Le,{capture:!0}),document.removeEventListener("keydown",this.#Le,{capture:!0}),document.removeEventListener("scroll",this.#Le,{capture:!0}),this.#Le=null),this.#Pe&&(document.removeEventListener("visibilitychange",this.#Pe),this.#Pe=null)}destroy(){try{document.removeEventListener("custom-api-error",this.#Fe),window.removeEventListener("beforeunload",this.#Ne),this.#Qe(),this.#Fe=null,this.#Ne=null,this.#P=!1}catch(S){this.#o?.error("Failed to cleanup event listeners:",S)}}}class TraceScoutMonitoringCore{#P=!1;#o=null;#Ke=null;#xe=null;#Ge=null;#Je=null;#Xe=null;#Ye=null;#_=null;#Ze=null;#et=null;#tt=null;#st=null;#Me=null;#rt=null;#nt=null;#it=null;#ot=null;#at=null;#lt=null;#ct=null;#ut=null;#ht=null;_consecutiveFailures=0;#je=!1;#dt=null;#gt=!1;static#pt=null;static#ft=!1;constructor(){this.config=R.defaults({retryIntervalMs:R.get(A,"RETRY_INTERVAL_MS",5e3),deduplicationWindowMs:R.get(A,"DEDUPLICATION_WINDOW_MS",3e4),maxQueueSize:R.get(A,"MAX_QUEUE_SIZE",1e3),maxRetries:R.get(A,"MAX_RETRIES",3),batchSize:R.get(A,"BATCH_SIZE",10),debug:!1,logPreflight:!1,logResourceErrors:!1},{}),this.#o=new Logger("[TraceScoutMonitoringCore]",this.config.debug),"function"!=typeof this.#o.debug&&(this.#o.debug=(...S)=>this.#o.info(...S));try{this.#Ke=new ConfigManager(this.config)}catch(S){this.#o.error("Failed to initialize ConfigManager:",S)}this.appContext={appVersion:"1.0.0",environment:"unknown"},"function"==typeof this.sendEvents&&(this.#ct=throttle$1(this.sendEvents.bind(this),1e3))}static setTransport(S){TraceScoutMonitoringCore.#ft?console.error("[TraceScout] setTransport() must be called before init()"):"object"==typeof S&&null!==S?"string"==typeof S.apiBaseUrl&&S.apiBaseUrl?TraceScoutMonitoringCore.#pt=S:console.error("[TraceScout] setTransport() requires a non-empty apiBaseUrl string"):console.error("[TraceScout] setTransport() requires an object with apiBaseUrl")}async init(S,b={}){if(this.#gt)return this.#o.warn("TraceScoutMonitoringCore already initialized"),{sampled:this.#dt??!1,sdkVersion:"2.0.0",projectId:"",environment:""};const I=validateConfig(S,b);if(!I.ok){return function surfaceConfigError(S,b){if(b)try{console.error("[TraceScout] init() refused — invalid arguments:",S)}catch{}}(I.keys?{code:I.code,keys:I.keys}:{code:I.code},b?.debug||!1),{sampled:!1,sdkVersion:"2.0.0",projectId:"",environment:""}}this.#gt=!0,TraceScoutMonitoringCore.#ft=!0;const x=TraceScoutMonitoringCore.#pt,R={projectId:I.projectId,environment:I.options.environment||"production",release:I.options.release,sourceName:I.options.sourceName??"web-client",debug:I.options.debug||!1,apiBaseUrl:x?.apiBaseUrl,...void 0!==I.options.network?{network:I.options.network}:{}},A=peekAnonymousId();if(this.#dt=shouldSampleSession(1,{anonymousId:A}),!this.#dt)return R.debug&&console.log("[TraceScout] Session not sampled — SDK will not instrument this page-load."),{sampled:!1,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment};try{R.debug&&(console.log("[TraceScout] ============================================"),console.log("[TraceScout] Initializing SDK v2.0..."),console.log("[TraceScout] ============================================"));const S=new InitializationPipeline(this.#o),I=await S.run(R);this.#Ye=I.sessionManager.sessionManager,this.#_=I.sdkContext,this.#Ze=I.remoteConfigService,this.config=I.config,this.#et=R,this.#xe=I.managers.eventManager,this.#Ge=I.managers.serviceManager,this.#Je=I.managers.userProfileManager,this.#Xe=I.managers.performanceMonitor,this.config.appName&&(this.appContext.appName=this.config.appName),I.serverConfig?.project?.name&&(this.appContext.appName=I.serverConfig.project.name),this.#o&&"function"==typeof this.#o.updateDebugMode&&this.#o.updateDebugMode(this.config.debug),this.#st=new LoggingFeature({logger:this.#o,sdkContext:this.#_,config:this.config}),this.#st.initialize(I.serverConfig),this.#st.configure(this.config);const x=I.serverConfig?.features?.performanceMonitoring?.enabled;x&&(this.#lt=new CoreWebVitalsMonitor(this.config),console.log("[TraceScout] ✓ Performance monitoring initialized")),this.#tt=new SessionRecordingFeature({logger:this.#o,sdkContext:this.#_,config:this.config,options:b}),this.#tt.setCallbacks({onChunkCreated:S=>this.#K(S),onSessionEnd:S=>this.#mt(S),onQuotaExceeded:S=>this.#yt(S),onSpaNavigation:(S,b,I)=>{this.#it?.recordNavigation(S,b,I)}});const A=await this.#tt.initialize(I.serverConfig,this.#Ze);if(this.#it=new PageviewManager({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getBaseContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#_.setPageviewManager(this.#it),this.#nt=new SessionLifecycleEmitter({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),readGuard:()=>this.#Ye?.getLifecycleGuard?.()??null,writeGuard:S=>this.#Ye?.setLifecycleGuard?.(S),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Ye&&(this.#Ye.onLifecycleEnd=({reason:S})=>{this.#nt?.emitEnd({reason:S})}),A&&this.#lt){const S=this.#it.getCurrentPageviewId(),b="undefined"!=typeof window&&"string"==typeof window.location?.href?window.location.href:"";b&&(this.#ot=new WebVitalsEmitter({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getBaseContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),initialPageviewId:S,initialUrl:b,debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#lt.addCallback?.((S,b)=>{this.#ot?.emit(S,b)}),this.#lt.metrics&&"function"==typeof this.#lt.metrics.forEach&&this.#lt.metrics.forEach(S=>{this.#ot?.emit(S.type,S)}))}if(A&&(this.#at=new TrackIdentifyEmitter({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getBaseContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}})),A){const S=!0===this.#Ye?.isResumedSession?.();this.#it.emitInitialPageView({isResumed:S})}return A&&this.#Ye&&!this.#Ye.isResumedSession?.()&&!this.#Ye.getLifecycleGuard?.()?.sessionStartEmitted&&this.#nt.emitStart({}),A?(this.#Me=new InterceptorFeature({logger:this.#o,config:this.config,monitoringCore:this,eventManager:this.#xe}),this.#Me.initialize(this.#tt.recorder,this.#st.logManager),console.log("[TraceScout] ✓ Session recording bundle initialized (DOM + Network + Console + Errors)")):console.log("[TraceScout] ⏭️ Skipping interceptors (bundled with session recording)"),this.#rt=new EventLifecycleFeature({logger:this.#o,config:this.config}),this.#rt.setCallbacks({onCustomApiError:S=>this.#qe(S),onBeforeUnload:S=>this.#We(S),onUserActivity:()=>this.#He(),onVisibilityChange:S=>this.#Ve(S)}),this.#rt.initialize(),this.#vt(),this.#xe&&this.#xe.loadFromLocal(),this.#Je&&this.#Je.ensureProfile(),this.#P=!0,this.#St(I.serverConfig),{sampled:!0,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment}}catch(S){throw console.error("[TraceScout] ❌ Initialization failed:",S),this.#o.error("Failed to initialize TraceScoutMonitoringCore:",S),S}}#St(S){console.log("[TraceScout] ============================================"),console.log("[TraceScout] ✅ SDK Initialized Successfully"),console.log("[TraceScout] ============================================"),console.log(` Workspace: ${S.workspace.name}`),console.log(` Project: ${S.project.name}`),console.log(` Session: ${this.#_.sessionId}`),console.log(` Environment: ${this.#_.environment}`),console.log(` Config Version: ${S.configVersion}`);const b=Object.keys(S.features||{}).filter(b=>S.features[b].enabled);console.log(` Features: ${b.join(", ")||"none"}`),console.log("[TraceScout] ============================================"),this.#o.info("TraceScoutMonitoringCore initialized successfully",{configSource:"server",configVersion:S.configVersion,workspace:S.workspace.name,project:S.project.name,sessionId:this.#_.sessionId})}#wt(S,b){try{const I=Object.keys(b.features||{}).filter(S=>b.features[S].enabled);S({sessionId:this.#_.sessionId,workspace:b.workspace.name,project:b.project.name,environment:this.#_.environment,featuresEnabled:I,configVersion:b.configVersion})}catch(S){this.#o.error("Error in onReady callback:",S)}}#K(S){this.#Ye&&(this.#Ye.incrementChunkCount(),this.#Ye.incrementEventCount(S.eventCount||0))}#mt(S){if(!S||"object"!=typeof S)return;const b=mapInternalEndReason(S.reason);b&&this.#nt?.emitEnd({reason:b,totalChunks:"number"==typeof S.totalChunks?S.totalChunks:void 0,totalEvents:"number"==typeof S.totalEvents?S.totalEvents:void 0})}#qe(S){}#We(S){}#He(){this.#je||this.#tt?.sessionEnded&&!this.#tt?.isRecording&&(console.log("[TraceScout] 🔄 User activity detected after session end - starting new session"),this.forceNewSession("activity_after_"+this.#tt.sessionEndReason))}#Ve(S){this.#je||"visible"===S&&this.#tt?.sessionEnded&&!this.#tt?.isRecording&&(console.log("[TraceScout] 🔄 Tab visible after session end - starting new session"),this.forceNewSession("tab_focus_after_"+this.#tt.sessionEndReason))}#yt(S){this.#je||(this.#je=!0,console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been permanently stopped.","color: #ff4444;"),console.error("%c[TraceScout] Your workspace has reached its monthly session limit.","color: #ff4444;"),S?.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions (${S.usage.percentage}%)`,"color: #ff4444;"),console.error("%c[TraceScout] To continue recording, upgrade your plan at: /billing","color: #ff4444;"),this.#rt?.setQuotaExceeded(!0),this.#tt?.stop(),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:recording_stopped",{detail:{reason:"quota_exceeded",usage:S?.usage,message:S?.message||"Session quota exceeded"}})))}#vt(){"development"===this.config.environment||this.config.debug?this.#o.log("⚠️ Auto-retry DISABLED (development mode) - reduces API spam"):(this.#ut=setInterval(()=>{this.#bt()},this.config.retryIntervalMs),this.#o.log("Auto-retry enabled (production mode)")),this.#ht=setInterval(()=>{this.#Ct()},6e4),this.#o.log("Background processes started")}#kt(){this.#ut&&(clearInterval(this.#ut),this.#ut=null),this.#ht&&(clearInterval(this.#ht),this.#ht=null)}async#bt(){try{if(this.#Ge?.isSending)return;const S=this.#xe?.getQueueSize();if(S>0){if(this._consecutiveFailures>=10)return this.#o.warn(`⛔ Stopped retrying after ${this._consecutiveFailures} consecutive failures`),this.#o.warn(`⛔ Clearing ${S} queued events to prevent infinite loop`),this.#xe.clearEvents(),void(this._consecutiveFailures=0);this.#o.info(`🔄 Retrying ${S} queued events (attempt ${this._consecutiveFailures+1}/10)`);await this.sendEvents()?(this.#o.info("✅ Retry succeeded - resetting failure counter"),this._consecutiveFailures=0):(this._consecutiveFailures++,this.#o.warn(`❌ Retry failed (${this._consecutiveFailures}/10)`))}else this._consecutiveFailures>0&&(this.#o.info("✅ Queue empty - resetting failure counter"),this._consecutiveFailures=0)}catch(S){this.#o.error("Error during retry:",S),this._consecutiveFailures++}}#Ct(){try{if(this.#xe){const S=this.config.eventMaxAge||864e5;this.#xe.cleanupOldEvents(S)}}catch(S){this.#o.error("Error during cleanup:",S)}}#It(){return"evt_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}destroy(){if(this.#P)try{this.#st?.destroy(),this.#Me?.destroy(),this.#tt?.destroy(),this.#rt?.destroy(),this.#kt(),this.#Ye&&this.#Ye.destroy(),this.#P=!1,this.#o.info("TraceScoutMonitoringCore destroyed successfully")}catch(S){this.#o.error("Error during destruction:",S)}}logEvent(S,b={},I={}){if(this.#P)try{let x;"object"==typeof S&&S.type?(x={id:S.id||this.#It(),timestamp:S.timestamp||Date.now(),...S},x.context||(x.context={}),void 0===x.context.isMonitored&&(x.context.isMonitored=!0),void 0===x.context.forceLog&&(x.context.forceLog=x.type?.includes("error")||x.type?.includes("alert")||x.type?.includes("p1_incident")||"critical"===x.severity)):x={id:this.#It(),type:S,data:b,context:{isMonitored:!0,forceLog:I.forceLog||!1,status:I.status||"success",...I.context},timestamp:Date.now()};if(this.#xe.addEvent(x)){this.#o.log("Event logged:",x.type);this.#xe.getQueueSize()>=this.config.batchSize&&this.sendEvents()}}catch(S){this.#o.error("Failed to log event:",S)}else this.#o.warn("TraceScoutMonitoringCore not initialized")}async sendEvents(S=null){if(!this.#Ge||!this.#xe)return this.#o.warn("ServiceManager or EventManager not available"),!1;try{const b=S||this.#xe.getEvents();if(!b||0===b.length)return!0;this.#o.info(`📤 Attempting to send ${b.length} events`);const I=await this.#Ge.sendEvents(b);this.#o.info(`📊 Send results: ${I.length} results received`);const x=I.filter(S=>S.success).map(S=>S.event.id);x.length>0&&(this.#xe.removeEvents(x),this.#o.info(`✅ Successfully sent ${x.length}/${b.length} events`));const R=I.filter(S=>!S.success).length;if(R>0){this.#o.warn(`❌ Failed to send ${R}/${b.length} events - will retry`);const S=I.find(S=>!S.success);S&&S.error&&this.#o.error("First failure reason:",S.error.message||S.error)}return 0===x.length&&I.length>0&&this.#o.warn(`⚠️ 0 events succeeded out of ${b.length} - all failed`),0===R}catch(S){return this.#o.error("❌ Failed to send events:",S),!1}}clearEvents(){this.#xe?(this.#xe.clearEvents(),this.#o.log("Event queue cleared")):this.#o.warn("EventManager not available")}isMonitoredEndpoint(S){if("string"!=typeof S||R.isEmpty(S))return!1;try{const b=this.config.endpoints||[],I=this.config.domainsToTrack||[];if(b.includes("*")||"*"===b)return!0;const x=S.toLowerCase();let A;try{A=new URL(x)}catch{return!1}if(!R.isEmpty(I)){const S=A.hostname;if(I.some(b=>S===b.toLowerCase()||S.endsWith(`.${b.toLowerCase()}`)))return!0}const _=A.pathname;return b.some(S=>_.includes(S.toLowerCase()))}catch(S){return this.#o?.warn("Error checking monitored endpoint:",S),!1}}shouldExtractFields(S,b){return"string"==typeof S&&!R.isEmpty(S)&&(!!R.isArray(this.config.fieldsToExtract)&&this.config.fieldsToExtract.some(I=>{const x=R.toLower(R.get(I,"api","")),A=R.get(I,"source","");return("*"===x||S.toLowerCase().includes(x))&&("*"===A||A===b)}))}extractUserContextFromBody({data:S,source:b="response",url:I=""}){if(!this.#Je)return{};try{return this.#Je.extractContextFromData({data:S,source:b,url:I})}catch(S){return this.#o.error("Failed to extract user context:",S),{}}}async startSessionRecording(S={}){return this.#tt?.start(S)||null}stopSessionRecording(){return this.#tt?.stop()||null}addSessionCustomEvent(S,b){if(this.#_&&"object"==typeof b&&null!==b){const I=this.#Et(S);if(I){let x;try{const S=this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"});"string"==typeof b.traceId&&b.traceId.length>0&&(S.traceId=b.traceId),"string"==typeof b.spanId&&b.spanId.length>0&&(S.spanId=b.spanId);x=wrapInEnvelope(I,this.#xt(I,b),S)}catch(S){if(this.config?.debug&&this.#o.warn?.("addSessionCustomEvent: envelope build failed; skipping v1 emit:",S),"function"==typeof this.#et?.onError)try{this.#et.onError(S)}catch(S){}return!1}return this.#tt?.addCustomEvent(S,x)||!1}}return this.#tt?.addCustomEvent(S,b)||!1}#Et(S){switch(S){case"network_request":case"network_response":case"network_error":case"network_resource":return"network_request";case"console":return"console_event";case"error":case"unhandledRejection":return"js_error";default:return null}}#xt(S,b){switch(S){case"console_event":{const S=Array.isArray(b.args)?b.args.map(S=>"object"==typeof S&&null!==S&&"type"in S?S:{type:"string"==typeof S?"string":"object",preview:String(S).slice(0,2e3)}):void 0,I={level:b.level||b.method||"log",message:"string"==typeof b.message?b.message:String(b.message??"")};return void 0!==S&&(I.args=S),void 0!==b.stack&&null!==b.stack&&(I.stack=b.stack),"number"==typeof b.timestamp&&(I.timestamp=b.timestamp),I}case"js_error":{const S={handled:b.handled||"window.onerror",message:"string"==typeof b.message?b.message:String(b.message??""),fingerprint:b.fingerprint,occurrenceCount:b.occurrenceCount||1,severity:b.severity||"error"},I=b.errorName??b.name;return null!=I&&(S.errorName=I),void 0!==b.stack&&null!==b.stack&&(S.stack=b.stack),void 0!==b.source&&null!==b.source&&(S.source=b.source),"number"==typeof b.lineno&&(S.lineno=b.lineno),"number"==typeof b.colno&&(S.colno=b.colno),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}case"network_request":{const S={initiator:"xhr"===b.interceptor?"xhr":"fetch",method:(b.method||"GET").toUpperCase(),requestUrl:b.url||b.requestUrl||"",status:"number"==typeof b.status?b.status:0,durationMs:"number"==typeof b.duration?Math.round(b.duration):0,errored:"number"!=typeof b.status||(b.status>=400||0===b.status)};return void 0!==b.statusText&&null!==b.statusText&&(S.statusText=b.statusText),"string"==typeof b.requestPath&&b.requestPath.length>0&&(S.requestPath=b.requestPath),"string"==typeof b.requestQuery&&b.requestQuery.length>0&&(S.requestQuery=b.requestQuery),b.requestHeaders&&"object"==typeof b.requestHeaders&&(S.requestHeaders=b.requestHeaders),b.responseHeaders&&"object"==typeof b.responseHeaders&&(S.responseHeaders=b.responseHeaders),"requestBody"in b&&(S.requestBody="string"==typeof b.requestBody?b.requestBody:null),"responseBody"in b&&(S.responseBody="string"==typeof b.responseBody?b.responseBody:null),"string"==typeof b.requestBodyState&&(S.requestBodyState=b.requestBodyState),"string"==typeof b.responseBodyState&&(S.responseBodyState=b.responseBodyState),"boolean"==typeof b.requestBodyRedacted&&(S.requestBodyRedacted=b.requestBodyRedacted),"boolean"==typeof b.responseBodyRedacted&&(S.responseBodyRedacted=b.responseBodyRedacted),"boolean"==typeof b.requestBodyTruncated&&(S.requestBodyTruncated=b.requestBodyTruncated),"boolean"==typeof b.responseBodyTruncated&&(S.responseBodyTruncated=b.responseBodyTruncated),"number"==typeof b.requestBodySize&&(S.requestBodySize=b.requestBodySize),"number"==typeof b.responseBodySize&&(S.responseBodySize=b.responseBodySize),"number"==typeof b.requestBodyCapturedBytes&&(S.requestBodyCapturedBytes=b.requestBodyCapturedBytes),"number"==typeof b.responseBodyCapturedBytes&&(S.responseBodyCapturedBytes=b.responseBodyCapturedBytes),"string"==typeof b.requestBodyContentType&&(S.requestBodyContentType=b.requestBodyContentType),"string"==typeof b.responseBodyContentType&&(S.responseBodyContentType=b.responseBodyContentType),"number"==typeof b.requestSize&&(S.requestSize=b.requestSize),"number"==typeof b.responseSize&&(S.responseSize=b.responseSize),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}default:return{...b}}}getSessionRecordingStatus(){return this.#tt?.getStatus()||{available:!1,error:"Session recording not enabled"}}async getSessionEvents(S){return this.#tt?.getEvents()||[]}exportSessionData(S="json"){if(!this.#tt?.isAvailable)return this.#o.warn("Session recording not enabled"),null;try{const b=this.#tt.getEvents(),I=this.#tt.getChunks(),x=this.#tt.getMetadata(),R=this.#tt.getSessionId();let A=b;(!b||0===b.length)&&I&&I.length>0&&(A=[],I.forEach(S=>{S.events&&Array.isArray(S.events)&&A.push(...S.events)}));const _=JSON.stringify(A).length,D=_>5e6,L={sessionId:R,startTime:this.#tt.recorder?.recordingStartTime,endTime:this.#tt.isRecording?null:Date.now(),duration:this.#tt.recorder?.recordingStartTime?Date.now()-this.#tt.recorder.recordingStartTime:0,eventCount:A.length,chunkCount:I.length,totalSize:_,isLarge:D,metadata:x,events:D?[]:A,chunks:I,userAgent:navigator.userAgent,url:window.location.href,timestamp:Date.now(),...D&&{warning:"Session data is large. Use exportChunk() to get individual chunks for replay."}};return"json"===S?JSON.stringify(L,null,2):"object"===S?L:"blob"===S?new Blob([JSON.stringify(L,null,2)],{type:"application/json"}):L}catch(S){return this.#o.error("Failed to export session data:",S),null}}getSessionChunks(){return this.#tt?.getChunks()||[]}listChunks(){return(this.#tt?.getChunks()||[]).map((S,b)=>({index:b,chunkId:S.chunkId,eventCount:S.events?.length||0,size:JSON.stringify(S.events||[]).length,sizeKB:Math.round(JSON.stringify(S.events||[]).length/1024),startTime:S.startTime,endTime:S.endTime,duration:(S.endTime||0)-(S.startTime||0)}))}getUploadQueueStats(){return this.#tt?.uploadQueue?.getStats()||null}getUploadQueue(){return this.#tt?.uploadQueue?.getQueue()||null}pauseUploads(){return this.#tt?.uploadQueue?.pause(),!0}resumeUploads(){return this.#tt?.uploadQueue?.resume(),!0}getSessionStorageStats(){return this.#tt?.sessionStorage?.getStorageStats()||null}getStoredSessions(){return this.#tt?.sessionStorage?.getSessions()||{}}clearSessionStorage(){return this.#tt?.sessionStorage?.clearAll()||!1}log(S,b,I={}){return this.#st?.log(S,b,I)||!1}debug(S,b={}){return this.#st?.debug(S,b)||!1}info(S,b={}){return this.#st?.info(S,b)||!1}warn(S,b={}){return this.#st?.warn(S,b)||!1}error(S,b={}){return this.#st?.error(S,b)||!1}fatal(S,b={}){return this.#st?.fatal(S,b)||!1}setLogContext(S,b){return this.#st?.setContext(S,b)||!1}clearLogContext(){return this.#st?.clearContext()||!1}setLogLevel(S){return this.#st?.setLogLevel(S)||!1}getLogStats(){return this.#st?.getStats()||null}async flushLogs(){return this.#st?.flush()||!1}enableLogging(S,b="info"){return this.#st?.enableServices(S,b)||!1}disableLogging(S){return this.#st?.disableServices(S)||!1}enableAllLogging(S="info"){return this.#st?.enableAll(S)||!1}disableAllLogging(){return this.#st?.disableAll()||!1}getLoggingConfig(){return this.#st?.getConfig()||null}getEnabledLogServices(){return this.#st?.getEnabledServices()||[]}getAvailableLogServices(){return this.#st?.getAvailableServices()||[]}setUserProfile(S){if(!this.#Je)return this.#o.warn("UserProfileManager not available"),!1;let b=!1;try{b=!0===this.#Je.setProfile(S)}catch(S){return this.#o.error("Failed to set user profile:",S),!1}if(S&&"object"==typeof S&&isValidUserId(S.userId)){const{userId:b,...I}=S;try{this.#Mt(b,I,{mode:"merge"},{skipUserProfileWrite:!0})}catch(S){this.#o.warn?.("Failed to route setUserProfile through identify:",S)}}return b}getUserProfile(){if(!this.#Je)return{};try{return this.#Je.getProfile()}catch(S){return this.#o.error("Failed to get user profile:",S),{}}}getSdkContext(){return!1===this.#dt?{sampled:!1}:this.#_}setUserMetadata(S,b={}){return this.identify(S,b,{mode:"merge"})}clearUserMetadata(){return!!this.#_&&(this.#_.clearUser(),this.#Ye&&this.#Ye.clearUserMetadata(),!0)}identify(S,b={},I={}){return this.#Mt(S,b,I,{skipUserProfileWrite:!1})}#Mt(S,b={},I={},x={}){if(!isValidUserId(S))return this.#o.error("identify: userId is required and must be a non-empty string (≤256 chars)"),!1;if(!this.#_)return this.#o.warn("Cannot identify — SDK not initialized"),!1;const R=I&&"set"===I.mode?"set":"merge",A=[],onDrop=(S,b)=>A.push({reason:S,key:b}),{userEmail:_,userName:D,traits:L}=function extractIdentityFromTraits(S,b){const I="function"==typeof b?b:()=>{};if(!S||"object"!=typeof S||Array.isArray(S))return{userEmail:null,userName:null,traits:{}};const x=Object.assign({},S),R=void 0!==x.userEmail?x.userEmail:x.email;delete x.email,delete x.userEmail;let A=null;null!=R&&(isValidEmail(R)?A=R:I("invalid-email","email"));const _=void 0!==x.userName?x.userName:x.name;delete x.name,delete x.userName;let D=null;return null!=_&&(isValidUserName(_)?D=_:I("invalid-name","name")),{userEmail:A,userName:D,traits:x}}(b||{},onDrop),B=sanitizeScalarBag(L,onDrop);this.config?.debug&&A.length>0&&this.#o.warn?.("identify: dropped invalid trait entries:",A);const U=this.#_.userAttributes||{},$="set"===R?{}:{...U};null!==_&&($.email=_),null!==D&&($.name=D);const j=Object.assign({},$,B);if(this.#_.setUser(S,j),this.#Ye)try{this.#Ye.updateUserMetadata(S,j)}catch(S){this.#o.warn?.("SessionManager.updateUserMetadata threw:",S)}if(!x.skipUserProfileWrite&&this.#Je)try{this.#Je.setProfile({userId:S,...j})}catch(S){this.#o.warn?.("UserProfileManager.setProfile threw:",S)}return this.#at?this.#at.emitUserIdentified({userId:S,userEmail:_,userName:D,traits:B,mode:R}):this.config?.debug&&this.#o.warn?.("identify: emitter not available (recording disabled?) — context updated but no v1 envelope emitted"),!0}track(S,b={}){if(!this.#P)return this.#o.warn("SDK not initialized"),!1;try{this.logEvent({type:`custom.${S}`,category:"custom",severity:"info",data:b,timestamp:Date.now()})}catch(S){}return this.#at?this.#at.emitCustomEvent(S,b):(this.config?.debug&&this.#o.warn?.("track: v1 emitter not available (recording disabled?) — legacy event emitted, no v1 envelope"),!1)}captureException(S,b={}){return this.#P?(this.logEvent({type:"error.captured",category:"error",severity:"error",data:{message:S.message,stack:S.stack,name:S.name,...b},timestamp:Date.now()}),!0):(this.#o.warn("SDK not initialized"),!1)}getStatus(){const S=this.#Ye?.getSessionInfo?.()||{};return{initialized:this.#P,recording:this.#tt?.isRecording||!1,sessionId:this.#_?.sessionId||null,eventQueueSize:this.#xe?.getQueueSize()||0,session:{id:S.sessionId,duration:S.durationMinutes,events:S.eventCount,chunks:S.chunkCount,pages:S.pageCount,expiresIn:S.willExpireInMinutes}}}forceNewSession(S="manual"){if(!this.#P)return this.#o.warn("SDK not initialized"),null;if(this.#je)return console.warn("[TraceScout] Cannot start new session - quota exceeded."),null;console.log("[TraceScout] 🔄 Forcing new session, reason:",S),this.#tt?.stop(),this.#Ye&&this.#Ye.forceNewSession(S);const b=this.#Ye?.getOrCreateSession({projectId:this.#_.projectId,environment:this.#_.environment,userId:this.#_.userId});if(this.#_&&b&&(this.#_.sessionId=b,this.#_.sessionStartTime=Date.now()),this.#tt&&b){this.#tt.updateSessionId(b);const S=this.config.apiBaseUrl||"http://localhost:3001";this.#tt.updateUploadEndpoint(`${S}/api/projects/${this.#_.projectId}/sessions/${b}/chunks`),this.#tt.recorder?.start()}return b}debugMode(S){this.config.debug=S,this.#o.updateDebugMode(S),this.#Ge&&this.#Ge.updateDebugMode(S),this.#Me?.updateDebugMode(S),this.#o.log("Debug mode "+(S?"enabled":"disabled"))}getQueueStatus(){return{queueSize:this.#xe?this.#xe.getQueueSize():0,isSending:!!this.#Ge&&this.#Ge.isSending,isInitialized:this.#P,service:this.#Ge?this.#Ge.getServiceName():"none",configSource:this.config?.configSource||"local",configVersion:this.config?.configVersion||"local"}}getPerformanceMetrics(){return this.#Xe?.getMetrics()||null}getCoreWebVitalsMonitor(){return this.#lt}getCoreWebVitalsMetrics(){return this.#lt?.getAllMetrics()||null}getCoreWebVitalsInsights(){return this.#lt?.getPerformanceInsights()||null}generateCoreWebVitalsReport(){return this.#lt?.generateReport()||null}updateCoreWebVitalsThresholds(S){this.#lt?this.#lt.updateThresholds(S):this.#o.warn("Core Web Vitals monitor not available")}}let He;try{He=new TraceScoutMonitoringCore}catch(S){He={init:()=>Promise.reject(new Error("TraceScoutMonitoringCore failed to initialize")),logEvent:()=>{},destroy:()=>{},debugMode:()=>{},setUserProfile:()=>{},getUserProfile:()=>({}),getQueueStatus:()=>({error:"Not available"}),getPerformanceMetrics:()=>null,getCoreWebVitalsMonitor:()=>null,getCoreWebVitalsMetrics:()=>null,getCoreWebVitalsInsights:()=>null,generateCoreWebVitalsReport:()=>null,updateCoreWebVitalsThresholds:()=>{},getSessionRecorder:()=>null,startSessionRecording:()=>Promise.resolve(null),stopSessionRecording:()=>!1,getSessionRecordingStatus:()=>({available:!1,error:"Not available"}),getStatus:()=>({initialized:!1,error:"Not available"}),forceNewSession:()=>null}}if("undefined"!=typeof window)try{window.monitoringCore=He}catch(S){}var Ve=He;var Qe,Ke=Object.defineProperty,__publicField=(S,b,I)=>((S,b,I)=>b in S?Ke(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),Ge=Object.defineProperty,__publicField$1=(S,b,I)=>((S,b,I)=>b in S?Ge(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),Je=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(Je||{});const Xe={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Ye={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Ze={};function getUntaintedPrototype$1(S){if(Ze[S])return Ze[S];const b=globalThis[S],I=b.prototype,x=S in Xe?Xe[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in Ye?Ye[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return Ze[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?Ze[S]=A:I}catch{return I}}const et={};function getUntaintedAccessor$1(S,b,I){var x;const R=`${S}.${String(I)}`;if(et[R])return et[R].call(b);const A=getUntaintedPrototype$1(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(et[R]=_,_.call(b)):b[I]}const tt={};function getUntaintedMethod$1(S,b,I){const x=`${S}.${String(I)}`;if(tt[x])return tt[x].bind(b);const R=getUntaintedPrototype$1(S)[I];return"function"!=typeof R?b[I]:(tt[x]=R,R.bind(b))}const st={childNodes:function childNodes$1(S){return getUntaintedAccessor$1("Node",S,"childNodes")},parentNode:function parentNode$1(S){return getUntaintedAccessor$1("Node",S,"parentNode")},parentElement:function parentElement$1(S){return getUntaintedAccessor$1("Node",S,"parentElement")},textContent:function textContent$1(S){return getUntaintedAccessor$1("Node",S,"textContent")},contains:function contains$1(S,b){return getUntaintedMethod$1("Node",S,"contains")(b)},getRootNode:function getRootNode$1(S){return getUntaintedMethod$1("Node",S,"getRootNode")()},host:function host$1(S){return S&&"host"in S?getUntaintedAccessor$1("ShadowRoot",S,"host"):null},styleSheets:function styleSheets$1(S){return S.styleSheets},shadowRoot:function shadowRoot$1(S){return S&&"shadowRoot"in S?getUntaintedAccessor$1("Element",S,"shadowRoot"):null},querySelector:function querySelector$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelectorAll")(b)},mutationObserver:function mutationObserverCtor$1(){return getUntaintedPrototype$1("MutationObserver").constructor}};function isElement(S){return S.nodeType===S.ELEMENT_NODE}function isShadowRoot(S){const b=S&&"host"in S&&"mode"in S&&st.host(S)||null;return Boolean(b&&"shadowRoot"in b&&st.shadowRoot(b)===S)}function isNativeShadowDom(S){return"[object ShadowRoot]"===Object.prototype.toString.call(S)}function stringifyStylesheet(S){try{const b=S.rules||S.cssRules;if(!b)return null;let I=S.href;!I&&S.ownerNode&&S.ownerNode.ownerDocument&&(I=S.ownerNode.ownerDocument.location.href);return function fixBrowserCompatibilityIssuesInCSS(S){return S.includes(" background-clip: text;")&&!S.includes(" -webkit-background-clip: text;")&&(S=S.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),S}(Array.from(b,S=>stringifyRule(S,I)).join(""))}catch(S){return null}}function stringifyRule(S,b){if(function isCSSImportRule(S){return"styleSheet"in S}(S)){let b;try{b=stringifyStylesheet(S.styleSheet)||function escapeImportStatement(S){const{cssText:b}=S;if(b.split('"').length<3)return b;const I=["@import",`url(${JSON.stringify(S.href)})`];return""===S.layerName?I.push("layer"):S.layerName&&I.push(`layer(${S.layerName})`),S.supportsText&&I.push(`supports(${S.supportsText})`),S.media.length&&I.push(S.media.mediaText),I.join(" ")+";"}(S)}catch(I){b=S.cssText}return S.styleSheet.href?absolutifyURLs(b,S.styleSheet.href):b}{let I=S.cssText;return function isCSSStyleRule(S){return"selectorText"in S}(S)&&S.selectorText.includes(":")&&(I=function fixSafariColons(S){const b=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return S.replace(b,"$1\\$2")}(I)),b?absolutifyURLs(I,b):I}}class Mirror{constructor(){__publicField$1(this,"idNodeMap",new Map),__publicField$1(this,"nodeMetaMap",new WeakMap)}getId(S){var b;if(!S)return-1;return(null==(b=this.getMeta(S))?void 0:b.id)??-1}getNode(S){return this.idNodeMap.get(S)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(S){return this.nodeMetaMap.get(S)||null}removeNodeFromMap(S){const b=this.getId(S);this.idNodeMap.delete(b),S.childNodes&&S.childNodes.forEach(S=>this.removeNodeFromMap(S))}has(S){return this.idNodeMap.has(S)}hasNode(S){return this.nodeMetaMap.has(S)}add(S,b){const I=b.id;this.idNodeMap.set(I,S),this.nodeMetaMap.set(S,b)}replace(S,b){const I=this.getNode(S);if(I){const S=this.nodeMetaMap.get(I);S&&this.nodeMetaMap.set(b,S)}this.idNodeMap.set(S,b)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function maskInputValue({element:S,maskInputOptions:b,tagName:I,type:x,value:R,maskInputFn:A}){let _=R||"";const D=x&&toLowerCase(x);return(b[I.toLowerCase()]||D&&b[D])&&(_=A?A(_,S):"*".repeat(_.length)),_}function toLowerCase(S){return S.toLowerCase()}const rt="__rrweb_original__";function getInputType(S){const b=S.type;return S.hasAttribute("data-rr-is-password")?"password":b?toLowerCase(b):null}function extractFileExtension(S,b){let I;try{I=new URL(S,b??window.location.href)}catch(S){return null}const x=I.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==x?void 0:x[1])??null}const nt=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,it=/^(?:[a-z+]+:)?\/\//i,ot=/^www\..*/i,at=/^(data:)([^,]*),(.*)/i;function absolutifyURLs(S,b){return(S||"").replace(nt,(S,I,x,R,A,_)=>{const D=x||A||_,L=I||R||"";if(!D)return S;if(it.test(D)||ot.test(D))return`url(${L}${D}${L})`;if(at.test(D))return`url(${L}${D}${L})`;if("/"===D[0])return`url(${L}${function extractOrigin(S){let b="";return b=S.indexOf("//")>-1?S.split("/").slice(0,3).join("/"):S.split("/")[0],b=b.split("?")[0],b}(b)+D}${L})`;const B=b.split("/"),U=D.split("/");B.pop();for(const S of U)"."!==S&&(".."===S?B.pop():B.push(S));return`url(${L}${B.join("/")}${L})`})}function normalizeCssString(S){return S.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"")}function markCssSplits(S,b){return function splitCssText(S,b){const I=Array.from(b.childNodes),x=[];if(I.length>1&&S&&"string"==typeof S){const b=normalizeCssString(S);for(let R=1;R<I.length;R++)if(I[R].textContent&&"string"==typeof I[R].textContent){const A=normalizeCssString(I[R].textContent);for(let I=3;I<A.length;I++){const R=A.substring(0,I);if(2===b.split(R).length){const I=b.indexOf(R);for(let b=I;b<S.length;b++)if(normalizeCssString(S.substring(0,b)).length===I){x.push(S.substring(0,b)),S=S.substring(b);break}break}}}}return x.push(S),x}(S,b).join("/* rr_split */")}let lt=1;const ct=new RegExp("[^a-z0-9-_:]");function genId(){return lt++}let ut,ht;const dt=/^[^ \t\n\r\u000c]+/,gt=/^[, \t\n\r\u000c]+/;const pt=new WeakMap;function absoluteToDoc(S,b){return b&&""!==b.trim()?getHref(S,b):b}function isSVGElement(S){return Boolean("svg"===S.tagName||S.ownerSVGElement)}function getHref(S,b){let I=pt.get(S);if(I||(I=S.createElement("a"),pt.set(S,I)),b){if(b.startsWith("blob:")||b.startsWith("data:"))return b}else b="";return I.setAttribute("href",b),I.href}function transformAttribute(S,b,I,x){return x?"src"===I||"href"===I&&("use"!==b||"#"!==x[0])||"xlink:href"===I&&"#"!==x[0]?absoluteToDoc(S,x):"background"!==I||"table"!==b&&"td"!==b&&"th"!==b?"srcset"===I?function getAbsoluteSrcsetString(S,b){if(""===b.trim())return b;let I=0;function collectCharacters(S){let x;const R=S.exec(b.substring(I));return R?(x=R[0],I+=x.length,x):""}const x=[];for(;collectCharacters(gt),!(I>=b.length);){let R=collectCharacters(dt);if(","===R.slice(-1))R=absoluteToDoc(S,R.substring(0,R.length-1)),x.push(R);else{let A="";R=absoluteToDoc(S,R);let _=!1;for(;;){const S=b.charAt(I);if(""===S){x.push((R+A).trim());break}if(_)")"===S&&(_=!1);else{if(","===S){I+=1,x.push((R+A).trim());break}"("===S&&(_=!0)}A+=S,I+=1}}}return x.join(", ")}(S,x):"style"===I?absolutifyURLs(x,getHref(S)):"object"===b&&"data"===I?absoluteToDoc(S,x):x:absoluteToDoc(S,x):x}function ignoreAttribute(S,b,I){return("video"===S||"audio"===S)&&"autoplay"===b}function classMatchesRegex(S,b,I){if(!S)return!1;if(S.nodeType!==S.ELEMENT_NODE)return!!I&&classMatchesRegex(st.parentNode(S),b,I);for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}return!!I&&classMatchesRegex(st.parentNode(S),b,I)}function needMaskingText(S,b,I,x){let R;if(isElement(S)){if(R=S,!st.childNodes(R).length)return!1}else{if(null===st.parentElement(S))return!1;R=st.parentElement(S)}try{if("string"==typeof b){if(x){if(R.closest(`.${b}`))return!0}else if(R.classList.contains(b))return!0}else if(classMatchesRegex(R,b,x))return!0;if(I)if(x){if(R.closest(I))return!0}else if(R.matches(I))return!0}catch(S){}return!1}function serializeNode(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:_,inlineStylesheet:D,maskInputOptions:L={},maskTextFn:B,maskInputFn:U,dataURLOptions:$={},inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V=!1,cssCaptured:Q=!1}=b,G=function getRootId(S,b){if(!b.hasNode(S))return;const I=b.getId(S);return 1===I?void 0:I}(I,x);switch(S.nodeType){case S.DOCUMENT_NODE:return"CSS1Compat"!==S.compatMode?{type:Je.Document,childNodes:[],compatMode:S.compatMode}:{type:Je.Document,childNodes:[]};case S.DOCUMENT_TYPE_NODE:return{type:Je.DocumentType,name:S.name,publicId:S.publicId,systemId:S.systemId,rootId:G};case S.ELEMENT_NODE:return function serializeElementNode(S,b){const{doc:I,blockClass:x,blockSelector:R,inlineStylesheet:A,maskInputOptions:_={},maskInputFn:D,dataURLOptions:L={},inlineImages:B,recordCanvas:U,keepIframeSrcFn:$,newlyAddedElement:j=!1,rootId:W}=b,H=function _isBlockedElement(S,b,I){try{if("string"==typeof b){if(S.classList.contains(b))return!0}else for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}if(I)return S.matches(I)}catch(S){}return!1}(S,x,R),V=function getValidTagName$1(S){if(S instanceof HTMLFormElement)return"form";const b=toLowerCase(S.tagName);return ct.test(b)?"div":b}(S);let Q={};const G=S.attributes.length;for(let b=0;b<G;b++){const x=S.attributes[b];ignoreAttribute(V,x.name)||(Q[x.name]=transformAttribute(I,V,toLowerCase(x.name),x.value))}if("link"===V&&A){const b=Array.from(I.styleSheets).find(b=>b.href===S.href);let x=null;b&&(x=stringifyStylesheet(b)),x&&(delete Q.rel,delete Q.href,Q._cssText=x)}if("style"===V&&S.sheet){let b=stringifyStylesheet(S.sheet);b&&(S.childNodes.length>1&&(b=markCssSplits(b,S)),Q._cssText=b)}if("input"===V||"textarea"===V||"select"===V){const b=S.value,I=S.checked;"radio"!==Q.type&&"checkbox"!==Q.type&&"submit"!==Q.type&&"button"!==Q.type&&b?Q.value=maskInputValue({element:S,type:getInputType(S),tagName:V,value:b,maskInputOptions:_,maskInputFn:D}):I&&(Q.checked=I)}"option"===V&&(S.selected&&!_.select?Q.selected=!0:delete Q.selected);"dialog"===V&&S.open&&(Q.rr_open_mode=S.matches("dialog:modal")?"modal":"non-modal");if("canvas"===V&&U)if("2d"===S.__context)(function is2DCanvasBlank(S){const b=S.getContext("2d");if(!b)return!0;for(let I=0;I<S.width;I+=50)for(let x=0;x<S.height;x+=50){const R=b.getImageData,A=rt in R?R[rt]:R;if(new Uint32Array(A.call(b,I,x,Math.min(50,S.width-I),Math.min(50,S.height-x)).data.buffer).some(S=>0!==S))return!1}return!0})(S)||(Q.rr_dataURL=S.toDataURL(L.type,L.quality));else if(!("__context"in S)){const b=S.toDataURL(L.type,L.quality),x=I.createElement("canvas");x.width=S.width,x.height=S.height;b!==x.toDataURL(L.type,L.quality)&&(Q.rr_dataURL=b)}if("img"===V&&B){ut||(ut=I.createElement("canvas"),ht=ut.getContext("2d"));const b=S,x=b.currentSrc||b.getAttribute("src")||"<unknown-src>",R=b.crossOrigin,recordInlineImage=()=>{b.removeEventListener("load",recordInlineImage);try{ut.width=b.naturalWidth,ut.height=b.naturalHeight,ht.drawImage(b,0,0),Q.rr_dataURL=ut.toDataURL(L.type,L.quality)}catch(S){if("anonymous"!==b.crossOrigin)return b.crossOrigin="anonymous",void(b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage));console.warn(`Cannot inline img src=${x}! Error: ${S}`)}"anonymous"===b.crossOrigin&&(R?Q.crossOrigin=R:b.removeAttribute("crossorigin"))};b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage)}if("audio"===V||"video"===V){const b=Q;b.rr_mediaState=S.paused?"paused":"played",b.rr_mediaCurrentTime=S.currentTime,b.rr_mediaPlaybackRate=S.playbackRate,b.rr_mediaMuted=S.muted,b.rr_mediaLoop=S.loop,b.rr_mediaVolume=S.volume}j||(S.scrollLeft&&(Q.rr_scrollLeft=S.scrollLeft),S.scrollTop&&(Q.rr_scrollTop=S.scrollTop));if(H){const{width:b,height:I}=S.getBoundingClientRect();Q={class:Q.class,rr_width:`${b}px`,rr_height:`${I}px`}}"iframe"!==V||$(Q.src)||(S.contentDocument||(Q.rr_src=Q.src),delete Q.src);let J;try{customElements.get(V)&&(J=!0)}catch(S){}return{type:Je.Element,tagName:V,attributes:Q,childNodes:[],isSVG:isSVGElement(S)||void 0,needBlock:H,rootId:W,isCustom:J}}(S,{doc:I,blockClass:R,blockSelector:A,inlineStylesheet:D,maskInputOptions:L,maskInputFn:U,dataURLOptions:$,inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V,rootId:G});case S.TEXT_NODE:return function serializeTextNode(S,b){const{needsMask:I,maskTextFn:x,rootId:R,cssCaptured:A}=b,_=st.parentNode(S),D=_&&_.tagName;let L="";const B="STYLE"===D||void 0,U="SCRIPT"===D||void 0;U?L="SCRIPT_PLACEHOLDER":A||(L=st.textContent(S),B&&L&&(L=absolutifyURLs(L,getHref(b.doc))));!B&&!U&&L&&I&&(L=x?x(L,st.parentElement(S)):L.replace(/[\S]/g,"*"));return{type:Je.Text,textContent:L||"",rootId:R}}(S,{doc:I,needsMask:_,maskTextFn:B,rootId:G,cssCaptured:Q});case S.CDATA_SECTION_NODE:return{type:Je.CDATA,textContent:"",rootId:G};case S.COMMENT_NODE:return{type:Je.Comment,textContent:st.textContent(S)||"",rootId:G};default:return!1}}function lowerIfExists(S){return null==S?"":S.toLowerCase()}function serializeNodeWithId(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,maskTextClass:_,maskTextSelector:D,skipChild:L=!1,inlineStylesheet:B=!0,maskInputOptions:U={},maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H={},inlineImages:V=!1,recordCanvas:Q=!1,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X=5e3,onStylesheetLoad:Y,stylesheetLoadTimeout:ee=5e3,keepIframeSrcFn:te=()=>!1,newlyAddedElement:se=!1,cssCaptured:re=!1}=b;let{needsMask:ne}=b,{preserveWhiteSpace:ie=!0}=b;if(!ne){ne=needMaskingText(S,_,D,void 0===ne)}const oe=serializeNode(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,dataURLOptions:H,inlineImages:V,recordCanvas:Q,keepIframeSrcFn:te,newlyAddedElement:se,cssCaptured:re});if(!oe)return console.warn(S,"not serialized"),null;let ae;ae=x.hasNode(S)?x.getId(S):function slimDOMExcluded(S,b){if(b.comment&&S.type===Je.Comment)return!0;if(S.type===Je.Element){if(b.script&&("script"===S.tagName||"link"===S.tagName&&("preload"===S.attributes.rel||"modulepreload"===S.attributes.rel)&&"script"===S.attributes.as||"link"===S.tagName&&"prefetch"===S.attributes.rel&&"string"==typeof S.attributes.href&&"js"===extractFileExtension(S.attributes.href)))return!0;if(b.headFavicon&&("link"===S.tagName&&"shortcut icon"===S.attributes.rel||"meta"===S.tagName&&(lowerIfExists(S.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===lowerIfExists(S.attributes.name)||"icon"===lowerIfExists(S.attributes.rel)||"apple-touch-icon"===lowerIfExists(S.attributes.rel)||"shortcut icon"===lowerIfExists(S.attributes.rel))))return!0;if("meta"===S.tagName){if(b.headMetaDescKeywords&&lowerIfExists(S.attributes.name).match(/^description|keywords$/))return!0;if(b.headMetaSocial&&(lowerIfExists(S.attributes.property).match(/^(og|twitter|fb):/)||lowerIfExists(S.attributes.name).match(/^(og|twitter):/)||"pinterest"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaRobots&&("robots"===lowerIfExists(S.attributes.name)||"googlebot"===lowerIfExists(S.attributes.name)||"bingbot"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaHttpEquiv&&void 0!==S.attributes["http-equiv"])return!0;if(b.headMetaAuthorship&&("author"===lowerIfExists(S.attributes.name)||"generator"===lowerIfExists(S.attributes.name)||"framework"===lowerIfExists(S.attributes.name)||"publisher"===lowerIfExists(S.attributes.name)||"progid"===lowerIfExists(S.attributes.name)||lowerIfExists(S.attributes.property).match(/^article:/)||lowerIfExists(S.attributes.property).match(/^product:/)))return!0;if(b.headMetaVerification&&("google-site-verification"===lowerIfExists(S.attributes.name)||"yandex-verification"===lowerIfExists(S.attributes.name)||"csrf-token"===lowerIfExists(S.attributes.name)||"p:domain_verify"===lowerIfExists(S.attributes.name)||"verify-v1"===lowerIfExists(S.attributes.name)||"verification"===lowerIfExists(S.attributes.name)||"shopify-checkout-api-token"===lowerIfExists(S.attributes.name)))return!0}}return!1}(oe,W)||!ie&&oe.type===Je.Text&&!oe.textContent.replace(/^\s+|\s+$/gm,"").length?-2:genId();const le=Object.assign(oe,{id:ae});if(x.add(S,le),-2===ae)return null;G&&G(S);let ce=!L;if(le.type===Je.Element){ce=ce&&!le.needBlock,delete le.needBlock;const b=st.shadowRoot(S);b&&isNativeShadowDom(b)&&(le.isShadowHost=!0)}if((le.type===Je.Document||le.type===Je.Element)&&ce){W.headWhitespace&&le.type===Je.Element&&"head"===le.tagName&&(ie=!1);const b={doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:L,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te,cssCaptured:!1};if(le.type===Je.Element&&"textarea"===le.tagName&&void 0!==le.attributes.value);else{le.type===Je.Element&&void 0!==le.attributes._cssText&&"string"==typeof le.attributes._cssText&&(b.cssCaptured=!0);for(const I of Array.from(st.childNodes(S))){const S=serializeNodeWithId(I,b);S&&le.childNodes.push(S)}}let se=null;if(isElement(S)&&(se=st.shadowRoot(S)))for(const S of Array.from(st.childNodes(se))){const I=serializeNodeWithId(S,b);I&&(isNativeShadowDom(se)&&(I.isShadow=!0),le.childNodes.push(I))}}const ue=st.parentNode(S);return ue&&isShadowRoot(ue)&&isNativeShadowDom(ue)&&(le.isShadow=!0),le.type===Je.Element&&"iframe"===le.tagName&&function onceIframeLoaded(S,b,I){const x=S.contentWindow;if(!x)return;let R,A=!1;try{R=x.document.readyState}catch(S){return}if("complete"!==R){const x=setTimeout(()=>{A||(b(),A=!0)},I);return void S.addEventListener("load",()=>{clearTimeout(x),A=!0,b()})}const _="about:blank";if(x.location.href!==_||S.src===_||""===S.src)return setTimeout(b,0),S.addEventListener("load",b);S.addEventListener("load",b)}(S,()=>{const b=S.contentDocument;if(b&&J){const I=serializeNodeWithId(b,{doc:b,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});I&&J(S,I)}},X),le.type===Je.Element&&"link"===le.tagName&&"string"==typeof le.attributes.rel&&("stylesheet"===le.attributes.rel||"preload"===le.attributes.rel&&"string"==typeof le.attributes.href&&"css"===extractFileExtension(le.attributes.href))&&function onceStylesheetLoaded(S,b,I){let x,R=!1;try{x=S.sheet}catch(S){return}if(x)return;const A=setTimeout(()=>{R||(b(),R=!0)},I);S.addEventListener("load",()=>{clearTimeout(A),R=!0,b()})}(S,()=>{if(Y){const b=serializeNodeWithId(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});b&&Y(S,b)}},ee),le}function getAugmentedNamespace$1(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var ft={exports:{}},mt=String,create$1=function(){return{isColorSupported:!1,reset:mt,bold:mt,dim:mt,italic:mt,underline:mt,inverse:mt,hidden:mt,strikethrough:mt,black:mt,red:mt,green:mt,yellow:mt,blue:mt,magenta:mt,cyan:mt,white:mt,gray:mt,bgBlack:mt,bgRed:mt,bgGreen:mt,bgYellow:mt,bgBlue:mt,bgMagenta:mt,bgCyan:mt,bgWhite:mt}};ft.exports=create$1(),ft.exports.createColors=create$1;var yt=ft.exports;const vt=getAugmentedNamespace$1(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let St=yt,wt=vt,bt=class CssSyntaxError extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=St.isColorSupported),wt&&S&&(b=wt(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=St.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var Ct=bt;bt.default=bt;var kt={};kt.isClean=Symbol("isClean"),kt.my=Symbol("my");const It={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Et=class Stringifier{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return It[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize$1(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=It[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var xt=Et;Et.default=Et;let Mt=xt;function stringify$4$1(S,b){new Mt(b).stringify(S)}var Rt=stringify$4$1;stringify$4$1.default=stringify$4$1;let{isClean:Tt,my:At}=kt,_t=Ct,Ot=xt,Dt=Rt;function cloneNode$1(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode$1(S,I)):("object"===A&&null!==R&&(R=cloneNode$1(R)),I[x]=R)}return I}let Ft=class Node2{constructor(S={}){this.raws={},this[Tt]=!1,this[At]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode$1(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new _t(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[Tt]){this[Tt]=!1;let S=this;for(;S=S.parent;)S[Tt]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new Ot).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=Dt){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var Nt=Ft;Ft.default=Ft;let Lt=Nt,Pt=class Declaration extends Lt{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var Bt=Pt;Pt.default=Pt;var zt={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:Ut,SourceMapGenerator:$t}=vt,{existsSync:jt,readFileSync:qt}=vt,{dirname:Wt,join:Ht}=vt;let Vt=class PreviousMap{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=Wt(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new Ut(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64$1(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=Wt(S),jt(S))return this.mapFile=S,qt(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof Ut)return $t.fromSourceMap(b).toString();if(b instanceof $t)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=Ht(Wt(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var Qt=Vt;Vt.default=Vt;let{SourceMapConsumer:Kt,SourceMapGenerator:Gt}=vt,{fileURLToPath:Jt,pathToFileURL:Xt}=vt,{isAbsolute:Yt,resolve:Zt}=vt,{nanoid:es}=zt,ts=vt,ss=Ct,rs=Qt,ns=Symbol("fromOffsetCache"),is=Boolean(Kt&&Gt),os=Boolean(Zt&&Yt),as=class Input{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||""===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!os||/^\w+:\/\//.test(b.from)||Yt(b.from)?this.file=b.from:this.file=Zt(b.from)),os&&is){let S=new rs(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+es(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new ss(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new ss(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(Xt&&(R.input.url=Xt(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[ns])I=this[ns];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[ns]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:Zt(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=Yt(D.source)?Xt(D.source):new URL(D.source,this.map.consumer().sourceRoot||Xt(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!Jt)throw new Error("file: protocol is not available in this PostCSS build");L.file=Jt(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var ls=as;as.default=as,ts&&ts.registerInput&&ts.registerInput(as);let{SourceMapConsumer:cs,SourceMapGenerator:us}=vt,{dirname:hs,relative:ds,resolve:gs,sep:ps}=vt,{pathToFileURL:fs}=vt,ms=ls,ys=Boolean(cs&&us),vs=Boolean(hs&&gs&&ds&&ps);var Ss=class MapGenerator{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||hs(S.file);!1===this.mapOpts.sourcesContent?(b=new cs(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),vs&&ys&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=us.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new us({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new us({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?hs(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=hs(gs(I,this.mapOpts.annotation)));let x=ds(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new ms(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(fs){let b=fs(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===ps&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let ws=Nt,bs=class Comment extends ws{constructor(S){super(S),this.type="comment"}};var Cs=bs;bs.default=bs;let ks,Is,Es,xs,{isClean:Ms,my:Rs}=kt,Ts=Bt,As=Cs,_s=Nt;function cleanSource$1(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource$1(S.nodes)),delete S.source,S))}function markDirtyUp$1(S){if(S[Ms]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp$1(b)}let Os=class Container extends _s{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource$1(ks(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new Ts(S)]}else if(S.selector)S=[new Is(S)];else if(S.name)S=[new Es(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new As(S)]}return S.map(S=>(S[Rs]||Container.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[Ms]&&markDirtyUp$1(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Os.registerParse=S=>{ks=S},Os.registerRule=S=>{Is=S},Os.registerAtRule=S=>{Es=S},Os.registerRoot=S=>{xs=S};var Ds=Os;Os.default=Os,Os.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,Es.prototype):"rule"===S.type?Object.setPrototypeOf(S,Is.prototype):"decl"===S.type?Object.setPrototypeOf(S,Ts.prototype):"comment"===S.type?Object.setPrototypeOf(S,As.prototype):"root"===S.type&&Object.setPrototypeOf(S,xs.prototype),S[Rs]=!0,S.nodes&&S.nodes.forEach(S=>{Os.rebuild(S)})};let Fs,Ns,Ls=Ds,Ps=class Document2 extends Ls{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Fs(new Ns,this,S).stringify()}};Ps.registerLazyResult=S=>{Fs=S},Ps.registerProcessor=S=>{Ns=S};var Bs=Ps;Ps.default=Ps;let zs=class Warning{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var Us=zs;zs.default=zs;let $s=Us,js=class Result{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new $s(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var qs=js;js.default=js;const Ws="'".charCodeAt(0),Hs='"'.charCodeAt(0),Vs="\\".charCodeAt(0),Qs="/".charCodeAt(0),Ks="\n".charCodeAt(0),Gs=" ".charCodeAt(0),Js="\f".charCodeAt(0),Xs="\t".charCodeAt(0),Ys="\r".charCodeAt(0),Zs="[".charCodeAt(0),er="]".charCodeAt(0),tr="(".charCodeAt(0),sr=")".charCodeAt(0),rr="{".charCodeAt(0),nr="}".charCodeAt(0),ir=";".charCodeAt(0),or="*".charCodeAt(0),ar=":".charCodeAt(0),lr="@".charCodeAt(0),cr=/[\t\n\f\r "#'()/;[\\\]{}]/g,ur=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,hr=/.[\r\n"'(/\\]/,dr=/[\da-f]/i;let gr=Ds,pr=class AtRule extends gr{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var fr=pr;pr.default=pr,gr.registerAtRule(pr);let mr,yr,vr=Ds,Sr=class Root extends vr{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new mr(new yr,this,S).stringify()}};Sr.registerLazyResult=S=>{mr=S},Sr.registerProcessor=S=>{yr=S};var wr=Sr;Sr.default=Sr,vr.registerRoot(Sr);let br={comma:S=>br.split(S,[","],!0),space:S=>br.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var Cr=br;br.default=br;let kr=Ds,Ir=Cr,Er=class Rule extends kr{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Ir.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var xr=Er;Er.default=Er,kr.registerRule(Er);let Mr=Bt,Rr=function tokenizer(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case Ks:case Gs:case Xs:case Ys:case Js:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===Gs||I===Ks||I===Xs||I===Ys||I===Js);$=["space",j.slice(V,x)],V=x-1;break;case Zs:case er:case rr:case nr:case ar:case ir:case sr:{let S=String.fromCharCode(I);$=[S,S,V];break}case tr:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==Ws&&U!==Hs&&U!==Gs&&U!==Ks&&U!==Xs&&U!==Js&&U!==Ys){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===Vs;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||hr.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case Ws:case Hs:R=I===Ws?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===Vs;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case lr:cr.lastIndex=V+1,cr.test(j),x=0===cr.lastIndex?j.length-1:cr.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case Vs:for(x=V,_=!0;j.charCodeAt(x+1)===Vs;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==Qs&&I!==Gs&&I!==Ks&&I!==Xs&&I!==Ys&&I!==Js&&(x+=1,dr.test(j.charAt(x)))){for(;dr.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===Gs&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===Qs&&j.charCodeAt(V+1)===or?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(ur.lastIndex=V+1,ur.test(j),x=0===ur.lastIndex?j.length-1:ur.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},Tr=Cs,Ar=fr,_r=wr,Or=xr;const Dr={empty:!0,space:!0};var Fr=class Parser{constructor(S){this.input=S,this.root=new _r,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new Ar;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new Tr;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=Rr(this.input)}decl(S,b){let I=new Mr;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition$1(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new Or;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",Dr[D]||Dr[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new Or;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let Nr=Ds,Lr=Fr,Pr=ls;function parse$3$1(S,b){let I=new Pr(S,b),x=new Lr(I);try{x.parse()}catch(S){throw S}return x.root}var Br=parse$3$1;parse$3$1.default=parse$3$1,Nr.registerParse(parse$3$1);let{isClean:zr,my:Ur}=kt,$r=Ss,jr=Rt,qr=Ds,Wr=Bs,Hr=qs,Vr=Br,Qr=wr;const Kr={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},Gr={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Jr={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise$1(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents$1(S){let b=!1,I=Kr[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack$1(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents$1(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks$1(S){return S[zr]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks$1(S)),S}let Xr={},Yr=class LazyResult{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult||b instanceof Hr)x=cleanMarks$1(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=Vr;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[Ur]&&qr.rebuild(x)}else x=cleanMarks$1(b);this.result=new Hr(S,x,I),this.helpers={...Xr,postcss:Xr,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!Gr[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Jr[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise$1(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[zr];){S[zr]=!0;let b=[toStack$1(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise$1(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise$1(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=jr;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new $r(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise$1(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[zr];)S[zr]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise$1(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[zr])return x[zr]=!0,void S.push(toStack$1(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[zr]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[zr]=!0;let b=getEvents$1(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[zr]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Yr.registerPostcss=S=>{Xr=S};var Zr=Yr;Yr.default=Yr,Qr.registerLazyResult(Yr),Wr.registerLazyResult(Yr);let en=Ss,tn=Rt,sn=Br;const rn=qs;let nn=class NoWorkResult{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=tn;this.result=new rn(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new en(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=sn;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var an=nn;nn.default=nn;let cn=an,un=Zr,hn=Bs,dn=wr,gn=class Processor{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new un(this,S,b):new cn(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var pn=gn;gn.default=gn,dn.registerProcessor(gn),hn.registerProcessor(gn);let fn=Bt,mn=Qt,yn=Cs,vn=fr,Sn=ls,wn=wr,bn=xr;function fromJSON$1$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:Sn.prototype};I.map&&(I.map={...I.map,__proto__:mn.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new wn(x);if("decl"===x.type)return new fn(x);if("rule"===x.type)return new bn(x);if("comment"===x.type)return new yn(x);if("atrule"===x.type)return new vn(x);throw new Error("Unknown node type: "+S.type)}var Cn=fromJSON$1$1;fromJSON$1$1.default=fromJSON$1$1;let kn=Ct,In=Bt,En=Zr,xn=Ds,Mn=pn,Rn=Rt,Tn=Cn,An=Bs,_n=Us,On=Cs,Dn=fr,Fn=qs,Nn=ls,Ln=Br,Pn=Cr,Bn=xr,zn=wr,Un=Nt;function postcss$3(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new Mn(S)}postcss$3.plugin=function plugin(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new Mn).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss$3([creator(I)]).process(S,b)},creator},postcss$3.stringify=Rn,postcss$3.parse=Ln,postcss$3.fromJSON=Tn,postcss$3.list=Pn,postcss$3.comment=S=>new On(S),postcss$3.atRule=S=>new Dn(S),postcss$3.decl=S=>new In(S),postcss$3.rule=S=>new Bn(S),postcss$3.root=S=>new zn(S),postcss$3.document=S=>new An(S),postcss$3.CssSyntaxError=kn,postcss$3.Declaration=In,postcss$3.Container=xn,postcss$3.Processor=Mn,postcss$3.Document=An,postcss$3.Comment=On,postcss$3.Warning=_n,postcss$3.AtRule=Dn,postcss$3.Result=Fn,postcss$3.Input=Nn,postcss$3.Rule=Bn,postcss$3.Root=zn,postcss$3.Node=Un,En.registerPostcss(postcss$3),postcss$3.default=postcss$3;var $n=Object.defineProperty,__publicField2=(S,b,I)=>((S,b,I)=>b in S?$n(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I);function getAugmentedNamespace(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var jn={exports:{}},qn=String,create=function(){return{isColorSupported:!1,reset:qn,bold:qn,dim:qn,italic:qn,underline:qn,inverse:qn,hidden:qn,strikethrough:qn,black:qn,red:qn,green:qn,yellow:qn,blue:qn,magenta:qn,cyan:qn,white:qn,gray:qn,bgBlack:qn,bgRed:qn,bgGreen:qn,bgYellow:qn,bgBlue:qn,bgMagenta:qn,bgCyan:qn,bgWhite:qn}};jn.exports=create(),jn.exports.createColors=create;var Wn=jn.exports;const Hn=getAugmentedNamespace(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Vn=Wn,Qn=Hn,Kn=class CssSyntaxError2 extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError2)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=Vn.isColorSupported),Qn&&S&&(b=Qn(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=Vn.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var Gn=Kn;Kn.default=Kn;var Jn={};Jn.isClean=Symbol("isClean"),Jn.my=Symbol("my");const Xn={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Yn=class Stringifier2{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return Xn[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=Xn[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var Zn=Yn;Yn.default=Yn;let ei=Zn;function stringify$4(S,b){new ei(b).stringify(S)}var ti=stringify$4;stringify$4.default=stringify$4;let{isClean:si,my:ri}=Jn,ni=Gn,ii=Zn,oi=ti;function cloneNode(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode(S,I)):("object"===A&&null!==R&&(R=cloneNode(R)),I[x]=R)}return I}let ai=class Node3{constructor(S={}){this.raws={},this[si]=!1,this[ri]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new ni(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[si]){this[si]=!1;let S=this;for(;S=S.parent;)S[si]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new ii).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=oi){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var li=ai;ai.default=ai;let ci=li,ui=class Declaration2 extends ci{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var hi=ui;ui.default=ui;var di={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:gi,SourceMapGenerator:pi}=Hn,{existsSync:fi,readFileSync:mi}=Hn,{dirname:yi,join:vi}=Hn;let Si=class PreviousMap2{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=yi(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new gi(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=yi(S),fi(S))return this.mapFile=S,mi(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof gi)return pi.fromSourceMap(b).toString();if(b instanceof pi)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=vi(yi(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var wi=Si;Si.default=Si;let{SourceMapConsumer:bi,SourceMapGenerator:Ci}=Hn,{fileURLToPath:ki,pathToFileURL:Ii}=Hn,{isAbsolute:Ei,resolve:xi}=Hn,{nanoid:Mi}=di,Ri=Hn,Ti=Gn,Ai=wi,_i=Symbol("fromOffsetCache"),Oi=Boolean(bi&&Ci),Di=Boolean(xi&&Ei),Fi=class Input2{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||""===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!Di||/^\w+:\/\//.test(b.from)||Ei(b.from)?this.file=b.from:this.file=xi(b.from)),Di&&Oi){let S=new Ai(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+Mi(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new Ti(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new Ti(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(Ii&&(R.input.url=Ii(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[_i])I=this[_i];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[_i]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:xi(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=Ei(D.source)?Ii(D.source):new URL(D.source,this.map.consumer().sourceRoot||Ii(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!ki)throw new Error("file: protocol is not available in this PostCSS build");L.file=ki(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var Ni=Fi;Fi.default=Fi,Ri&&Ri.registerInput&&Ri.registerInput(Fi);let{SourceMapConsumer:Li,SourceMapGenerator:Pi}=Hn,{dirname:Bi,relative:zi,resolve:Ui,sep:$i}=Hn,{pathToFileURL:ji}=Hn,qi=Ni,Wi=Boolean(Li&&Pi),Hi=Boolean(Bi&&Ui&&zi&&$i);var Vi=class MapGenerator2{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||Bi(S.file);!1===this.mapOpts.sourcesContent?(b=new Li(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),Hi&&Wi&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=Pi.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Pi({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Pi({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?Bi(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=Bi(Ui(I,this.mapOpts.annotation)));let x=zi(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new qi(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(ji){let b=ji(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===$i&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let Qi=li,Ki=class Comment2 extends Qi{constructor(S){super(S),this.type="comment"}};var Gi=Ki;Ki.default=Ki;let Ji,Xi,Yi,Zi,{isClean:eo,my:to}=Jn,so=hi,ro=Gi,no=li;function cleanSource(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource(S.nodes)),delete S.source,S))}function markDirtyUp(S){if(S[eo]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp(b)}let io=class Container2 extends no{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource(Ji(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new so(S)]}else if(S.selector)S=[new Xi(S)];else if(S.name)S=[new Yi(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new ro(S)]}return S.map(S=>(S[to]||Container2.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[eo]&&markDirtyUp(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};io.registerParse=S=>{Ji=S},io.registerRule=S=>{Xi=S},io.registerAtRule=S=>{Yi=S},io.registerRoot=S=>{Zi=S};var oo=io;io.default=io,io.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,Yi.prototype):"rule"===S.type?Object.setPrototypeOf(S,Xi.prototype):"decl"===S.type?Object.setPrototypeOf(S,so.prototype):"comment"===S.type?Object.setPrototypeOf(S,ro.prototype):"root"===S.type&&Object.setPrototypeOf(S,Zi.prototype),S[to]=!0,S.nodes&&S.nodes.forEach(S=>{io.rebuild(S)})};let ao,lo,co=oo,uo=class Document23 extends co{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new ao(new lo,this,S).stringify()}};uo.registerLazyResult=S=>{ao=S},uo.registerProcessor=S=>{lo=S};var ho=uo;uo.default=uo;let go=class Warning2{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var po=go;go.default=go;let fo=po,mo=class Result2{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new fo(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var yo=mo;mo.default=mo;const vo="'".charCodeAt(0),So='"'.charCodeAt(0),wo="\\".charCodeAt(0),bo="/".charCodeAt(0),Co="\n".charCodeAt(0),ko=" ".charCodeAt(0),Io="\f".charCodeAt(0),Eo="\t".charCodeAt(0),xo="\r".charCodeAt(0),Mo="[".charCodeAt(0),Ro="]".charCodeAt(0),To="(".charCodeAt(0),Ao=")".charCodeAt(0),_o="{".charCodeAt(0),Oo="}".charCodeAt(0),Do=";".charCodeAt(0),Fo="*".charCodeAt(0),No=":".charCodeAt(0),Lo="@".charCodeAt(0),Po=/[\t\n\f\r "#'()/;[\\\]{}]/g,Bo=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,zo=/.[\r\n"'(/\\]/,Uo=/[\da-f]/i;let $o=oo,jo=class AtRule2 extends $o{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var qo=jo;jo.default=jo,$o.registerAtRule(jo);let Wo,Ho,Vo=oo,Qo=class Root2 extends Vo{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new Wo(new Ho,this,S).stringify()}};Qo.registerLazyResult=S=>{Wo=S},Qo.registerProcessor=S=>{Ho=S};var Ko=Qo;Qo.default=Qo,Vo.registerRoot(Qo);let Go={comma:S=>Go.split(S,[","],!0),space:S=>Go.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var Jo=Go;Go.default=Go;let Xo=oo,Yo=Jo,Zo=class Rule2 extends Xo{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Yo.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var ea=Zo;Zo.default=Zo,Xo.registerRule(Zo);let ta=hi,sa=function tokenizer2(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case Co:case ko:case Eo:case xo:case Io:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===ko||I===Co||I===Eo||I===xo||I===Io);$=["space",j.slice(V,x)],V=x-1;break;case Mo:case Ro:case _o:case Oo:case No:case Do:case Ao:{let S=String.fromCharCode(I);$=[S,S,V];break}case To:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==vo&&U!==So&&U!==ko&&U!==Co&&U!==Eo&&U!==Io&&U!==xo){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===wo;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||zo.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case vo:case So:R=I===vo?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===wo;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Lo:Po.lastIndex=V+1,Po.test(j),x=0===Po.lastIndex?j.length-1:Po.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case wo:for(x=V,_=!0;j.charCodeAt(x+1)===wo;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==bo&&I!==ko&&I!==Co&&I!==Eo&&I!==xo&&I!==Io&&(x+=1,Uo.test(j.charAt(x)))){for(;Uo.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===ko&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===bo&&j.charCodeAt(V+1)===Fo?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(Bo.lastIndex=V+1,Bo.test(j),x=0===Bo.lastIndex?j.length-1:Bo.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},ra=Gi,na=qo,ia=Ko,oa=ea;const aa={empty:!0,space:!0};var la=class Parser2{constructor(S){this.input=S,this.root=new ia,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new na;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new ra;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=sa(this.input)}decl(S,b){let I=new ta;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new oa;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",aa[D]||aa[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new oa;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let ca=oo,ua=la,ha=Ni;function parse$3(S,b){let I=new ha(S,b),x=new ua(I);try{x.parse()}catch(S){throw S}return x.root}var da=parse$3;parse$3.default=parse$3,ca.registerParse(parse$3);let{isClean:ga,my:pa}=Jn,fa=Vi,ma=ti,ya=oo,va=ho,Sa=yo,wa=da,ba=Ko;const Ca={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},ka={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Ia={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents(S){let b=!1,I=Ca[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks(S){return S[ga]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks(S)),S}let Ea={},xa=class LazyResult2{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult2||b instanceof Sa)x=cleanMarks(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=wa;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[pa]&&ya.rebuild(x)}else x=cleanMarks(b);this.result=new Sa(S,x,I),this.helpers={...Ea,postcss:Ea,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!ka[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Ia[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[ga];){S[ga]=!0;let b=[toStack(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=ma;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new fa(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[ga];)S[ga]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[ga])return x[ga]=!0,void S.push(toStack(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[ga]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[ga]=!0;let b=getEvents(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[ga]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};xa.registerPostcss=S=>{Ea=S};var Ma=xa;xa.default=xa,ba.registerLazyResult(xa),va.registerLazyResult(xa);let Ra=Vi,Ta=ti,Aa=da;const _a=yo;let Oa=class NoWorkResult2{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=Ta;this.result=new _a(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new Ra(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=Aa;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var Da=Oa;Oa.default=Oa;let Fa=Da,Na=Ma,La=ho,Pa=Ko,Ba=class Processor2{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new Na(this,S,b):new Fa(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var za=Ba;Ba.default=Ba,Pa.registerProcessor(Ba),La.registerProcessor(Ba);let Ua=hi,$a=wi,ja=Gi,qa=qo,Wa=Ni,Ha=Ko,Va=ea;function fromJSON$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:Wa.prototype};I.map&&(I.map={...I.map,__proto__:$a.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new Ha(x);if("decl"===x.type)return new Ua(x);if("rule"===x.type)return new Va(x);if("comment"===x.type)return new ja(x);if("atrule"===x.type)return new qa(x);throw new Error("Unknown node type: "+S.type)}var Qa=fromJSON$1;fromJSON$1.default=fromJSON$1;let Ka=Gn,Ga=hi,Ja=Ma,Xa=oo,Ya=za,Za=ti,el=Qa,tl=ho,sl=po,rl=Gi,nl=qo,il=yo,ol=Ni,al=da,ll=Jo,cl=ea,ul=Ko,hl=li;function postcss(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new Ya(S)}postcss.plugin=function plugin2(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new Ya).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss([creator(I)]).process(S,b)},creator},postcss.stringify=Za,postcss.parse=al,postcss.fromJSON=el,postcss.list=ll,postcss.comment=S=>new rl(S),postcss.atRule=S=>new nl(S),postcss.decl=S=>new Ga(S),postcss.rule=S=>new cl(S),postcss.root=S=>new ul(S),postcss.document=S=>new tl(S),postcss.CssSyntaxError=Ka,postcss.Declaration=Ga,postcss.Container=Xa,postcss.Processor=Ya,postcss.Document=tl,postcss.Comment=rl,postcss.Warning=sl,postcss.AtRule=nl,postcss.Result=il,postcss.Input=ol,postcss.Rule=cl,postcss.Root=ul,postcss.Node=hl,Ja.registerPostcss(postcss),postcss.default=postcss;class BaseRRNode{constructor(...S){__publicField2(this,"parentElement",null),__publicField2(this,"parentNode",null),__publicField2(this,"ownerDocument"),__publicField2(this,"firstChild",null),__publicField2(this,"lastChild",null),__publicField2(this,"previousSibling",null),__publicField2(this,"nextSibling",null),__publicField2(this,"ELEMENT_NODE",1),__publicField2(this,"TEXT_NODE",3),__publicField2(this,"nodeType"),__publicField2(this,"nodeName"),__publicField2(this,"RRNodeType")}get childNodes(){const S=[];let b=this.firstChild;for(;b;)S.push(b),b=b.nextSibling;return S}contains(S){if(!(S instanceof BaseRRNode))return!1;if(S.ownerDocument!==this.ownerDocument)return!1;if(S===this)return!0;for(;S.parentNode;){if(S.parentNode===this)return!0;S=S.parentNode}return!1}appendChild(S){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(S,b){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(S){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}}const dl={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},gl={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},pl={};function getUntaintedPrototype(S){if(pl[S])return pl[S];const b=globalThis[S],I=b.prototype,x=S in dl?dl[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in gl?gl[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return pl[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?pl[S]=A:I}catch{return I}}const fl={};function getUntaintedAccessor(S,b,I){var x;const R=`${S}.${String(I)}`;if(fl[R])return fl[R].call(b);const A=getUntaintedPrototype(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(fl[R]=_,_.call(b)):b[I]}const ml={};function getUntaintedMethod(S,b,I){const x=`${S}.${String(I)}`;if(ml[x])return ml[x].bind(b);const R=getUntaintedPrototype(S)[I];return"function"!=typeof R?b[I]:(ml[x]=R,R.bind(b))}function mutationObserverCtor(){return getUntaintedPrototype("MutationObserver").constructor}const yl={childNodes:function childNodes(S){return getUntaintedAccessor("Node",S,"childNodes")},parentNode:function parentNode(S){return getUntaintedAccessor("Node",S,"parentNode")},parentElement:function parentElement(S){return getUntaintedAccessor("Node",S,"parentElement")},textContent:function textContent(S){return getUntaintedAccessor("Node",S,"textContent")},contains:function contains(S,b){return getUntaintedMethod("Node",S,"contains")(b)},getRootNode:function getRootNode(S){return getUntaintedMethod("Node",S,"getRootNode")()},host:function host(S){return S&&"host"in S?getUntaintedAccessor("ShadowRoot",S,"host"):null},styleSheets:function styleSheets(S){return S.styleSheets},shadowRoot:function shadowRoot(S){return S&&"shadowRoot"in S?getUntaintedAccessor("Element",S,"shadowRoot"):null},querySelector:function querySelector(S,b){return getUntaintedAccessor("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll(S,b){return getUntaintedAccessor("Element",S,"querySelectorAll")(b)},mutationObserver:mutationObserverCtor};function on(S,b,I=document){const x={capture:!0,passive:!0};return I.addEventListener(S,b,x),()=>I.removeEventListener(S,b,x)}const vl="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 Sl={map:{},getId:()=>(console.error(vl),-1),getNode:()=>(console.error(vl),null),removeNodeFromMap(){console.error(vl)},has:()=>(console.error(vl),!1),reset(){console.error(vl)}};function throttle(S,b,I={}){let x=null,R=0;return function(...A){const _=Date.now();R||!1!==I.leading||(R=_);const D=b-(_-R),L=this;D<=0||D>b?(x&&(clearTimeout(x),x=null),R=_,S.apply(L,A)):x||!1===I.trailing||(x=setTimeout(()=>{R=!1===I.leading?0:Date.now(),x=null,S.apply(L,A)},D))}}function hookSetter(S,b,I,x,R=window){const A=R.Object.getOwnPropertyDescriptor(S,b);return R.Object.defineProperty(S,b,x?I:{set(S){setTimeout(()=>{I.set.call(this,S)},0),A&&A.set&&A.set.call(this,S)}}),()=>hookSetter(S,b,A||{},!0)}function patch(S,b,I){try{if(!(b in S))return()=>{};const x=S[b],R=I(x);return"function"==typeof R&&(R.prototype=R.prototype||{},Object.defineProperties(R,{__rrweb_original__:{enumerable:!1,value:x}})),S[b]=R,()=>{S[b]=x}}catch{return()=>{}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Sl=new Proxy(Sl,{get:(S,b,I)=>("map"===b&&console.error(vl),Reflect.get(S,b,I))}));let wl=Date.now;function getWindowScroll(S){var b,I,x,R;const A=S.document;return{left:A.scrollingElement?A.scrollingElement.scrollLeft:void 0!==S.pageXOffset?S.pageXOffset:A.documentElement.scrollLeft||(null==A?void 0:A.body)&&(null==(b=yl.parentElement(A.body))?void 0:b.scrollLeft)||(null==(I=null==A?void 0:A.body)?void 0:I.scrollLeft)||0,top:A.scrollingElement?A.scrollingElement.scrollTop:void 0!==S.pageYOffset?S.pageYOffset:(null==A?void 0:A.documentElement.scrollTop)||(null==A?void 0:A.body)&&(null==(x=yl.parentElement(A.body))?void 0:x.scrollTop)||(null==(R=null==A?void 0:A.body)?void 0:R.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(S){if(!S)return null;return S.nodeType===S.ELEMENT_NODE?S:yl.parentElement(S)}function isBlocked(S,b,I,x){if(!S)return!1;const R=closestElementOfNode(S);if(!R)return!1;try{if("string"==typeof b){if(R.classList.contains(b))return!0;if(x&&null!==R.closest("."+b))return!0}else if(classMatchesRegex(R,b,x))return!0}catch(S){}if(I){if(R.matches(I))return!0;if(x&&null!==R.closest(I))return!0}return!1}function isIgnored(S,b,I){return!("TITLE"!==S.tagName||!I.headTitleMutations)||-2===b.getId(S)}function isAncestorRemoved(S,b){if(isShadowRoot(S))return!1;const I=b.getId(S);if(!b.has(I))return!0;const x=yl.parentNode(S);return(!x||x.nodeType!==S.DOCUMENT_NODE)&&(!x||isAncestorRemoved(x,b))}function legacy_isTouchEvent(S){return Boolean(S.changedTouches)}function isSerializedIframe(S,b){return Boolean("IFRAME"===S.nodeName&&b.getMeta(S))}function isSerializedStylesheet(S,b){return Boolean("LINK"===S.nodeName&&S.nodeType===S.ELEMENT_NODE&&S.getAttribute&&"stylesheet"===S.getAttribute("rel")&&b.getMeta(S))}function hasShadowRoot(S){return!!S&&(S instanceof BaseRRNode&&"shadowRoot"in S?Boolean(S.shadowRoot):Boolean(yl.shadowRoot(S)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(wl=()=>(new Date).getTime());class StyleSheetMirror{constructor(){__publicField(this,"id",1),__publicField(this,"styleIDMap",new WeakMap),__publicField(this,"idStyleMap",new Map)}getId(S){return this.styleIDMap.get(S)??-1}has(S){return this.styleIDMap.has(S)}add(S,b){if(this.has(S))return this.getId(S);let I;return I=void 0===b?this.id++:b,this.styleIDMap.set(S,I),this.idStyleMap.set(I,S),I}getStyle(S){return this.idStyleMap.get(S)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function getShadowHost(S){var b;let I=null;return"getRootNode"in S&&(null==(b=yl.getRootNode(S))?void 0:b.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&yl.host(yl.getRootNode(S))&&(I=yl.host(yl.getRootNode(S))),I}function shadowHostInDom(S){const b=S.ownerDocument;if(!b)return!1;const I=function getRootShadowHost(S){let b,I=S;for(;b=getShadowHost(I);)I=b;return I}(S);return yl.contains(b,I)}function inDom(S){const b=S.ownerDocument;return!!b&&(yl.contains(b,S)||shadowHostInDom(S))}var bl=(S=>(S[S.DomContentLoaded=0]="DomContentLoaded",S[S.Load=1]="Load",S[S.FullSnapshot=2]="FullSnapshot",S[S.IncrementalSnapshot=3]="IncrementalSnapshot",S[S.Meta=4]="Meta",S[S.Custom=5]="Custom",S[S.Plugin=6]="Plugin",S))(bl||{}),Cl=(S=>(S[S.Mutation=0]="Mutation",S[S.MouseMove=1]="MouseMove",S[S.MouseInteraction=2]="MouseInteraction",S[S.Scroll=3]="Scroll",S[S.ViewportResize=4]="ViewportResize",S[S.Input=5]="Input",S[S.TouchMove=6]="TouchMove",S[S.MediaInteraction=7]="MediaInteraction",S[S.StyleSheetRule=8]="StyleSheetRule",S[S.CanvasMutation=9]="CanvasMutation",S[S.Font=10]="Font",S[S.Log=11]="Log",S[S.Drag=12]="Drag",S[S.StyleDeclaration=13]="StyleDeclaration",S[S.Selection=14]="Selection",S[S.AdoptedStyleSheet=15]="AdoptedStyleSheet",S[S.CustomElement=16]="CustomElement",S))(Cl||{}),kl=(S=>(S[S.MouseUp=0]="MouseUp",S[S.MouseDown=1]="MouseDown",S[S.Click=2]="Click",S[S.ContextMenu=3]="ContextMenu",S[S.DblClick=4]="DblClick",S[S.Focus=5]="Focus",S[S.Blur=6]="Blur",S[S.TouchStart=7]="TouchStart",S[S.TouchMove_Departed=8]="TouchMove_Departed",S[S.TouchEnd=9]="TouchEnd",S[S.TouchCancel=10]="TouchCancel",S))(kl||{}),Il=(S=>(S[S.Mouse=0]="Mouse",S[S.Pen=1]="Pen",S[S.Touch=2]="Touch",S))(Il||{}),El=(S=>(S[S["2D"]=0]="2D",S[S.WebGL=1]="WebGL",S[S.WebGL2=2]="WebGL2",S))(El||{}),xl=(S=>(S[S.Play=0]="Play",S[S.Pause=1]="Pause",S[S.Seeked=2]="Seeked",S[S.VolumeChange=3]="VolumeChange",S[S.RateChange=4]="RateChange",S))(xl||{}),Ml=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(Ml||{});function isNodeInLinkedList(S){return"__ln"in S}class DoubleLinkedList{constructor(){__publicField(this,"length",0),__publicField(this,"head",null),__publicField(this,"tail",null)}get(S){if(S>=this.length)throw new Error("Position outside of list range");let b=this.head;for(let I=0;I<S;I++)b=(null==b?void 0:b.next)||null;return b}addNode(S){const b={value:S,previous:null,next:null};if(S.__ln=b,S.previousSibling&&isNodeInLinkedList(S.previousSibling)){const I=S.previousSibling.__ln.next;b.next=I,b.previous=S.previousSibling.__ln,S.previousSibling.__ln.next=b,I&&(I.previous=b)}else if(S.nextSibling&&isNodeInLinkedList(S.nextSibling)&&S.nextSibling.__ln.previous){const I=S.nextSibling.__ln.previous;b.previous=I,b.next=S.nextSibling.__ln,S.nextSibling.__ln.previous=b,I&&(I.next=b)}else this.head&&(this.head.previous=b),b.next=this.head,this.head=b;null===b.next&&(this.tail=b),this.length++}removeNode(S){const b=S.__ln;this.head&&(b.previous?(b.previous.next=b.next,b.next?b.next.previous=b.previous:this.tail=b.previous):(this.head=b.next,this.head?this.head.previous=null:this.tail=null),S.__ln&&delete S.__ln,this.length--)}}const moveKey=(S,b)=>`${S}@${b}`;class MutationBuffer{constructor(){__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"texts",[]),__publicField(this,"attributes",[]),__publicField(this,"attributeMap",new WeakMap),__publicField(this,"removes",[]),__publicField(this,"mapRemoves",[]),__publicField(this,"movedMap",{}),__publicField(this,"addedSet",new Set),__publicField(this,"movedSet",new Set),__publicField(this,"droppedSet",new Set),__publicField(this,"removesSubTreeCache",new Set),__publicField(this,"mutationCb"),__publicField(this,"blockClass"),__publicField(this,"blockSelector"),__publicField(this,"maskTextClass"),__publicField(this,"maskTextSelector"),__publicField(this,"inlineStylesheet"),__publicField(this,"maskInputOptions"),__publicField(this,"maskTextFn"),__publicField(this,"maskInputFn"),__publicField(this,"keepIframeSrcFn"),__publicField(this,"recordCanvas"),__publicField(this,"inlineImages"),__publicField(this,"slimDOMOptions"),__publicField(this,"dataURLOptions"),__publicField(this,"doc"),__publicField(this,"mirror"),__publicField(this,"iframeManager"),__publicField(this,"stylesheetManager"),__publicField(this,"shadowDomManager"),__publicField(this,"canvasManager"),__publicField(this,"processedNodeManager"),__publicField(this,"unattachedDoc"),__publicField(this,"processMutations",S=>{S.forEach(this.processMutation),this.emit()}),__publicField(this,"emit",()=>{if(this.frozen||this.locked)return;const S=[],b=new Set,I=new DoubleLinkedList,getNextId=S=>{let b=S,I=-2;for(;-2===I;)b=b&&b.nextSibling,I=b&&this.mirror.getId(b);return I},pushAdd=x=>{const R=yl.parentNode(x);if(!R||!inDom(x))return;let A=!1;if(x.nodeType===Node.TEXT_NODE){const S=R.tagName;if("TEXTAREA"===S)return;"STYLE"===S&&this.addedSet.has(R)&&(A=!0)}const _=isShadowRoot(R)?this.mirror.getId(getShadowHost(x)):this.mirror.getId(R),D=getNextId(x);if(-1===_||-1===D)return I.addNode(x);const L=serializeNodeWithId(x,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:S=>{isSerializedIframe(S,this.mirror)&&this.iframeManager.addIframe(S),isSerializedStylesheet(S,this.mirror)&&this.stylesheetManager.trackLinkElement(S),hasShadowRoot(x)&&this.shadowDomManager.addShadowRoot(yl.shadowRoot(x),this.doc)},onIframeLoad:(S,b)=>{this.iframeManager.attachIframe(S,b),this.shadowDomManager.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{this.stylesheetManager.attachLinkElement(S,b)},cssCaptured:A});L&&(S.push({parentId:_,nextId:D,node:L}),b.add(L.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const S of this.movedSet)isParentRemoved(this.removesSubTreeCache,S)&&!this.movedSet.has(yl.parentNode(S))||pushAdd(S);for(const S of this.addedSet)isAncestorInSet(this.droppedSet,S)||isParentRemoved(this.removesSubTreeCache,S)?isAncestorInSet(this.movedSet,S)?pushAdd(S):this.droppedSet.add(S):pushAdd(S);let x=null;for(;I.length;){let S=null;if(x){const b=this.mirror.getId(yl.parentNode(x.value)),I=getNextId(x.value);-1!==b&&-1!==I&&(S=x)}if(!S){let b=I.tail;for(;b;){const I=b;if(b=b.previous,I){const b=this.mirror.getId(yl.parentNode(I.value));if(-1===getNextId(I.value))continue;if(-1!==b){S=I;break}{const b=I.value,x=yl.parentNode(b);if(x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const b=yl.host(x);if(-1!==this.mirror.getId(b)){S=I;break}}}}}}if(!S){for(;I.head;)I.removeNode(I.head.value);break}x=S.previous,I.removeNode(S.value),pushAdd(S.value)}const R={texts:this.texts.map(S=>{const b=S.node,I=yl.parentNode(b);return I&&"TEXTAREA"===I.tagName&&this.genTextAreaValueMutation(I),{id:this.mirror.getId(b),value:S.value}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),attributes:this.attributes.map(S=>{const{attributes:b}=S;if("string"==typeof b.style){const I=JSON.stringify(S.styleDiff),x=JSON.stringify(S._unchangedStyles);I.length<b.style.length&&(I+x).split("var(").length===b.style.split("var(").length&&(b.style=S.styleDiff)}return{id:this.mirror.getId(S.node),attributes:b}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),removes:this.removes,adds:S};(R.texts.length||R.attributes.length||R.removes.length||R.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.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(R))}),__publicField(this,"genTextAreaValueMutation",S=>{let b=this.attributeMap.get(S);b||(b={node:S,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(b),this.attributeMap.set(S,b)),b.attributes.value=Array.from(yl.childNodes(S),S=>yl.textContent(S)||"").join("")}),__publicField(this,"processMutation",S=>{if(!isIgnored(S.target,this.mirror,this.slimDOMOptions))switch(S.type){case"characterData":{const b=yl.textContent(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||b===S.oldValue||this.texts.push({value:needMaskingText(S.target,this.maskTextClass,this.maskTextSelector,!0)&&b?this.maskTextFn?this.maskTextFn(b,closestElementOfNode(S.target)):b.replace(/[\S]/g,"*"):b,node:S.target});break}case"attributes":{const b=S.target;let I=S.attributeName,x=S.target.getAttribute(I);if("value"===I){const S=getInputType(b);x=maskInputValue({element:b,maskInputOptions:this.maskInputOptions,tagName:b.tagName,type:S,value:x,maskInputFn:this.maskInputFn})}if(isBlocked(S.target,this.blockClass,this.blockSelector,!1)||x===S.oldValue)return;let R=this.attributeMap.get(S.target);if("IFRAME"===b.tagName&&"src"===I&&!this.keepIframeSrcFn(x)){if(b.contentDocument)return;I="rr_src"}if(R||(R={node:S.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(R),this.attributeMap.set(S.target,R)),"type"===I&&"INPUT"===b.tagName&&"password"===(S.oldValue||"").toLowerCase()&&b.setAttribute("data-rr-is-password","true"),!ignoreAttribute(b.tagName,I))if(R.attributes[I]=transformAttribute(this.doc,toLowerCase(b.tagName),toLowerCase(I),x),"style"===I){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(S){this.unattachedDoc=this.doc}const I=this.unattachedDoc.createElement("span");S.oldValue&&I.setAttribute("style",S.oldValue);for(const S of Array.from(b.style)){const x=b.style.getPropertyValue(S),A=b.style.getPropertyPriority(S);x!==I.style.getPropertyValue(S)||A!==I.style.getPropertyPriority(S)?R.styleDiff[S]=""===A?x:[x,A]:R._unchangedStyles[S]=[x,A]}for(const S of Array.from(I.style))""===b.style.getPropertyValue(S)&&(R.styleDiff[S]=!1)}else"open"===I&&"DIALOG"===b.tagName&&(b.matches("dialog:modal")?R.attributes.rr_open_mode="modal":R.attributes.rr_open_mode="non-modal");break}case"childList":if(isBlocked(S.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===S.target.tagName)return void this.genTextAreaValueMutation(S.target);S.addedNodes.forEach(b=>this.genAdds(b,S.target)),S.removedNodes.forEach(b=>{const I=this.mirror.getId(b),x=isShadowRoot(S.target)?this.mirror.getId(yl.host(S.target)):this.mirror.getId(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||isIgnored(b,this.mirror,this.slimDOMOptions)||!function isSerialized(S,b){return-1!==b.getId(S)}(b,this.mirror)||(this.addedSet.has(b)?(deepDelete(this.addedSet,b),this.droppedSet.add(b)):this.addedSet.has(S.target)&&-1===I||isAncestorRemoved(S.target,this.mirror)||(this.movedSet.has(b)&&this.movedMap[moveKey(I,x)]?deepDelete(this.movedSet,b):(this.removes.push({parentId:x,id:I,isShadow:!(!isShadowRoot(S.target)||!isNativeShadowDom(S.target))||void 0}),function processRemoves(S,b){const I=[S];for(;I.length;){const S=I.pop();b.has(S)||(b.add(S),yl.childNodes(S).forEach(S=>I.push(S)))}return}(b,this.removesSubTreeCache))),this.mapRemoves.push(b))})}}),__publicField(this,"genAdds",(S,b)=>{if(!this.processedNodeManager.inOtherBuffer(S,this)&&!this.addedSet.has(S)&&!this.movedSet.has(S)){if(this.mirror.hasNode(S)){if(isIgnored(S,this.mirror,this.slimDOMOptions))return;this.movedSet.add(S);let I=null;b&&this.mirror.hasNode(b)&&(I=this.mirror.getId(b)),I&&-1!==I&&(this.movedMap[moveKey(this.mirror.getId(S),I)]=!0)}else this.addedSet.add(S),this.droppedSet.delete(S);isBlocked(S,this.blockClass,this.blockSelector,!1)||(yl.childNodes(S).forEach(S=>this.genAdds(S)),hasShadowRoot(S)&&yl.childNodes(yl.shadowRoot(S)).forEach(b=>{this.processedNodeManager.add(b,this),this.genAdds(b,S)}))}})}init(S){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(b=>{this[b]=S[b]})}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(S,b){S.delete(b),yl.childNodes(b).forEach(b=>deepDelete(S,b))}function isParentRemoved(S,b,I){return 0!==S.size&&function _isParentRemoved(S,b,I){const x=yl.parentNode(b);return!!x&&S.has(x)}(S,b)}function isAncestorInSet(S,b){return 0!==S.size&&_isAncestorInSet(S,b)}function _isAncestorInSet(S,b){const I=yl.parentNode(b);return!!I&&(!!S.has(I)||_isAncestorInSet(S,I))}let Rl;const callbackWrapper=S=>{if(!Rl)return S;return(...b)=>{try{return S(...b)}catch(S){if(Rl&&!0===Rl(S))return;throw S}}},Tl=[];function getEventTarget(S){try{if("composedPath"in S){const b=S.composedPath();if(b.length)return b[0]}else if("path"in S&&S.path.length)return S.path[0]}catch{}return S&&S.target}function initMutationObserver(S,b){const I=new MutationBuffer;Tl.push(I),I.init(S);const x=new(mutationObserverCtor())(callbackWrapper(I.processMutations.bind(I)));return x.observe(b,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),x}function initMouseInteractionObserver({mouseInteractionCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){if(!1===A.mouseInteraction)return()=>{};const _=!0===A.mouseInteraction||void 0===A.mouseInteraction?{}:A.mouseInteraction,D=[];let L=null;return Object.keys(kl).filter(S=>Number.isNaN(Number(S))&&!S.endsWith("_Departed")&&!1!==_[S]).forEach(A=>{let _=toLowerCase(A);const B=(b=>A=>{const _=getEventTarget(A);if(isBlocked(_,x,R,!0))return;let D=null,B=b;if("pointerType"in A){switch(A.pointerType){case"mouse":D=Il.Mouse;break;case"touch":D=Il.Touch;break;case"pen":D=Il.Pen}D===Il.Touch&&(kl[b]===kl.MouseDown?B="TouchStart":kl[b]===kl.MouseUp&&(B="TouchEnd"))}else legacy_isTouchEvent(A)&&(D=Il.Touch);null!==D?(L=D,(B.startsWith("Touch")&&D===Il.Touch||B.startsWith("Mouse")&&D===Il.Mouse)&&(D=null)):kl[b]===kl.Click&&(D=L,L=null);const U=legacy_isTouchEvent(A)?A.changedTouches[0]:A;if(!U)return;const $=I.getId(_),{clientX:j,clientY:W}=U;callbackWrapper(S)({type:kl[B],id:$,x:j,y:W,...null!==D&&{pointerType:D}})})(A);if(window.PointerEvent)switch(kl[A]){case kl.MouseDown:case kl.MouseUp:_=_.replace("mouse","pointer");break;case kl.TouchStart:case kl.TouchEnd:return}D.push(on(_,B,b))}),callbackWrapper(()=>{D.forEach(S=>S())})}function initScrollObserver({scrollCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){return on("scroll",callbackWrapper(throttle(callbackWrapper(A=>{const _=getEventTarget(A);if(!_||isBlocked(_,x,R,!0))return;const D=I.getId(_);if(_===b&&b.defaultView){const I=getWindowScroll(b.defaultView);S({id:D,x:I.left,y:I.top})}else S({id:D,x:_.scrollLeft,y:_.scrollTop})}),A.scroll||100)),b)}const Al=["INPUT","TEXTAREA","SELECT"],_l=new WeakMap;function getNestedCSSRulePositions(S){return function recurse(S,b){if(hasNestedCSSRule("CSSGroupingRule")&&S.parentRule instanceof CSSGroupingRule||hasNestedCSSRule("CSSMediaRule")&&S.parentRule instanceof CSSMediaRule||hasNestedCSSRule("CSSSupportsRule")&&S.parentRule instanceof CSSSupportsRule||hasNestedCSSRule("CSSConditionRule")&&S.parentRule instanceof CSSConditionRule){const I=Array.from(S.parentRule.cssRules).indexOf(S);b.unshift(I)}else if(S.parentStyleSheet){const I=Array.from(S.parentStyleSheet.cssRules).indexOf(S);b.unshift(I)}return b}(S,[])}function getIdAndStyleId(S,b,I){let x,R;return S?(S.ownerNode?x=b.getId(S.ownerNode):R=I.getId(S),{styleId:R,id:x}):{}}function initAdoptedStyleSheetObserver({mirror:S,stylesheetManager:b},I){var x,R,A;let _=null;_="#document"===I.nodeName?S.getId(I):S.getId(yl.host(I));const D="#document"===I.nodeName?null==(x=I.defaultView)?void 0:x.Document:null==(A=null==(R=I.ownerDocument)?void 0:R.defaultView)?void 0:A.ShadowRoot,L=(null==D?void 0:D.prototype)?Object.getOwnPropertyDescriptor(null==D?void 0:D.prototype,"adoptedStyleSheets"):void 0;return null!==_&&-1!==_&&D&&L?(Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get(){var S;return null==(S=L.get)?void 0:S.call(this)},set(S){var I;const x=null==(I=L.set)?void 0:I.call(this,S);if(null!==_&&-1!==_)try{b.adoptStyleSheets(S,_)}catch(S){}return x}}),callbackWrapper(()=>{Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get:L.get,set:L.set})})):()=>{}}function initObservers(S,b={}){const I=S.doc.defaultView;if(!I)return()=>{};let x;!function mergeHooks(S,b){const{mutationCb:I,mousemoveCb:x,mouseInteractionCb:R,scrollCb:A,viewportResizeCb:_,inputCb:D,mediaInteractionCb:L,styleSheetRuleCb:B,styleDeclarationCb:U,canvasMutationCb:$,fontCb:j,selectionCb:W,customElementCb:H}=S;S.mutationCb=(...S)=>{b.mutation&&b.mutation(...S),I(...S)},S.mousemoveCb=(...S)=>{b.mousemove&&b.mousemove(...S),x(...S)},S.mouseInteractionCb=(...S)=>{b.mouseInteraction&&b.mouseInteraction(...S),R(...S)},S.scrollCb=(...S)=>{b.scroll&&b.scroll(...S),A(...S)},S.viewportResizeCb=(...S)=>{b.viewportResize&&b.viewportResize(...S),_(...S)},S.inputCb=(...S)=>{b.input&&b.input(...S),D(...S)},S.mediaInteractionCb=(...S)=>{b.mediaInteaction&&b.mediaInteaction(...S),L(...S)},S.styleSheetRuleCb=(...S)=>{b.styleSheetRule&&b.styleSheetRule(...S),B(...S)},S.styleDeclarationCb=(...S)=>{b.styleDeclaration&&b.styleDeclaration(...S),U(...S)},S.canvasMutationCb=(...S)=>{b.canvasMutation&&b.canvasMutation(...S),$(...S)},S.fontCb=(...S)=>{b.font&&b.font(...S),j(...S)},S.selectionCb=(...S)=>{b.selection&&b.selection(...S),W(...S)},S.customElementCb=(...S)=>{b.customElement&&b.customElement(...S),H(...S)}}(S,b),S.recordDOM&&(x=initMutationObserver(S,S.doc));const R=function initMoveObserver({mousemoveCb:S,sampling:b,doc:I,mirror:x}){if(!1===b.mousemove)return()=>{};const R="number"==typeof b.mousemove?b.mousemove:50,A="number"==typeof b.mousemoveCallback?b.mousemoveCallback:500;let _,D=[];const L=throttle(callbackWrapper(b=>{const I=Date.now()-_;S(D.map(S=>(S.timeOffset-=I,S)),b),D=[],_=null}),A),B=callbackWrapper(throttle(callbackWrapper(S=>{const b=getEventTarget(S),{clientX:I,clientY:R}=legacy_isTouchEvent(S)?S.changedTouches[0]:S;_||(_=wl()),D.push({x:I,y:R,id:x.getId(b),timeOffset:wl()-_}),L("undefined"!=typeof DragEvent&&S instanceof DragEvent?Cl.Drag:S instanceof MouseEvent?Cl.MouseMove:Cl.TouchMove)}),R,{trailing:!1})),U=[on("mousemove",B,I),on("touchmove",B,I),on("drag",B,I)];return callbackWrapper(()=>{U.forEach(S=>S())})}(S),A=initMouseInteractionObserver(S),_=initScrollObserver(S),D=function initViewportResizeObserver({viewportResizeCb:S},{win:b}){let I=-1,x=-1;return on("resize",callbackWrapper(throttle(callbackWrapper(()=>{const b=getWindowHeight(),R=getWindowWidth();I===b&&x===R||(S({width:Number(R),height:Number(b)}),I=b,x=R)}),200)),b)}(S,{win:I}),L=function initInputObserver({inputCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,ignoreClass:A,ignoreSelector:_,maskInputOptions:D,maskInputFn:L,sampling:B,userTriggeredOnInput:U}){function eventHandler(S){let I=getEventTarget(S);const B=S.isTrusted,$=I&&I.tagName;if(I&&"OPTION"===$&&(I=yl.parentElement(I)),!I||!$||Al.indexOf($)<0||isBlocked(I,x,R,!0))return;if(I.classList.contains(A)||_&&I.matches(_))return;let j=I.value,W=!1;const H=getInputType(I)||"";"radio"===H||"checkbox"===H?W=I.checked:(D[$.toLowerCase()]||D[H])&&(j=maskInputValue({element:I,maskInputOptions:D,tagName:$,type:H,value:j,maskInputFn:L})),cbWithDedup(I,U?{text:j,isChecked:W,userTriggered:B}:{text:j,isChecked:W});const V=I.name;"radio"===H&&V&&W&&b.querySelectorAll(`input[type="radio"][name="${V}"]`).forEach(S=>{if(S!==I){const b=S.value;cbWithDedup(S,U?{text:b,isChecked:!W,userTriggered:!1}:{text:b,isChecked:!W})}})}function cbWithDedup(b,x){const R=_l.get(b);if(!R||R.text!==x.text||R.isChecked!==x.isChecked){_l.set(b,x);const R=I.getId(b);callbackWrapper(S)({...x,id:R})}}const $=("last"===B.input?["change"]:["input","change"]).map(S=>on(S,callbackWrapper(eventHandler),b)),j=b.defaultView;if(!j)return()=>{$.forEach(S=>S())};const W=j.Object.getOwnPropertyDescriptor(j.HTMLInputElement.prototype,"value"),H=[[j.HTMLInputElement.prototype,"value"],[j.HTMLInputElement.prototype,"checked"],[j.HTMLSelectElement.prototype,"value"],[j.HTMLTextAreaElement.prototype,"value"],[j.HTMLSelectElement.prototype,"selectedIndex"],[j.HTMLOptionElement.prototype,"selected"]];return W&&W.set&&$.push(...H.map(S=>hookSetter(S[0],S[1],{set(){callbackWrapper(eventHandler)({target:this,isTrusted:!1})}},!1,j))),callbackWrapper(()=>{$.forEach(S=>S())})}(S),B=function initMediaInteractionObserver({mediaInteractionCb:S,blockClass:b,blockSelector:I,mirror:x,sampling:R,doc:A}){const _=callbackWrapper(A=>throttle(callbackWrapper(R=>{const _=getEventTarget(R);if(!_||isBlocked(_,b,I,!0))return;const{currentTime:D,volume:L,muted:B,playbackRate:U,loop:$}=_;S({type:A,id:x.getId(_),currentTime:D,volume:L,muted:B,playbackRate:U,loop:$})}),R.media||500)),D=[on("play",_(xl.Play),A),on("pause",_(xl.Pause),A),on("seeked",_(xl.Seeked),A),on("volumechange",_(xl.VolumeChange),A),on("ratechange",_(xl.RateChange),A)];return callbackWrapper(()=>{D.forEach(S=>S())})}(S);let styleSheetObserver=()=>{},adoptedStyleSheetObserver=()=>{},styleDeclarationObserver=()=>{},fontObserver=()=>{};S.recordDOM&&(styleSheetObserver=function initStyleSheetObserver({styleSheetRuleCb:S,mirror:b,stylesheetManager:I},{win:x}){if(!x.CSSStyleSheet||!x.CSSStyleSheet.prototype)return()=>{};const R=x.CSSStyleSheet.prototype.insertRule;x.CSSStyleSheet.prototype.insertRule=new Proxy(R,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:D}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.addRule=function(S,b,I=this.cssRules.length){const R=`${S} { ${b} }`;return x.CSSStyleSheet.prototype.insertRule.apply(this,[R,I])};const A=x.CSSStyleSheet.prototype.deleteRule;let _,D;x.CSSStyleSheet.prototype.deleteRule=new Proxy(A,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:_}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.removeRule=function(S){return x.CSSStyleSheet.prototype.deleteRule.apply(this,[S])},x.CSSStyleSheet.prototype.replace&&(_=x.CSSStyleSheet.prototype.replace,x.CSSStyleSheet.prototype.replace=new Proxy(_,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replace:_}),x.apply(R,A)})})),x.CSSStyleSheet.prototype.replaceSync&&(D=x.CSSStyleSheet.prototype.replaceSync,x.CSSStyleSheet.prototype.replaceSync=new Proxy(D,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replaceSync:_}),x.apply(R,A)})}));const L={};canMonkeyPatchNestedCSSRule("CSSGroupingRule")?L.CSSGroupingRule=x.CSSGroupingRule:(canMonkeyPatchNestedCSSRule("CSSMediaRule")&&(L.CSSMediaRule=x.CSSMediaRule),canMonkeyPatchNestedCSSRule("CSSConditionRule")&&(L.CSSConditionRule=x.CSSConditionRule),canMonkeyPatchNestedCSSRule("CSSSupportsRule")&&(L.CSSSupportsRule=x.CSSSupportsRule));const B={};return Object.entries(L).forEach(([x,R])=>{B[x]={insertRule:R.prototype.insertRule,deleteRule:R.prototype.deleteRule},R.prototype.insertRule=new Proxy(B[x].insertRule,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:[...getNestedCSSRulePositions(R),D||0]}]}),x.apply(R,A)})}),R.prototype.deleteRule=new Proxy(B[x].deleteRule,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:[...getNestedCSSRulePositions(R),_]}]}),x.apply(R,A)})})}),callbackWrapper(()=>{x.CSSStyleSheet.prototype.insertRule=R,x.CSSStyleSheet.prototype.deleteRule=A,_&&(x.CSSStyleSheet.prototype.replace=_),D&&(x.CSSStyleSheet.prototype.replaceSync=D),Object.entries(L).forEach(([S,b])=>{b.prototype.insertRule=B[S].insertRule,b.prototype.deleteRule=B[S].deleteRule})})}(S,{win:I}),adoptedStyleSheetObserver=initAdoptedStyleSheetObserver(S,S.doc),styleDeclarationObserver=function initStyleDeclarationObserver({styleDeclarationCb:S,mirror:b,ignoreCSSAttributes:I,stylesheetManager:x},{win:R}){const A=R.CSSStyleDeclaration.prototype.setProperty;R.CSSStyleDeclaration.prototype.setProperty=new Proxy(A,{apply:callbackWrapper((R,_,D)=>{var L;const[B,U,$]=D;if(I.has(B))return A.apply(_,[B,U,$]);const{id:j,styleId:W}=getIdAndStyleId(null==(L=_.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(j&&-1!==j||W&&-1!==W)&&S({id:j,styleId:W,set:{property:B,value:U,priority:$},index:getNestedCSSRulePositions(_.parentRule)}),R.apply(_,D)})});const _=R.CSSStyleDeclaration.prototype.removeProperty;return R.CSSStyleDeclaration.prototype.removeProperty=new Proxy(_,{apply:callbackWrapper((R,A,D)=>{var L;const[B]=D;if(I.has(B))return _.apply(A,[B]);const{id:U,styleId:$}=getIdAndStyleId(null==(L=A.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(U&&-1!==U||$&&-1!==$)&&S({id:U,styleId:$,remove:{property:B},index:getNestedCSSRulePositions(A.parentRule)}),R.apply(A,D)})}),callbackWrapper(()=>{R.CSSStyleDeclaration.prototype.setProperty=A,R.CSSStyleDeclaration.prototype.removeProperty=_})}(S,{win:I}),S.collectFonts&&(fontObserver=function initFontObserver({fontCb:S,doc:b}){const I=b.defaultView;if(!I)return()=>{};const x=[],R=new WeakMap,A=I.FontFace;I.FontFace=function FontFace2(S,b,I){const x=new A(S,b,I);return R.set(x,{family:S,buffer:"string"!=typeof b,descriptors:I,fontSource:"string"==typeof b?b:JSON.stringify(Array.from(new Uint8Array(b)))}),x};const _=patch(b.fonts,"add",function(b){return function(I){return setTimeout(callbackWrapper(()=>{const b=R.get(I);b&&(S(b),R.delete(I))}),0),b.apply(this,[I])}});return x.push(()=>{I.FontFace=A}),x.push(_),callbackWrapper(()=>{x.forEach(S=>S())})}(S)));const U=function initSelectionObserver(S){const{doc:b,mirror:I,blockClass:x,blockSelector:R,selectionCb:A}=S;let _=!0;const D=callbackWrapper(()=>{const S=b.getSelection();if(!S||_&&(null==S?void 0:S.isCollapsed))return;_=S.isCollapsed||!1;const D=[],L=S.rangeCount||0;for(let b=0;b<L;b++){const A=S.getRangeAt(b),{startContainer:_,startOffset:L,endContainer:B,endOffset:U}=A;isBlocked(_,x,R,!0)||isBlocked(B,x,R,!0)||D.push({start:I.getId(_),startOffset:L,end:I.getId(B),endOffset:U})}A({ranges:D})});return D(),on("selectionchange",D)}(S),$=function initCustomElementObserver({doc:S,customElementCb:b}){const I=S.defaultView;return I&&I.customElements?patch(I.customElements,"define",function(S){return function(I,x,R){try{b({define:{name:I}})}catch(S){console.warn(`Custom element callback failed for ${I}`)}return S.apply(this,[I,x,R])}}):()=>{}}(S),j=[];for(const b of S.plugins)j.push(b.observer(b.callback,I,b.options));return callbackWrapper(()=>{Tl.forEach(S=>S.reset()),null==x||x.disconnect(),R(),A(),_(),D(),L(),B(),styleSheetObserver(),adoptedStyleSheetObserver(),styleDeclarationObserver(),fontObserver(),U(),$(),j.forEach(S=>S())})}function hasNestedCSSRule(S){return void 0!==window[S]}function canMonkeyPatchNestedCSSRule(S){return Boolean(void 0!==window[S]&&window[S].prototype&&"insertRule"in window[S].prototype&&"deleteRule"in window[S].prototype)}class CrossOriginIframeMirror{constructor(S){__publicField(this,"iframeIdToRemoteIdMap",new WeakMap),__publicField(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=S}getId(S,b,I,x){const R=I||this.getIdToRemoteIdMap(S),A=x||this.getRemoteIdToIdMap(S);let _=R.get(b);return _||(_=this.generateIdFn(),R.set(b,_),A.set(_,b)),_}getIds(S,b){const I=this.getIdToRemoteIdMap(S),x=this.getRemoteIdToIdMap(S);return b.map(b=>this.getId(S,b,I,x))}getRemoteId(S,b,I){const x=I||this.getRemoteIdToIdMap(S);if("number"!=typeof b)return b;const R=x.get(b);return R||-1}getRemoteIds(S,b){const I=this.getRemoteIdToIdMap(S);return b.map(b=>this.getRemoteId(S,b,I))}reset(S){if(!S)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(S),this.iframeRemoteIdToIdMap.delete(S)}getIdToRemoteIdMap(S){let b=this.iframeIdToRemoteIdMap.get(S);return b||(b=new Map,this.iframeIdToRemoteIdMap.set(S,b)),b}getRemoteIdToIdMap(S){let b=this.iframeRemoteIdToIdMap.get(S);return b||(b=new Map,this.iframeRemoteIdToIdMap.set(S,b)),b}}class IframeManager{constructor(S){__publicField(this,"iframes",new WeakMap),__publicField(this,"crossOriginIframeMap",new WeakMap),__publicField(this,"crossOriginIframeMirror",new CrossOriginIframeMirror(genId)),__publicField(this,"crossOriginIframeStyleMirror"),__publicField(this,"crossOriginIframeRootIdMap",new WeakMap),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"wrappedEmit"),__publicField(this,"loadListener"),__publicField(this,"stylesheetManager"),__publicField(this,"recordCrossOriginIframes"),this.mutationCb=S.mutationCb,this.wrappedEmit=S.wrappedEmit,this.stylesheetManager=S.stylesheetManager,this.recordCrossOriginIframes=S.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=S.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(S){this.iframes.set(S,!0),S.contentWindow&&this.crossOriginIframeMap.set(S.contentWindow,S)}addLoadListener(S){this.loadListener=S}attachIframe(S,b){var I,x;this.mutationCb({adds:[{parentId:this.mirror.getId(S),nextId:null,node:b}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(I=S.contentWindow)||I.addEventListener("message",this.handleMessage.bind(this))),null==(x=this.loadListener)||x.call(this,S),S.contentDocument&&S.contentDocument.adoptedStyleSheets&&S.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(S.contentDocument.adoptedStyleSheets,this.mirror.getId(S.contentDocument))}handleMessage(S){const b=S;if("rrweb"!==b.data.type||b.origin!==b.data.origin)return;if(!S.source)return;const I=this.crossOriginIframeMap.get(S.source);if(!I)return;const x=this.transformCrossOriginEvent(I,b.data.event);x&&this.wrappedEmit(x,b.data.isCheckout)}transformCrossOriginEvent(S,b){var I;switch(b.type){case bl.FullSnapshot:{this.crossOriginIframeMirror.reset(S),this.crossOriginIframeStyleMirror.reset(S),this.replaceIdOnNode(b.data.node,S);const I=b.data.node.id;return this.crossOriginIframeRootIdMap.set(S,I),this.patchRootIdOnNode(b.data.node,I),{timestamp:b.timestamp,type:bl.IncrementalSnapshot,data:{source:Cl.Mutation,adds:[{parentId:this.mirror.getId(S),nextId:null,node:b.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case bl.Meta:case bl.Load:case bl.DomContentLoaded:return!1;case bl.Plugin:return b;case bl.Custom:return this.replaceIds(b.data.payload,S,["id","parentId","previousId","nextId"]),b;case bl.IncrementalSnapshot:switch(b.data.source){case Cl.Mutation:return b.data.adds.forEach(b=>{this.replaceIds(b,S,["parentId","nextId","previousId"]),this.replaceIdOnNode(b.node,S);const I=this.crossOriginIframeRootIdMap.get(S);I&&this.patchRootIdOnNode(b.node,I)}),b.data.removes.forEach(b=>{this.replaceIds(b,S,["parentId","id"])}),b.data.attributes.forEach(b=>{this.replaceIds(b,S,["id"])}),b.data.texts.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case Cl.Drag:case Cl.TouchMove:case Cl.MouseMove:return b.data.positions.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case Cl.ViewportResize:return!1;case Cl.MediaInteraction:case Cl.MouseInteraction:case Cl.Scroll:case Cl.CanvasMutation:case Cl.Input:return this.replaceIds(b.data,S,["id"]),b;case Cl.StyleSheetRule:case Cl.StyleDeclaration:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleId"]),b;case Cl.Font:return b;case Cl.Selection:return b.data.ranges.forEach(b=>{this.replaceIds(b,S,["start","end"])}),b;case Cl.AdoptedStyleSheet:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleIds"]),null==(I=b.data.styles)||I.forEach(b=>{this.replaceStyleIds(b,S,["styleId"])}),b}}return!1}replace(S,b,I,x){for(const R of x)(Array.isArray(b[R])||"number"==typeof b[R])&&(Array.isArray(b[R])?b[R]=S.getIds(I,b[R]):b[R]=S.getId(I,b[R]));return b}replaceIds(S,b,I){return this.replace(this.crossOriginIframeMirror,S,b,I)}replaceStyleIds(S,b,I){return this.replace(this.crossOriginIframeStyleMirror,S,b,I)}replaceIdOnNode(S,b){this.replaceIds(S,b,["id","rootId"]),"childNodes"in S&&S.childNodes.forEach(S=>{this.replaceIdOnNode(S,b)})}patchRootIdOnNode(S,b){S.type===Ml.Document||S.rootId||(S.rootId=b),"childNodes"in S&&S.childNodes.forEach(S=>{this.patchRootIdOnNode(S,b)})}}class ShadowDomManager{constructor(S){__publicField(this,"shadowDoms",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"scrollCb"),__publicField(this,"bypassOptions"),__publicField(this,"mirror"),__publicField(this,"restoreHandlers",[]),this.mutationCb=S.mutationCb,this.scrollCb=S.scrollCb,this.bypassOptions=S.bypassOptions,this.mirror=S.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(S,b){if(!isNativeShadowDom(S))return;if(this.shadowDoms.has(S))return;this.shadowDoms.add(S);const I=initMutationObserver({...this.bypassOptions,doc:b,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},S);this.restoreHandlers.push(()=>I.disconnect()),this.restoreHandlers.push(initScrollObserver({...this.bypassOptions,scrollCb:this.scrollCb,doc:S,mirror:this.mirror})),setTimeout(()=>{S.adoptedStyleSheets&&S.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(S.adoptedStyleSheets,this.mirror.getId(yl.host(S))),this.restoreHandlers.push(initAdoptedStyleSheetObserver({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},S))},0)}observeAttachShadow(S){S.contentWindow&&S.contentDocument&&this.patchAttachShadow(S.contentWindow.Element,S.contentDocument)}patchAttachShadow(S,b){const I=this;this.restoreHandlers.push(patch(S.prototype,"attachShadow",function(S){return function(x){const R=S.call(this,x),A=yl.shadowRoot(this);return A&&inDom(this)&&I.addShadowRoot(A,b),R}}))}reset(){this.restoreHandlers.forEach(S=>{try{S()}catch(S){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}for(var Ol="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Dl="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Fl=0;Fl<64;Fl++)Dl[Ol.charCodeAt(Fl)]=Fl;const Nl=new Map;const saveWebGLVar=(S,b,I)=>{if(!S||!isInstanceOfWebGLObject(S,b)&&"object"!=typeof S)return;const x=function variableListFor$1(S,b){let I=Nl.get(S);return I||(I=new Map,Nl.set(S,I)),I.has(b)||I.set(b,[]),I.get(b)}(I,S.constructor.name);let R=x.indexOf(S);return-1===R&&(R=x.length,x.push(S)),R};function serializeArg(S,b,I){if(S instanceof Array)return S.map(S=>serializeArg(S,b,I));if(null===S)return S;if(S instanceof Float32Array||S instanceof Float64Array||S instanceof Int32Array||S instanceof Uint32Array||S instanceof Uint8Array||S instanceof Uint16Array||S instanceof Int16Array||S instanceof Int8Array||S instanceof Uint8ClampedArray){return{rr_type:S.constructor.name,args:[Object.values(S)]}}if(S instanceof ArrayBuffer){return{rr_type:S.constructor.name,base64:function(S){var b,I=new Uint8Array(S),x=I.length,R="";for(b=0;b<x;b+=3)R+=Ol[I[b]>>2],R+=Ol[(3&I[b])<<4|I[b+1]>>4],R+=Ol[(15&I[b+1])<<2|I[b+2]>>6],R+=Ol[63&I[b+2]];return x%3==2?R=R.substring(0,R.length-1)+"=":x%3==1&&(R=R.substring(0,R.length-2)+"=="),R}(S)}}if(S instanceof DataView){return{rr_type:S.constructor.name,args:[serializeArg(S.buffer,b,I),S.byteOffset,S.byteLength]}}if(S instanceof HTMLImageElement){const b=S.constructor.name,{src:I}=S;return{rr_type:b,src:I}}if(S instanceof HTMLCanvasElement){return{rr_type:"HTMLImageElement",src:S.toDataURL()}}if(S instanceof ImageData){return{rr_type:S.constructor.name,args:[serializeArg(S.data,b,I),S.width,S.height]}}if(isInstanceOfWebGLObject(S,b)||"object"==typeof S){return{rr_type:S.constructor.name,index:saveWebGLVar(S,b,I)}}return S}const serializeArgs=(S,b,I)=>S.map(S=>serializeArg(S,b,I)),isInstanceOfWebGLObject=(S,b)=>{const I=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(S=>"function"==typeof b[S]);return Boolean(I.find(I=>S instanceof b[I]))};function initCanvasContextObserver(S,b,I,x){const R=[];try{const A=patch(S.HTMLCanvasElement.prototype,"getContext",function(S){return function(R,...A){if(!isBlocked(this,b,I,!0)){const S=function getNormalizedContextName(S){return"experimental-webgl"===S?"webgl":S}(R);if("__context"in this||(this.__context=S),x&&["webgl","webgl2"].includes(S))if(A[0]&&"object"==typeof A[0]){const S=A[0];S.preserveDrawingBuffer||(S.preserveDrawingBuffer=!0)}else A.splice(0,1,{preserveDrawingBuffer:!0})}return S.apply(this,[R,...A])}});R.push(A)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{R.forEach(S=>S())}}function patchGLPrototype(S,b,I,x,R,A){const _=[],D=Object.getOwnPropertyNames(S);for(const L of D)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(L))try{if("function"!=typeof S[L])continue;const D=patch(S,L,function(S){return function(..._){const D=S.apply(this,_);if(saveWebGLVar(D,A,this),"tagName"in this.canvas&&!isBlocked(this.canvas,x,R,!0)){const S=serializeArgs(_,A,this),x={type:b,property:L,args:S};I(this.canvas,x)}return D}});_.push(D)}catch{const x=hookSetter(S,L,{set(S){I(this.canvas,{type:b,property:L,args:[S],setter:!0})}});_.push(x)}return _}const Ll="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Pl="undefined"!=typeof window&&window.Blob&&new Blob([(Bl=Ll,Uint8Array.from(atob(Bl),S=>S.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});var Bl;function WorkerWrapper(S){let b;try{if(b=Pl&&(window.URL||window.webkitURL).createObjectURL(Pl),!b)throw"";const I=new Worker(b,{name:null==S?void 0:S.name});return I.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(b)}),I}catch(b){return new Worker("data:text/javascript;base64,"+Ll,{name:null==S?void 0:S.name})}finally{b&&(window.URL||window.webkitURL).revokeObjectURL(b)}}class CanvasManager{constructor(S){__publicField(this,"pendingCanvasMutations",new Map),__publicField(this,"rafStamps",{latestId:0,invokeId:null}),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"resetObservers"),__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"processMutation",(S,b)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(S)||this.pendingCanvasMutations.set(S,[]),this.pendingCanvasMutations.get(S).push(b)});const{sampling:b="all",win:I,blockClass:x,blockSelector:R,recordCanvas:A,dataURLOptions:_}=S;this.mutationCb=S.mutationCb,this.mirror=S.mirror,A&&"all"===b&&this.initCanvasMutationObserver(I,x,R),A&&"number"==typeof b&&this.initCanvasFPSObserver(b,I,x,R,{dataURLOptions:_})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(S,b,I,x,R){const A=initCanvasContextObserver(b,I,x,!0),_=new Map,D=new WorkerWrapper;D.onmessage=S=>{const{id:b}=S.data;if(_.set(b,!1),!("base64"in S.data))return;const{base64:I,type:x,width:R,height:A}=S.data;this.mutationCb({id:b,type:El["2D"],commands:[{property:"clearRect",args:[0,0,R,A]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:I}],type:x}]},0,0]}]})};const L=1e3/S;let B,U=0;const takeCanvasSnapshots=S=>{U&&S-U<L||(U=S,(()=>{const S=[];return b.document.querySelectorAll("canvas").forEach(b=>{isBlocked(b,I,x,!0)||S.push(b)}),S})().forEach(async S=>{var b;const I=this.mirror.getId(S);if(_.get(I))return;if(0===S.width||0===S.height)return;if(_.set(I,!0),["webgl","webgl2"].includes(S.__context)){const I=S.getContext(S.__context);!1===(null==(b=null==I?void 0:I.getContextAttributes())?void 0:b.preserveDrawingBuffer)&&I.clear(I.COLOR_BUFFER_BIT)}const x=await createImageBitmap(S);D.postMessage({id:I,bitmap:x,width:S.width,height:S.height,dataURLOptions:R.dataURLOptions},[x])})),B=requestAnimationFrame(takeCanvasSnapshots)};B=requestAnimationFrame(takeCanvasSnapshots),this.resetObservers=()=>{A(),cancelAnimationFrame(B)}}initCanvasMutationObserver(S,b,I){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const x=initCanvasContextObserver(S,b,I,!1),R=function initCanvas2DMutationObserver(S,b,I,x){const R=[],A=Object.getOwnPropertyNames(b.CanvasRenderingContext2D.prototype);for(const _ of A)try{if("function"!=typeof b.CanvasRenderingContext2D.prototype[_])continue;const A=patch(b.CanvasRenderingContext2D.prototype,_,function(R){return function(...A){return isBlocked(this.canvas,I,x,!0)||setTimeout(()=>{const I=serializeArgs(A,b,this);S(this.canvas,{type:El["2D"],property:_,args:I})},0),R.apply(this,A)}});R.push(A)}catch{const I=hookSetter(b.CanvasRenderingContext2D.prototype,_,{set(b){S(this.canvas,{type:El["2D"],property:_,args:[b],setter:!0})}});R.push(I)}return()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I),A=function initCanvasWebGLMutationObserver(S,b,I,x){const R=[];return R.push(...patchGLPrototype(b.WebGLRenderingContext.prototype,El.WebGL,S,I,x,b)),void 0!==b.WebGL2RenderingContext&&R.push(...patchGLPrototype(b.WebGL2RenderingContext.prototype,El.WebGL2,S,I,x,b)),()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I);this.resetObservers=()=>{x(),R(),A()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const setLatestRAFTimestamp=S=>{this.rafStamps.latestId=S,requestAnimationFrame(setLatestRAFTimestamp)};requestAnimationFrame(setLatestRAFTimestamp)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((S,b)=>{const I=this.mirror.getId(b);this.flushPendingCanvasMutationFor(b,I)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(S,b){if(this.frozen||this.locked)return;const I=this.pendingCanvasMutations.get(S);if(!I||-1===b)return;const x=I.map(S=>{const{type:b,...I}=S;return I}),{type:R}=I[0];this.mutationCb({id:b,type:R,commands:x}),this.pendingCanvasMutations.delete(S)}}class StylesheetManager{constructor(S){__publicField(this,"trackedLinkElements",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"adoptedStyleSheetCb"),__publicField(this,"styleMirror",new StyleSheetMirror),this.mutationCb=S.mutationCb,this.adoptedStyleSheetCb=S.adoptedStyleSheetCb}attachLinkElement(S,b){"_cssText"in b.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:b.id,attributes:b.attributes}]}),this.trackLinkElement(S)}trackLinkElement(S){this.trackedLinkElements.has(S)||(this.trackedLinkElements.add(S),this.trackStylesheetInLinkElement(S))}adoptStyleSheets(S,b){if(0===S.length)return;const I={id:b,styleIds:[]},x=[];for(const b of S){let S;this.styleMirror.has(b)?S=this.styleMirror.getId(b):(S=this.styleMirror.add(b),x.push({styleId:S,rules:Array.from(b.rules||CSSRule,(S,I)=>({rule:stringifyRule(S,b.href),index:I}))})),I.styleIds.push(S)}x.length>0&&(I.styles=x),this.adoptedStyleSheetCb(I)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(S){}}class ProcessedNodeManager{constructor(){__publicField(this,"nodeMap",new WeakMap),__publicField(this,"active",!1)}inOtherBuffer(S,b){const I=this.nodeMap.get(S);return I&&Array.from(I).some(S=>S!==b)}add(S,b){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(S,(this.nodeMap.get(S)||new Set).add(b))}destroy(){}}let zl,Ul,$l,jl=!1;try{if(2!==Array.from([1],S=>2*S)[0]){const S=document.createElement("iframe");document.body.appendChild(S),Array.from=(null==(Qe=S.contentWindow)?void 0:Qe.Array.from)||Array.from,document.body.removeChild(S)}}catch(err){console.debug("Unable to override Array.from",err)}const ql=function createMirror$2(){return new Mirror}();function record(S={}){const{emit:b,checkoutEveryNms:I,checkoutEveryNth:x,blockClass:R="rr-block",blockSelector:A=null,ignoreClass:_="rr-ignore",ignoreSelector:D=null,maskTextClass:L="rr-mask",maskTextSelector:B=null,inlineStylesheet:U=!0,maskAllInputs:$,maskInputOptions:j,slimDOMOptions:W,maskInputFn:H,maskTextFn:V,hooks:Q,packFn:G,sampling:J={},dataURLOptions:X={},mousemoveWait:Y,recordDOM:ee=!0,recordCanvas:te=!1,recordCrossOriginIframes:se=!1,recordAfter:re=("DOMContentLoaded"===S.recordAfter?S.recordAfter:"load"),userTriggeredOnInput:ne=!1,collectFonts:ie=!1,inlineImages:oe=!1,plugins:ae,keepIframeSrcFn:le=()=>!1,ignoreCSSAttributes:ce=new Set([]),errorHandler:ue}=S;!function registerErrorHandler(S){Rl=S}(ue);const he=!se||window.parent===window;let de=!1;if(!he)try{window.parent.document&&(de=!1)}catch(S){de=!0}if(he&&!b)throw new Error("emit function is required");if(!he&&!de)return()=>{};void 0!==Y&&void 0===J.mousemove&&(J.mousemove=Y),ql.reset();const ge=!0===$?{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,password:!0}:void 0!==j?j:{password:!0},pe=!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===W,headMetaDescKeywords:"all"===W,headTitleMutations:"all"===W}:W||{};let fe;!function polyfill$1(S=window){"NodeList"in S&&!S.NodeList.prototype.forEach&&(S.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in S&&!S.DOMTokenList.prototype.forEach&&(S.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let me=0;const eventProcessor=S=>{for(const b of ae||[])b.eventProcessor&&(S=b.eventProcessor(S));return G&&!de&&(S=G(S)),S};zl=(S,R)=>{var A;const _=S;if(_.timestamp=wl(),!(null==(A=Tl[0])?void 0:A.isFrozen())||_.type===bl.FullSnapshot||_.type===bl.IncrementalSnapshot&&_.data.source===Cl.Mutation||Tl.forEach(S=>S.unfreeze()),he)null==b||b(eventProcessor(_),R);else if(de){const S={type:"rrweb",event:eventProcessor(_),origin:window.location.origin,isCheckout:R};window.parent.postMessage(S,"*")}if(_.type===bl.FullSnapshot)fe=_,me=0;else if(_.type===bl.IncrementalSnapshot){if(_.data.source===Cl.Mutation&&_.data.isAttachIframe)return;me++;const S=x&&me>=x,b=I&&_.timestamp-fe.timestamp>I;(S||b)&&Ul(!0)}};const wrappedMutationEmit=S=>{zl({type:bl.IncrementalSnapshot,data:{source:Cl.Mutation,...S}})},wrappedScrollEmit=S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.Scroll,...S}}),wrappedCanvasMutationEmit=S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.CanvasMutation,...S}}),ye=new StylesheetManager({mutationCb:wrappedMutationEmit,adoptedStyleSheetCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.AdoptedStyleSheet,...S}})}),ve=new IframeManager({mirror:ql,mutationCb:wrappedMutationEmit,stylesheetManager:ye,recordCrossOriginIframes:se,wrappedEmit:zl});for(const S of ae||[])S.getMirror&&S.getMirror({nodeMirror:ql,crossOriginIframeMirror:ve.crossOriginIframeMirror,crossOriginIframeStyleMirror:ve.crossOriginIframeStyleMirror});const Se=new ProcessedNodeManager;$l=new CanvasManager({recordCanvas:te,mutationCb:wrappedCanvasMutationEmit,win:window,blockClass:R,blockSelector:A,mirror:ql,sampling:J.canvas,dataURLOptions:X});const we=new ShadowDomManager({mutationCb:wrappedMutationEmit,scrollCb:wrappedScrollEmit,bypassOptions:{blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskInputOptions:ge,dataURLOptions:X,maskTextFn:V,maskInputFn:H,recordCanvas:te,inlineImages:oe,sampling:J,slimDOMOptions:pe,iframeManager:ve,stylesheetManager:ye,canvasManager:$l,keepIframeSrcFn:le,processedNodeManager:Se},mirror:ql});Ul=(S=!1)=>{if(!ee)return;zl({type:bl.Meta,data:{href:window.location.href,width:getWindowWidth(),height:getWindowHeight()}},S),ye.reset(),we.init(),Tl.forEach(S=>S.lock());const b=function snapshot(S,b){const{mirror:I=new Mirror,blockClass:x="rr-block",blockSelector:R=null,maskTextClass:A="rr-mask",maskTextSelector:_=null,inlineStylesheet:D=!0,inlineImages:L=!1,recordCanvas:B=!1,maskAllInputs:U=!1,maskTextFn:$,maskInputFn:j,slimDOM:W=!1,dataURLOptions:H,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee=()=>!1}=b||{};return serializeNodeWithId(S,{doc:S,mirror:I,blockClass:x,blockSelector:R,maskTextClass:A,maskTextSelector:_,skipChild:!1,inlineStylesheet:D,maskInputOptions:!0===U?{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,password:!0}:!1===U?{password:!0}:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===W,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===W?{}:W,dataURLOptions:H,inlineImages:L,recordCanvas:B,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee,newlyAddedElement:!1})}(document,{mirror:ql,blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskAllInputs:ge,maskTextFn:V,maskInputFn:H,slimDOM:pe,dataURLOptions:X,recordCanvas:te,inlineImages:oe,onSerialize:S=>{isSerializedIframe(S,ql)&&ve.addIframe(S),isSerializedStylesheet(S,ql)&&ye.trackLinkElement(S),hasShadowRoot(S)&&we.addShadowRoot(yl.shadowRoot(S),document)},onIframeLoad:(S,b)=>{ve.attachIframe(S,b),we.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{ye.attachLinkElement(S,b)},keepIframeSrcFn:le});if(!b)return console.warn("Failed to snapshot the document");zl({type:bl.FullSnapshot,data:{node:b,initialOffset:getWindowScroll(window)}},S),Tl.forEach(S=>S.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ye.adoptStyleSheets(document.adoptedStyleSheets,ql.getId(document))};try{const S=[],observe=S=>{var b;return callbackWrapper(initObservers)({mutationCb:wrappedMutationEmit,mousemoveCb:(S,b)=>zl({type:bl.IncrementalSnapshot,data:{source:b,positions:S}}),mouseInteractionCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.MouseInteraction,...S}}),scrollCb:wrappedScrollEmit,viewportResizeCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.ViewportResize,...S}}),inputCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.Input,...S}}),mediaInteractionCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.MediaInteraction,...S}}),styleSheetRuleCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.StyleSheetRule,...S}}),styleDeclarationCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.StyleDeclaration,...S}}),canvasMutationCb:wrappedCanvasMutationEmit,fontCb:S=>zl({type:bl.IncrementalSnapshot,data:{source:Cl.Font,...S}}),selectionCb:S=>{zl({type:bl.IncrementalSnapshot,data:{source:Cl.Selection,...S}})},customElementCb:S=>{zl({type:bl.IncrementalSnapshot,data:{source:Cl.CustomElement,...S}})},blockClass:R,ignoreClass:_,ignoreSelector:D,maskTextClass:L,maskTextSelector:B,maskInputOptions:ge,inlineStylesheet:U,sampling:J,recordDOM:ee,recordCanvas:te,inlineImages:oe,userTriggeredOnInput:ne,collectFonts:ie,doc:S,maskInputFn:H,maskTextFn:V,keepIframeSrcFn:le,blockSelector:A,slimDOMOptions:pe,dataURLOptions:X,mirror:ql,iframeManager:ve,stylesheetManager:ye,shadowDomManager:we,processedNodeManager:Se,canvasManager:$l,ignoreCSSAttributes:ce,plugins:(null==(b=null==ae?void 0:ae.filter(S=>S.observer))?void 0:b.map(S=>({observer:S.observer,options:S.options,callback:b=>zl({type:bl.Plugin,data:{plugin:S.name,payload:b}})})))||[]},Q)};ve.addLoadListener(b=>{try{S.push(observe(b.contentDocument))}catch(S){console.warn(S)}});const init=()=>{Ul(),S.push(observe(document)),jl=!0};return"interactive"===document.readyState||"complete"===document.readyState?init():(S.push(on("DOMContentLoaded",()=>{zl({type:bl.DomContentLoaded,data:{}}),"DOMContentLoaded"===re&&init()})),S.push(on("load",()=>{zl({type:bl.Load,data:{}}),"load"===re&&init()},window))),()=>{S.forEach(S=>S()),Se.destroy(),jl=!1,function unregisterErrorHandler(){Rl=void 0}()}}catch(S){console.warn(S)}}var Wl,Hl;record.addCustomEvent=(S,b)=>{if(!jl)throw new Error("please add custom event after start recording");zl({type:bl.Custom,data:{tag:S,payload:b}})},record.freezePage=()=>{Tl.forEach(S=>S.freeze())},record.takeFullSnapshot=S=>{if(!jl)throw new Error("please take full snapshot after start recording");Ul(S)},record.mirror=ql,(Hl=Wl||(Wl={}))[Hl.NotStarted=0]="NotStarted",Hl[Hl.Running=1]="Running",Hl[Hl.Stopped=2]="Stopped";const Vl=createLogger("RRWeb-Loader");let Ql=null,Kl=null;try{record?(Ql=record,Kl={record:record,addCustomEvent:record.addCustomEvent,freezePage:record.freezePage,takeFullSnapshot:record.takeFullSnapshot,mirror:record.mirror},console.log("%c[TraceScout] ✅ rrweb RECORD bundled","color: #00aa00; font-weight: bold;"),Vl.log("rrweb record() statically imported and ready")):console.error("[TraceScout] ❌ rrweb record import found but not a function")}catch(D){console.error("[TraceScout] ❌ Static rrweb record import failed:",D.message),Vl.warn("Static rrweb record import failed:",D.message)}async function loadRRWeb(){if(!Kl||!Kl.record)throw new Error("rrweb record not available - bundling failed");return Kl}function getRRWeb(){return Kl}function getRecord(){return Ql}function isRRWebLoaded(){return!!Kl}function getRRWebSource(){return{isBundled:!0,source:"bundled",details:"@rrweb/record bundled with SDK",isRecordOnly:!0}}var Gl=Uint8Array,Jl=Uint16Array,Xl=Int32Array,Yl=new Gl([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]),Zl=new Gl([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]),ec=new Gl([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(S,b){for(var I=new Jl(31),x=0;x<31;++x)I[x]=b+=1<<S[x-1];var R=new Xl(I[30]);for(x=1;x<30;++x)for(var A=I[x];A<I[x+1];++A)R[A]=A-I[x]<<5|x;return{b:I,r:R}},tc=freb(Yl,2),sc=tc.b,rc=tc.r;sc[28]=258,rc[258]=28;for(var nc=freb(Zl,0),ic=nc.b,oc=nc.r,ac=new Jl(32768),cc=0;cc<32768;++cc){var uc=(43690&cc)>>1|(21845&cc)<<1;uc=(61680&(uc=(52428&uc)>>2|(13107&uc)<<2))>>4|(3855&uc)<<4,ac[cc]=((65280&uc)>>8|(255&uc)<<8)>>1}var hMap=function(S,b,I){for(var x=S.length,R=0,A=new Jl(b);R<x;++R)S[R]&&++A[S[R]-1];var _,D=new Jl(b);for(R=1;R<b;++R)D[R]=D[R-1]+A[R-1]<<1;if(I){_=new Jl(1<<b);var L=15-b;for(R=0;R<x;++R)if(S[R])for(var B=R<<4|S[R],U=b-S[R],$=D[S[R]-1]++<<U,j=$|(1<<U)-1;$<=j;++$)_[ac[$]>>L]=B}else for(_=new Jl(x),R=0;R<x;++R)S[R]&&(_[R]=ac[D[S[R]-1]++]>>15-S[R]);return _},hc=new Gl(288);for(cc=0;cc<144;++cc)hc[cc]=8;for(cc=144;cc<256;++cc)hc[cc]=9;for(cc=256;cc<280;++cc)hc[cc]=7;for(cc=280;cc<288;++cc)hc[cc]=8;var dc=new Gl(32);for(cc=0;cc<32;++cc)dc[cc]=5;var gc=hMap(hc,9,0),pc=hMap(hc,9,1),fc=hMap(dc,5,0),mc=hMap(dc,5,1),max=function(S){for(var b=S[0],I=1;I<S.length;++I)S[I]>b&&(b=S[I]);return b},bits=function(S,b,I){var x=b/8|0;return(S[x]|S[x+1]<<8)>>(7&b)&I},bits16=function(S,b){var I=b/8|0;return(S[I]|S[I+1]<<8|S[I+2]<<16)>>(7&b)},shft=function(S){return(S+7)/8|0},slc=function(S,b,I){return(null==b||b<0)&&(b=0),(null==I||I>S.length)&&(I=S.length),new Gl(S.subarray(b,I))},yc=["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"],err=function(S,b,I){var x=new Error(b||yc[S]);if(x.code=S,Error.captureStackTrace&&Error.captureStackTrace(x,err),!I)throw x;return x},wbits=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8},wbits16=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8,S[x+2]|=I>>16},hTree=function(S,b){for(var I=[],x=0;x<S.length;++x)S[x]&&I.push({s:x,f:S[x]});var R=I.length,A=I.slice();if(!R)return{t:Sc,l:0};if(1==R){var _=new Gl(I[0].s+1);return _[I[0].s]=1,{t:_,l:1}}I.sort(function(S,b){return S.f-b.f}),I.push({s:-1,f:25001});var D=I[0],L=I[1],B=0,U=1,$=2;for(I[0]={s:-1,f:D.f+L.f,l:D,r:L};U!=R-1;)D=I[I[B].f<I[$].f?B++:$++],L=I[B!=U&&I[B].f<I[$].f?B++:$++],I[U++]={s:-1,f:D.f+L.f,l:D,r:L};var j=A[0].s;for(x=1;x<R;++x)A[x].s>j&&(j=A[x].s);var W=new Jl(j+1),H=ln(I[U-1],W,0);if(H>b){x=0;var V=0,Q=H-b,G=1<<Q;for(A.sort(function(S,b){return W[b.s]-W[S.s]||S.f-b.f});x<R;++x){var J=A[x].s;if(!(W[J]>b))break;V+=G-(1<<H-W[J]),W[J]=b}for(V>>=Q;V>0;){var X=A[x].s;W[X]<b?V-=1<<b-W[X]++-1:++x}for(;x>=0&&V;--x){var Y=A[x].s;W[Y]==b&&(--W[Y],++V)}H=b}return{t:new Gl(W),l:H}},ln=function(S,b,I){return-1==S.s?Math.max(ln(S.l,b,I+1),ln(S.r,b,I+1)):b[S.s]=I},lc=function(S){for(var b=S.length;b&&!S[--b];);for(var I=new Jl(++b),x=0,R=S[0],A=1,w=function(S){I[x++]=S},_=1;_<=b;++_)if(S[_]==R&&_!=b)++A;else{if(!R&&A>2){for(;A>138;A-=138)w(32754);A>2&&(w(A>10?A-11<<5|28690:A-3<<5|12305),A=0)}else if(A>3){for(w(R),--A;A>6;A-=6)w(8304);A>2&&(w(A-3<<5|8208),A=0)}for(;A--;)w(R);A=1,R=S[_]}return{c:I.subarray(0,x),n:b}},clen=function(S,b){for(var I=0,x=0;x<b.length;++x)I+=S[x]*b[x];return I},wfblk=function(S,b,I){var x=I.length,R=shft(b+2);S[R]=255&x,S[R+1]=x>>8,S[R+2]=255^S[R],S[R+3]=255^S[R+1];for(var A=0;A<x;++A)S[R+A+4]=I[A];return 8*(R+4+x)},wblk=function(S,b,I,x,R,A,_,D,L,B,U){wbits(b,U++,I),++R[256];for(var $=hTree(R,15),j=$.t,W=$.l,H=hTree(A,15),V=H.t,Q=H.l,G=lc(j),J=G.c,X=G.n,Y=lc(V),ee=Y.c,te=Y.n,se=new Jl(19),re=0;re<J.length;++re)++se[31&J[re]];for(re=0;re<ee.length;++re)++se[31&ee[re]];for(var ne=hTree(se,7),ie=ne.t,oe=ne.l,ae=19;ae>4&&!ie[ec[ae-1]];--ae);var le,ce,ue,he,de=B+5<<3,ge=clen(R,hc)+clen(A,dc)+_,pe=clen(R,j)+clen(A,V)+_+14+3*ae+clen(se,ie)+2*se[16]+3*se[17]+7*se[18];if(L>=0&&de<=ge&&de<=pe)return wfblk(b,U,S.subarray(L,L+B));if(wbits(b,U,1+(pe<ge)),U+=2,pe<ge){le=hMap(j,W,0),ce=j,ue=hMap(V,Q,0),he=V;var fe=hMap(ie,oe,0);wbits(b,U,X-257),wbits(b,U+5,te-1),wbits(b,U+10,ae-4),U+=14;for(re=0;re<ae;++re)wbits(b,U+3*re,ie[ec[re]]);U+=3*ae;for(var me=[J,ee],ye=0;ye<2;++ye){var ve=me[ye];for(re=0;re<ve.length;++re){var Se=31&ve[re];wbits(b,U,fe[Se]),U+=ie[Se],Se>15&&(wbits(b,U,ve[re]>>5&127),U+=ve[re]>>12)}}}else le=gc,ce=hc,ue=fc,he=dc;for(re=0;re<D;++re){var we=x[re];if(we>255){wbits16(b,U,le[(Se=we>>18&31)+257]),U+=ce[Se+257],Se>7&&(wbits(b,U,we>>23&31),U+=Yl[Se]);var be=31&we;wbits16(b,U,ue[be]),U+=he[be],be>3&&(wbits16(b,U,we>>5&8191),U+=Zl[be])}else wbits16(b,U,le[we]),U+=ce[we]}return wbits16(b,U,le[256]),U+ce[256]},vc=new Xl([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Sc=new Gl(0),adler=function(){var S=1,b=0;return{p:function(I){for(var x=S,R=b,A=0|I.length,_=0;_!=A;){for(var D=Math.min(_+2655,A);_<D;++_)R+=x+=I[_];x=(65535&x)+15*(x>>16),R=(65535&R)+15*(R>>16)}S=x,b=R},d:function(){return(255&(S%=65521))<<24|(65280&S)<<8|(255&(b%=65521))<<8|b>>8}}},dopt=function(S,b,I,x,R){if(!R&&(R={l:1},b.dictionary)){var A=b.dictionary.subarray(-32768),_=new Gl(A.length+S.length);_.set(A),_.set(S,A.length),S=_,R.w=A.length}return function(S,b,I,x,R,A){var _=A.z||S.length,D=new Gl(x+_+5*(1+Math.ceil(_/7e3))+R),L=D.subarray(x,D.length-R),B=A.l,U=7&(A.r||0);if(b){U&&(L[0]=A.r>>3);for(var $=vc[b-1],j=$>>13,W=8191&$,H=(1<<I)-1,V=A.p||new Jl(32768),Q=A.h||new Jl(H+1),G=Math.ceil(I/3),J=2*G,hsh=function(b){return(S[b]^S[b+1]<<G^S[b+2]<<J)&H},X=new Xl(25e3),Y=new Jl(288),ee=new Jl(32),te=0,se=0,re=A.i||0,ne=0,ie=A.w||0,oe=0;re+2<_;++re){var ae=hsh(re),le=32767&re,ce=Q[ae];if(V[le]=ce,Q[ae]=le,ie<=re){var ue=_-re;if((te>7e3||ne>24576)&&(ue>423||!B)){U=wblk(S,L,0,X,Y,ee,se,ne,oe,re-oe,U),ne=te=se=0,oe=re;for(var he=0;he<286;++he)Y[he]=0;for(he=0;he<30;++he)ee[he]=0}var de=2,ge=0,pe=W,fe=le-ce&32767;if(ue>2&&ae==hsh(re-fe))for(var me=Math.min(j,ue)-1,ye=Math.min(32767,re),ve=Math.min(258,ue);fe<=ye&&--pe&&le!=ce;){if(S[re+de]==S[re+de-fe]){for(var Se=0;Se<ve&&S[re+Se]==S[re+Se-fe];++Se);if(Se>de){if(de=Se,ge=fe,Se>me)break;var we=Math.min(fe,Se-2),be=0;for(he=0;he<we;++he){var Ce=re-fe+he&32767,ke=Ce-V[Ce]&32767;ke>be&&(be=ke,ce=Ce)}}}fe+=(le=ce)-(ce=V[le])&32767}if(ge){X[ne++]=268435456|rc[de]<<18|oc[ge];var Ie=31&rc[de],Ee=31&oc[ge];se+=Yl[Ie]+Zl[Ee],++Y[257+Ie],++ee[Ee],ie=re+de,++te}else X[ne++]=S[re],++Y[S[re]]}}for(re=Math.max(re,ie);re<_;++re)X[ne++]=S[re],++Y[S[re]];U=wblk(S,L,B,X,Y,ee,se,ne,oe,re-oe,U),B||(A.r=7&U|L[U/8|0]<<3,U-=7,A.h=Q,A.p=V,A.i=re,A.w=ie)}else{for(re=A.w||0;re<_+B;re+=65535){var xe=re+65535;xe>=_&&(L[U/8|0]=B,xe=_),U=wfblk(L,U+1,S.subarray(re,xe))}A.i=_}return slc(D,0,x+shft(U)+R)}(S,null==b.level?6:b.level,null==b.mem?R.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(S.length)))):20:12+b.mem,I,x,R)},wbytes=function(S,b,I){for(;I;++b)S[b]=I,I>>>=8};function zlibSync(S,b){b||(b={});var I=adler();I.p(S);var x=dopt(S,b,b.dictionary?6:2,4);return function(S,b){var I=b.level,x=0==I?0:I<6?1:9==I?3:2;if(S[0]=120,S[1]=x<<6|(b.dictionary&&32),S[1]|=31-(S[0]<<8|S[1])%31,b.dictionary){var R=adler();R.p(b.dictionary),wbytes(S,2,R.d())}}(x,b),wbytes(x,x.length-4,I.d()),x}function unzlibSync(S,b){return function(S,b,I,x){var R=S.length,A=x?x.length:0;if(!R||b.f&&!b.l)return I||new Gl(0);var _=!I,D=_||2!=b.i,L=b.i;_&&(I=new Gl(3*R));var cbuf=function(S){var b=I.length;if(S>b){var x=new Gl(Math.max(2*b,S));x.set(I),I=x}},B=b.f||0,U=b.p||0,$=b.b||0,j=b.l,W=b.d,H=b.m,V=b.n,Q=8*R;do{if(!j){B=bits(S,U,1);var G=bits(S,U+1,3);if(U+=3,!G){var J=S[(le=shft(U)+4)-4]|S[le-3]<<8,X=le+J;if(X>R){L&&err(0);break}D&&cbuf($+J),I.set(S.subarray(le,X),$),b.b=$+=J,b.p=U=8*X,b.f=B;continue}if(1==G)j=pc,W=mc,H=9,V=5;else if(2==G){var Y=bits(S,U,31)+257,ee=bits(S,U+10,15)+4,te=Y+bits(S,U+5,31)+1;U+=14;for(var se=new Gl(te),re=new Gl(19),ne=0;ne<ee;++ne)re[ec[ne]]=bits(S,U+3*ne,7);U+=3*ee;var ie=max(re),oe=(1<<ie)-1,ae=hMap(re,ie,1);for(ne=0;ne<te;){var le,ce=ae[bits(S,U,oe)];if(U+=15&ce,(le=ce>>4)<16)se[ne++]=le;else{var ue=0,he=0;for(16==le?(he=3+bits(S,U,3),U+=2,ue=se[ne-1]):17==le?(he=3+bits(S,U,7),U+=3):18==le&&(he=11+bits(S,U,127),U+=7);he--;)se[ne++]=ue}}var de=se.subarray(0,Y),ge=se.subarray(Y);H=max(de),V=max(ge),j=hMap(de,H,1),W=hMap(ge,V,1)}else err(1);if(U>Q){L&&err(0);break}}D&&cbuf($+131072);for(var pe=(1<<H)-1,fe=(1<<V)-1,me=U;;me=U){var ye=(ue=j[bits16(S,U)&pe])>>4;if((U+=15&ue)>Q){L&&err(0);break}if(ue||err(2),ye<256)I[$++]=ye;else{if(256==ye){me=U,j=null;break}var ve=ye-254;if(ye>264){var Se=Yl[ne=ye-257];ve=bits(S,U,(1<<Se)-1)+sc[ne],U+=Se}var we=W[bits16(S,U)&fe],be=we>>4;if(we||err(3),U+=15&we,ge=ic[be],be>3&&(Se=Zl[be],ge+=bits16(S,U)&(1<<Se)-1,U+=Se),U>Q){L&&err(0);break}D&&cbuf($+131072);var Ce=$+ve;if($<ge){var ke=A-ge,Ie=Math.min(ge,Ce);for(ke+$<0&&err(3);$<Ie;++$)I[$]=x[ke+$]}for(;$<Ce;++$)I[$]=I[$-ge]}}b.l=j,b.p=me,b.b=$,b.f=B,j&&(B=1,b.m=H,b.d=W,b.n=V)}while(!B);return $!=I.length&&_?slc(I,0,$):I.subarray(0,$)}(S.subarray(function(S,b){return(8!=(15&S[0])||S[0]>>4>7||(S[0]<<8|S[1])%31)&&err(6,"invalid zlib data"),(S[1]>>5&1)==+!b&&err(6,"invalid zlib data: "+(32&S[1]?"need":"unexpected")+" dictionary"),2+(S[1]>>3&4)}(S,b&&b.dictionary),-4),{i:2},b&&b.out,b&&b.dictionary)}var wc="undefined"!=typeof TextEncoder&&new TextEncoder,bc="undefined"!=typeof TextDecoder&&new TextDecoder;try{bc.decode(Sc,{stream:!0})}catch(D){}function strToU8(S,b){if(b){for(var I=new Gl(S.length),x=0;x<S.length;++x)I[x]=S.charCodeAt(x);return I}if(wc)return wc.encode(S);var R=S.length,A=new Gl(S.length+(S.length>>1)),_=0,w=function(S){A[_++]=S};for(x=0;x<R;++x){if(_+5>A.length){var D=new Gl(_+8+(R-x<<1));D.set(A),A=D}var L=S.charCodeAt(x);L<128||b?w(L):L<2048?(w(192|L>>6),w(128|63&L)):L>55295&&L<57344?(w(240|(L=65536+(1047552&L)|1023&S.charCodeAt(++x))>>18),w(128|L>>12&63),w(128|L>>6&63),w(128|63&L)):(w(224|L>>12),w(128|L>>6&63),w(128|63&L))}return slc(A,0,_)}function strFromU8(S,b){if(b){for(var I="",x=0;x<S.length;x+=16384)I+=String.fromCharCode.apply(null,S.subarray(x,x+16384));return I}if(bc)return bc.decode(S);var R=function(S){for(var b="",I=0;;){var x=S[I++],R=(x>127)+(x>223)+(x>239);if(I+R>S.length)return{s:b,r:slc(S,I-1)};R?3==R?(x=((15&x)<<18|(63&S[I++])<<12|(63&S[I++])<<6|63&S[I++])-65536,b+=String.fromCharCode(55296|x>>10,56320|1023&x)):b+=1&R?String.fromCharCode((31&x)<<6|63&S[I++]):String.fromCharCode((15&x)<<12|(63&S[I++])<<6|63&S[I++]):b+=String.fromCharCode(x)}}(S),A=R.s;return(I=R.r).length&&err(8),A}const Cc=["token","key","secret","password","auth","api_key","apikey","access_token","refresh_token","jwt","bearer","credential","session_id","session","sid","ssid","private_token"];function sanitizeUrl(S){if(!S)return"";try{const b=new URL(S);for(const S of Cc)b.searchParams.delete(S),b.searchParams.delete(S.toLowerCase()),b.searchParams.delete(S.toUpperCase());return b.toString()}catch{return S.replace(/[?&](token|key|secret|password|auth|api_key|apikey|access_token|jwt)=[^&]*/gi,"$1=[REDACTED]")}}function hashCode(S){let b=0;for(let I=0;I<S.length;I++){b=(b<<5)-b+S.charCodeAt(I),b&=b}return Math.abs(b).toString(36)}function generateNetworkId(S,b,I,x){return`net_${b}_${hashCode(sanitizeUrl(x))}`}function generateConsoleId(S,b,I){return`log_${b}_${hashCode(String(I||"").substring(0,100))}`}function generateResourceId(S,b){return`res_${S}_${hashCode(b)}`}function flatNetworkFields(S){const b=S||{},I=b.requestUrl||b.url||"";return{method:b.method,url:I,status:"number"==typeof b.status?b.status:b.statusCode,duration:"number"==typeof b.durationMs?b.durationMs:b.duration,size:"number"==typeof b.responseSize?b.responseSize:b.size,error:b.error||b.errorMessage,resourceType:b.resourceType||(I?getResourceType(I):void 0)}}function extractNetworkRef(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=flatNetworkFields(S.data?.payload),R=sanitizeUrl(x.url),A={networkId:generateNetworkId(0,S.timestamp,x.method,R),timestamp:S.timestamp,method:x.method||"GET",url:R,status:x.status,duration:x.duration,size:x.size,type:I.replace("network_","")};return"network_resource"===I&&x.resourceType&&(A.resourceType=x.resourceType),A}function extractConsoleRef(S,b){if(5!==S.type)return null;if("console"!==S.data?.tag)return null;const I=S.data?.payload||{};let x="";I.args&&Array.isArray(I.args)?x=JSON.stringify(I.args).substring(0,100):I.message&&(x=String(I.message).substring(0,100));const R=generateConsoleId(0,S.timestamp,x);let A="";return I.message?(A=String(I.message).slice(0,100),I.message.length>100&&(A+="...")):I.args&&Array.isArray(I.args)&&(A=I.args.map(S=>String(S)).join(" ").slice(0,100),A.length>=100&&(A+="...")),{consoleId:R,timestamp:S.timestamp,level:I.level||"log",preview:A}}function extractResourceRef(S){if(5!==S.type)return null;if("network_resource"!==S.data?.tag)return null;const b=S.data?.payload||{};return{resourceId:generateResourceId(S.timestamp,b.url||""),timestamp:S.timestamp,method:b.method||"GET",url:b.url||"",status:b.status||0,resourceType:b.resourceType||"other",size:b.size||null,duration:b.duration||null}}function extractNetworkFull(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=S.data?.payload||{},R=flatNetworkFields(x),A=sanitizeUrl(R.url);return{id:generateNetworkId(0,S.timestamp,R.method,A),timestamp:S.timestamp,method:R.method||"GET",url:A,requestHeaders:x.requestHeaders||{},requestBody:x.requestBody||null,status:R.status,statusText:x.statusText,responseHeaders:x.responseHeaders||{},responseBody:x.responseBody||null,duration:R.duration,size:R.size,timing:x.timing,error:R.error}}function stripNetworkPayload(S){if(5!==S.type)return S;const b=S.data?.tag;if(!b||!b.startsWith("network_"))return S;const I=flatNetworkFields(S.data?.payload);return{...S,data:{tag:S.data.tag,payload:{method:I.method,url:I.url,status:I.status,duration:I.duration,size:I.size,resourceType:I.resourceType,error:I.error}}}}function extractVersion(S,b){const I=S.match(b);return I?I[1]:"unknown"}function parseBrowserInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";return b.includes("edg/")?(I="Edge",x=extractVersion(S,/edg\/(\d+(\.\d+)?)/i)):b.includes("chrome")&&!b.includes("chromium")?(I="Chrome",x=extractVersion(S,/chrome\/(\d+(\.\d+)?)/i)):b.includes("firefox")?(I="Firefox",x=extractVersion(S,/firefox\/(\d+(\.\d+)?)/i)):b.includes("safari")&&!b.includes("chrome")?(I="Safari",x=extractVersion(S,/version\/(\d+(\.\d+)?)/i)):b.includes("opera")||b.includes("opr")?(I="Opera",x=extractVersion(S,/(?:opera|opr)\/(\d+(\.\d+)?)/i)):(b.includes("msie")||b.includes("trident"))&&(I="IE",x=extractVersion(S,/(?:msie |rv:)(\d+(\.\d+)?)/i)),{name:I,version:x}}function parseOSInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";if(b.includes("windows"))I="Windows",b.includes("windows nt 10")?x="10":b.includes("windows nt 6.3")?x="8.1":b.includes("windows nt 6.2")?x="8":b.includes("windows nt 6.1")&&(x="7");else if(b.includes("mac os x")){I="macOS";const b=S.match(/mac os x (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else if(b.includes("android"))I="Android",x=extractVersion(S,/android (\d+(\.\d+)?)/i);else if(b.includes("iphone")||b.includes("ipad")||b.includes("ipod")){I="iOS";const b=S.match(/os (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else b.includes("linux")&&(I="Linux");return{name:I,version:x}}function detectDeviceType(S){if(!S)return"desktop";const b=S.toLowerCase();return/mobile|android|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(b)?/ipad|tablet/i.test(b)||b.includes("android")&&!b.includes("mobile")?"tablet":"mobile":"desktop"}function detectTouchCapability(){return"undefined"!=typeof window&&("ontouchstart"in window||"undefined"!=typeof navigator&&navigator.maxTouchPoints>0)}function getConnectionInfo(){if("undefined"==typeof navigator||!navigator.connection)return null;const S=navigator.connection;return{effectiveType:S.effectiveType||null,downlink:S.downlink||null,rtt:S.rtt||null,saveData:S.saveData||!1}}function getMemoryInfo(){return"undefined"!=typeof navigator&&navigator.deviceMemory?{deviceMemory:navigator.deviceMemory}:null}function collectDeviceMetadata(){const S="undefined"!=typeof navigator?navigator.userAgent:null;return{screen:{width:"undefined"!=typeof screen?screen.width:null,height:"undefined"!=typeof screen?screen.height:null,colorDepth:"undefined"!=typeof screen?screen.colorDepth:null,pixelRatio:"undefined"!=typeof window?window.devicePixelRatio:null},viewport:{width:"undefined"!=typeof window?window.innerWidth:null,height:"undefined"!=typeof window?window.innerHeight:null},userAgent:S,language:"undefined"!=typeof navigator?navigator.language:null,languages:"undefined"!=typeof navigator?navigator.languages:null,platform:"undefined"!=typeof navigator?navigator.platform:null,connection:getConnectionInfo(),deviceType:detectDeviceType(S),touchCapable:detectTouchCapability(),memory:getMemoryInfo(),browser:parseBrowserInfo(S),os:parseOSInfo(S)}}function analyzeSnapshotsInEvents(S){const b=[];let I=-1;for(let x=0;x<S.length;x++){const R=S[x];2===R.type&&(b.push(R.timestamp),-1===I&&(I=x))}return{hasSnapshot:b.length>0,snapshotCount:b.length,snapshotTimestamps:b,firstSnapshotIndex:I}}function buildSnapshotIndex(S){const b=[];for(const I of S)if(I.snapshotInfo?.hasSnapshot)for(let S=0;S<I.events.length;S++){const x=I.events[S];2===x.type&&b.push({chunkSequence:I.sequence,timestamp:x.timestamp,eventIndex:S})}return b.sort((S,b)=>S.timestamp-b.timestamp),b}function findNearestSnapshotBefore(S,b){if(!S||0===S.length)return null;let I=0,x=S.length-1,R=null;for(;I<=x;){const A=Math.floor((I+x)/2),_=S[A];_.timestamp<=b?(R=_,I=A+1):x=A-1}return R}function getEventsAfterSnapshot(S,b,I){if(!S||!S.events)return[];const x=[];for(let R=b;R<S.events.length;R++){const b=S.events[R];if(!(b.timestamp<=I))break;x.push(b)}return x}function chunkHasSnapshot(S){return!0===S?.snapshotInfo?.hasSnapshot}function getSnapshotTimestamps(S){return S?.snapshotInfo?.snapshotTimestamps||[]}function createChunk(S){const{sequence:b,sessionId:I,events:x=[],networkRefs:R=[],consoleRefs:A=[],networkFullData:_=[],metadata:D={},isFirstChunk:L=!1,isLastChunk:B=!1}=S,U=x.map(S=>S.timestamp).filter(S=>"number"==typeof S),$=U.length>0?Math.min(...U):Date.now(),j=U.length>0?Math.max(...U):Date.now(),W=analyzeSnapshotsInEvents(x);return{version:4,chunkId:I?`${I}_chunk_${b}`:`chunk_${b}_${Date.now()}`,sequence:b,sessionId:I,startTimestamp:$,endTimestamp:j,eventCount:x.length,events:x,networkRefs:R,consoleRefs:A,networkFullData:_,snapshotInfo:{hasSnapshot:W.hasSnapshot,snapshotCount:W.snapshotCount,snapshotTimestamps:W.snapshotTimestamps,firstSnapshotIndex:W.firstSnapshotIndex},metadata:{...D,createdAt:Date.now(),isFirstChunk:L,isLastChunk:B,hasSnapshotInChunk:W.hasSnapshot}}}function isCompatibleVersion(S){return 4===S.version}class InactivityManager{constructor(S={}){this.inactivityTimeout=S.inactivityTimeout||3e5,this.maxInactivityDuration=S.maxInactivityDuration||18e5,this.maxSessionDuration=S.maxSessionDuration||36e5,this.enabled=!1!==S.enableInactivityDetection,this.lastActivityTime=Date.now(),this.isPaused=!1,this.pauseStartTime=null,this.totalPausedTime=0,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.inactivityTimer=null,this.sessionEndTimer=null,this.onPause=S.onPause||(()=>{}),this.onResume=S.onResume||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.enabled&&(this.lastActivityTime=Date.now(),this.sessionStartTime=Date.now(),this.totalPausedTime=0,this.isPaused=!1,this.sessionEnded=!1,this.sessionEndReason=null,this.resetInactivityTimer(),this.logger.info?.(`[Inactivity] Detection enabled: pause after ${this.inactivityTimeout/1e3}s, end session after ${this.maxInactivityDuration/1e3}s`))}stop(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null)}trackActivity(S){if(!this.enabled)return;this.isUserActivityEvent(S)&&(this.lastActivityTime=Date.now(),this.isPaused&&this.resumeFromInactivity(),this.resetInactivityTimer())}isUserActivityEvent(S){if(3===S.type&&S.data){return[1,2,3,5,6,7].includes(S.data.source)}return!1}resetInactivityTimer(){if(Date.now()-this.sessionStartTime>this.maxSessionDuration)return this.logger.warn?.(`[Inactivity] Max session duration (${Math.round(this.maxSessionDuration/6e4)}min) exceeded - ending session`),void this.onMaxSessionDurationReached();this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout(()=>{this.onInactivityTimeout()},this.inactivityTimeout)}onInactivityTimeout(){if(this.isPaused)return;const S=Date.now()-this.lastActivityTime;this.logger.info?.(`[Inactivity] User inactive for ${Math.round(S/1e3)}s - pausing recording`),this.pauseForInactivity(),this.sessionEndTimer=setTimeout(()=>{this.onMaxInactivityReached()},this.maxInactivityDuration-this.inactivityTimeout)}pauseForInactivity(){this.isPaused||(this.isPaused=!0,this.pauseStartTime=Date.now(),this.onAddCustomEvent("inactivity",{action:"pause",inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}),this.logger.info?.("[Inactivity] Recording paused - waiting for user activity"),this.onPause({inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}))}resumeFromInactivity(){if(!this.isPaused)return;const S=Date.now()-this.pauseStartTime;this.totalPausedTime+=S;const b=Date.now()-this.sessionStartTime;if(b>this.maxSessionDuration)return this.logger.warn?.("[Inactivity] Max session duration exceeded during pause - ending session"),void this.onMaxSessionDurationReached();this.isPaused=!1,this.pauseStartTime=null,this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null),this.onAddCustomEvent("inactivity",{action:"resume",pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()}),this.logger.info?.(`[Inactivity] Recording resumed after ${Math.round(S/1e3)}s pause (session: ${Math.round(b/6e4)}min)`),this.onResume({pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()})}onMaxInactivityReached(){const S=Date.now()-this.lastActivityTime,b=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Inactivity] Max inactivity (${Math.round(S/1e3)}s) reached - ending session`),this.onAddCustomEvent("inactivity",{action:"session_ended",reason:"max_inactivity",inactiveFor:S,sessionDuration:b,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_inactivity")}onMaxSessionDurationReached(){const S=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Session] Max duration (${Math.round(S/6e4)}min) reached - ending session`),this.onAddCustomEvent("session_lifecycle",{action:"session_ended",reason:"max_duration",sessionDuration:S,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_duration")}endSession(S="manual"){this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.onSessionEnd({reason:S,duration:Date.now()-this.sessionStartTime,totalPausedTime:this.totalPausedTime})}shouldRecordEvent(S){return!this.isPaused||5===S.type}getState(){return{enabled:this.enabled,isPaused:this.isPaused,sessionEnded:this.sessionEnded,sessionEndReason:this.sessionEndReason,lastActivityTime:this.lastActivityTime,totalPausedTime:this.totalPausedTime,sessionDuration:Date.now()-this.sessionStartTime,timeSinceLastActivity:Date.now()-this.lastActivityTime}}updateConfig(S){void 0!==S.inactivityTimeout&&(this.inactivityTimeout=S.inactivityTimeout),void 0!==S.maxInactivityDuration&&(this.maxInactivityDuration=S.maxInactivityDuration),void 0!==S.maxSessionDuration&&(this.maxSessionDuration=S.maxSessionDuration),void 0!==S.enableInactivityDetection&&(this.enabled=S.enableInactivityDetection)}destroy(){this.stop(),this.onPause=null,this.onResume=null,this.onSessionEnd=null,this.onAddCustomEvent=null,this.logger=null}}class PageLifecycleManager{constructor(S={}){this.onFlush=S.onFlush||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.onSendBeacon=S.onSendBeacon||(()=>{}),this.getIsRecording=S.getIsRecording||(()=>!1),this.getCurrentChunkLength=S.getCurrentChunkLength||(()=>0),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.logger=S.logger||console,this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this._pageCloseFlushAttempted=!1}setup(){"undefined"!=typeof window&&(this._pageCloseFlushAttempted=!1,this._boundBeforeUnload=this._handleBeforeUnload.bind(this),this._boundPageHide=this._handlePageHide.bind(this),this._boundVisibilityChange=this._handleVisibilityChange.bind(this),window.addEventListener("beforeunload",this._boundBeforeUnload),window.addEventListener("pagehide",this._boundPageHide),document.addEventListener("visibilitychange",this._boundVisibilityChange),this.logger.info?.("[PageLifecycle] Page close handlers installed"))}remove(){"undefined"!=typeof window&&(this._boundBeforeUnload&&window.removeEventListener("beforeunload",this._boundBeforeUnload),this._boundPageHide&&window.removeEventListener("pagehide",this._boundPageHide),this._boundVisibilityChange&&document.removeEventListener("visibilitychange",this._boundVisibilityChange),this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this.logger.info?.("[PageLifecycle] Page close handlers removed"))}_handleBeforeUnload(S){this._flushOnPageClose("beforeunload")}_handlePageHide(S){this._flushOnPageClose("pagehide",S.persisted)}_handleVisibilityChange(){"hidden"===document.visibilityState&&this._flushOnPageClose("visibilitychange")}_flushOnPageClose(S,b=!1){if(this._pageCloseFlushAttempted)return void this.logger.log?.(`[PageLifecycle] Flush already attempted, skipping duplicate (${S})`);const I=this.getIsRecording(),x=this.getCurrentChunkLength();if(!I||0===x)return void this.logger.log?.(`[PageLifecycle] No pending events to flush on ${S}`);this._pageCloseFlushAttempted=!0,this.logger.log?.(`[PageLifecycle] Flushing ${x} events on ${S}`),this.onAddCustomEvent("session_lifecycle",{action:"page_close",trigger:S,persisted:b,timestamp:Date.now(),pendingEvents:x,sessionDuration:Date.now()-this.getSessionStartTime(),totalChunks:this.getChunkCounter()});const R=this.onFlush();R&&(R.metadata=R.metadata||{},R.metadata.isLastChunk=!0,R.metadata.closeTrigger=S,R.metadata.sessionEndedGracefully=!0,this.onSendBeacon(R,S))}resetFlushGuard(){this._pageCloseFlushAttempted=!1}getState(){return{handlersInstalled:null!==this._boundBeforeUnload,flushAttempted:this._pageCloseFlushAttempted}}destroy(){this.remove(),this.onFlush=null,this.onAddCustomEvent=null,this.onSendBeacon=null,this.getIsRecording=null,this.getCurrentChunkLength=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.logger=null}}class CheckpointManager{constructor(S={}){this.checkpointInterval=S.checkpointInterval||6e4,this.lastCheckpointTime=0,this.checkpointTimer=null,this.checkpointCount=0,this.checkpointAvailable=null,this.getRRWeb=S.getRRWeb||(()=>null),this.getIsRecording=S.getIsRecording||(()=>!1),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.getEventCount=S.getEventCount||(()=>0),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.checkpointTimer&&clearInterval(this.checkpointTimer),this.lastCheckpointTime=Date.now(),this.checkpointCount=0,this.checkpointTimer=setInterval(()=>{this.requestCheckpoint()},this.checkpointInterval),this.logger.info?.(`[Checkpoint] Timer started (interval: ${this.checkpointInterval/1e3}s)`)}stop(){this.checkpointTimer&&(clearInterval(this.checkpointTimer),this.checkpointTimer=null)}requestCheckpoint(){if(!this.getIsRecording())return;const S=Date.now();if(!(S-this.lastCheckpointTime<.9*this.checkpointInterval))try{const b=this.getRRWeb();let I=null;if(b&&("function"==typeof b.takeFullSnapshot?I=b.takeFullSnapshot:b.record&&"function"==typeof b.record.takeFullSnapshot&&(I=b.record.takeFullSnapshot)),I)try{I(),this.lastCheckpointTime=S,this.checkpointAvailable=!0,this.checkpointCount++,this.onAddCustomEvent("checkpoint",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),checkpointNumber:this.checkpointCount,snapshotRequested:!0}),this.logger.info?.(`[Checkpoint] #${this.checkpointCount} at ${Math.round((S-this.getSessionStartTime())/1e3)}s`)}catch(b){this.logger.warn?.("[Checkpoint] takeFullSnapshot error:",b.message),this.checkpointAvailable=!1,this._addCheckpointMarker(S,"takeFullSnapshot error: "+b.message)}else!1!==this.checkpointAvailable&&(this.logger.warn?.("[Checkpoint] Manual snapshots not available - relying on rrweb checkoutEveryNms"),this.checkpointAvailable=!1),this._addCheckpointMarker(S,"using rrweb auto-checkout")}catch(S){this.logger.warn?.("[Checkpoint] Request failed:",S.message),this._addCheckpointMarker(Date.now(),"Error: "+S.message)}}_addCheckpointMarker(S,b){this.onAddCustomEvent("checkpoint_marker",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),snapshotRequested:!1,reason:b})}takeManualCheckpoint(){this.logger.info?.("[Checkpoint] Manual checkpoint requested"),this.requestCheckpoint()}getState(){return{checkpointCount:this.checkpointCount,lastCheckpointTime:this.lastCheckpointTime,checkpointAvailable:this.checkpointAvailable,checkpointInterval:this.checkpointInterval,timerRunning:null!==this.checkpointTimer}}updateConfig(S){void 0!==S.checkpointInterval&&(this.checkpointInterval=S.checkpointInterval,this.checkpointTimer&&(this.stop(),this.start()))}destroy(){this.stop(),this.getRRWeb=null,this.getIsRecording=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.getEventCount=null,this.onAddCustomEvent=null,this.logger=null}}class RecorderMemoryManager{constructor(S={}){this.maxChunksInMemory=S.maxChunksInMemory||10,this.maxEventsPerSession=S.maxEventsPerSession||5e4,this.maxSessionBytes=S.maxSessionBytes||52428800,this.maxEventsInBuffer=S.maxEventsInBuffer||2e3,this.cleanupInterval=S.cleanupInterval||6e4,this.totalSessionBytes=0,this.cleanupTimer=null,this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=S.onForceFlush||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setDataReferences(S){this._allChunks=S.allChunks||null,this._events=S.events||null,this._eventDedupeCache=S.eventDedupeCache||null,this._eventStats=S.eventStats||null}start(){this.cleanupTimer||(this.totalSessionBytes=0,this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.cleanupInterval),this.logger.log?.("[Memory] Started periodic cleanup (60s interval)"))}stop(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.logger.log?.("[Memory] Stopped cleanup timer"))}trackBytes(S){return this.totalSessionBytes+=S,!(this.totalSessionBytes>this.maxSessionBytes)||(this.logger.warn?.(`[Memory] Session size limit reached (${Math.round(this.totalSessionBytes/1024/1024)}MB / ${Math.round(this.maxSessionBytes/1024/1024)}MB)`),!1)}checkEventLimit(S){return!(S>this.maxEventsPerSession)||(this.logger.warn?.(`[Memory] Max events per session (${this.maxEventsPerSession}) exceeded`),!1)}performCleanup(){const S=Date.now();let b={dedupeEntries:0,statsEvents:0,chunks:0,eventsBuffer:0};if(this._eventDedupeCache){const I=S-1e4;for(const[S,x]of this._eventDedupeCache.entries())x<I&&(this._eventDedupeCache.delete(S),b.dedupeEntries++)}if(this._eventStats?.lastMinuteEvents){const I=S-6e4,x=this._eventStats.lastMinuteEvents.length;this._eventStats.lastMinuteEvents=this._eventStats.lastMinuteEvents.filter(S=>S>I),b.statsEvents=x-this._eventStats.lastMinuteEvents.length}if(this._allChunks&&this._allChunks.length>this.maxChunksInMemory)for(;this._allChunks.length>this.maxChunksInMemory;)this._allChunks.shift(),b.chunks++;return this._events&&this._events.length>this.maxEventsInBuffer&&(this.logger.warn?.(`[Memory] Events buffer exceeded ${this.maxEventsInBuffer}, forcing flush`),this.onForceFlush()),(b.dedupeEntries>0||b.statsEvents>0||b.chunks>0)&&this.logger.log?.(`[Memory] Cleanup: ${b.dedupeEntries} dedupe entries, ${b.statsEvents} stat entries, ${b.chunks} chunks`),b}trimEventsArray(S=1e3){if(!this._events||this._events.length<=S)return 0;const b=this._events.length-S;return this._events.splice(0,b),this.logger.log&&this.logger.log?.(`[Memory] Cleared ${b} old events from events array`),b}trimChunksArray(){if(!this._allChunks||this._allChunks.length<=this.maxChunksInMemory)return null;const S=this._allChunks.shift();return this.logger.log?.(`[Memory] Removed old chunk ${S?.sequence} from memory (keeping ${this.maxChunksInMemory} chunks)`),S}getStats(){return{eventsInBuffer:this._events?.length||0,maxEventsInBuffer:this.maxEventsInBuffer,chunksInMemory:this._allChunks?.length||0,maxChunksInMemory:this.maxChunksInMemory,dedupeCacheSize:this._eventDedupeCache?.size||0,totalSessionBytes:this.totalSessionBytes,maxSessionBytes:this.maxSessionBytes,sessionSizePercent:Math.round(this.totalSessionBytes/this.maxSessionBytes*100),statsEventsTracked:this._eventStats?.lastMinuteEvents?.length||0,totalEventsRecorded:this._eventStats?.total||0,estimatedMemoryMB:this.estimateMemoryUsage()}}estimateMemoryUsage(){let S=0;if(S+=500*(this._events?.length||0),this._allChunks)for(const b of this._allChunks)S+=b.sizeBytes||5e4;return S+=100*(this._eventDedupeCache?.size||0),Math.round(S/1048576*100)/100}suggestGC(){if(this._allChunks)for(const S of this._allChunks)S._rawEvents&&(S._rawEvents=null);this.logger.log?.("[Memory] GC hint sent")}updateConfig(S){void 0!==S.maxChunksInMemory&&(this.maxChunksInMemory=S.maxChunksInMemory),void 0!==S.maxEventsPerSession&&(this.maxEventsPerSession=S.maxEventsPerSession),void 0!==S.maxSessionBytes&&(this.maxSessionBytes=S.maxSessionBytes),void 0!==S.maxEventsInBuffer&&(this.maxEventsInBuffer=S.maxEventsInBuffer)}reset(){this.totalSessionBytes=0}destroy(){this.stop(),this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=null,this.onSessionEnd=null,this.logger=null}}const kc={0:"DomContentLoaded",1:"Load",2:"FullSnapshot",3:"IncrementalSnapshot",4:"Meta",5:"Custom"};class EventOptimizer{constructor(S={}){this.samplingEnabled=S.enableSampling||!1,this.deduplicationEnabled=S.enableDeduplication||!1,this.mousemoveSampling=S.mousemoveSampling||1,this.scrollSampling=S.scrollSampling||1,this.mutationSampling=S.mutationSampling||1,this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0},this.eventDedupeCache=new Map,this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.logger=S.logger||console}getDedupeCache(){return this.eventDedupeCache}getEventStats(){return this.eventStats}shouldRecordEvent(S){const b=this.getEventTypeName(S.type);return!!["DomContentLoaded","Load","FullSnapshot","Meta","Custom"].includes(b)||!(this.samplingEnabled&&!this._applySampling(S))&&(!this.deduplicationEnabled||!this._isDuplicateEvent(S))}updateStats(S){this.eventStats.total++;const b=this.getEventTypeName(S.type);this.eventStats.byType[b]=(this.eventStats.byType[b]||0)+1;try{const I=JSON.stringify(S).length;this.eventStats.sizeByType[b]||(this.eventStats.sizeByType[b]={total:0,count:0,average:0}),this.eventStats.sizeByType[b].total+=I,this.eventStats.sizeByType[b].count++,this.eventStats.sizeByType[b].average=Math.round(this.eventStats.sizeByType[b].total/this.eventStats.sizeByType[b].count)}catch(S){}const I=Date.now();this.eventStats.lastMinuteEvents.push(I),this.eventStats.lastMinuteEvents=this.eventStats.lastMinuteEvents.filter(S=>I-S<6e4),this.eventStats.currentRate=this.eventStats.lastMinuteEvents.length}adaptToEventRate(){if(!this.samplingEnabled)return;const S=this.eventStats.currentRate;S>3e3?(this.mousemoveSampling=Math.max(.1,this.mousemoveSampling-.1),this.scrollSampling=Math.max(.2,this.scrollSampling-.1),this.logger.warn?.(`[Optimizer] High event rate (${S}/min), increasing sampling`)):S<600&&this.mousemoveSampling<.5&&(this.mousemoveSampling=Math.min(.5,this.mousemoveSampling+.05),this.scrollSampling=Math.min(.7,this.scrollSampling+.05))}_applySampling(S){if(3===S.type&&1===S.data?.source){if(Math.random()>=this.mousemoveSampling)return!1;if(S.data.positions&&S.data.positions.length>0){const b=S.data.positions[S.data.positions.length-1];if(Math.sqrt(Math.pow(b.x-this.lastMousePosition.x,2)+Math.pow(b.y-this.lastMousePosition.y,2))<5)return!1;this.lastMousePosition={x:b.x,y:b.y}}}return 3!==S.type||3!==S.data?.source||Math.random()<this.scrollSampling}_isDuplicateEvent(S){const b=this._getEventKey(S),I=Date.now();if(this.eventDedupeCache.has(b)){if(I-this.eventDedupeCache.get(b)<100)return!0}if(this.eventDedupeCache.set(b,I),this.eventDedupeCache.size>1e3){const S=I-5e3;for(const[b,I]of this.eventDedupeCache.entries())I<S&&this.eventDedupeCache.delete(b)}return!1}_getEventKey(S){if(3===S.type){const b=S.data?.source,I=S.data?.id,x=S.data?.action;return`${S.type}-${b}-${I}-${x}`}try{return`${S.type}-${JSON.stringify(S.data).substring(0,50)}`}catch(b){return`${S.type}-unknown`}}getEventTypeName(S){return kc[S]||`Unknown(${S})`}getOptimizationStats(){return{eventStats:{...this.eventStats},samplingRates:{mousemove:this.mousemoveSampling,scroll:this.scrollSampling},samplingEnabled:this.samplingEnabled,deduplicationEnabled:this.deduplicationEnabled,deduplicatedEvents:this.eventDedupeCache.size}}logOptimizationReport(){const S=this.getOptimizationStats();this.logger.info?.("📊 Optimization Report:"),this.logger.info?.(" Sampling: "+(S.samplingEnabled?"Enabled":"Disabled")),this.logger.info?.(" Deduplication: "+(S.deduplicationEnabled?"Enabled":"Disabled")),this.logger.info?.(` Event Rate: ${S.eventStats.currentRate}/min`),this.logger.info?.(` Total Events: ${S.eventStats.total}`),this.logger.info?.(` Deduplicated: ${S.deduplicatedEvents}`),S.samplingEnabled&&(this.logger.info?.(" Sampling Rates:"),this.logger.info?.(` Mouse Move: ${(100*S.samplingRates.mousemove).toFixed(0)}%`),this.logger.info?.(` Scroll: ${(100*S.samplingRates.scroll).toFixed(0)}%`)),this.logger.info?.(" Event Distribution:");for(const[b,I]of Object.entries(S.eventStats.byType)){const x=(I/S.eventStats.total*100).toFixed(1),R=S.eventStats.sizeByType[b]?.average||0;this.logger.info?.(` ${b}: ${I} (${x}%) - Avg: ${R}B`)}}updateConfig(S){void 0!==S.enableSampling&&(this.samplingEnabled=S.enableSampling),void 0!==S.enableDeduplication&&(this.deduplicationEnabled=S.enableDeduplication),void 0!==S.mousemoveSampling&&(this.mousemoveSampling=S.mousemoveSampling),void 0!==S.scrollSampling&&(this.scrollSampling=S.scrollSampling),void 0!==S.mutationSampling&&(this.mutationSampling=S.mutationSampling)}reset(){this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.eventDedupeCache.clear(),this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0}}destroy(){this.eventDedupeCache.clear(),this.eventStats=null,this.logger=null}}class ChunkManager{constructor(S={}){this.chunkDuration=S.chunkDuration||3e4,this.maxChunkSize=S.maxChunkSize||5e5,this.maxEventsPerChunk=S.maxEventsPerChunk||500,this.minFlushInterval=S.minFlushInterval||1e4,this.firstChunkFlushed=!1,this.firstChunkFlushTimeout=2e3,this.recordingStartTime=null,this._firstChunkTimer=null,this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.chunkTimer=null,this.sessionId=null,this.sdkContext=null,this.onChunkCreated=S.onChunkCreated||(()=>{}),this.onServerUpload=S.onServerUpload||null,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setSessionInfo(S){this.sessionId=S.sessionId,this.sdkContext=S.sdkContext}startRecording(){this.recordingStartTime=Date.now(),this.firstChunkFlushed=!1,this._firstChunkTimer&&clearTimeout(this._firstChunkTimer),this._firstChunkTimer=setTimeout(()=>{!this.firstChunkFlushed&&this.currentChunk.length>0&&(this.logger.info?.("[ChunkManager] Force-flushing first chunk (2s timeout)"),this.flush({force:!0})),this._firstChunkTimer=null},this.firstChunkFlushTimeout)}startTimer(){this.chunkTimer||(this.chunkTimer=setTimeout(()=>{this.flush(),this.startTimer()},this.chunkDuration))}stopTimer(){this.chunkTimer&&(clearTimeout(this.chunkTimer),this.chunkTimer=null)}resetTimer(){this.stopTimer(),this.startTimer()}addEvent(S){return this.currentChunk.push(S),!0}getCurrentChunkLength(){return this.currentChunk.length}checkFlush(){if(0===this.currentChunk.length)return!1;if(!this.firstChunkFlushed&&this.currentChunk.length>0){const S=this.currentChunk.some(S=>2===S.type);if(S)return this.logger.info?.("[ChunkManager] FullSnapshot detected - immediate flush"),this.flush({force:!0}),this.resetTimer(),!0}const S=this.estimateSize(this.currentChunk)>=this.maxChunkSize,b=this.currentChunk.length>=this.maxEventsPerChunk,I=Date.now()-this._lastFlushTime;return(S||!!(b&&I>=this.minFlushInterval))&&(this.flush(),this.resetTimer(),!0)}flush(S={}){if(this._isFlushing)return null;this._isFlushing=!0;try{if(0===this.currentChunk.length)return null;!this.firstChunkFlushed&&(this.firstChunkFlushed=!0,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.logger.info?.("[ChunkManager] First chunk flushed"));const S=this.currentChunk;this.currentChunk=[];const b=this.chunkCounter;this.chunkCounter++,this.sessionId||(this.sessionId=generateSessionId(),this.logger.warn(`[ChunkManager] sessionId was null at flush time for chunk ${b}, generated fallback: ${this.sessionId}`));const I=[],x=[],R=[],A=[];for(const b of S){const S=extractNetworkRef(b,this.sessionId);if(S){I.push(S);const x=extractNetworkFull(b,this.sessionId);x&&R.push(x),A.push(stripNetworkPayload(b));continue}const _=extractConsoleRef(b,this.sessionId);_?(x.push(_),A.push(b)):A.push(b)}const _={projectId:this.sdkContext?.projectId,environment:this.sdkContext?.environment,userId:this.sdkContext?.userId};0===b&&(_.device=collectDeviceMetadata());let D=createChunk({sequence:b,sessionId:this.sessionId,events:A,networkRefs:I,consoleRefs:x,networkFullData:R,metadata:_,isFirstChunk:0===b,isLastChunk:!1});return this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&(D=this.sdkContext.enrichChunk(D)),this.allChunks.push(D),this._lastFlushTime=Date.now(),this.onChunkCreated(D,b),this.onServerUpload&&this.sendToServer(D),D}finally{this._isFlushing=!1}}estimateSize(S){if(!S||0===S.length)return 0;try{if(S.length<=50)return JSON.stringify(S).length;const b=Math.min(50,Math.max(10,Math.floor(.1*S.length))),I=Math.floor(S.length/b);let x=0;for(let b=0;b<S.length;b+=I)x+=JSON.stringify(S[b]).length;const R=x/Math.ceil(S.length/I);return Math.ceil(R*S.length)+2*S.length}catch(S){return 0}}async sendToServer(S){if(this.onServerUpload)try{await this.onServerUpload(S),this.logger.info?.(`Chunk ${S.sequence} sent successfully`)}catch(S){this.logger.warn?.("Failed to send chunk to server:",S)}}getChunks(){return[...this.allChunks]}getChunkCounter(){return this.chunkCounter}setChunkCounter(S){this.chunkCounter=S}getCurrentChunk(){return[...this.currentChunk]}exportChunkedData(S="json"){const b={sessionId:this.sessionId,chunks:this.allChunks,totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length};return"json"===S?JSON.stringify(b,null,2):b}getStats(){const S=this.allChunks.reduce((S,b)=>S+(b.sizeBytes||0),0),b=this.estimateSize(this.currentChunk);return{totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length,currentChunkSize:b,totalSize:S,chunkCounter:this.chunkCounter,avgChunkSize:this.allChunks.length>0?Math.round(S/this.allChunks.length):0}}updateConfig(S){void 0!==S.chunkDuration&&(this.chunkDuration=S.chunkDuration),void 0!==S.maxChunkSize&&(this.maxChunkSize=S.maxChunkSize),void 0!==S.maxEventsPerChunk&&(this.maxEventsPerChunk=S.maxEventsPerChunk),void 0!==S.minFlushInterval&&(this.minFlushInterval=S.minFlushInterval)}reset(){this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.stopTimer(),this.firstChunkFlushed=!1,this.recordingStartTime=null,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null)}destroy(){this.stopTimer(),this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.currentChunk=[],this.allChunks=[],this.onChunkCreated=null,this.onServerUpload=null,this.onSessionEnd=null,this.sdkContext=null,this.logger=null}}class RecorderLogger{constructor(S,b=!1){const I=S.replace(/^\[|\]$/g,"");this.serviceLogger=createLogger(I),this.prefix=`[TraceScout][${S}]`,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.debug&&this.serviceLogger.log(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class Recorder{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[Recorder] No SDKContext provided - running in v1.x compatibility mode");const b=S.preset?Recorder.getPresetConfig(S.preset):{};this.config={emit:()=>{},checkoutEveryNms:6e4,checkoutEveryNth:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,debug:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},chunkDuration:3e4,maxChunkSize:5e5,onChunk:null,enableSampling:!1,enableDeduplication:!1,mousemoveSampling:1,scrollSampling:1,mutationSampling:1,inactivityTimeout:3e5,maxInactivityDuration:18e5,maxSessionDuration:36e5,enableInactivityDetection:!0,maxChunksInMemory:S.maxChunksInMemory||10,maxEventsPerSession:S.maxEventsPerSession||5e4,maxSessionBytes:S.maxSessionBytes||52428800,checkpointInterval:S.checkpointInterval||6e4,...b,...S},this.events=[],this.isRecording=!1,this.stopFn=null,this.metadata={},this.sessionId=null,this.recordingStartTime=null,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.statusTimer=null,this.statusInterval=1e4,this.aggregationTimer=null,this.aggregationInterval=3e4,this.lastAggregationThresholdSec=0,this._uploadQueue=null,this.logger=new RecorderLogger("Recorder",this.config.debug),this._initializeModules()}_initializeModules(){this.inactivityManager=new InactivityManager({inactivityTimeout:this.config.inactivityTimeout,maxInactivityDuration:this.config.maxInactivityDuration,maxSessionDuration:this.config.maxSessionDuration,enableInactivityDetection:this.config.enableInactivityDetection,logger:this.logger,onPause:S=>this._onInactivityPause(S),onResume:S=>this._onInactivityResume(S),onSessionEnd:S=>this._onInactivitySessionEnd(S),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.pageLifecycleManager=new PageLifecycleManager({logger:this.logger,getIsRecording:()=>this.isRecording,getCurrentChunkLength:()=>this.chunkManager.getCurrentChunkLength(),getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),onFlush:()=>this.chunkManager.flush(),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b),onSendBeacon:(S,b)=>this._sendChunkWithBeacon(S,b)}),this.checkpointManager=new CheckpointManager({checkpointInterval:this.config.checkpointInterval,logger:this.logger,getRRWeb:()=>getRRWeb(),getIsRecording:()=>this.isRecording,getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),getEventCount:()=>this.events.length,onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.memoryManager=new RecorderMemoryManager({maxChunksInMemory:this.config.maxChunksInMemory,maxEventsPerSession:this.config.maxEventsPerSession,maxSessionBytes:this.config.maxSessionBytes,logger:this.logger,onForceFlush:()=>this.chunkManager.flush(),onSessionEnd:S=>this.endSession(S)}),this.eventOptimizer=new EventOptimizer({enableSampling:this.config.enableSampling,enableDeduplication:this.config.enableDeduplication,mousemoveSampling:this.config.mousemoveSampling,scrollSampling:this.config.scrollSampling,mutationSampling:this.config.mutationSampling,logger:this.logger}),this.chunkManager=new ChunkManager({chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize,logger:this.logger,onChunkCreated:(S,b)=>this._onChunkCreated(S,b),onServerUpload:this.config.serverUrl?S=>this.sendChunkToServer(S):null})}async start(S={}){if(this.isRecording)return this.logger.warn("Recording already in progress"),this.stopFn;this.logger.info("Starting session recording...");const b=this._getSessionResumeInfo();b.isResumed&&(this.logger.info(`[V3] Resuming session ${b.sessionId}, continuing from chunk ${b.lastChunkSequence}`),this.chunkManager.setChunkCounter(b.lastChunkSequence+1));try{const b=await loadRRWeb();this.sdkContext&&this.sdkContext.sessionId?this.sessionId=this.sdkContext.sessionId:this.sessionId=this.generateSessionId(),this.chunkManager.setSessionInfo({sessionId:this.sessionId,sdkContext:this.sdkContext});let I=0,x=Date.now();const R={...this.config,...S,emit:b=>{if(I++,this.config.debug&&I%50==0){const S=Date.now()-x;this.logger.log(`${I} events captured (${S}ms since last log)`),x=Date.now()}const R={...b,tracescoutVersion:"1.0.0",sessionId:this.getSessionId()},A=this.chunkManager.estimateSize([R]),_=2===R.type||4===R.type;if(A>1e6&&!_)return void(this.config.debug&&this.logger.warn(`Skipping extremely large event: ${A} bytes, type: ${R.type}`));if(!this.onEvent(R))return;this.chunkManager.addEvent(R),this.events.push(R),this.chunkManager.checkFlush();(S.emit||this.config.emit)(R)}};if(this.stopFn=b.record(R),this.isRecording=!0,this.recordingStartTime=Date.now(),this.sessionStartTime=Date.now(),this._rrweb=b,this.chunkManager&&(this.chunkManager.startRecording(),this.logger.info("[Recorder] First-chunk flush timer started (2s)")),this.memoryManager.setDataReferences({allChunks:this.chunkManager.allChunks,events:this.events,eventDedupeCache:this.eventOptimizer.getDedupeCache(),eventStats:this.eventOptimizer.getEventStats()}),this.config.enableStreamingStorage)try{const{ChunkedCompressedStorage:S}=await Promise.resolve().then(function(){return xc});this.__streamStore=S,this.__streamStore.initSession(this.sessionId),this.logger.info("Streaming storage initialized")}catch(S){this.logger.warn("Failed to init streaming storage:",S)}return this.chunkManager.startTimer(),this.checkpointManager.start(),this.memoryManager.start(),this.inactivityManager.start(),this.pageLifecycleManager.setup(),this._startStatusTimer(),this.sessionEnded=!1,this.sessionEndReason=null,this._uploadQueue?.didIndexedDBFail?.()&&(this.logger.warn("[Recorder] IndexedDB failed - scheduling backup snapshot"),this._scheduleBackupSnapshot()),this._uploadQueue?.on&&this._uploadQueue.on("firstSnapshotUploadFailed",()=>{this.logger.warn("[Recorder] First snapshot upload failed 3x - taking immediate backup"),this._takeBackupSnapshot()}),this._setupSPANavigationDetection(),this.logger.info("🔴 Recording started",{sessionId:this.sessionId,startTime:this.recordingStartTime,chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize}),this.stopFn}catch(S){throw this.logger.error("Failed to load or initialize rrweb:",S),S}}stop(){if(!this.isRecording)return this.logger.warn("No recording in progress"),this.events;this.chunkManager.stopTimer(),this.checkpointManager.stop(),this.memoryManager.stop(),this.inactivityManager.stop(),this.pageLifecycleManager.remove(),this._stopStatusTimer(),this._cleanupSPANavigationDetection(),this._backupSnapshotTimer&&(clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=null),this.chunkManager.flush(),this.stopFn&&(this.stopFn(),this.stopFn=null),this._rrweb=null,this.isRecording=!1;const S=Date.now()-this.recordingStartTime;return this.logger.info("Recording stopped",{sessionId:this.sessionId,duration:S,eventCount:this.events.length,totalChunks:this.chunkManager.getChunks().length}),this.events}onEvent(S){return this.eventOptimizer.updateStats(S),this.inactivityManager.trackActivity(S),!!this.inactivityManager.shouldRecordEvent(S)&&(5===S.type||!!this.eventOptimizer.shouldRecordEvent(S)&&(this.eventOptimizer.adaptToEventRate(),!0))}addCustomEvent(S,b){if(!this.isRecording)return!1;if(!S||"string"!=typeof S)return!1;try{let I=b||{};this.sdkContext&&(I={...b,sessionId:this.sdkContext.sessionId,projectId:this.sdkContext.projectId,environment:this.sdkContext.environment,userId:this.sdkContext.userId});const x={type:5,data:{tag:S,payload:I},timestamp:Date.now(),tracescoutVersion:this.sdkContext?"2.0.0":"1.0.0",sessionId:this.getSessionId()};return!!this.onEvent(x)&&(this.chunkManager.addEvent(x),this.events.push(x),this.chunkManager.checkFlush(),!0)}catch(S){return this.logger.error("Failed to add custom event:",S),!1}}_setupSPANavigationDetection(){if("undefined"==typeof window||"undefined"==typeof history)return;this._lastKnownUrl=window.location.href,this._originalPushState=history.pushState,this._originalReplaceState=history.replaceState;const S=this;history.pushState=function(...b){const I=S._originalPushState.apply(this,b);return S._onSPANavigation("pushState"),I},history.replaceState=function(...b){const I=S._originalReplaceState.apply(this,b);return S._onSPANavigation("replaceState"),I},this._popstateHandler=()=>{S._onSPANavigation("popstate")},window.addEventListener("popstate",this._popstateHandler),this._hashchangeHandler=()=>{S._onSPANavigation("hashchange")},window.addEventListener("hashchange",this._hashchangeHandler),this.logger.info("SPA navigation detection enabled")}_onSPANavigation(S){const b=window.location.href;if(b===this._lastKnownUrl)return;const I=this._lastKnownUrl;if(this._lastKnownUrl=b,this.logger.info(`SPA navigation detected (${S}): ${I} → ${b}`),this.addCustomEvent("page_navigation",{url:b,previousUrl:I,title:document.title,navigationType:S,timestamp:Date.now()}),"function"==typeof this.config?.onSpaNavigation)try{this.config.onSpaNavigation(S,I,b)}catch(S){this.logger.warn?.("[Recorder] onSpaNavigation callback threw:",S)}setTimeout(()=>{this._takeFullSnapshotForNavigation(b)},100)}_takeFullSnapshotForNavigation(S){if(this._rrweb&&this.isRecording)try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info(`Taking full snapshot for SPA navigation to: ${S}`),this._rrweb.record.takeFullSnapshot()):this.logger.warn("rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("Failed to take full snapshot for SPA navigation:",S)}}_scheduleBackupSnapshot(){this._backupSnapshotTimer&&clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=setTimeout(()=>{if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] Chunk 0 already acked, skipping backup snapshot");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (2s safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}},2e3)}_takeBackupSnapshot(){if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] First snapshot ACKed - skipping backup");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}}_cleanupSPANavigationDetection(){"undefined"!=typeof window&&"undefined"!=typeof history&&(this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null),this._popstateHandler&&(window.removeEventListener("popstate",this._popstateHandler),this._popstateHandler=null),this._hashchangeHandler&&(window.removeEventListener("hashchange",this._hashchangeHandler),this._hashchangeHandler=null),this._lastKnownUrl=null,this.logger.info("SPA navigation detection disabled"))}_onInactivityPause(S){this.logger.info("[Inactivity] Recording paused")}_onInactivityResume(S){this.logger.info("[Inactivity] Recording resumed")}_onInactivitySessionEnd(S){this.endSession(S.reason)}_onChunkCreated(S,b){const I=this.memoryManager.trackBytes(S.sizeBytes||0);if(this.memoryManager.trimChunksArray(),this.memoryManager.trimEventsArray(1e3),I)if(this.memoryManager.checkEventLimit(this.events.length)){if(this._updateSessionChunkSequence(b),this.__streamStore)try{this.__streamStore.saveChunk(this.sessionId,b,S.events),this.__streamStore.updateSessionInfo(this.sessionId,b+1,this.events.length)}catch(S){}this.config.onChunk&&this.config.onChunk(S)}else this.endSession("max_events");else this.endSession("max_size")}endSession(S="manual"){this.logger.info(`[Session] Ending session: ${this.sessionId} (reason: ${S})`),this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.config.onSessionEnd&&this.config.onSessionEnd({sessionId:this.sessionId,reason:S,duration:Date.now()-this.sessionStartTime,totalEvents:this.events.length,totalPausedTime:this.inactivityManager.totalPausedTime})}_getSessionResumeInfo(){return this.sdkContext?.sessionManager?this.sdkContext.sessionManager.getResumeInfo():this.config.sessionManager?this.config.sessionManager.getResumeInfo():{isResumed:!1,sessionId:null,lastChunkSequence:0}}_updateSessionChunkSequence(S){this.sdkContext?.sessionManager?this.sdkContext.sessionManager.updateLastChunkSequence(S):this.config.sessionManager&&this.config.sessionManager.updateLastChunkSequence(S)}setUploadQueue(S){this._uploadQueue=S}_sendChunkWithBeacon(S,b){if(this._uploadQueue?.sendFinalChunkWithBeacon){if(this._uploadQueue.sendFinalChunkWithBeacon(S,b))return void this.logger.info(`[P0] Chunk ${S.sequence} sent via UploadQueue.sendFinalChunkWithBeacon`)}const I=this.sdkContext?.getChunkEndpoint?.()||(this.config.serverUrl?`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`:null);if(!I)return void(this.config.onChunk&&this.config.onChunk(S));const x={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],metadata:{...S.metadata,sentVia:"sendBeacon",closeTrigger:b},sizeBytes:S.sizeBytes},R=JSON.stringify(x);if("undefined"!=typeof navigator&&navigator.sendBeacon)try{const b=new Blob([R],{type:"application/json"});navigator.sendBeacon(I,b)?this.logger.info(`[P0] Chunk ${S.sequence} sent via sendBeacon`):this.config.onChunk&&this.config.onChunk(S)}catch(b){this.config.onChunk&&this.config.onChunk(S)}else this.config.onChunk&&this.config.onChunk(S)}async sendChunkToServer(S){try{const b={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],networkFullData:S._networkFullData||[],metadata:S.metadata,sizeBytes:S.sizeBytes},I=this.sdkContext?.getChunkEndpoint?.()||`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`,x=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!x.ok)throw new Error(`Server responded with ${x.status}`);return await x.json()}catch(S){throw this.logger.warn("Failed to send chunk to server:",S),S}}_startStatusTimer(){this.statusTimer&&clearInterval(this.statusTimer),setTimeout(()=>this.logStatus(),1e3),this.statusTimer=setInterval(()=>{this.logStatus()},this.statusInterval),this.config.debug&&(this.aggregationTimer&&clearInterval(this.aggregationTimer),this.aggregationTimer=setInterval(()=>{this._maybeLogAggregationExport()},this.aggregationInterval))}_stopStatusTimer(){this.statusTimer&&(clearInterval(this.statusTimer),this.statusTimer=null),this.aggregationTimer&&(clearInterval(this.aggregationTimer),this.aggregationTimer=null),this.lastAggregationThresholdSec=0}logStatus(){if(!this.isRecording)return;const S=this.chunkManager.getStats(),b=Date.now()-this.recordingStartTime,I=Math.floor(b/1e3),x=Math.floor(I/60),R=I%60,fmtSize=S=>S>=1048576?`${(S/1048576).toFixed(1)}MB`:`${Math.round(S/1024)}KB`;this.logger.info(`📊 Session Status [${x}m ${R}s]:`,{totalEvents:this.events.length,totalSize:fmtSize(S.totalSize),currentChunk:`${S.currentChunkEvents} events (${fmtSize(S.currentChunkSize)})`,completedChunks:S.totalChunks})}_maybeLogAggregationExport(){if(!this.isRecording||!this.recordingStartTime)return;const S=Date.now()-this.recordingStartTime,b=Math.floor(S/this.aggregationInterval)*(this.aggregationInterval/1e3);if(b>0&&b!==this.lastAggregationThresholdSec){this.lastAggregationThresholdSec=b;try{const S=this.buildReplayExport();this.logger.info(`🧩 Session export (${b}s):`,S)}catch(S){this.logger.warn("Failed to export session data:",S)}}}getStatus(){return{isRecording:this.isRecording,eventCount:this.events.length,duration:this.isRecording?Date.now()-this.recordingStartTime:0}}getSessionId(){return this.sessionId||(this.sessionId=generateSessionId()),this.sessionId}getEvents(){return[...this.events]}getChunks(){return this.chunkManager.getChunks()}getMetadata(){return{...this.metadata,sessionId:this.sessionId,startTime:this.recordingStartTime,isRecording:this.isRecording,eventCount:this.events.length}}getConfig(){return{...this.config}}getMemoryStats(){return this.memoryManager.getStats()}getOptimizationStats(){return this.eventOptimizer.getOptimizationStats()}setMetadata(S){this.metadata={...this.metadata,...S}}updateConfig(S){this.config={...this.config,...S},void 0!==S.debug&&this.logger.updateDebugMode(S.debug),this.inactivityManager.updateConfig(S),this.eventOptimizer.updateConfig(S),this.chunkManager.updateConfig(S),this.memoryManager.updateConfig(S),this.checkpointManager.updateConfig(S)}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode(S)}clear(){this.events=[],this.logger.info("Events cleared")}pause(){this.isRecording?this.stopFn&&(this.stopFn(),this.stopFn=null,this.isRecording=!1,this.logger.info("Recording paused")):this.logger.warn("No recording to pause")}resume(){this.isRecording?this.logger.warn("Recording already active"):(this.start(),this.logger.info("Recording resumed"))}takeCheckpoint(){this.checkpointManager.takeManualCheckpoint()}flushChunk(){return this.chunkManager.flush()}exportEvents(){return JSON.stringify({sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:this.events,metadata:this.metadata},null,2)}exportChunkedData(S="json"){const b=this.chunkManager.getChunks(),I={sessionId:this.getSessionId(),startTime:this.recordingStartTime,chunks:b,totalChunks:b.length,totalEvents:this.events.length,metadata:this.metadata};return"json"===S?JSON.stringify(I,null,2):I}buildReplayExport(){const S=this.chunkManager.getChunks().map(S=>{if(S?.compressed)try{return this.decompressChunk(S)}catch(b){return S}return S}),b=[];for(const I of S)I?.events&&Array.isArray(I.events)&&b.push(...I.events);return{sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:b,chunks:S,totalChunks:S.length,totalEvents:b.length,metadata:this.metadata}}compressChunkSync(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}async compressChunk(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}decompressChunk(S){if(!S.compressed)return S;try{const b=S.compressedData||S.data,I=new Uint8Array(b);if("fflate"===S.compressionType){const S=strFromU8(unzlibSync(I));return JSON.parse(S)}return S}catch(b){return this.logger.error("Failed to decompress chunk:",b),S}}generateSessionId(){return generateSessionId()}getEventTypeName(S){return this.eventOptimizer.getEventTypeName(S)}analyzeLargestEvents(S=5){if(!this.events||0===this.events.length)return void this.logger.info("No events to analyze");const b=this.events.map((S,b)=>({index:b,type:S.type,size:this.chunkManager.estimateSize([S]),timestamp:S.timestamp}));b.sort((S,b)=>b.size-S.size),this.logger.info(`🔍 Top ${S} Largest Events:`),b.slice(0,S).forEach((S,b)=>{this.logger.info(`${b+1}. Event #${S.index}: ${S.type} - ${Math.round(S.size/1024)}KB`)})}logOptimizationReport(){this.eventOptimizer.logOptimizationReport()}static getPresetConfig(S){return{minimal:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:18e4,checkoutEveryNth:300,chunkDuration:9e4,maxChunkSize:2e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.3,scrollSampling:.5,debug:!1},production:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:45e3,maxChunkSize:3e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.7,scrollSampling:.8,debug:!1},standard:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:6e4,maxChunkSize:35e4,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.5,scrollSampling:.7,debug:!1},detailed:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0},checkoutEveryNms:6e4,checkoutEveryNth:100,chunkDuration:3e4,maxChunkSize:5e5,enableSampling:!1,enableDeduplication:!1,debug:!1},full:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!0,collectFonts:!0,slimDOMOptions:!1,checkoutEveryNms:3e4,checkoutEveryNth:50,chunkDuration:15e3,maxChunkSize:1e6,enableSampling:!1,enableDeduplication:!1,debug:!1}}[S]||{}}}const Ic={MINIMAL:"minimal",STANDARD:"standard",DETAILED:"detailed",FULL:"full"},Ec="pending_chunks";class IndexedDBQueue{constructor(S={}){if(this.db=null,this.isSupported="undefined"!=typeof indexedDB,this.initFailed=!1,this.maxItems=S.maxItems||100,this.onError=S.onError||(()=>{}),"undefined"!=typeof window&&!0===window.__TRACESCOUT_FORCE_DISABLE_INDEXEDDB)return console.warn("[IndexedDBQueue] Disabled via FORCE_DISABLE_INDEXEDDB flag"),this.isSupported=!1,void(this.initFailed=!0);this.isSupported&&this._initDB()}async _initDB(){if(this.isSupported)return new Promise((S,b)=>{const I=indexedDB.open("tracescout_queue",1);I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to open database:",b.target.error),this.isSupported=!1,this.initFailed=!0,S(null)},I.onsuccess=b=>{this.db=b.target.result,S(this.db)},I.onupgradeneeded=S=>{const b=S.target.result;if(!b.objectStoreNames.contains(Ec)){const S=b.createObjectStore(Ec,{keyPath:"id"});S.createIndex("sessionId","sessionId",{unique:!1}),S.createIndex("createdAt","createdAt",{unique:!1}),S.createIndex("priority","priority",{unique:!1})}}})}async _ensureDB(){if(!this.isSupported)return!1;if(!this.db)try{await this._initDB()}catch(S){return!1}return!!this.db}async enqueue(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([Ec],"readwrite"),x=I.objectStore(Ec),R={id:S.id||`queue_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:S.chunk?.sessionId||S.sessionId,chunk:S.chunk,priority:S.priority||"normal",attempts:S.attempts||0,createdAt:S.createdAt||Date.now(),lastAttempt:S.lastAttempt||null,error:S.error||null},A=x.add(R);A.onsuccess=()=>{b(!0)},A.onerror=S=>{if("ConstraintError"===S.target.error?.name){const S=x.put(R);S.onsuccess=()=>b(!0),S.onerror=()=>b(!1)}else console.warn("[IndexedDBQueue] Failed to enqueue:",S.target.error),b(!1)},I.oncomplete=async()=>{await this._enforceLimit()}}catch(S){console.warn("[IndexedDBQueue] Enqueue error:",S),b(!1)}})}async getAll(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([Ec],"readonly"),I=b.objectStore(Ec).getAll();I.onsuccess=b=>{const I=b.target.result||[],x={high:3,normal:2,low:1};I.sort((S,b)=>{const I=x[S.priority]||2,R=x[b.priority]||2;return I!==R?R-I:S.createdAt-b.createdAt}),S(I)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to get items:",b.target.error),S([])}}catch(b){console.warn("[IndexedDBQueue] GetAll error:",b),S([])}}):[]}async getBySession(S){return await this._ensureDB()?new Promise(b=>{try{const I=this.db.transaction([Ec],"readonly").objectStore(Ec),x=I.index("sessionId").getAll(S);x.onsuccess=S=>{b(S.target.result||[])},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to get by session:",S.target.error),b([])}}catch(S){console.warn("[IndexedDBQueue] GetBySession error:",S),b([])}}):[]}async remove(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([Ec],"readwrite"),x=I.objectStore(Ec).delete(S);x.onsuccess=()=>{b(!0)},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to remove:",S.target.error),b(!1)}}catch(S){console.warn("[IndexedDBQueue] Remove error:",S),b(!1)}})}async removeMany(S){if(!await this._ensureDB()||!S||0===S.length)return 0;let b=0;for(const I of S)await this.remove(I)&&b++;return b}async update(S,b){return!!await this._ensureDB()&&new Promise(I=>{try{const x=this.db.transaction([Ec],"readwrite").objectStore(Ec),R=x.get(S);R.onsuccess=S=>{const R=S.target.result;if(!R)return void I(!1);const A={...R,...b},_=x.put(A);_.onsuccess=()=>I(!0),_.onerror=()=>I(!1)},R.onerror=()=>I(!1)}catch(S){console.warn("[IndexedDBQueue] Update error:",S),I(!1)}})}async clear(){return!!await this._ensureDB()&&new Promise(S=>{try{const b=this.db.transaction([Ec],"readwrite"),I=b.objectStore(Ec).clear();I.onsuccess=()=>{S(!0)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to clear:",b.target.error),S(!1)}}catch(b){console.warn("[IndexedDBQueue] Clear error:",b),S(!1)}})}async count(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([Ec],"readonly"),I=b.objectStore(Ec).count();I.onsuccess=b=>{S(b.target.result)},I.onerror=()=>S(0)}catch(b){S(0)}}):0}async _enforceLimit(){const S=await this.count();if(S<=this.maxItems)return;const b=await this.getAll(),I=S-this.maxItems,x=[...b].sort((S,b)=>{const I={high:3,normal:2,low:1},x=I[S.priority]||2,R=I[b.priority]||2;return x!==R?x-R:S.createdAt-b.createdAt}),R=x.slice(0,I).map(S=>S.id);await this.removeMany(R),console.log(`[IndexedDBQueue] Removed ${R.length} old items to enforce limit of ${this.maxItems}`)}isAvailable(){return this.isSupported&&null!==this.db}didInitFail(){return!0===this.initFailed}close(){this.db&&(this.db.close(),this.db=null)}}class CircuitBreaker{constructor(S={}){this.threshold=S.threshold||5,this.resetTimeout=S.resetTimeout||6e4,this.halfOpenMaxAttempts=S.halfOpenMaxAttempts||1,this.failures=0,this.lastFailure=null,this.state="closed",this.halfOpenAttempts=0,this.logger=S.logger||console}canMakeRequest(){if("closed"===this.state)return!0;if("open"===this.state){return Date.now()-this.lastFailure>=this.resetTimeout&&(this.state="half-open",this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Transitioning to half-open state"),!0)}return"half-open"!==this.state||this.halfOpenAttempts<this.halfOpenMaxAttempts}recordSuccess(){"half-open"===this.state?(this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Circuit closed after successful request")):"closed"===this.state&&(this.failures=0)}recordFailure(){this.failures++,this.lastFailure=Date.now(),"half-open"===this.state?(this.state="open",this.halfOpenAttempts=0,this.logger.warn?.("[CircuitBreaker] Circuit reopened after failed test request")):"closed"===this.state&&this.failures>=this.threshold&&(this.state="open",this.logger.error?.(`[CircuitBreaker] Circuit OPENED after ${this.failures} consecutive failures`),this.logger.error?.(`[CircuitBreaker] Will retry after ${this.resetTimeout/1e3}s cooldown`))}recordHalfOpenAttempt(){"half-open"===this.state&&this.halfOpenAttempts++}getStatus(){return{state:this.state,failures:this.failures,lastFailure:this.lastFailure,threshold:this.threshold,resetTimeout:this.resetTimeout,timeUntilReset:"open"===this.state&&this.lastFailure?Math.max(0,this.resetTimeout-(Date.now()-this.lastFailure)):null,halfOpenAttempts:this.halfOpenAttempts,halfOpenMaxAttempts:this.halfOpenMaxAttempts}}reset(){this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Manually reset to closed state")}forceOpen(){this.state="open",this.lastFailure=Date.now(),this.logger.warn?.("[CircuitBreaker] Manually forced to open state")}updateConfig(S){void 0!==S.threshold&&(this.threshold=S.threshold),void 0!==S.resetTimeout&&(this.resetTimeout=S.resetTimeout),void 0!==S.halfOpenMaxAttempts&&(this.halfOpenMaxAttempts=S.halfOpenMaxAttempts)}destroy(){this.logger=null}}class NetworkMonitor{constructor(S={}){this.checkInterval=S.checkInterval||3e4,this.isOnline="undefined"==typeof navigator||navigator.onLine,this.onStatusChange=S.onStatusChange||(()=>{}),this.logger=S.logger||console,this.checkTimer=null,this._boundOnline=null,this._boundOffline=null}start(){"undefined"!=typeof window&&(this._boundOnline=()=>this._handleStatusChange(!0),this._boundOffline=()=>this._handleStatusChange(!1),window.addEventListener("online",this._boundOnline),window.addEventListener("offline",this._boundOffline),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval),this.logger.log?.("[NetworkMonitor] Started monitoring"))}stop(){"undefined"!=typeof window&&(this._boundOnline&&window.removeEventListener("online",this._boundOnline),this._boundOffline&&window.removeEventListener("offline",this._boundOffline)),this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=null),this._boundOnline=null,this._boundOffline=null,this.logger.log?.("[NetworkMonitor] Stopped monitoring")}_handleStatusChange(S){const b=this.isOnline;this.isOnline=S,b!==S&&(this.logger.log?.("[NetworkMonitor] Status changed: "+(S?"online":"offline")),this.onStatusChange(S,b))}checkStatus(){if("undefined"==typeof navigator)return;const S=navigator.onLine;this.isOnline!==S&&this._handleStatusChange(S)}getStatus(){return this.isOnline}updateConfig(S){void 0!==S.checkInterval&&(this.checkInterval=S.checkInterval,this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval)))}destroy(){this.stop(),this.onStatusChange=null,this.logger=null}}class BeaconSender{constructor(S={}){this.endpoint=S.endpoint||"/api/sessions/upload",this.maxBeaconSize=S.maxBeaconSize||6e4,this.sdkContext=S.sdkContext||null,this.logger=S.logger||console}setEndpoint(S){this.endpoint=S}setSdkContext(S){this.sdkContext=S}send(S,b="unknown"){if(!S||!S.events||0===S.events.length)return this.logger.log?.("[BeaconSender] No events to send"),!1;const I=this._buildPayload(S,b),x=JSON.stringify(I),R=x.length;return R>this.maxBeaconSize?(this.logger.warn?.(`[BeaconSender] Payload too large (${R} bytes), using keepalive fetch`),this._sendWithKeepaliveFetch(x,b)):this._sendWithBeacon(x,b,R)||this._sendWithKeepaliveFetch(x,b)}_buildPayload(S,b){return{chunks:[{id:`final_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunkId:S.chunkId||`chunk_${S.sequence}`,sessionId:S.sessionId,data:S,compressed:!1,originalSize:this._estimateSize(S),projectId:S.metadata?.projectId||this.sdkContext?.projectId,environment:S.metadata?.environment||this.sdkContext?.environment}],batchId:`beacon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:1,sentVia:"sendBeacon",closeTrigger:b}}_sendWithBeacon(S,b,I){if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;try{const x=new Blob([S],{type:"application/json"});return navigator.sendBeacon(this.endpoint,x)?(this.logger.log?.(`[BeaconSender] ✅ Sent via sendBeacon (${b}, ${I} bytes)`),!0):(this.logger.warn?.("[BeaconSender] sendBeacon returned false"),!1)}catch(S){return this.logger.warn?.(`[BeaconSender] sendBeacon failed: ${S.message}`),!1}}_sendWithKeepaliveFetch(S,b){if("undefined"==typeof fetch)return this.logger.warn?.("[BeaconSender] fetch not available"),!1;try{const I={"Content-Type":"application/json","X-SDK-Version":"2.0.0","X-Sent-Via":"keepalive","X-Close-Trigger":b};return this.sdkContext&&(I["X-Project-ID"]=this.sdkContext.projectId||""),fetch(this.endpoint,{method:"POST",headers:I,body:S,keepalive:!0}).catch(S=>{this.logger.warn?.("[BeaconSender] keepalive fetch error:",S)}),this.logger.log?.(`[BeaconSender] ✅ Sent via keepalive fetch (${b})`),!0}catch(S){return this.logger.warn?.(`[BeaconSender] keepalive fetch failed: ${S.message}`),!1}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}updateConfig(S){void 0!==S.endpoint&&(this.endpoint=S.endpoint),void 0!==S.maxBeaconSize&&(this.maxBeaconSize=S.maxBeaconSize)}destroy(){this.sdkContext=null,this.logger=null}}class QueueMemoryManager{constructor(S={}){this.maxQueueSize=S.maxQueueSize||100,this.maxFailedQueueSize=S.maxFailedQueueSize||50,this.maxOfflineItems=S.maxOfflineItems||100,this.logger=S.logger||console}enforceLimit(S,b=this.maxQueueSize){if(S.length<b)return null;const I=S.findIndex(S=>"low"===S.priority);if(I>=0){const x=S.splice(I,1)[0];return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped low-priority chunk:`,x.chunk?.chunkId),x}const x=S.shift();return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped oldest chunk:`,x?.chunk?.chunkId),x}enforceFailedLimit(S){if(S.length<this.maxFailedQueueSize)return null;const b=S.shift();return this.logger.warn?.(`[QueueMemory] Failed queue at max (${this.maxFailedQueueSize}) - dropped oldest:`,b?.chunk?.chunkId),b}enforceOfflineLimit(S){if(S.length<=this.maxOfflineItems)return null;const b=S.pop();return this.logger.warn?.("[QueueMemory] Offline queue full - dropped oldest:",b?.chunk?.chunkId),b}calculateQueueBytes(S){return S.reduce((S,b)=>S+(b.originalSize||0),0)}getStats(S,b){const I=this.calculateQueueBytes(S),x=this.calculateQueueBytes(b);return{uploadQueueSize:S.length,uploadQueueBytes:I,failedQueueSize:b.length,failedQueueBytes:x,totalQueuedItems:S.length+b.length,totalQueuedBytes:I+x,maxQueueSize:this.maxQueueSize,maxFailedQueueSize:this.maxFailedQueueSize,maxOfflineItems:this.maxOfflineItems,uploadQueuePercent:Math.round(S.length/this.maxQueueSize*100),failedQueuePercent:Math.round(b.length/this.maxFailedQueueSize*100)}}forceCleanup(S,b,I={}){const{keepUploads:x=10,keepFailed:R=5,clearAll:A=!1}=I,_={uploadQueue:S.length,failedQueue:b.length};let D=0,L=0;A?(D=S.length,L=b.length,S.length=0,b.length=0):(S.length>x&&(D=S.length-x,S.splice(0,D)),b.length>R&&(L=b.length-R,b.splice(0,L)));const B={uploadQueue:S.length,failedQueue:b.length};return this.logger.log?.(`[QueueMemory] Force cleanup: removed ${D} uploads, ${L} failed items`),{before:_,after:B,removed:{uploadQueue:D,failedQueue:L}}}needsCleanup(S,b){const I=S.length/this.maxQueueSize,x=b.length/this.maxFailedQueueSize;return I>=.8||x>=.8}updateConfig(S){void 0!==S.maxQueueSize&&(this.maxQueueSize=S.maxQueueSize),void 0!==S.maxFailedQueueSize&&(this.maxFailedQueueSize=S.maxFailedQueueSize),void 0!==S.maxOfflineItems&&(this.maxOfflineItems=S.maxOfflineItems)}destroy(){this.logger=null}}class UploadQueue{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[UploadQueue] No SDKContext provided - running in v1.x compatibility mode");const b=this._generateEndpoint(S);this.config={endpoint:S.endpoint||b,batchSize:S.batchSize||5,maxRetries:S.maxRetries||3,retryDelay:S.retryDelay||1e3,maxRetryDelay:S.maxRetryDelay||3e4,uploadTimeout:S.uploadTimeout||3e4,enableOfflineQueue:!1!==S.enableOfflineQueue,maxOfflineItems:S.maxOfflineItems||100,networkCheckInterval:S.networkCheckInterval||3e4,enableCompression:!1!==S.enableCompression,compressionThreshold:S.compressionThreshold||1024,onUploadSuccess:S.onUploadSuccess||(()=>{}),onUploadError:S.onUploadError||(()=>{}),onNetworkChange:S.onNetworkChange||(()=>{}),onQueueEmpty:S.onQueueEmpty||(()=>{}),headers:S.headers||{},authToken:S.authToken||null,...S},this.uploadQueue=[],this.failedQueue=[],this.isUploading=!1,this._uploadLock=null,this.isQuotaExceeded=!1,this.uploadStats={totalUploaded:0,totalFailed:0,totalBytes:0,averageUploadTime:0,lastUploadTime:null},this.firstSnapshotAcked=!1,this.firstSnapshotChunkId=null,this.firstSnapshotAttempts=0,this._backupSnapshotRequested=!1,this._listeners=new Map,this.retryTimer=null,this._processingTimer=null,this.logger=S.logger||createLogger("UploadQueue"),this._initializeModules(S),this._startProcessing(),this._loadPersistentQueue()}on(S,b){this._listeners.has(S)||this._listeners.set(S,[]),this._listeners.get(S).push(b)}emit(S,...b){const I=this._listeners.get(S);if(I)for(const x of I)try{x(...b)}catch(b){this.logger.warn(`[UploadQueue] Event listener error for '${S}':`,b)}}_generateEndpoint(S){if(this.sdkContext){const b="undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname);return`${S.baseUrl||(b?"http://localhost:3001":"https://api.tracescout.com")}/api/projects/${this.sdkContext.projectId}/sessions/${this.sdkContext.sessionId}/chunks`}return"/api/sessions/upload"}_initializeModules(S){this.circuitBreaker=new CircuitBreaker({threshold:S.circuitBreakerThreshold||5,resetTimeout:S.circuitBreakerResetTimeout||6e4,halfOpenMaxAttempts:S.halfOpenMaxAttempts||1,logger:this.logger}),this.networkMonitor=new NetworkMonitor({checkInterval:this.config.networkCheckInterval,logger:this.logger,onStatusChange:(S,b)=>this._handleNetworkChange(S,b)}),this.networkMonitor.start(),this.beaconSender=new BeaconSender({endpoint:this.config.endpoint,sdkContext:this.sdkContext,logger:this.logger}),this.memoryManager=new QueueMemoryManager({maxQueueSize:S.maxQueueSize||100,maxFailedQueueSize:S.maxFailedQueueSize||50,maxOfflineItems:S.maxOfflineItems||100,logger:this.logger}),this.persistentQueue=new IndexedDBQueue({maxItems:this.config.maxOfflineItems,onError:S=>{this.logger.warn("[UploadQueue] IndexedDB error:",S)}})}async _loadPersistentQueue(){try{const S=await this.persistentQueue.getAll();if(S.length>0){this.logger.log(`[UploadQueue] Recovered ${S.length} items from persistent storage`);for(const b of S)this.uploadQueue.push(b);this._sortQueue(),this.networkMonitor.getStatus()&&!this.isUploading&&this._processQueue()}}catch(S){this.logger.warn("[UploadQueue] Failed to load persistent queue:",S)}}enqueue(S,b="normal"){if(this.isQuotaExceeded)return this.logger.warn("[UploadQueue] Quota exceeded - dropping chunk:",S.chunkId),!1;this.memoryManager.enforceLimit(this.uploadQueue);const I=this._validateChunk(S);if(!I.valid)return this.logger.error(`[UploadQueue] Invalid chunk rejected: ${I.reason}`,S),!1;try{const I=0===S.sequence||!0===S.isFirstChunk;I&&!this.firstSnapshotAcked&&(b="high",this.logger.log("[UploadQueue] Chunk 0 prioritized for immediate upload (contains FullSnapshot)"));const x={id:`upload_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunk:S,priority:b,attempts:0,createdAt:Date.now(),lastAttempt:null,error:null,compressed:!1,originalSize:this._estimateSize(S),compressedSize:null,isFirstChunk:I};if(I&&!this.firstSnapshotChunkId&&(this.firstSnapshotChunkId=x.id),this.networkMonitor.getStatus())this.uploadQueue.push(x),this._sortQueue();else{if(!this.config.enableOfflineQueue)return this.logger.warn("Network offline and offline queue disabled, dropping chunk:",S.chunkId),!1;this._addToOfflineQueue(x)}return this.logger.log(`Chunk queued for upload: ${S.chunkId} (queue size: ${this.uploadQueue.length})`),I&&this.networkMonitor.getStatus()&&!this.isUploading?(this.logger.log("[UploadQueue] Triggering immediate upload for chunk 0"),this._processQueue()):this.isUploading||this._processQueue(),x.id}catch(S){return this.logger.error("Failed to enqueue chunk:",S),!1}}async _processQueue(){if(!this.circuitBreaker.canMakeRequest())return void this.logger.warn("[UploadQueue] Circuit breaker is open - request blocked");if(this.isUploading||!this.networkMonitor.getStatus()||0===this.uploadQueue.length)return;if(this._uploadLock)return;let S;this._uploadLock=new Promise(b=>{S=b}),this.isUploading=!0,this.logger.log(`Processing upload queue (${this.uploadQueue.length} items)`);try{for(;this.uploadQueue.length>0&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest();){const S=this._createBatch();if(0===S.length)break;if(await this._uploadBatch(S))this.circuitBreaker.recordSuccess();else if(this.circuitBreaker.recordFailure(),"open"===this.circuitBreaker.getStatus().state){this.logger.warn("[UploadQueue] Circuit breaker opened - pausing uploads");break}await this._delay(100)}0===this.uploadQueue.length&&0===this.failedQueue.length&&(this.config.onQueueEmpty(),this.logger.log("Upload queue is empty"))}catch(S){this.logger.error("Error processing upload queue:",S),this.circuitBreaker.recordFailure()}finally{this.isUploading=!1,this._uploadLock=null,S(),this.failedQueue.length>0&&this._scheduleRetry()}}_createBatch(){const S=[],b=Math.min(this.config.batchSize,this.uploadQueue.length);this._sortQueue();for(let I=0;I<b;I++)this.uploadQueue.length>0&&S.push(this.uploadQueue.shift());return S}async _uploadBatch(S){const b=Date.now();try{this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&S.forEach(S=>{S.chunk=this.sdkContext.enrichChunk(S.chunk)});const I={chunks:(await this._processBatch(S)).map(S=>({id:S.id,chunkId:S.chunk.chunkId,sessionId:S.chunk.sessionId,data:S.compressed?S.compressedData:S.chunk,compressed:S.compressed,originalSize:S.originalSize,compressedSize:S.compressedSize||S.originalSize,projectId:S.chunk.projectId,environment:S.chunk.environment})),batchId:`batch_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:S.length},x=await this._makeRequest(I);if(x.ok){const I=await x.json().catch(()=>({}));if(I.results){const S=I.results.find(S=>429===S.code||"QUOTA_EXCEEDED"===S.data?.code);if(S)return this._handleQuotaExceeded(S.data||S),!1}const R=Date.now()-b;this._updateStats(S,R,!0);for(const b of S)try{await this.persistentQueue.remove(b.id)}catch(S){}for(const b of S)(b.id===this.firstSnapshotChunkId||b.isFirstChunk)&&(this.firstSnapshotAcked=!0,this.logger.log("[UploadQueue] ✓ First snapshot (chunk 0) acknowledged by server - session is replayable"));return S.forEach(S=>{this.config.onUploadSuccess(S.chunk,I)}),this.logger.log(`Batch uploaded successfully: ${S.length} chunks in ${R}ms`),!0}if(429===x.status){const S=await x.json().catch(()=>({}));return this._handleQuotaExceeded(S),!1}throw new Error(`Upload failed with status: ${x.status}`)}catch(b){return this.logger.error("Batch upload failed:",b),S.forEach(S=>{S.attempts++,S.lastAttempt=Date.now(),S.error=b.message,(S.id===this.firstSnapshotChunkId||S.isFirstChunk)&&S.attempts>=3&&!this._backupSnapshotRequested&&(this._backupSnapshotRequested=!0,this.logger.warn("[UploadQueue] First snapshot failed 3+ times - requesting backup"),this.emit("firstSnapshotUploadFailed")),S.attempts<this.config.maxRetries?(this.memoryManager.enforceFailedLimit(this.failedQueue),this.failedQueue.push(S)):(this._updateStats([S],0,!1),this.config.onUploadError(S.chunk,b),this.logger.error(`Chunk permanently failed after ${S.attempts} attempts: ${S.chunk.chunkId}`))}),!1}}_handleQuotaExceeded(S){this.isQuotaExceeded=!0,this.uploadQueue=[],this.failedQueue=[],console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been stopped.","color: #ff4444;"),S.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions`,"color: #ff4444;"),this.config.onUploadError(null,{code:"QUOTA_EXCEEDED",message:S.message||"Session quota exceeded",usage:S.usage}),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:quota_exceeded",{detail:S}))}async _processBatch(S){const b=[];for(const I of S)try{if(this.config.enableCompression&&I.originalSize>this.config.compressionThreshold){const S=await this._compressChunk(I.chunk);S.compressed&&S.compressedSize<I.originalSize&&(I.compressed=!0,I.compressedData=S.data,I.compressedSize=S.compressedSize)}b.push(I)}catch(S){this.logger.warn("Failed to process chunk, using original:",S),b.push(I)}return b}async _makeRequest(S){const b=new AbortController,I=setTimeout(()=>b.abort(),this.config.uploadTimeout);try{const x={"Content-Type":"application/json",...this.config.headers};this.sdkContext&&(x["X-Project-ID"]=this.sdkContext.projectId,x["X-Environment"]=this.sdkContext.environment||"production",x["X-SDK-Version"]="2.0.0");const R=await fetch(this.config.endpoint,{method:"POST",headers:x,body:JSON.stringify(S),signal:b.signal});return clearTimeout(I),R}catch(S){throw clearTimeout(I),S}}async _compressChunk(S){if(!this.config.enableCompression)return this.logger.debug("[UploadQueue] Compression disabled via config"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"!=typeof window&&!0===window.__TRACESCOUT_DISABLE_COMPRESSION)return this.logger.debug("[UploadQueue] Compression disabled via __TRACESCOUT_DISABLE_COMPRESSION"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"==typeof window||"undefined"==typeof CompressionStream)return{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};try{const b=JSON.stringify(S),I=(new TextEncoder).encode(b).length,x=new Blob([b],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),R=await new Response(x).arrayBuffer(),A=new Uint8Array(R),_=this._uint8ArrayToBase64(A),D=(100*(1-A.length/I)).toFixed(0),L=JSON.stringify(Array.from(A)).length,B=_.length+2;return this.logger.debug(`[UploadQueue] Compressed chunk: original=${I}B, gzip=${A.length}B (${D}% saved), base64=${B}B vs array=${L}B`),{compressed:!0,data:_,originalSize:I,compressedSize:A.length}}catch(b){return this.logger.warn("[UploadQueue] Compression failed, using uncompressed:",b.message),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)}}}_uint8ArrayToBase64(S){if(S.length<32768){let b="";for(let I=0;I<S.length;I++)b+=String.fromCharCode(S[I]);return btoa(b)}let b="";for(let I=0;I<S.length;I+=32768){const x=S.subarray(I,Math.min(I+32768,S.length));for(let S=0;S<x.length;S++)b+=String.fromCharCode(x[S])}return btoa(b)}_handleNetworkChange(S,b){this.logger.log("Network status changed: "+(S?"online":"offline")),this.config.onNetworkChange(S,b),S&&!b&&(this._sortQueue(),this.isUploading||this._processQueue())}_sortQueue(){const S={high:3,normal:2,low:1};this.uploadQueue.sort((b,I)=>{const x=S[b.priority]||2,R=S[I.priority]||2;return x!==R?R-x:b.createdAt-I.createdAt})}async _addToOfflineQueue(S){this.uploadQueue.unshift(S);try{await this.persistentQueue.enqueue(S),this.logger.log(`[UploadQueue] Item persisted to IndexedDB: ${S.id}`)}catch(S){this.logger.warn("[UploadQueue] Failed to persist to IndexedDB:",S)}const b=this.memoryManager.enforceOfflineLimit(this.uploadQueue);if(b)try{await this.persistentQueue.remove(b.id)}catch(S){}}_scheduleRetry(){this.retryTimer&&clearTimeout(this.retryTimer);const S=this.circuitBreaker.getStatus();if("open"===S.state){const b=S.timeUntilReset;if(b>0)return this.logger.warn(`[UploadQueue] Delaying retry until circuit resets in ${Math.round(b/1e3)}s`),void(this.retryTimer=setTimeout(()=>{this._scheduleRetry()},b+1e3))}const b=this.config.retryDelay,I=this.config.maxRetryDelay,x=this.failedQueue[0]?.attempts||0,R=b*Math.pow(2,x),A=Math.min(R,I),_=.25*A,D=2*(Math.random()-.5)*_,L=Math.max(b,Math.round(A+D));this.retryTimer=setTimeout(()=>{this.logger.log(`Retrying ${this.failedQueue.length} failed items (attempt ${x+1})`),this.uploadQueue.unshift(...this.failedQueue),this.failedQueue=[],!this.isUploading&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest()&&this._processQueue()},L),this.logger.log(`[Retry] Scheduled in ${L}ms`)}_startProcessing(){this._processingTimer=setInterval(()=>{!this.isUploading&&this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()},5e3)}_updateStats(S,b,I){if(I){this.uploadStats.totalUploaded+=S.length,this.uploadStats.lastUploadTime=Date.now();const I=this.uploadStats.averageUploadTime,x=this.uploadStats.totalUploaded;this.uploadStats.averageUploadTime=(I*(x-S.length)+b)/x}else this.uploadStats.totalFailed+=S.length;S.forEach(S=>{this.uploadStats.totalBytes+=S.compressedSize||S.originalSize})}_validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};if(0===S.events.length&&!S.metadata?.isLastChunk)return{valid:!1,reason:"Empty events array (non-final chunk)"};if("number"!=typeof S.startTimestamp||"number"!=typeof S.endTimestamp)return{valid:!1,reason:"Invalid timestamps"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}_delay(S){return new Promise(b=>setTimeout(b,S))}getStats(){return{...this.uploadStats,queueSize:this.uploadQueue.length,failedQueueSize:this.failedQueue.length,isOnline:this.networkMonitor.getStatus(),isUploading:this.isUploading,isQuotaExceeded:this.isQuotaExceeded,circuitBreaker:this.circuitBreaker.getStatus()}}getCircuitBreakerStatus(){return this.circuitBreaker.getStatus()}resetCircuitBreaker(){this.circuitBreaker.reset()}isQuotaExceededStatus(){return this.isQuotaExceeded}isFirstSnapshotAcked(){return this.firstSnapshotAcked}didIndexedDBFail(){return!!this.persistentQueue&&this.persistentQueue.didInitFail()}getQueue(){return{pending:[...this.uploadQueue],failed:[...this.failedQueue]}}clearQueue(){const S=this.uploadQueue.length+this.failedQueue.length;return this.uploadQueue=[],this.failedQueue=[],this.logger.log(`Cleared ${S} items from queue`),S}pause(){this.isUploading=!0,this.logger.log("Upload queue paused")}resume(){this.isUploading=!1,this.logger.log("Upload queue resumed"),this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()}updateConfig(S){this.config={...this.config,...S},this.logger.log("Upload queue configuration updated")}getMemoryStats(){return this.memoryManager.getStats(this.uploadQueue,this.failedQueue)}forceMemoryCleanup(S={}){return this.memoryManager.forceCleanup(this.uploadQueue,this.failedQueue,S)}sendFinalChunkWithBeacon(S,b="unknown"){const I=this._validateChunk(S);return I.valid?this.beaconSender.send(S,b):(this.logger.warn(`[Beacon] Invalid final chunk: ${I.reason}`),!1)}async getPersistentQueueStats(){return{persistentQueueSize:await this.persistentQueue.count(),isIndexedDBAvailable:this.persistentQueue.isAvailable()}}destroy(){this.networkMonitor.destroy(),this.retryTimer&&clearTimeout(this.retryTimer),this._processingTimer&&clearInterval(this._processingTimer),this.persistentQueue&&this.persistentQueue.close(),this.circuitBreaker.destroy(),this.beaconSender.destroy(),this.memoryManager.destroy(),this.clearQueue(),this.logger.log("Upload queue destroyed")}}class ChunkedCompressedStorage{static CHUNK_SIZE=50;static CHUNK_PREFIX="rrweb_chunk_";static logger=createLogger("ChunkedCompressedStorage");static initSession(S){sessionStorage.setItem(`${S}_info`,JSON.stringify({startTime:Date.now(),chunkCount:0,totalEvents:0,isActive:!0}))}static updateSessionInfo(S,b,I){try{const x=JSON.parse(sessionStorage.getItem(`${S}_info`)||"{}");x.chunkCount=b,x.totalEvents=I,sessionStorage.setItem(`${S}_info`,JSON.stringify(x))}catch(S){this.logger.warn("Failed to update session info",S)}}static compress(S){const b=zlibSync(strToU8(JSON.stringify(S)),{level:6});return Array.from(b)}static decompress(S){const b=strFromU8(unzlibSync(new Uint8Array(S)));return JSON.parse(b)}static saveChunk(S,b,I){try{const x=this.compress({events:I}),R=`${S}_${this.CHUNK_PREFIX}${b}`;return sessionStorage.setItem(R,JSON.stringify(x)),!0}catch(S){return this.logger.error("saveChunk failed",S),!1}}static loadChunk(S,b){const I=`${S}_${this.CHUNK_PREFIX}${b}`,x=sessionStorage.getItem(I);if(!x)return null;try{const S=JSON.parse(x);return this.decompress(S).events||[]}catch(S){return this.logger.warn("loadChunk failed",S),null}}static getChunkCount(S){const b=sessionStorage.getItem(`${S}_info`);return b&&JSON.parse(b).chunkCount||0}static async streamChunks(S,b={}){const{onChunkLoad:I=()=>{},onProgress:x=()=>{},onComplete:R=()=>{},chunkDelay:A=50,startChunk:_=0}=b,D=this.getChunkCount(S);for(let b=_;b<D;b++){const R=this.loadChunk(S,b);R&&R.length&&I(R,b),x(b+1,D),b<D-1&&A>0&&await new Promise(S=>setTimeout(S,A))}R()}static clearSession(S){Object.keys(sessionStorage).forEach(b=>{b.startsWith(S)&&sessionStorage.removeItem(b)}),sessionStorage.removeItem(`${S}_info`)}}var xc=Object.freeze({__proto__:null,ChunkedCompressedStorage:ChunkedCompressedStorage});class SessionStorage{constructor(S={}){this.storageKey=S.storageKey||"__tracescout_sessions__",this.maxStorageSize=S.maxStorageSize||52428800,this.maxSessions=S.maxSessions||10,this.logger=S.logger||createLogger("SessionStorage")}storeChunk(S,b){try{const I=this.getSessions();return I[S]||(I[S]={chunks:[],metadata:{startTime:Date.now(),lastActivity:Date.now(),totalEvents:0,totalChunks:0}}),I[S].chunks.push(b),I[S].metadata.lastActivity=Date.now(),I[S].metadata.totalEvents+=b.eventCount,I[S].metadata.totalChunks+=1,this.calculateSize(I)>this.maxStorageSize&&this.cleanup(I),this.saveSessions(I),this.logger.log(`Stored chunk ${b.chunkId} for session ${S}`),!0}catch(S){return this.logger.error("Failed to store chunk:",S),!1}}getSessions(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.error("Failed to load sessions:",S),{}}}getSession(S){return this.getSessions()[S]||null}saveSessions(S){try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(b){if("QuotaExceededError"===b.name){this.logger.warn("Storage quota exceeded, performing emergency cleanup"),this.emergencyCleanup();try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(S){this.logger.error("Storage failed even after cleanup:",S)}}else this.logger.error("Failed to save sessions:",b)}}calculateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}cleanup(S){const b=Object.entries(S).sort(([,S],[,b])=>S.metadata.lastActivity-b.metadata.lastActivity);for(;this.calculateSize(S)>this.maxStorageSize&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed old session: ${I}`)}for(;Object.keys(S).length>this.maxSessions&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed session due to count limit: ${I}`)}}emergencyCleanup(){try{localStorage.removeItem(this.storageKey),this.logger.warn("Emergency cleanup: cleared all session storage")}catch(S){this.logger.error("Emergency cleanup failed:",S)}}removeSession(S){try{const b=this.getSessions();return!!b[S]&&(delete b[S],this.saveSessions(b),this.logger.log(`Removed session: ${S}`),!0)}catch(S){return this.logger.error("Failed to remove session:",S),!1}}getStorageStats(){try{const S=this.getSessions(),b=this.calculateSize(S),I=Object.keys(S).length;let x=0,R=0;return Object.values(S).forEach(S=>{x+=S.metadata.totalEvents,R+=S.metadata.totalChunks}),{totalSize:b,sessionCount:I,totalEvents:x,totalChunks:R,maxStorageSize:this.maxStorageSize,maxSessions:this.maxSessions,storageUsagePercent:Math.round(b/this.maxStorageSize*100)}}catch(S){return this.logger.error("Failed to get storage stats:",S),null}}exportSession(S,b="json"){try{const I=this.getSession(S);if(!I)return null;const x={sessionId:S,metadata:I.metadata,chunks:I.chunks,totalChunks:I.chunks.length,totalEvents:I.metadata.totalEvents,exportTimestamp:Date.now()};return"json"===b?JSON.stringify(x,null,2):x}catch(S){return this.logger.error("Failed to export session:",S),null}}importSession(S){try{const b="string"==typeof S?JSON.parse(S):S;if(!b.sessionId||!b.chunks)throw new Error("Invalid session data format");const I=this.getSessions();return I[b.sessionId]={chunks:b.chunks,metadata:b.metadata||{startTime:Date.now(),lastActivity:Date.now(),totalEvents:b.totalEvents||0,totalChunks:b.totalChunks||0}},this.saveSessions(I),this.logger.log(`Imported session: ${b.sessionId}`),!0}catch(S){return this.logger.error("Failed to import session:",S),!1}}clearAll(){try{return localStorage.removeItem(this.storageKey),this.logger.log("Cleared all sessions"),!0}catch(S){return this.logger.error("Failed to clear all sessions:",S),!1}}}var Mc=Object.freeze({__proto__:null,BeaconSender:BeaconSender,CHUNK_FORMAT_VERSION:4,CheckpointManager:CheckpointManager,ChunkManager:ChunkManager,ChunkedCompressedStorage:ChunkedCompressedStorage,CircuitBreaker:CircuitBreaker,EventOptimizer:EventOptimizer,InactivityManager:InactivityManager,IndexedDBQueue:IndexedDBQueue,NetworkMonitor:NetworkMonitor,PageLifecycleManager:PageLifecycleManager,QueueMemoryManager:QueueMemoryManager,Recorder:Recorder,RecorderMemoryManager:RecorderMemoryManager,RecorderPresets:Ic,SessionStorage:SessionStorage,UploadQueue:UploadQueue,analyzeSnapshotsInEvents:analyzeSnapshotsInEvents,buildSnapshotIndex:buildSnapshotIndex,chunkHasSnapshot:chunkHasSnapshot,collectDeviceMetadata:collectDeviceMetadata,createChunk:createChunk,detectDeviceType:detectDeviceType,detectTouchCapability:detectTouchCapability,extractConsoleRef:extractConsoleRef,extractNetworkFull:extractNetworkFull,extractNetworkRef:extractNetworkRef,extractResourceRef:extractResourceRef,findNearestSnapshotBefore:findNearestSnapshotBefore,generateConsoleId:generateConsoleId,generateNetworkId:generateNetworkId,generateResourceId:generateResourceId,getConnectionInfo:getConnectionInfo,getEventsAfterSnapshot:getEventsAfterSnapshot,getMemoryInfo:getMemoryInfo,getRRWeb:getRRWeb,getRRWebSource:getRRWebSource,getRecord:getRecord,getSnapshotTimestamps:getSnapshotTimestamps,hashCode:hashCode,isCompatibleVersion:isCompatibleVersion,isRRWebLoaded:isRRWebLoaded,loadRRWeb:loadRRWeb,parseBrowserInfo:parseBrowserInfo,parseOSInfo:parseOSInfo,sanitizeUrl:sanitizeUrl,stripNetworkPayload:stripNetworkPayload});"undefined"!=typeof window&&(window.TraceScout=Ve,Ve.setTransport=TraceScoutMonitoringCore.setTransport.bind(TraceScoutMonitoringCore)),S.BODY_REDACTED_VALUE=Ne,S.BaseInterceptor=BaseInterceptor,S.BeaconSender=BeaconSender,S.CHUNK_FORMAT_VERSION=4,S.CORE_WEB_VITALS_DEFAULTS={THRESHOLDS:{lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3}},COLLECT_METRICS:{lcp:!0,fid:!0,cls:!0,inp:!0,ttfb:!0,fcp:!0},USE_WEB_VITALS_LIBRARY:!0,REPORTING_ENABLED:!0,REPORT_THRESHOLD:"needsImprovement"},S.CheckpointManager=CheckpointManager,S.ChunkManager=ChunkManager,S.ChunkedCompressedStorage=ChunkedCompressedStorage,S.CircuitBreaker=CircuitBreaker,S.ConfigManager=ConfigManager,S.ConsoleInterceptor=ConsoleInterceptor,S.CoreWebVitalsMonitor=CoreWebVitalsMonitor,S.DEFAULT_CONFIG=A,S.DEFAULT_FIELD_PATTERNS={EMAIL_REGEX:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,PHONE_REGEX:/^[\+]?[1-9][\d]{0,15}$/,UUID_REGEX:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i},S.DEFAULT_MAX_BODY_BYTES=Le,S.DEFAULT_MAX_BODY_SIZE=Fe,S.DEFAULT_SENSITIVE_FIELDS=Be,S.EVENT_TYPES={FETCH_HTTP_ERROR:"fetch_http_error",FETCH_NETWORK_ERROR:"fetch_network_error",FETCH_SILENT_LOGIN_FAILURE:"fetch_silent_login_failure",XHR_HTTP_ERROR:"xhr_http_error",XHR_NETWORK_ERROR:"xhr_network_error",XHR_TIMEOUT_ERROR:"xhr_timeout_error",XHR_ABORTED_ERROR:"xhr_aborted_error",XHR_SILENT_LOGIN_FAILURE:"xhr_silent_login_failure",RESOURCE_LOAD_ERROR:"resource_load_error",CUSTOM_API_ERROR:"custom_api_error",UNKNOWN_ERROR:"unknown_error",POSTMESSAGE_COMMUNICATION:"postmessage_communication",POSTMESSAGE_CROSS_ORIGIN:"postmessage_cross_origin",POSTMESSAGE_LARGE_PAYLOAD:"postmessage_large_payload",POSTMESSAGE_SUSPICIOUS_ORIGIN:"postmessage_suspicious_origin",POSTMESSAGE_ERROR:"postmessage_error",FETCH_SLOW_REQUEST:"fetch_slow_request",XHR_SLOW_REQUEST:"xhr_slow_request",PERFORMANCE_DEGRADATION_ALERT:"performance_degradation_alert",P1_INCIDENT_EVENT:"p1_incident_event",CORE_WEB_VITAL:"core_web_vital"},S.ErrorFingerprint=ErrorFingerprint,S.ErrorHandler=ErrorHandler,S.EventManager=EventManager,S.EventOptimizer=EventOptimizer,S.FetchInterceptor=FetchInterceptor,S.InactivityManager=InactivityManager,S.IndexedDBQueue=IndexedDBQueue,S.LOCAL_STORAGE_KEYS={EVENTS:"__api_reporter_events__",USER_PROFILE:"__api_reporter_user_profile__"},S.LogBuffer=LogBuffer,S.LogManager=LogManager,S.Logger=Logger,S.LoggingManager=LoggingManager,S.MAX_BODY_BYTES_CEILING=Pe,S.NetworkMonitor=NetworkMonitor,S.PageLifecycleManager=PageLifecycleManager,S.PerformanceMonitor=class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=createLogger("PerformanceMonitor"),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}},S.PerformanceResourceObserver=PerformanceResourceObserver,S.PostMessageInterceptor=PostMessageInterceptor,S.QueueMemoryManager=QueueMemoryManager,S.REDACTED_VALUE=Ae,S.REPORTER_LOG_PREFIX="[TraceScoutMonitoringCore]",S.RESOURCE_EXTENSIONS=_e,S.Recorder=Recorder,S.RecorderMemoryManager=RecorderMemoryManager,S.RecorderPresets=Ic,S.RemoteConfigService=class RemoteConfigService{constructor(S,b=null){this.context=S;const I="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname?"https://api.tracescout.com":"http://localhost:3001";this.baseUrl=b||I,this.config=null,this.lastFetched=null,this.refreshInterval=3e5,this.refreshTimer=null,this.logger=createLogger("RemoteConfig"),this.fetchAttempts=0,this.maxFetchAttempts=3,console.log("[RemoteConfigService] Using API base URL:",this.baseUrl)}async fetchConfig(){try{this.fetchAttempts++,this.logger.log("Fetching remote SDK configuration..."),this.logger.log(` Project: ${this.context.projectId}`),this.logger.log(` Workspace: ${this.context.workspaceId}`),this.logger.log(` Attempt: ${this.fetchAttempts}/${this.maxFetchAttempts}`);const S=`${this.baseUrl}/api/projects/${this.context.projectId}/sdk-config`,b=await fetch(S,{method:"GET",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},signal:AbortSignal.timeout(1e4)});if(!b.ok){const S=await b.text();throw new Error(`Config fetch failed: ${b.status} ${b.statusText} - ${S}`)}const I=await b.json();this.#Rt(I),this.config=I,this.lastFetched=Date.now(),this.fetchAttempts=0,this.logger.log("✅ Remote configuration loaded successfully"),this.logger.log(` Config version: ${I.configVersion}`),this.logger.log(` Workspace: ${I.workspace.name}`),this.logger.log(` Project: ${I.project.name}`);const x=Object.keys(I.features).filter(S=>I.features[S].enabled).join(", ");return this.logger.log(` Features enabled: ${x||"none"}`),this.#Tt(),I}catch(S){this.logger.error("Failed to fetch remote config:",S.message),this.fetchAttempts<this.maxFetchAttempts?this.logger.warn(`Will retry... (${this.fetchAttempts}/${this.maxFetchAttempts})`):this.logger.warn("Max fetch attempts reached, using fallback configuration");const b=this.#At();return this.config=b,b}}#Rt(S){if(!S.success)throw new Error("Server returned unsuccessful config response");if(!S.project||S.project.id!==this.context.projectId)throw new Error(`Config projectId mismatch. Expected: ${this.context.projectId}, Got: ${S.project?.id}`);if(!S.workspace||!S.workspace.id)throw new Error("Config missing workspace data");if(!S.features)throw new Error("Config missing features object");if(!S.privacy)throw new Error("Config missing privacy object");if(!S.telemetry)throw new Error("Config missing telemetry object");this.logger.log("✓ Config validation passed")}#At(){return this.logger.warn("⚠️ Using fallback configuration - limited functionality"),this.logger.warn(" Session recording: enabled (100% sample rate)"),this.logger.warn(" Error tracking: enabled"),this.logger.warn(" Other features: disabled"),{success:!0,configVersion:"2.0.0-fallback",lastUpdated:(new Date).toISOString(),workspace:{id:this.context.workspaceId,name:"Unknown Workspace (Fallback)"},project:{id:this.context.projectId,name:"Unknown Project (Fallback)",environment:this.context.environment,allowedOrigins:[]},features:{sessionRecording:{enabled:!0,sampleRate:1,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[],chunkDuration:3e4,maxChunkSize:5e5,recordCanvas:!1,collectFonts:!1},errorTracking:{enabled:!0,ignoreErrors:[],sourceMaps:!1,stackTraceLimit:30},performanceMonitoring:{enabled:!1,coreWebVitals:!1,longTaskThreshold:50,resourceTimingBufferSize:250},consoleCapture:{enabled:!0,levels:["error","warn"]},networkMonitoring:{enabled:!1,endpoints:[],captureHeaders:!1,captureBody:!1}},privacy:{maskInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},telemetry:{endpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`,sessionEndpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/sessions`,batchSize:10,flushInterval:5e3,enableCompression:!0},service:{send:async S=>{const b=`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`;console.log("[TraceScout][FallbackService] Sending to:",b),console.log("[TraceScout][FallbackService] Events:",S);try{const I=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},body:JSON.stringify({events:S,context:{workspaceId:this.context.workspaceId,projectId:this.context.projectId,environment:this.context.environment,sessionId:this.context.sessionId}})});if(!I.ok)throw new Error(`HTTP ${I.status}: ${I.statusText}`);return await I.json()}catch(S){throw console.error("[TraceScout][FallbackService] Send failed:",S),S}}}}}#Tt(){this.refreshTimer&&clearTimeout(this.refreshTimer),this.refreshTimer=setTimeout(async()=>{this.logger.log("⏰ Refreshing remote configuration...");try{await this.fetchConfig(),this.logger.log("✅ Config refreshed successfully")}catch(S){this.logger.error("Config refresh failed:",S.message)}},this.refreshInterval),this.logger.log(`Next config refresh in ${this.refreshInterval/1e3}s`)}stopRefresh(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null,this.logger.log("Config refresh stopped"))}getConfig(){return this.config}isStale(){return!this.lastFetched||Date.now()-this.lastFetched>this.refreshInterval}async refresh(){return this.logger.log("Forcing config refresh..."),await this.fetchConfig()}getConfigAge(){return this.lastFetched?Math.floor((Date.now()-this.lastFetched)/1e3):-1}},S.ResourceInterceptor=class ResourceInterceptor{constructor(S){this.reporter=S,this.interceptorName="resource",this.logger=createLogger("ResourceInterceptor"),this.boundErrorHandler=this.handleResourceError.bind(this),this.isDestroyed=!1}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed ResourceInterceptor"):(window.addEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor setup complete"))}handleResourceError(S){if(this.isDestroyed)return;const b=S.target;if(b instanceof HTMLScriptElement||b instanceof HTMLLinkElement||b instanceof HTMLImageElement){const S=b.src||b.href||"",I=b.tagName.toLowerCase(),x=parseUrl(S),R={type:"resource_load_error",request:{method:"GET",url:S,domain:x.hostname||this.#_t(S),path:x.pathname||this.#Ot(S),status:0,statusText:"Resource failed to load",response:`${I} element failed to load`,headers:{},interceptor:"resource"},extraData:{tag:I,elementType:b.constructor.name,errorType:"resource_load_failure",resourceType:this.#Dt(I),crossOrigin:this.#Ft(S),isDomElement:!0,integrity:b.integrity||null,crossorigin:b.crossOrigin||null,async:b.async||!1,defer:b.defer||!1,rel:b.rel||null,type:b.type||null},context:{forceLog:!0,isMonitored:this.shouldMonitor(S),scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logger.log(`Creating resource error event: ${S} [${I}]`),this.reporter&&this.reporter.logEvent?(this.reporter.logEvent(R),this.logger.log(`Resource error event sent for: ${S}`)):this.logger.error("Could not send resource error - reporter.logEvent not available"),this.logger.log(`Resource failed to load: ${S} [${I}]`)}}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!0}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}#_t(S){try{return new URL(S,location.origin).hostname}catch{return""}}#Ot(S){try{return new URL(S,location.origin).pathname}catch{return""}}#Dt(S){switch(S.toLowerCase()){case"script":return"javascript";case"link":return"stylesheet";case"img":return"image";case"video":return"video";case"audio":return"audio";case"source":return"media-source";case"track":return"text-track";case"object":return"object";case"embed":return"embed";case"iframe":return"iframe";default:return"unknown"}}#Ft(S){try{return new URL(S,location.origin).origin!==location.origin}catch{return!1}}destroy(){this.isDestroyed?this.logger.warn("ResourceInterceptor already destroyed"):(this.isDestroyed=!0,window.removeEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor destroyed"),this.reporter=null,this.boundErrorHandler=null)}},S.SDKContext=SDKContext,S.SENSITIVE_HEADERS=Te,S.SENSITIVE_QUERY_PARAMS=Ue,S.ServiceLogger=ServiceLogger,S.ServiceManager=ServiceManager,S.SessionManager=SessionManager,S.SessionStorage=SessionStorage,S.TraceScoutMonitoringCore=TraceScoutMonitoringCore,S.UploadQueue=UploadQueue,S.UserProfileManager=UserProfileManager,S.XHRInterceptor=XHRInterceptor,S.analyzeSnapshotsInEvents=analyzeSnapshotsInEvents,S.buildFieldDenylist=buildFieldDenylist,S.buildSnapshotIndex=buildSnapshotIndex,S.captureRequestBody=captureRequestBody,S.captureResponseBody=captureResponseBody,S.chunkHasSnapshot=chunkHasSnapshot,S.classifyMime=classifyMime,S.collectDeviceMetadata=collectDeviceMetadata,S.createChunk=createChunk,S.createLogger=createLogger,S.createSensitiveHeaderSet=function createSensitiveHeaderSet(S=[]){return new Set([...Te,...S.map(S=>S.toLowerCase())])},S.debounce=debounce,S.deepClone=function deepClone(S){if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>deepClone(S));if(S instanceof Object){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=deepClone(S[I]));return b}},S.default=Ve,S.detectDeviceType=detectDeviceType,S.detectTouchCapability=detectTouchCapability,S.extractConsoleRef=extractConsoleRef,S.extractNetworkFull=extractNetworkFull,S.extractNetworkRef=extractNetworkRef,S.extractRequestDetails=function extractRequestDetails(S,b,I,x,R="",A="unknown"){try{const _=new URL(S,location.origin);return{method:b.toUpperCase(),url:S,domain:_.hostname,path:_.pathname,status:I,statusText:x,response:R,interceptor:A}}catch{return{method:b.toUpperCase(),url:S,domain:"",path:"",status:I,statusText:x,response:R,interceptor:A}}},S.extractResourceRef=extractResourceRef,S.filterSensitiveHeaders=filterSensitiveHeaders,S.findNearestSnapshotBefore=findNearestSnapshotBefore,S.generateConsoleId=generateConsoleId,S.generateId=generateId,S.generateNetworkId=generateNetworkId,S.generateResourceId=generateResourceId,S.getConnectionInfo=getConnectionInfo,S.getEventsAfterSnapshot=getEventsAfterSnapshot,S.getMemoryInfo=getMemoryInfo,S.getRRWeb=getRRWeb,S.getRRWebSource=getRRWebSource,S.getRecord=getRecord,S.getResourceType=getResourceType,S.getSensitiveHeadersList=function getSensitiveHeadersList(){return[...Te]},S.getSnapshotTimestamps=getSnapshotTimestamps,S.handleRequestBody=handleRequestBody,S.handleResponseBody=handleResponseBody,S.hashCode=hashCode,S.initializeErrorHandler=function initializeErrorHandler(S,b={}){const I=new ErrorHandler(S,b);return I.install(),I},S.isApiEndpoint=function isApiEndpoint(S){if(!S)return!1;const b=S.toLowerCase();return!![/\/api\//i,/\/v\d+\//i,/\/graphql/i,/\/rest\//i,/\/rpc\//i,/\.json(\?|$)/i].some(S=>S.test(b))||!isStaticResource(S)},S.isCompatibleVersion=isCompatibleVersion,S.isRRWebLoaded=isRRWebLoaded,S.isResourceUrl=(S,b="")=>{const I=S.split("?")[0].toLowerCase();return[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".woff",".woff2",".ttf",".eot",".otf",".pdf",".mp4",".mp3",".wav",".zip",".tar",".gz",".xml",".txt",".csv"].some(S=>I.endsWith(S))},S.isSensitiveField=isSensitiveField,S.isSensitiveHeader=function isSensitiveHeader(S){return!!S&&Te.includes(S.toLowerCase())},S.isStaticResource=isStaticResource,S.isTextualContentType=isTextualContentType,S.loadRRWeb=loadRRWeb,S.loggingManager=_,S.monitoringCore=Ve,S.parseBrowserInfo=parseBrowserInfo,S.parseFormData=parseFormData,S.parseOSInfo=parseOSInfo,S.parseRequestUrl=function parseRequestUrl(S){try{return new URL(S,location.origin)}catch(S){return null}},S.parseUrl=parseUrl,S.redactFormUrlEncoded=redactFormUrlEncoded,S.redactObject=redactObject,S.safeJsonParse=function safeJsonParse(S,b=null){try{return JSON.parse(S)}catch(S){return b}},S.safeJsonStringify=function safeJsonStringify(S,b="{}"){try{return JSON.stringify(S)}catch(S){return b}},S.safeMime=safeMime,S.safeParseConsoleArgs=safeParseConsoleArgs,S.safeSessionStorage=I,S.safeStorage=b,S.safeStringify=safeStringify,S.splitSanitizedUrl=splitSanitizedUrl,S.stripNetworkPayload=stripNetworkPayload,S.throttle=throttle$1,S.truncateToBytes=truncateToBytes,S.typeUtils=x,S.utf8Bytes=utf8Bytes,S.utils=R,S.validateDomains=validateDomains,S.validateEndpoints=validateEndpoints,S.validateService=validateService,Object.defineProperty(S,"__esModule",{value:!0})});
|
|
1
|
+
!function(S,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define("tracescout",["exports"],b):b((S="undefined"!=typeof globalThis?globalThis:S||self).TraceScout={})}(this,function(S){"use strict";function generateId(){return Math.random().toString(36).substr(2,9)+Date.now().toString(36)}function parseUrl(S,b=("undefined"!=typeof location?location.origin:void 0)){try{const I=new URL(S,b);return{hostname:I.hostname,pathname:I.pathname,search:I.search,protocol:I.protocol,origin:I.origin,hash:I.hash}}catch(S){return{hostname:"",pathname:"",search:"",protocol:"",origin:"",hash:""}}}const b={get(S){try{const b=localStorage.getItem(S);return b?JSON.parse(b):null}catch(S){return null}},set(S,b){try{return localStorage.setItem(S,JSON.stringify(b)),!0}catch(S){return!1}},remove(S){try{return localStorage.removeItem(S),!0}catch(S){return!1}},getItem(S){return this.get(S)},setItem(S,b){return this.set(S,b)},removeItem(S){return this.remove(S)}},I={getItem(S){try{return sessionStorage.getItem(S)}catch(S){return null}},setItem(S,b){try{return sessionStorage.setItem(S,b),!0}catch(S){return!1}},removeItem(S){try{return sessionStorage.removeItem(S),!0}catch(S){return!1}}},x={isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isString:S=>"string"==typeof S,isFunction:S=>"function"==typeof S,isEmpty:S=>null==S||""===S||Array.isArray(S)&&0===S.length,get:(S,b,I)=>{if(!S)return I;const x=b.split(".");let R=S;for(const S of x){if(!R||"object"!=typeof R||!(S in R))return I;R=R[S]}return R}};function debounce(S,b){let I;return function executedFunction(...x){clearTimeout(I),I=setTimeout(()=>{clearTimeout(I),S(...x)},b)}}function throttle$1(S,b){let I;return function(...x){I||(S.apply(this,x),I=!0,setTimeout(()=>I=!1,b))}}function safeStringify(S,b=10,I=1e4){const x=new WeakSet;let R=0;const A=JSON.stringify(S,function(S,I){if("object"==typeof I&&null!==I&&(R++,R>b))return"[Max Depth Exceeded]";if("object"==typeof I&&null!==I){if(x.has(I))return"[Circular Reference]";x.add(I)}return"function"==typeof I?`[Function: ${I.name||"anonymous"}]`:I instanceof Error?{__type:"Error",name:I.name,message:I.message,stack:I.stack}:I instanceof RegExp?`[RegExp: ${I.toString()}]`:I instanceof Date?`[Date: ${I.toISOString()}]`:"symbol"==typeof I?`[Symbol: ${I.toString()}]`:"bigint"==typeof I?`[BigInt: ${I.toString()}]`:"undefined"!=typeof HTMLElement&&I instanceof HTMLElement?`[HTMLElement: <${I.tagName.toLowerCase()}${I.id?' id="'+I.id+'"':""}>]`:"undefined"!=typeof Window&&I instanceof Window?"[Window]":"undefined"!=typeof Document&&I instanceof Document?"[Document]":I});return A&&A.length>I?A.substring(0,I)+"... [truncated]":A}function safeParseConsoleArgs(S,b=5e3,I=1e4){if(!Array.isArray(S))return[];const x=[];let R=0;for(let A=0;A<S.length;A++){if(R>=I){x.push(`[${S.length-A} more arguments truncated]`);break}const _=S[A];let D;try{D=null===_?"null":void 0===_?"undefined":"string"==typeof _?_.length>b?_.substring(0,b)+"... [truncated]":_:"number"==typeof _||"boolean"==typeof _?String(_):"object"==typeof _?safeStringify(_,5,b):String(_)}catch(S){D=`[Unserializable: ${typeof _}]`}const L="string"==typeof D?D.length:0;if(R+L>I){const S=I-R;if(!(S>50&&"string"==typeof D)){x.push("[Remaining arguments truncated]");break}D=D.substring(0,S)+"... [truncated]"}x.push(D),R+=L}return x}const R={get:(S,b,I)=>{const x=b.split(".");let R=S;for(const S of x){if(null==R)return I;R=R[S]}return void 0!==R?R:I},set:(S,b,I)=>{const x=b.split("."),R=x.pop();let A=S;for(const S of x)S in A&&"object"==typeof A[S]||(A[S]={}),A=A[S];return A[R]=I,S},has:(S,b)=>{const I=b.split(".");let x=S;for(const S of I){if(null==x||!(S in x))return!1;x=x[S]}return!0},isObject:S=>null!==S&&"object"==typeof S&&!Array.isArray(S),isArray:S=>Array.isArray(S),isString:S=>"string"==typeof S,isNumber:S=>"number"==typeof S&&!isNaN(S),isBoolean:S=>"boolean"==typeof S,isFunction:S=>"function"==typeof S,isNull:S=>null===S,isUndefined:S=>void 0===S,isEmpty:S=>null==S||("string"==typeof S||Array.isArray(S)?0===S.length:"object"==typeof S&&0===Object.keys(S).length),toLower:S=>String(S).toLowerCase(),toUpper:S=>String(S).toUpperCase(),trim:S=>String(S).trim(),startsWith:(S,b)=>String(S).startsWith(b),endsWith:(S,b)=>String(S).endsWith(b),includes:(S,b)=>String(S).includes(b),filter:(S,b)=>Array.isArray(S)?S.filter(b):[],map:(S,b)=>Array.isArray(S)?S.map(b):[],find:(S,b)=>{if(Array.isArray(S))return S.find(b)},sortBy:(S,b)=>Array.isArray(S)?[...S].sort((S,I)=>{const x="function"==typeof b?b(S):S[b],R="function"==typeof b?b(I):I[b];return x<R?-1:x>R?1:0}):[],keys:S=>Object.keys(S||{}),values:S=>Object.values(S||{}),entries:S=>Object.entries(S||{}),assign:(S,...b)=>Object.assign({},S,...b),cloneDeep:S=>{if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>R.cloneDeep(S));if("object"==typeof S){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=R.cloneDeep(S[I]));return b}return S},merge:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&(R.isObject(S[b])&&R.isObject(I[b])?I[b]=R.merge(I[b],S[b]):I[b]=S[b]);return I},defaults:(S,...b)=>{const I={...S};for(const S of b)if(S)for(const b in S)S.hasOwnProperty(b)&&void 0===I[b]&&(I[b]=S[b]);return I},min:(...S)=>Math.min(...S),max:(...S)=>Math.max(...S),round:(S,b=0)=>{const I=Math.pow(10,b);return Math.round(S*I)/I},noop:()=>{},identity:S=>S,isEqual:(S,b)=>{if(S===b)return!0;if(null===S||null===b)return!1;if(typeof S!=typeof b)return!1;if("object"!=typeof S)return!1;const I=Object.keys(S),x=Object.keys(b);if(I.length!==x.length)return!1;for(const A of I){if(!x.includes(A))return!1;if(!R.isEqual(S[A],b[A]))return!1}return!0}},A={RETRY_INTERVAL_MS:3e4,DEDUPLICATION_WINDOW_MS:6e4,MAX_QUEUE_SIZE:1e3,MAX_RETRIES:3,BATCH_SIZE:10,DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS:[]};class LoggingManager{constructor(){this.globalConfig={enabled:!1,level:"info",showTimestamps:!0,showServiceIcons:!0},this.serviceConfig={TraceScoutMonitoringCore:{enabled:!1,level:"info"},ConfigManager:{enabled:!1,level:"info"},EventManager:{enabled:!1,level:"info"},ServiceManager:{enabled:!1,level:"info"},UserProfileManager:{enabled:!1,level:"info"},PerformanceMonitor:{enabled:!1,level:"info"},FetchInterceptor:{enabled:!1,level:"info"},XHRInterceptor:{enabled:!1,level:"info"},ResourceInterceptor:{enabled:!1,level:"info"},PostMessageInterceptor:{enabled:!1,level:"info"},CoreWebVitalsMonitor:{enabled:!1,level:"info"},Recorder:{enabled:!1,level:"info"},SessionStorage:{enabled:!1,level:"info"},UploadQueue:{enabled:!1,level:"info"},"CDN-Loader":{enabled:!1,level:"info"},Replayer:{enabled:!1,level:"info"},Validation:{enabled:!1,level:"info"},BaseService:{enabled:!1,level:"info"}},this.logLevels={error:0,warn:1,info:2,debug:3},this.serviceStyles={TraceScoutMonitoringCore:{icon:"🎯",color:"#009688"},ConfigManager:{icon:"⚙️",color:"#607D8B"},EventManager:{icon:"📝",color:"#4CAF50"},ServiceManager:{icon:"🌐",color:"#9C27B0"},UserProfileManager:{icon:"👤",color:"#FF9800"},PerformanceMonitor:{icon:"⚡",color:"#795548"},FetchInterceptor:{icon:"🔌",color:"#8BC34A"},XHRInterceptor:{icon:"📡",color:"#FFC107"},ResourceInterceptor:{icon:"📦",color:"#E91E63"},PostMessageInterceptor:{icon:"💬",color:"#3F51B5"},CoreWebVitalsMonitor:{icon:"📊",color:"#2196F3"},Recorder:{icon:"🎬",color:"#FF5722"},SessionStorage:{icon:"💾",color:"#673AB7"},UploadQueue:{icon:"📤",color:"#FF9800"},"CDN-Loader":{icon:"📥",color:"#4CAF50"},Replayer:{icon:"▶️",color:"#9C27B0"},Validation:{icon:"✅",color:"#4CAF50"},BaseService:{icon:"🔧",color:"#607D8B"},default:{icon:"🔍",color:"#666"}}}configure(S={}){this.globalConfig={...this.globalConfig,...S},S.services&&Object.keys(S.services).forEach(b=>{this.serviceConfig[b]&&(this.serviceConfig[b]={...this.serviceConfig[b],...S.services[b]})})}enableServices(S,b="info"){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!0,this.serviceConfig[S].level=b)}),this.globalConfig.enabled=!0}disableServices(S){(Array.isArray(S)?S:[S]).forEach(S=>{this.serviceConfig[S]&&(this.serviceConfig[S].enabled=!1)})}enableAll(S="info"){Object.keys(this.serviceConfig).forEach(b=>{this.serviceConfig[b].enabled=!0,this.serviceConfig[b].level=S}),this.globalConfig.enabled=!0}disableAll(){Object.keys(this.serviceConfig).forEach(S=>{this.serviceConfig[S].enabled=!1}),this.globalConfig.enabled=!1}getConfig(){return{global:{...this.globalConfig},services:{...this.serviceConfig}}}getEnabledServices(){return Object.keys(this.serviceConfig).filter(S=>this.serviceConfig[S].enabled)}isEnabled(S,b="info"){if(!this.globalConfig.enabled)return!1;const I=this.serviceConfig[S];if(!I||!I.enabled)return!1;const x=this.logLevels[I.level]||this.logLevels.info;return(this.logLevels[b]||this.logLevels.info)<=x}createLogger(S){return new ServiceLogger(S,this)}formatMessage(S,b,I){const x=this.serviceStyles[S]||this.serviceStyles.default;return{prefix:`%c${`${this.globalConfig.showTimestamps?`[${(new Date).toLocaleTimeString()}]`:""}[TraceScout][${S}]${this.globalConfig.showServiceIcons?x.icon:""}`}`,style:`color: ${x.color}; font-weight: bold;`,args:I}}}class ServiceLogger{constructor(S,b){this.serviceName=S,this.loggingManager=b}log(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.log(b.prefix,b.style,...b.args)}}info(...S){if(this.loggingManager.isEnabled(this.serviceName,"info")){const b=this.loggingManager.formatMessage(this.serviceName,"info",S);console.info(b.prefix,b.style,...b.args)}}warn(...S){if(this.loggingManager.isEnabled(this.serviceName,"warn")){const b=this.loggingManager.formatMessage(this.serviceName,"warn",S);console.warn(b.prefix,"color: #FF5722; font-weight: bold;",...b.args)}}error(...S){const b=this.loggingManager.formatMessage(this.serviceName,"error",S);console.error(b.prefix,"color: #F44336; font-weight: bold;",...b.args)}debug(...S){if(this.loggingManager.isEnabled(this.serviceName,"debug")){const b=this.loggingManager.formatMessage(this.serviceName,"debug",S);console.debug(b.prefix,"color: #9E9E9E; font-weight: bold;",...b.args)}}session(...S){this.log("🎬",...S)}performance(...S){this.log("⚡",...S)}network(...S){this.log("🌐",...S)}storage(...S){this.log("💾",...S)}updateDebugMode(S){S?this.loggingManager.enableServices(this.serviceName):this.loggingManager.disableServices(this.serviceName)}}const _=new LoggingManager;function createLogger(S){return _.createLogger(S)}class Logger{constructor(S="",b=!1){this.serviceName=S.replace(/^\[|\]$/g,""),this.serviceLogger=_.createLogger(this.serviceName),b&&_.enableServices(this.serviceName),this.prefix=S,this.debug=Boolean(b)}updateDebugMode(S){this.debug=Boolean(S),this.serviceLogger.updateDebugMode(S)}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.serviceLogger.debug(...S)}success(...S){this.serviceLogger.log("✅",...S)}important(...S){this.serviceLogger.log("⚠️",...S)}session(...S){this.serviceLogger.session(...S)}performance(...S){this.serviceLogger.performance(...S)}interceptor(...S){this.serviceLogger.network(...S)}service(...S){this.serviceLogger.network(...S)}monitor(...S){this.serviceLogger.log("📊",...S)}}function validateEndpoints(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateDomains(S){if(!S)return!1;const b=Array.isArray(S)?S:[S];return b.length>0&&b.every(S=>"string"==typeof S&&S.length>0)}function validateService(S){return S&&"object"==typeof S&&"function"==typeof S.send}class ConfigManager{constructor(S={}){this.defaultConfig=S,this.config={},this.logger=new Logger("[ConfigManager]",S.debug)}validate(S={}){const b=[];try{const I=validateEndpoints(S.endpoints),x=validateDomains(S.domainsToTrack);I||x||b.push("Either endpoints or domainsToTrack must be provided"),S.service&&!validateService(S.service)&&b.push("Invalid service: must be an object with send() method");const R={retryIntervalMs:{min:1e3,max:3e5},deduplicationWindowMs:{min:100,max:36e5},maxQueueSize:{min:10,max:1e4},maxRetries:{min:1,max:10},batchSize:{min:1,max:100}};if(Object.entries(R).forEach(([I,{min:x,max:R}])=>{const A=S[I];void 0!==A&&("number"!=typeof A||A<x||A>R)&&b.push(`${I} must be a number between ${x} and ${R}`)}),void 0!==S.monitorPostMessages)if("object"!=typeof S.monitorPostMessages||null===S.monitorPostMessages)b.push("monitorPostMessages must be an object");else{const I=S.monitorPostMessages;void 0!==I.postMessageOriginWhitelist&&(Array.isArray(I.postMessageOriginWhitelist)?I.postMessageOriginWhitelist.every(S=>"string"==typeof S)||b.push("postMessageOriginWhitelist must contain only strings"):b.push("postMessageOriginWhitelist must be an array")),void 0===I.excludePostMessagesEvents||Array.isArray(I.excludePostMessagesEvents)||b.push("excludePostMessagesEvents must be an array"),void 0===I.monitorSpecificPostMessagesEvents||Array.isArray(I.monitorSpecificPostMessagesEvents)||b.push("monitorSpecificPostMessagesEvents must be an array")}if(void 0!==S.monitorPerformance&&"boolean"!=typeof S.monitorPerformance&&b.push("monitorPerformance must be a boolean"),void 0!==S.slowRequestThreshold&&("number"!=typeof S.slowRequestThreshold||S.slowRequestThreshold<100||S.slowRequestThreshold>3e4)&&b.push("slowRequestThreshold must be a number between 100 and 30000 milliseconds"),void 0!==S.averageAlertThreshold&&("number"!=typeof S.averageAlertThreshold||S.averageAlertThreshold<100||S.averageAlertThreshold>3e4)&&b.push("averageAlertThreshold must be a number between 100 and 30000 milliseconds"),b.length>0)throw new Error(`Configuration validation failed: ${b.join(", ")}`);return!0}catch(S){throw S}}apply(S={}){this.logger.log("Applying configuration options"),this.validate(S);try{this.config=R.merge({},this.defaultConfig,S,{debug:"boolean"==typeof R.get(S,"debug")?R.get(S,"debug"):Boolean(R.get(S,"debug")),retryIntervalMs:Math.max(1e3,R.get(S,"retryIntervalMs",this.defaultConfig.retryIntervalMs)),deduplicationWindowMs:Math.max(100,R.get(S,"deduplicationWindowMs",this.defaultConfig.deduplicationWindowMs)),maxQueueSize:Math.max(10,R.get(S,"maxQueueSize",this.defaultConfig.maxQueueSize)),maxRetries:Math.max(1,Math.min(10,R.get(S,"maxRetries",this.defaultConfig.maxRetries))),batchSize:Math.max(1,Math.min(100,R.get(S,"batchSize",this.defaultConfig.batchSize)))}),S.service&&(this.config.service=S.service),S.endpoints&&(this.config.endpoints=S.endpoints),S.domainsToTrack&&(this.config.domainsToTrack=S.domainsToTrack),S.monitorPostMessages&&(this.config.monitorPostMessages={postMessageOriginWhitelist:S.monitorPostMessages.postMessageOriginWhitelist||[],excludePostMessagesEvents:S.monitorPostMessages.excludePostMessagesEvents||[],monitorSpecificPostMessagesEvents:S.monitorPostMessages.monitorSpecificPostMessagesEvents||[]}),void 0!==S.monitorPerformance&&(this.config.monitorPerformance=S.monitorPerformance),void 0!==S.slowRequestThreshold&&(this.config.slowRequestThreshold=Math.max(100,Math.min(3e4,S.slowRequestThreshold))),void 0!==S.averageAlertThreshold&&(this.config.averageAlertThreshold=Math.max(100,Math.min(3e4,S.averageAlertThreshold)));return["appName","appVersion","environment","userId","sessionId","logPreflight","logResourceErrors","enableSessionRecording","sessionRecordingOptions","coreWebVitalsConfig"].forEach(b=>{void 0!==S[b]&&(this.config[b]=S[b])}),this.logger.log("Configuration applied successfully"),this.config}catch(S){throw this.logger.error("Failed to apply configuration:",S),S}}get(S,b=void 0){return R.get(this.config,S,b)}getAll(){return{...this.config}}update(S,b){return"string"==typeof S?this.config[S]=b:"object"==typeof S&&(this.config={...this.config,...S}),this.config}reset(){return this.config={...this.defaultConfig},this.config}}var D,L,B,U,$,j=-1,o=function(S){addEventListener("pageshow",function(b){b.persisted&&(j=b.timeStamp,S(b))},!0)},c=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},u=function(){var S=c();return S&&S.activationStart||0},f=function(S,b){var I=c(),x="navigate";return j>=0?x="back-forward-cache":I&&(document.prerendering||u()>0?x="prerender":document.wasDiscarded?x="restore":I.type&&(x=I.type.replace(/_/g,"-"))),{name:S,value:void 0===b?-1:b,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:x}},s=function(S,b,I){try{if(PerformanceObserver.supportedEntryTypes.includes(S)){var x=new PerformanceObserver(function(S){Promise.resolve().then(function(){b(S.getEntries())})});return x.observe(Object.assign({type:S,buffered:!0},I||{})),x}}catch(S){}},d=function(S,b,I,x){var R,A;return function(_){b.value>=0&&(_||x)&&((A=b.value-(R||0))||void 0===R)&&(R=b.value,b.delta=A,b.rating=function(S,b){return S>b[1]?"poor":S>b[0]?"needs-improvement":"good"}(b.value,I),S(b))}},l=function(S){requestAnimationFrame(function(){return requestAnimationFrame(function(){return S()})})},p=function(S){var n=function(b){"pagehide"!==b.type&&"hidden"!==document.visibilityState||S(b)};addEventListener("visibilitychange",n,!0),addEventListener("pagehide",n,!0)},v=function(S){var b=!1;return function(I){b||(S(I),b=!0)}},W=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},g=function(S){"hidden"===document.visibilityState&&W>-1&&(W="visibilitychange"===S.type?S.timeStamp:0,T())},y=function(){addEventListener("visibilitychange",g,!0),addEventListener("prerenderingchange",g,!0)},T=function(){removeEventListener("visibilitychange",g,!0),removeEventListener("prerenderingchange",g,!0)},E=function(){return W<0&&(W=h(),y(),o(function(){setTimeout(function(){W=h(),y()},0)})),{get firstHiddenTime(){return W}}},C=function(S){document.prerendering?addEventListener("prerenderingchange",function(){return S()},!0):S()},H=[1800,3e3],w=function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FCP"),A=s("paint",function(S){S.forEach(function(S){"first-contentful-paint"===S.name&&(A.disconnect(),S.startTime<x.firstHiddenTime&&(R.value=Math.max(S.startTime-u(),0),R.entries.push(S),I(!0)))})});A&&(I=d(S,R,H,b.reportAllChanges),o(function(x){R=f("FCP"),I=d(S,R,H,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,I(!0)})}))})},V=[.1,.25],Q={passive:!0,capture:!0},G=new Date,P=function(S,b){D||(D=b,L=S,B=new Date,k(removeEventListener),F())},F=function(){if(L>=0&&L<B-G){var S={entryType:"first-input",name:D.type,target:D.target,cancelable:D.cancelable,startTime:D.timeStamp,processingStart:D.timeStamp+L};U.forEach(function(b){b(S)}),U=[]}},M=function(S){if(S.cancelable){var b=(S.timeStamp>1e12?new Date:performance.now())-S.timeStamp;"pointerdown"==S.type?function(S,b){var t=function(){P(S,b),r()},i=function(){r()},r=function(){removeEventListener("pointerup",t,Q),removeEventListener("pointercancel",i,Q)};addEventListener("pointerup",t,Q),addEventListener("pointercancel",i,Q)}(b,S):P(b,S)}},k=function(S){["mousedown","keydown","touchstart","pointerdown"].forEach(function(b){return S(b,M,Q)})},J=[100,300],X=0,Y=1/0,ee=0,N=function(S){S.forEach(function(S){S.interactionId&&(Y=Math.min(Y,S.interactionId),ee=Math.max(ee,S.interactionId),X=ee?(ee-Y)/7+1:0)})},O=function(){return $?X:performance.interactionCount||0},q=function(){"interactionCount"in performance||$||($=s("event",N,{type:"event",buffered:!0,durationThreshold:0}))},te=[200,500],se=0,z=function(){return O()-se},re=[],ne={},K=function(S){var b=re[re.length-1],I=ne[S.interactionId];if(I||re.length<10||S.duration>b.latency){if(I)I.entries.push(S),I.latency=Math.max(I.latency,S.duration);else{var x={id:S.interactionId,latency:S.duration,entries:[S]};ne[x.id]=x,re.push(x)}re.sort(function(S,b){return b.latency-S.latency}),re.splice(10).forEach(function(S){delete ne[S.id]})}},ie=[2500,4e3],oe={},ae=[800,1800],le=function e(S){document.prerendering?C(function(){return e(S)}):"complete"!==document.readyState?addEventListener("load",function(){return e(S)},!0):setTimeout(S,0)},Z=function(S,b){b=b||{};var I=f("TTFB"),x=d(S,I,ae,b.reportAllChanges);le(function(){var R=c();if(R){var A=R.responseStart;if(A<=0||A>performance.now())return;I.value=Math.max(A-u(),0),I.entries=[R],x(!0),o(function(){I=f("TTFB",0),(x=d(S,I,ae,b.reportAllChanges))(!0)})}})};class CoreWebVitalsMonitor{constructor(S={}){this.config=S,this.logger=new Logger("[CoreWebVitalsMonitor]",S.debug),this.enabled=!1!==S.enabled,this.metrics=new Map,this.observers=[],this.callbacks=[],this.useWebVitalsLibrary=!1!==S.useWebVitalsLibrary,this.thresholds={lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3},...S.thresholds},this.collectMetrics={lcp:!1!==S.collectLCP,fid:!1!==S.collectFID,cls:!1!==S.collectCLS,inp:!1!==S.collectINP,ttfb:!1!==S.collectTTFB,fcp:!1!==S.collectFCP},this.reportingEnabled=!1!==S.reportingEnabled,this.reportThreshold=S.reportThreshold||"needsImprovement",this.enabled&&"undefined"!=typeof window&&this.init()}init(){if(this.logger.log("Initializing Core Web Vitals monitoring..."),this.useWebVitalsLibrary)try{return this.initWithWebVitalsLibrary(),void this.logger.log("Core Web Vitals monitoring initialized with web-vitals library")}catch(S){this.logger.warn("web-vitals library subscription failed, falling back to custom implementation:",S)}this.initCustomImplementation(),this.logger.log("Core Web Vitals monitoring initialized with custom implementation")}initWithWebVitalsLibrary(){this.collectMetrics.lcp&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("LCP"),a=function(S){var b=S[S.length-1];b&&b.startTime<x.firstHiddenTime&&(R.value=Math.max(b.startTime-u(),0),R.entries=[b],I())},A=s("largest-contentful-paint",a);if(A){I=d(S,R,ie,b.reportAllChanges);var _=v(function(){oe[R.id]||(a(A.takeRecords()),A.disconnect(),oe[R.id]=!0,I(!0))});["keydown","click"].forEach(function(S){addEventListener(S,function(){return setTimeout(_,0)},!0)}),p(_),o(function(x){R=f("LCP"),I=d(S,R,ie,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,oe[R.id]=!0,I(!0)})})}})}(S=>this.handleWebVitalsMetric("lcp",S)),this.collectMetrics.fid&&function(S,b){b=b||{},C(function(){var I,x=E(),R=f("FID"),l=function(S){S.startTime<x.firstHiddenTime&&(R.value=S.processingStart-S.startTime,R.entries.push(S),I(!0))},m=function(S){S.forEach(l)},A=s("first-input",m);I=d(S,R,J,b.reportAllChanges),A&&p(v(function(){m(A.takeRecords()),A.disconnect()})),A&&o(function(){var x;R=f("FID"),I=d(S,R,J,b.reportAllChanges),U=[],L=-1,D=null,k(addEventListener),x=l,U.push(x),F()})})}(S=>this.handleWebVitalsMetric("fid",S)),this.collectMetrics.cls&&function(S,b){b=b||{},w(v(function(){var I,x=f("CLS",0),R=0,A=[],c=function(S){S.forEach(function(S){if(!S.hadRecentInput){var b=A[0],I=A[A.length-1];R&&S.startTime-I.startTime<1e3&&S.startTime-b.startTime<5e3?(R+=S.value,A.push(S)):(R=S.value,A=[S])}}),R>x.value&&(x.value=R,x.entries=A,I())},_=s("layout-shift",c);_&&(I=d(S,x,V,b.reportAllChanges),p(function(){c(_.takeRecords()),I(!0)}),o(function(){R=0,x=f("CLS",0),I=d(S,x,V,b.reportAllChanges),l(function(){return I()})}),setTimeout(I,0))}))}(S=>this.handleWebVitalsMetric("cls",S)),this.collectMetrics.inp&&function(S,b){b=b||{},C(function(){var I;q();var x,R=f("INP"),a=function(S){S.forEach(function(S){S.interactionId&&K(S),"first-input"===S.entryType&&!re.some(function(b){return b.entries.some(function(b){return S.duration===b.duration&&S.startTime===b.startTime})})&&K(S)});var b,I=(b=Math.min(re.length-1,Math.floor(z()/50)),re[b]);I&&I.latency!==R.value&&(R.value=I.latency,R.entries=I.entries,x())},A=s("event",a,{durationThreshold:null!==(I=b.durationThreshold)&&void 0!==I?I:40});x=d(S,R,te,b.reportAllChanges),A&&("PerformanceEventTiming"in window&&"interactionId"in PerformanceEventTiming.prototype&&A.observe({type:"first-input",buffered:!0}),p(function(){a(A.takeRecords()),R.value<0&&z()>0&&(R.value=0,R.entries=[]),x(!0)}),o(function(){re=[],se=O(),R=f("INP"),x=d(S,R,te,b.reportAllChanges)}))})}(S=>this.handleWebVitalsMetric("inp",S)),this.collectMetrics.ttfb&&Z(S=>this.handleWebVitalsMetric("ttfb",S)),this.collectMetrics.fcp&&w(S=>this.handleWebVitalsMetric("fcp",S)),this.setupVisibilityChangeHandler()}handleWebVitalsMetric(S,b){const I={type:S,value:b.value,id:b.id,timestamp:Date.now(),rating:this.getRating(S,b.value),threshold:this.thresholds[S],libRating:"string"==typeof b.rating?b.rating:null,navigationType:"string"==typeof b.navigationType?b.navigationType:null};this.metrics.set(S,I),this.logger.log(`Web Vital metric captured: ${S} = ${b.value}ms (${I.rating})`),this.reportingEnabled&&this.shouldReport(I)&&this.reportMetric(I),this.triggerCallbacks(S,I)}initCustomImplementation(){this.logger.log("Initializing custom Core Web Vitals implementation..."),this.collectMetrics.fcp&&this.trackFCP(),this.collectMetrics.lcp&&this.trackLCP(),this.collectMetrics.fid&&this.trackFID(),this.collectMetrics.cls&&this.trackCLS(),this.collectMetrics.ttfb&&this.trackTTFB(),this.setupVisibilityChangeHandler()}trackFCP(){try{const S=new PerformanceObserver(b=>{for(const I of b.getEntries())"first-contentful-paint"===I.name&&(this.handleWebVitalsMetric("fcp",{value:I.startTime,id:`fcp-${Date.now()}`,name:"FCP"}),S.disconnect())});S.observe({type:"paint",buffered:!0})}catch(S){this.logger.warn("Failed to track FCP:",S)}}trackLCP(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.size>S&&(S=I.size,this.handleWebVitalsMetric("lcp",{value:I.startTime,id:`lcp-${Date.now()}`,name:"LCP"}))});b.observe({type:"largest-contentful-paint",buffered:!0})}catch(S){this.logger.warn("Failed to track LCP:",S)}}trackFID(){let S=!1;const handleInput=b=>{if(S)return;S=!0;const I=b.timeStamp-b.timeStamp;this.handleWebVitalsMetric("fid",{value:I,id:`fid-${Date.now()}`,name:"FID"}),["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.removeEventListener(S,handleInput)})};["click","keydown","mousedown","pointerdown","touchstart"].forEach(S=>{window.addEventListener(S,handleInput,{once:!0,passive:!0})})}trackCLS(){try{let S=0;const b=new PerformanceObserver(b=>{for(const I of b.getEntries())I.hadRecentInput||(S+=I.value,this.handleWebVitalsMetric("cls",{value:S,id:`cls-${Date.now()}`,name:"CLS"}))});b.observe({type:"layout-shift",buffered:!0})}catch(S){this.logger.warn("Failed to track CLS:",S)}}trackTTFB(){try{if(window.performance&&window.performance.timing){const S=window.performance.timing,b=S.responseStart-S.navigationStart;b>0&&this.handleWebVitalsMetric("ttfb",{value:b,id:`ttfb-${Date.now()}`,name:"TTFB"})}}catch(S){this.logger.warn("Failed to track TTFB:",S)}}getRating(S,b){const I=this.thresholds[S];return I?b<=I.good?"good":b<=I.needsImprovement?"needsImprovement":"poor":"unknown"}shouldReport(S){return"good"===this.reportThreshold?"good"===S.rating:"needsImprovement"!==this.reportThreshold||("good"===S.rating||"needsImprovement"===S.rating)}reportMetric(S){const b={type:"core_web_vital",context:{forceLog:!0,isMonitored:!0,metricType:S.type,metricValue:S.value,metricRating:S.rating,threshold:S.threshold},data:S};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}triggerCallbacks(S,b){this.callbacks.forEach(I=>{try{I(S,b)}catch(S){this.logger.error("Error in metric callback:",S)}})}setupVisibilityChangeHandler(){document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.reportFinalMetrics()})}reportFinalMetrics(){if(!this.reportingEnabled)return;const S=Array.from(this.metrics.values());if(0===S.length)return;this.logger.log("Reporting final Core Web Vitals metrics:",S);const b={type:"core_web_vitals_final_report",context:{forceLog:!0,isMonitored:!0,timestamp:Date.now(),pageUrl:window.location.href},data:{metrics:S,summary:this.generateSummary(S)}};this.reporter&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(b)}generateSummary(S){const b={total:S.length,byRating:{good:0,needsImprovement:0,poor:0},average:0,worst:null};let I=0,x=null;return S.forEach(S=>{b.byRating[S.rating]++,I+=S.value,(!x||"poor"===S.rating||"needsImprovement"===S.rating&&"poor"!==x.rating)&&(x=S)}),b.average=I/S.length,b.worst=x,b}addCallback(S){"function"==typeof S&&this.callbacks.push(S)}removeCallback(S){const b=this.callbacks.indexOf(S);b>-1&&this.callbacks.splice(b,1)}getMetrics(){return Array.from(this.metrics.values())}getMetric(S){return this.metrics.get(S)}updateThresholds(S){this.thresholds={...this.thresholds,...S},this.logger.log("Core Web Vitals thresholds updated:",this.thresholds)}destroy(){this.observers.forEach(S=>{S&&"function"==typeof S.disconnect&&S.disconnect()}),this.observers=[],this.callbacks=[],this.metrics.clear(),this.logger=null}}const ce="0123456789abcdef";function generateSessionId(){return`ts_${Date.now()}_${function randomHexSuffix(S=12){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const b=new Uint8Array(Math.ceil(S/2));crypto.getRandomValues(b);let I="";for(let S=0;S<b.length;S++)I+=ce[b[S]>>4]+ce[15&b[S]];return I.slice(0,S)}let b="";for(let I=0;I<S;I++)b+=ce[Math.floor(16*Math.random())];return b}(12)}`}const ue=new Set(["confirmed","partial","disabled"]);class SDKContext{static#e=null;static initialize(S){return this.#e?(console.warn("[SDKContext] Already initialized, returning existing instance"),this.#e):(this.#e=new SDKContext(S),this.#e)}static updateSessionId(S){this.#e&&(this.#e.sessionId=S,this.#e.sessionStartTime=Date.now(),console.log("[SDKContext] ✅ Session ID updated:",S))}static getInstance(){return this.#e}static resetForTests(){if("undefined"!=typeof process)throw new Error("resetForTests() only allowed in test environment");this.#e=null}constructor({projectId:S,workspaceId:b,environment:I,userId:x,sessionId:R,sessionManager:A}){this.#t({projectId:S}),this.projectId=S,this.workspaceId=null,this.environment=I||"production",this.userId=x||null,this.userEmail=null,this.userAttributes={},this.sessionManager=A||null,this.pageviewManager=null,this.sessionId=R||this.#s(),this.sessionStartTime=Date.now(),this.device={userAgent:navigator.userAgent,viewport:this.#r(),platform:navigator.platform,language:navigator.language,timezone:this.#n(),screen:{width:window.screen.width,height:window.screen.height,colorDepth:window.screen.colorDepth}},this.uaInfo=function parseUserAgent(S){const b={browserName:null,browserVersion:null,osName:null,osVersion:null,deviceType:null};if(!S||"string"!=typeof S)return b;let I;return/iPad|Tablet|PlayBook|Silk/i.test(S)||/Android/i.test(S)&&!/Mobile/i.test(S)?b.deviceType="tablet":/Mobi|iPhone|iPod|Android.*Mobile|Windows Phone|BlackBerry/i.test(S)?b.deviceType="mobile":/Mozilla|Chrome|Safari|Firefox|Edg|Opera|OPR/i.test(S)&&(b.deviceType="desktop"),(I=S.match(/Edg(?:e|A|iOS)?\/([\d.]+)/))?(b.browserName="Edge",b.browserVersion=I[1]):(I=S.match(/(?:OPR|Opera)\/([\d.]+)/))?(b.browserName="Opera",b.browserVersion=I[1]):(I=S.match(/SamsungBrowser\/([\d.]+)/))?(b.browserName="Samsung Internet",b.browserVersion=I[1]):(I=S.match(/(?:FxiOS|Firefox)\/([\d.]+)/))?(b.browserName="Firefox",b.browserVersion=I[1]):(I=S.match(/(?:CriOS|Chrome)\/([\d.]+)/))?(b.browserName="Chrome",b.browserVersion=I[1]):/Safari\//.test(S)&&(I=S.match(/Version\/([\d.]+)/))&&(b.browserName="Safari",b.browserVersion=I[1]),(I=S.match(/Windows NT ([\d.]+)/))?(b.osName="Windows",b.osVersion={"10.0":"10/11",6.3:"8.1",6.2:"8",6.1:"7"}[I[1]]||I[1]):(I=S.match(/iPhone OS ([\d_]+)|iPad; CPU OS ([\d_]+)/))?(b.osName="iOS",b.osVersion=(I[1]||I[2]||"").replace(/_/g,".")||null):(I=S.match(/Mac OS X ([\d_.]+)/))?(b.osName="macOS",b.osVersion=I[1].replace(/_/g,".")):(I=S.match(/Android ([\d.]+)/))?(b.osName="Android",b.osVersion=I[1]):/Android/i.test(S)?b.osName="Android":/CrOS/.test(S)?b.osName="ChromeOS":/Linux/.test(S)&&(b.osName="Linux"),b}(navigator.userAgent),this.domPrivacy=null,this.errorCount=0,this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] ✅ Initialized successfully"),console.log(` Project ID: ${S}`),console.log(` Session ID: ${this.sessionId}`),console.log(` Environment: ${this.environment}`)}setWorkspaceId(S){this.workspaceId=S,console.log("[SDKContext] ✅ Workspace ID updated:",S)}#t(S){const b=[];if(S.projectId?this.#i(S.projectId)||b.push("projectId must be a valid UUID"):b.push("projectId is required"),b.length>0){const S=new Error(`TraceScout.init() validation failed:\n - ${b.join("\n - ")}`);throw S.name="ValidationError",S.validationErrors=b,S}}#i(S){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(S)}#s(){return generateSessionId()}#r(){return{width:window.innerWidth,height:window.innerHeight}}#n(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}enrichEvent(S){return{...S,sessionId:this.sessionId,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,relativeTime:S.timestamp?S.timestamp-this.sessionStartTime:0,browser:{...this.device,url:window.location.href,referrer:document.referrer,title:document.title},userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0}}enrichChunk(S){return{...S,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,metadata:{...S.metadata,metaSchema:2,sdkVersion:"2.4.1",projectId:this.projectId,workspaceId:this.workspaceId,environment:this.environment,userId:this.userId,userEmail:this.userEmail,userName:this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??void 0:void 0,userAttributes:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0,userTraits:this.userAttributes,browser:this.uaInfo.browserName?{name:this.uaInfo.browserName,version:this.uaInfo.browserVersion||void 0}:void 0,os:this.uaInfo.osName?{name:this.uaInfo.osName,version:this.uaInfo.osVersion||void 0}:void 0,deviceType:this.uaInfo.deviceType||void 0,userAgent:this.device.userAgent,viewport:this.device.viewport,platform:this.device.platform,language:this.device.language,timezone:this.device.timezone,screen:this.device.screen,errorCount:this.errorCount,domPrivacy:this.domPrivacy||void 0,url:window.location.href,referrer:document.referrer,title:document.title}}}recordError(){this.errorCount++}setDomPrivacy(S){"string"==typeof S&&ue.has(S)&&(this.domPrivacy=S)}setUser(S,b={}){this.userId=S,this.userEmail=b.email||this.userEmail,this.userAttributes=b,console.log("[SDKContext] User updated:",S)}clearUser(){this.userId=null,this.userEmail=null,this.userAttributes={},console.log("[SDKContext] User cleared")}updatePageContext(){this.page={url:window.location.href,referrer:document.referrer,title:document.title},console.log("[SDKContext] Page context updated:",this.page.url)}getContext(){return{workspace:{id:this.workspaceId},project:{id:this.projectId,environment:this.environment},session:{id:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime},user:{id:this.userId,email:this.userEmail,attributes:this.userAttributes},device:this.device,page:{url:window.location.href,referrer:document.referrer,title:document.title}}}getEventContext(S={}){const b=this.sessionManager?.currentSession?.anonymousId??null,I=this.userAttributes&&"object"==typeof this.userAttributes?this.userAttributes.name??null:null,x="function"==typeof this.pageviewManager?.getCurrentPageviewId?this.pageviewManager.getCurrentPageviewId():null;return{projectId:this.projectId,sessionId:this.sessionId,anonymousId:b,environment:this.environment,sdkVersion:S.sdkVersion??"1.0.0",workspaceId:this.workspaceId,userId:this.userId,userEmail:this.userEmail,userName:I,release:S.release??null,sourceName:S.sourceName??null,url:"undefined"!=typeof window?window.location.href:null,pageviewId:x}}setPageviewManager(S){this.pageviewManager=S||null}getSessionInfo(){return{sessionId:this.sessionId,startTime:this.sessionStartTime,duration:Date.now()-this.sessionStartTime,workspaceId:this.workspaceId,projectId:this.projectId,environment:this.environment,userId:this.userId}}}const he={CHANNEL_NAME:"ts_session",HEARTBEAT_INTERVAL:5e3,TAB_TIMEOUT:1e4,AWAY_THRESHOLD:12e4};class TabCoordinator{constructor(S={}){this.tabId=`tab_${Date.now()}_${Math.random().toString(36).substr(2,6)}`,this.awayAt=null,this.lastHeartbeat=Date.now(),this.knownTabs=new Map,this.channel=null,this.heartbeatTimer=null,this.channelName=S.channelName||he.CHANNEL_NAME,this.heartbeatInterval=S.heartbeatInterval||he.HEARTBEAT_INTERVAL,this.tabTimeout=S.tabTimeout||he.TAB_TIMEOUT,this.awayThreshold=S.awayThreshold||he.AWAY_THRESHOLD,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onActivity=S.onActivity||(()=>{}),this.debug=S.debug||!1,this._initBroadcastChannel(),this._initVisibilityTracking(),this._startHeartbeat(),this.debug&&console.log(`[TabCoordinator] Initialized tab: ${this.tabId}`)}_initBroadcastChannel(){if("undefined"!=typeof BroadcastChannel)try{this.channel=new BroadcastChannel(this.channelName),this.channel.onmessage=S=>this._handleMessage(S.data),this._broadcast({type:"hb",tabId:this.tabId,timestamp:Date.now()}),this.debug&&console.log("[TabCoordinator] BroadcastChannel connected")}catch(S){console.warn("[TabCoordinator] Failed to create BroadcastChannel:",S)}else console.warn("[TabCoordinator] BroadcastChannel not supported - single-tab mode")}_initVisibilityTracking(){document.addEventListener("visibilitychange",()=>{document.hidden?this._markAway():this._markVisible()}),window.addEventListener("pagehide",()=>{this._markAway(),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt})}),window.addEventListener("beforeunload",()=>{this._markAway()})}_startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.lastHeartbeat=Date.now(),this._broadcast({type:"hb",tabId:this.tabId,timestamp:this.lastHeartbeat,awayAt:this.awayAt}),this._pruneDeadTabs(),this._checkAwayRule()},this.heartbeatInterval)}_broadcast(S){if(this.channel)try{this.channel.postMessage(S)}catch(S){this.debug&&console.warn("[TabCoordinator] Broadcast failed:",S)}}_handleMessage(S){if(S.tabId!==this.tabId)switch(S.type){case"hb":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt}),this.debug&&console.log(`[TabCoordinator] Heartbeat from ${S.tabId}, away: ${S.awayAt?"yes":"no"}`);break;case"activity":this.onActivity(S.timestamp);break;case"away":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:S.awayAt});break;case"visible":this.knownTabs.set(S.tabId,{lastSeen:S.timestamp,awayAt:null});break;case"new_session":this.debug&&console.log("[TabCoordinator] New session broadcast received")}}_markAway(){this.awayAt||(this.awayAt=Date.now(),this.debug&&console.log("[TabCoordinator] Tab marked AWAY"),this._broadcast({type:"away",tabId:this.tabId,timestamp:Date.now(),awayAt:this.awayAt}))}_markVisible(){if(this.awayAt){const S=Date.now()-this.awayAt;this.debug&&console.log(`[TabCoordinator] Tab back VISIBLE after ${Math.round(S/1e3)}s`),this.awayAt=null,this._broadcast({type:"visible",tabId:this.tabId,timestamp:Date.now()})}}_pruneDeadTabs(){const S=Date.now();for(const[b,I]of this.knownTabs.entries())S-I.lastSeen>this.tabTimeout&&(this.debug&&console.log(`[TabCoordinator] Pruning dead tab: ${b}`),this.knownTabs.delete(b))}_checkAwayRule(){const S=Date.now(),b=this.awayAt&&S-this.awayAt>this.awayThreshold;if(this.awayAt){for(const[b,I]of this.knownTabs.entries())if(!I.awayAt||S-I.awayAt<this.awayThreshold)return;b&&(console.log("[TabCoordinator] ALL tabs away >2min - session should end"),this.onSessionEnd("away_rule"))}}reportActivity(){const S=Date.now();this._broadcast({type:"activity",tabId:this.tabId,timestamp:S})}broadcastNewSession(S){this._broadcast({type:"new_session",tabId:this.tabId,sessionId:S,timestamp:Date.now()})}hasActiveTab(){if(!this.awayAt)return!0;for(const[S,b]of this.knownTabs.entries())if(!b.awayAt)return!0;return!1}getTabCount(){return this.knownTabs.size+1}getTabId(){return this.tabId}isAway(){return null!==this.awayAt}getAwayDuration(){return this.awayAt?Date.now()-this.awayAt:0}destroy(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.channel&&(this.channel.close(),this.channel=null),this.knownTabs.clear(),this.debug&&console.log(`[TabCoordinator] Destroyed tab: ${this.tabId}`)}}function uuidv4(){try{if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID()}catch{}const S=new Uint8Array(16);let b=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(S),b=!0)}catch{}if(!b)for(let b=0;b<16;b++)S[b]=Math.floor(256*Math.random());S[6]=15&S[6]|64,S[8]=63&S[8]|128;const I=Array.from(S,S=>S.toString(16).padStart(2,"0")).join("");return I.slice(0,8)+"-"+I.slice(8,12)+"-"+I.slice(12,16)+"-"+I.slice(16,20)+"-"+I.slice(20)}const de="__ts_aid";let ge=null;function readCookie(S){if("undefined"==typeof document||"string"!=typeof document.cookie)return null;const b=document.cookie.split("; ");for(const I of b){const b=I.indexOf("=");if(!(b<0)&&I.slice(0,b)===S)try{return decodeURIComponent(I.slice(b+1))}catch{return I.slice(b+1)}}return null}function peekAnonymousId(){const S=readCookie(de);return S||ge}function getOrCreateAnonymousId(){const S=peekAnonymousId();if(S)return S;const b=uuidv4();return function writeCookie(S,b,I){if("undefined"==typeof document)return!1;let x=`${S}=${encodeURIComponent(b)}; max-age=${I}; path=/; SameSite=Lax`;"undefined"!=typeof window&&window.location&&"https:"===window.location.protocol&&(x+="; Secure");try{document.cookie=x}catch{return!1}return readCookie(S)===b}(de,b,63072e3)||(ge=b),b}const pe={INACTIVITY_TIMEOUT:18e5,ACTIVITY_THROTTLE:1e3,MAX_SESSION_DURATION:144e5};class SessionManager{constructor(S={}){this.sessionIdCookie=S.sessionIdCookie||"__ts_sid",this.lastActivityCookie=S.lastActivityCookie||"__ts_ts",this.sessionStartCookie=S.sessionStartCookie||"__ts_start",this.storageKey=S.storageKey||"__tracescout_session_stats__",this.inactivityTimeout=S.inactivityTimeout||pe.INACTIVITY_TIMEOUT,this.maxSessionDuration=S.maxSessionDuration||pe.MAX_SESSION_DURATION,this.activityThrottle=S.activityThrottle||pe.ACTIVITY_THROTTLE,this.cookieDomain=S.cookieDomain||window.location.hostname,this.cookiePath=S.cookiePath||"/",this.cookieSameSite=S.cookieSameSite||"Lax",this.debug=S.debug||!1,this.onLifecycleEnd="function"==typeof S.onLifecycleEnd?S.onLifecycleEnd:null,this.currentSession=null,this._lastActivityUpdate=0,this._boundActivityHandler=this._handleActivity.bind(this),this._trackingStarted=!1,this.tabCoordinator=new TabCoordinator({onSessionEnd:S=>this._handleSessionEnd(S),onActivity:S=>this._handleRemoteActivity(S),debug:this.debug,awayThreshold:S.awayThreshold,heartbeatInterval:S.heartbeatInterval,tabTimeout:S.tabTimeout})}getOrCreateSession(S={}){const b=this._getStoredSession();if(b&&this._isSessionValid(b))return console.log("[SessionManager] ✅ Continuing session:",b.sessionId),console.log(" Duration:",Math.round((Date.now()-b.startTime)/1e3/60),"min"),console.log(" Pages so far:",b.pageCount),this.currentSession=b,this.currentSession.pageCount++,this._updateActivity(),this._startActivityTracking(),b.sessionId;const I=generateSessionId(),x=getOrCreateAnonymousId();this.currentSession={sessionId:I,anonymousId:x,startTime:Date.now(),lastActivityTime:Date.now(),pageCount:1,eventCount:0,chunkCount:0,lastChunkSequence:0,projectId:S.projectId,workspaceId:S.workspaceId,environment:S.environment,userId:S.userId||null,userEmail:null,userAttributes:{},lifecycle:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}},this._saveSession(),this._startActivityTracking();const R=b?.expiredReason||(b?"Previous session invalid":"No previous session found");return console.log("[SessionManager] 🆕 Created new session:",I),console.log(" Reason:",R),this.tabCoordinator.broadcastNewSession(I),I}_isSessionValid(S){if(!S?.sessionId)return!1;const b=Date.now(),I=b-(S.lastActivityTime||0),x=b-(S.startTime||0),R=this.tabCoordinator?.awayThreshold||12e4;return I>R?(console.log("[SessionManager] ⏰ Session expired: away rule (all tabs closed)"),console.log(" Away for:",Math.round(I/1e3),"seconds"),console.log(" Threshold:",Math.round(R/1e3),"seconds"),S.expiredReason="away_rule",!1):I>this.inactivityTimeout?(console.log("[SessionManager] ⏰ Session expired: inactivity"),console.log(" Inactive for:",Math.round(I/1e3/60),"min"),S.expiredReason="inactivity",!1):!(x>this.maxSessionDuration)||(console.log("[SessionManager] ⏰ Session expired: max duration"),console.log(" Duration:",Math.round(x/1e3/60),"min"),S.expiredReason="max_duration",!1)}_getStoredSession(){try{const S=this._getCookie(this.sessionIdCookie);if(!S)return null;const b=getOrCreateAnonymousId(),I=parseInt(this._getCookie(this.sessionStartCookie))||Date.now(),x=parseInt(this._getCookie(this.lastActivityCookie))||Date.now();let R={};try{const S=localStorage.getItem(this.storageKey);S&&(R=JSON.parse(S))}catch(S){console.warn("[SessionManager] Failed to load stats from localStorage:",S)}if(R.anonymousId&&R.anonymousId!==b)return console.log("[SessionManager] 🔄 Storage cleared detected (anonymousId mismatch)"),console.log(" Cookie anonymousId:",b),console.log(" localStorage anonymousId:",R.anonymousId),this._clearSession(),null;if("number"==typeof R.schemaVersion&&5!==R.schemaVersion)return console.log("[SessionManager] 🔄 Stats schemaVersion mismatch — dropping cached session"),console.log(" cached schemaVersion:",R.schemaVersion),console.log(" required schemaVersion: 5"),this._clearSession(),null;return{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x,pageCount:R.pageCount||1,eventCount:R.eventCount||0,chunkCount:R.chunkCount||0,lastChunkSequence:R.lastChunkSequence||0,projectId:R.projectId,workspaceId:R.workspaceId,environment:R.environment,userId:R.userId,userEmail:R.userEmail,userAttributes:R.userAttributes||{},lifecycle:R.lifecycle&&"object"==typeof R.lifecycle?{sessionStartEmitted:!0===R.lifecycle.sessionStartEmitted,sessionEndEmitted:!0===R.lifecycle.sessionEndEmitted,startedAt:"number"==typeof R.lifecycle.startedAt?R.lifecycle.startedAt:null,endedAt:"number"==typeof R.lifecycle.endedAt?R.lifecycle.endedAt:null,endReason:"string"==typeof R.lifecycle.endReason?R.lifecycle.endReason:null}:{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}}}catch(S){return console.warn("[SessionManager] Failed to load stored session:",S),this._clearSession(),null}}_saveSession(){if(this.currentSession)try{const{sessionId:S,anonymousId:b,startTime:I,lastActivityTime:x}=this.currentSession,R=this.maxSessionDuration;this._setCookie(this.sessionIdCookie,S,R),this._setCookie(this.sessionStartCookie,I.toString(),R),this._setCookie(this.lastActivityCookie,x.toString(),R);const A={schemaVersion:5,anonymousId:b,pageCount:this.currentSession.pageCount,eventCount:this.currentSession.eventCount,chunkCount:this.currentSession.chunkCount,lastChunkSequence:this.currentSession.lastChunkSequence,projectId:this.currentSession.projectId,workspaceId:this.currentSession.workspaceId,environment:this.currentSession.environment,userId:this.currentSession.userId,userEmail:this.currentSession.userEmail,userAttributes:this.currentSession.userAttributes||{},lifecycle:this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null}};localStorage.setItem(this.storageKey,JSON.stringify(A))}catch(S){console.warn("[SessionManager] Failed to save session:",S)}}_handleActivity(){const S=Date.now();S-this._lastActivityUpdate<this.activityThrottle||(this._lastActivityUpdate=S,this._updateActivity(),this.tabCoordinator.reportActivity())}_handleRemoteActivity(S){this.currentSession&&(this.currentSession.lastActivityTime=S,this._setCookie(this.lastActivityCookie,S.toString(),this.maxSessionDuration))}_updateActivity(){this.currentSession&&(this.currentSession.lastActivityTime=Date.now(),this._saveSession())}_startActivityTracking(){if(this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.addEventListener(S,this._boundActivityHandler,{passive:!0})}),this._trackingStarted=!0,this.debug&&console.log("[SessionManager] ✅ Activity tracking started (mousemove/click/scroll)")}_stopActivityTracking(){if(!this._trackingStarted)return;["mousemove","click","scroll"].forEach(S=>{window.removeEventListener(S,this._boundActivityHandler)}),this._trackingStarted=!1}_handleSessionEnd(S){if(console.log("[SessionManager] 🛑 Session ended by TabCoordinator:",S),"away_rule"===S&&"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"allTabsClosed"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}}getLifecycleGuard(){if(!this.currentSession)return null;const S=this.currentSession.lifecycle;return S&&"object"==typeof S?{sessionStartEmitted:!0===S.sessionStartEmitted,sessionEndEmitted:!0===S.sessionEndEmitted,startedAt:"number"==typeof S.startedAt?S.startedAt:null,endedAt:"number"==typeof S.endedAt?S.endedAt:null,endReason:"string"==typeof S.endReason?S.endReason:null}:null}setLifecycleGuard(S){if(!this.currentSession)return;if(!S||"object"!=typeof S)return;const b=this.currentSession.lifecycle||{sessionStartEmitted:!1,sessionEndEmitted:!1,startedAt:null,endedAt:null,endReason:null};!0===S.sessionStartEmitted&&(b.sessionStartEmitted=!0),!0===S.sessionEndEmitted&&(b.sessionEndEmitted=!0),"number"==typeof S.startedAt&&(b.startedAt=S.startedAt),"number"==typeof S.endedAt&&(b.endedAt=S.endedAt),"string"==typeof S.endReason&&(b.endReason=S.endReason),this.currentSession.lifecycle=b,this._saveSession()}_getCookie(S){return document.cookie.split("; ").reduce((S,b)=>{const[I,x]=b.split("=");return I&&(S[I]=decodeURIComponent(x||"")),S},{})[S]||null}_setCookie(S,b,I){const x=Math.floor(I/1e3);let R=`${S}=${encodeURIComponent(b)}`;R+=`; max-age=${x}`,R+=`; path=${this.cookiePath}`,R+=`; SameSite=${this.cookieSameSite}`,"undefined"!=typeof window&&"https:"===window.location.protocol&&(R+="; Secure"),this.cookieDomain&&!this.cookieDomain.includes("localhost")&&(R+=`; domain=${this.cookieDomain}`),document.cookie=R}_deleteCookie(S){document.cookie=`${S}=; max-age=0; path=${this.cookiePath}`}_clearSession(){this._deleteCookie(this.sessionIdCookie),this._deleteCookie(this.lastActivityCookie),this._deleteCookie(this.sessionStartCookie);try{localStorage.removeItem(this.storageKey)}catch(S){console.warn("[SessionManager] Failed to clear localStorage:",S)}}getSessionInfo(){if(!this.currentSession)return null;const S=Date.now(),b=S-this.currentSession.startTime,I=S-this.currentSession.lastActivityTime;return{...this.currentSession,duration:b,durationMinutes:Math.round(b/1e3/60),timeSinceActivity:I,timeSinceActivityMinutes:Math.round(I/1e3/60),isValid:this._isSessionValid(this.currentSession),willExpireIn:this.inactivityTimeout-I,willExpireInMinutes:Math.round((this.inactivityTimeout-I)/1e3/60),tabCount:this.tabCoordinator.getTabCount(),tabId:this.tabCoordinator.getTabId(),isAway:this.tabCoordinator.isAway()}}incrementEventCount(S=1){this.currentSession&&(this.currentSession.eventCount+=S,this._updateActivity())}incrementPageCount(){this.currentSession&&(this.currentSession.pageCount++,this._updateActivity(),this.debug&&console.log("[SessionManager] 📄 Page navigation, count:",this.currentSession.pageCount))}incrementChunkCount(){this.currentSession&&(this.currentSession.chunkCount++,this._saveSession())}updateLastChunkSequence(S){this.currentSession&&(this.currentSession.lastChunkSequence=S,this._saveSession(),this.debug&&console.log(`[SessionManager] Updated lastChunkSequence to ${S}`))}getLastChunkSequence(){return this.currentSession?.lastChunkSequence||0}getResumeInfo(){const S=this._getStoredSession();return S&&this._isSessionValid(S)&&(S.pageCount||1)>1?{sessionId:S.sessionId,lastChunkSequence:S.lastChunkSequence||0,lastActivityTime:S.lastActivityTime,isResumed:!0,pageCount:S.pageCount||1,eventCount:S.eventCount||0,chunkCount:S.chunkCount||0}:{sessionId:null,lastChunkSequence:0,lastActivityTime:null,isResumed:!1,pageCount:0,eventCount:0,chunkCount:0}}isResumedSession(){return!!this.currentSession&&(this.currentSession.pageCount||1)>1}updateUser(S,b){this.updateUserMetadata(S,{email:b})}updateUserMetadata(S,b={}){this.currentSession&&(this.currentSession.userId=S,this.currentSession.userEmail=b.email||this.currentSession.userEmail,this.currentSession.userAttributes=b,this._saveSession(),console.log("[SessionManager] 👤 User metadata updated"))}clearUserMetadata(){this.currentSession&&(this.currentSession.userId=null,this.currentSession.userEmail=null,this.currentSession.userAttributes={},this._saveSession(),console.log("[SessionManager] 👤 User metadata cleared"))}endSession(){if(!this.currentSession)return;const S=Date.now()-this.currentSession.startTime;if(console.log("[SessionManager] 🛑 Ending session:",this.currentSession.sessionId),console.log(" Duration:",Math.round(S/1e3),"s"),console.log(" Events:",this.currentSession.eventCount),console.log(" Pages:",this.currentSession.pageCount),console.log(" Chunks:",this.currentSession.chunkCount),"function"==typeof this.onLifecycleEnd)try{this.onLifecycleEnd({reason:"manual"})}catch(S){console.warn("[SessionManager] onLifecycleEnd threw:",S)}this._stopActivityTracking(),this._clearSession(),this.currentSession=null}forceNewSession(S="manual"){console.log("[SessionManager] 🔄 Force new session, reason:",S),this.currentSession&&console.log(" Ending:",this.currentSession.sessionId),this.endSession()}destroy(){this._stopActivityTracking(),this.tabCoordinator.destroy()}}class EventManager{constructor(S={},b={}){this.config=S,this.storageKeys=b,this.logger=new Logger("[EventManager]",S.debug),this.eventQueue=[],this.eventOccurrenceTracker=new Map,this.debouncedSave=debounce(this.saveToLocal.bind(this),100),this._cleanupInterval=null,this._startCleanupTimer()}_startCleanupTimer(){const S=this.config.memoryCleanupIntervalMs||6e4;this._cleanupInterval=setInterval(()=>{this._cleanupOccurrenceTracker()},S)}_stopCleanupTimer(){this._cleanupInterval&&(clearInterval(this._cleanupInterval),this._cleanupInterval=null)}_cleanupOccurrenceTracker(){const S=Date.now(),b=this.config.deduplicationWindowMs||6e4,I=this.config.maxOccurrenceTrackerSize||5e3;let x=0;for(const[I,R]of this.eventOccurrenceTracker.entries())S-R>b&&(this.eventOccurrenceTracker.delete(I),x++);if(this.eventOccurrenceTracker.size>I){const S=Array.from(this.eventOccurrenceTracker.entries()).sort((S,b)=>b[1]-S[1]);this.eventOccurrenceTracker.clear();const b=S.slice(0,I);for(const[S,I]of b)this.eventOccurrenceTracker.set(S,I);const R=S.length-I;this.config.debug&&this.logger.log(`[Memory] Force-cleaned ${R} entries (exceeded max size ${I})`),x+=R}x>0&&this.config.debug&&this.logger.log(`[Memory] Cleaned up ${x} stale entries from occurrence tracker (size: ${this.eventOccurrenceTracker.size})`)}destroy(){this._stopCleanupTimer(),this.eventOccurrenceTracker.clear(),this.eventQueue=[]}addEvent(S){try{return!!this.shouldLogEvent(S)&&(!!this.deduplicateEvent(S)&&(this.eventQueue.length>=this.config.maxQueueSize&&(this.eventQueue.shift(),this.logger.warn("Queue size limit reached, removing oldest event")),this.eventQueue.push(S),this.debouncedSave(),this.logger.log("Event added:",S.type),!0))}catch(S){return this.logger.error("Failed to add event:",S),!1}}getEvents(){try{return R.sortBy(R.cloneDeep(this.eventQueue),"timestamp")}catch(S){return this.logger.error("Failed to get events:",S),[]}}removeEvents(S){try{const b=new Set(S);this.eventQueue=R.filter(this.eventQueue,S=>!b.has(S.id)),this.debouncedSave()}catch(S){this.logger.error("Failed to remove events:",S)}}clearEvents(){try{this.eventQueue.length=0,this.eventOccurrenceTracker.clear(),this.clearLocal(),this.logger.log("All events cleared")}catch(S){this.logger.error("Failed to clear events:",S)}}getQueueSize(){return this.eventQueue.length}shouldLogEvent(S){try{const b=S.context?.isMonitored,I=S.context?.forceLog;if(!(b||I))return!1;return!(this.config.ignoreEventTypes||[]).includes(S.type)}catch(S){return this.logger.error("Error in shouldLogEvent:",S),!1}}deduplicateEvent(S){try{const b=this.generateDedupeKey(S),I=Date.now(),x=this.eventOccurrenceTracker.get(b);return!(x&&I-x<this.config.deduplicationWindowMs)&&(this.eventOccurrenceTracker.set(b,I),!0)}catch(S){return this.logger.error("Error in deduplicateEvent:",S),!0}}generateDedupeKey(S){try{return`${S.type}_${S.context?.url||"unknown"}_${S.context?.method||"unknown"}`}catch(b){return this.logger.error("Error generating dedupe key:",b),`${S.type}_${Date.now()}`}}saveToLocal(){try{const S={events:this.eventQueue,timestamp:Date.now()};b.set(this.storageKeys.EVENTS||"__api_reporter_events__",S)}catch(S){this.logger.error("Failed to save events to local storage:",S)}}loadFromLocal(){try{const S=b.get(this.storageKeys.EVENTS||"__api_reporter_events__");S&&S.events&&(this.eventQueue=S.events,this.logger.log(`Loaded ${this.eventQueue.length} events from local storage`))}catch(S){this.logger.error("Failed to load events from local storage:",S)}}clearLocal(){try{b.remove(this.storageKeys.EVENTS||"__api_reporter_events__")}catch(S){this.logger.error("Failed to clear local storage:",S)}}getEventById(S){try{return this.eventQueue.find(b=>b.id===S)}catch(S){return this.logger.error("Failed to get event by ID:",S),null}}getEventsByType(S){try{return this.eventQueue.filter(b=>b.type===S)}catch(S){return this.logger.error("Failed to get events by type:",S),[]}}getEventsByTimeRange(S,b){try{return this.eventQueue.filter(I=>{const x=I.timestamp;return x>=S&&x<=b})}catch(S){return this.logger.error("Failed to get events by time range:",S),[]}}getEventStats(){try{const S={total:this.eventQueue.length,byType:{},byStatus:{}};return this.eventQueue.forEach(b=>{S.byType[b.type]=(S.byType[b.type]||0)+1;const I=b.context?.status||"unknown";S.byStatus[I]=(S.byStatus[I]||0)+1}),S}catch(S){return this.logger.error("Failed to get event stats:",S),{total:0,byType:{},byStatus:{}}}}cleanupOldEvents(S=864e5){try{const b=Date.now()-S,I=this.eventQueue.length;this.eventQueue=this.eventQueue.filter(S=>S.timestamp>b);const x=I-this.eventQueue.length;x>0&&(this.logger.log(`Cleaned up ${x} old events`),this.debouncedSave())}catch(S){this.logger.error("Failed to cleanup old events:",S)}}}class ServiceManager{constructor(S={},b=null){this.config=S,this.logger=b||new Logger("[ServiceManager]",S.debug),this.service=null,this.isSending=!1,this.retryCount=0,this.maxRetries=R.get(S,"maxRetries",3),this.initializeService()}initializeService(){if(!R.get(this.config,"service"))throw new Error("Service configuration is required");this.setService(R.get(this.config,"service"),R.get(this.config,"serviceOptions",{}))}setService(S,b={}){if(!R.isObject(S)||!R.isFunction(R.get(S,"send")))throw new Error("Invalid service: must be an object with send() method");this.service=S,this.logger.log(`Service initialized: ${this.getServiceName()}`)}async sendEvents(S){if(this.isSending||R.isEmpty(S)||!this.service)return this.logger.warn("Cannot send events:",{isSending:this.isSending,isEmpty:R.isEmpty(S),noService:!this.service}),R.map(S||[],S=>({event:S,success:!1,error:new Error("Service unavailable")}));this.isSending=!0;try{const b=[];for(const I of S)try{await this.sendSingleEvent(I),b.push({event:I,success:!0}),this.logger.log(`Event sent successfully: ${I.type}`)}catch(S){this.logger.error(`Event failed: ${I.type}`,S),b.push({event:I,success:!1,error:S})}return this.retryCount=0,b}catch(b){return this.logger.error("Failed to send events:",b),this.retryCount++,R.map(S,S=>({event:S,success:!1,error:b}))}finally{this.isSending=!1}}async sendSingleEvent(S){let b;for(let I=1;I<=this.maxRetries;I++)try{return void await this.service.send(S)}catch(x){b=x,this.logger.warn(`Attempt ${I}/${this.maxRetries} failed for event ${S.id}:`,x.message),I<this.maxRetries&&await this.delay(this.getRetryDelay(I))}throw b}getRetryDelay(S){return Math.min(1e3*Math.pow(2,S-1),3e4)}async delay(S){return new Promise(b=>setTimeout(b,S))}getServiceName(){return R.isString(this.config.service)?this.config.service:this.service.constructor.name}isServiceAvailable(){return null!==this.service}getServiceStatus(){return{available:this.isServiceAvailable(),name:this.getServiceName(),isSending:this.isSending,retryCount:this.retryCount}}resetRetryCount(){this.retryCount=0}destroy(){this.service=null,this.isSending=!1,this.retryCount=0}}class UserProfileManager{constructor(S,b=[],I=!1){this.storageKey=S,this.fieldsToExtract=b,this.logger=new Logger("[UserProfileManager]",I)}getProfile(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.warn("Failed to read user profile:",S),{}}}setProfile(S={}){if(!R.isObject(S))return this.logger.warn("Invalid profile object provided"),!1;try{const b=this.getProfile(),I=R.merge(b,S);return localStorage.setItem(this.storageKey,JSON.stringify(I)),this.logger.log("User profile updated:",I),!0}catch(S){return"QuotaExceededError"===S.name?this.logger.warn("Storage quota exceeded for user profile"):this.logger.error("Failed to save user profile:",S),!1}}ensureProfile(){try{const S=this.getProfile();if(R.isEmpty(R.get(S,"uniqId"))){const b=R.merge(S,{uniqId:generateId(),createdAt:(new Date).toISOString()});this.setProfile(b),this.logger.log("Generated new user profile:",R.get(b,"uniqId"))}}catch(S){this.logger.error("Failed to ensure user profile:",S)}}extractContextFromData({data:S,source:b="response",url:I=""}){const x={};try{if(!R.isObject(S)||!R.isArray(this.fieldsToExtract))return x;const A=R.toLower(I);return this.fieldsToExtract.forEach(_=>{try{const D=R.toLower(R.get(_,"api","")),L=R.get(_,"source",""),B="*"===D||A.includes(D);if(!B||!("*"===L||L===b))return;const U=R.get(_,"fields",[]);R.isArray(U)?U.forEach(R=>{try{this.recursiveFieldMatch({context:x,matchRule:R,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with pattern "${R}":`,S)}}):R.isObject(U)&&R.entries(U).forEach(([R,A])=>{try{this.recursiveFieldMatchWithMapping({context:x,newKey:R,matchRule:A,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with mapping "${R}": "${A}":`,S)}})}catch(S){this.logger.warn("Failed to process extraction rule:",S)}}),x}catch(S){return this.logger.error("Failed to extract context from data:",S),x}}updateFromContext({url:S,source:b,data:I}){try{const x=this.extractContextFromData({url:S,source:b,data:I});if(Object.keys(x).length>0){const S=this.getProfile(),b={...S,...x};if(JSON.stringify(S)!==JSON.stringify(b))return this.setProfile(b),!0}return!1}catch(S){return this.logger.warn("Failed to update user profile context:",S),!1}}recursiveFieldMatch({context:S,matchRule:b,data:I,source:x,url:A}){try{if(!R.isObject(I))return;if(R.isString(b)){const x=R.get(I,b);if(void 0!==x)return S[b]=x,void this.logger.log(`Found field by path: ${b} = ${JSON.stringify(x)}`);const A=R.find(R.entries(I),([S])=>R.toLower(S)===R.toLower(b));if(A){const[b,I]=A;return S[b]=I,void this.logger.log(`Found field by name: ${b} = ${JSON.stringify(I)}`)}}if(b instanceof RegExp){const x=R.find(R.entries(I),([S,I])=>R.isString(I)&&b.test(I));if(x){const[b,I]=x;return S[b]=I,void this.logger.log(`Found field by value pattern: ${b} = ${I}`)}}R.values(I).forEach(I=>{R.isObject(I)&&!R.isNull(I)&&this.recursiveFieldMatch({context:S,matchRule:b,data:I,source:x,url:A})})}catch(S){this.logger.warn("Error in recursive field matching:",S)}}recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:x,source:A,url:_}){try{if(!R.isObject(x))return;if(R.isString(I)){const A=R.get(x,I);if(void 0!==A)return S[b]=A,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(A)}`);const _=R.find(R.entries(x),([S])=>R.toLower(S)===R.toLower(I));if(_){const[I,x]=_;return S[b]=x,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(x)}`)}}if(I instanceof RegExp){const A=R.find(R.entries(x),([S,b])=>R.isString(b)&&I.test(b));if(A){const[I,x]=A;return S[b]=x,void this.logger.log(`Found field by pattern with mapping: ${I} -> ${b} = ${x}`)}}R.values(x).forEach(x=>{R.isObject(x)&&!R.isNull(x)&&this.recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:x,source:A,url:_})})}catch(S){this.logger.warn("Error in recursive field matching with mapping:",S)}}validateFieldValue(S,b){try{if(R.isString(b)){const I=R.get(DEFAULT_FIELD_PATTERNS,b);return I&&I.test(S)}if(R.isFunction(b))return b(S);if(R.isObject(b)){const{type:I,min:x,max:R,pattern:A}=b;return(!I||typeof S===I)&&(!(void 0!==x&&S<x)&&(!(void 0!==R&&S>R)&&!(A&&!A.test(S))))}return!0}catch(S){return this.logger.warn("Validation error:",S),!1}}transformFieldValue(S,b){try{if(R.isFunction(b))return b(S);if(R.isString(b))switch(b){case"toLowerCase":return R.toLower(S);case"toUpperCase":return R.toUpper(S);case"trim":return R.trim(S);case"toString":return String(S);case"toNumber":return Number(S);default:return S}return S}catch(b){return this.logger.warn("Transform error:",b),S}}clearProfile(){try{return localStorage.removeItem(this.storageKey),this.logger.log("User profile cleared"),!0}catch(S){return this.logger.error("Failed to clear user profile:",S),!1}}getProfileField(S){try{const b=this.getProfile();return R.get(b,S)}catch(S){return void this.logger.error("Failed to get profile field:",S)}}setProfileField(S,b){try{const I=this.getProfile();return I[S]=b,this.setProfile(I)}catch(S){return this.logger.error("Failed to set profile field:",S),!1}}hasProfile(){try{const S=this.getProfile();return!R.isEmpty(S)}catch(S){return this.logger.error("Failed to check profile existence:",S),!1}}getProfileSize(){try{const S=this.getProfile();return Object.keys(S).length}catch(S){return this.logger.error("Failed to get profile size:",S),0}}}class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=new Logger("[PerformanceMonitor]",this.debug),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function resolveApiBaseUrl(S={}){if(S&&"string"==typeof S.apiBaseUrl&&S.apiBaseUrl)return S.apiBaseUrl;if(S&&"string"==typeof S.backendUrl&&S.backendUrl)return S.backendUrl;if("undefined"!=typeof window&&window.location&&window.location.hostname){const S=window.location.hostname;if("localhost"===S||"127.0.0.1"===S)return"http://localhost:3001"}return"https://api.tracescout.com"}const fe=["/chunks","/logs/batch","/telemetry","/sdk-config"];function isInternalSdkEndpoint(S){if("string"!=typeof S||!S)return!1;if(!S.includes("/api/"))return!1;for(const b of fe)if(S.includes(b)){if(S.includes("/api/projects/")||S.includes("/api/sdk-config"))return!0;if("/sdk-config"===b&&S.includes("/sdk-config"))return!0}return!1}class InitializationPipeline{#o=null;#a=null;constructor(S){this.#o=S}async run(S){this.#a=S;try{this.#l();const S=this.#c(),b=this.#u(S),I=this.#h(b),x=this.#d(I,b);x&&(I.service=x);const R=this.#g(I);return{success:!0,sessionManager:S,sdkContext:b,remoteConfigService:null,serverConfig:this.#p(),config:I,managers:R}}catch(S){throw this.#o?.error("Initialization pipeline failed:",S),S}}#l(){const S=this.#a;if(!R.isObject(S))throw new Error("InitializationPipeline.run(options): options must be an object");if(!S.projectId)throw new Error("InitializationPipeline.run(options): projectId missing");S.debug&&console.log("[TraceScout] ✓ Required fields validated")}#c(){const S=this.#a;S.debug&&console.log("[TraceScout] 📅 Initializing session manager...");const b=new SessionManager({inactivityTimeout:18e5,maxSessionDuration:144e5,activityThrottle:1e3,awayThreshold:12e4,heartbeatInterval:5e3,tabTimeout:1e4,debug:S.debug||!1}),I=b.getOrCreateSession({projectId:S.projectId,environment:S.environment});return S.debug&&console.log("[TraceScout] ✓ Session manager initialized"),{sessionManager:b,sessionId:I}}#u(S){const b=this.#a,{sessionManager:I,sessionId:x}=S;try{const S=SDKContext.initialize({projectId:b.projectId,environment:b.environment||"production",userId:void 0,sessionId:x,sessionManager:I});if(I&&I.currentSession){const x=I.currentSession;x.userId&&x.userAttributes&&(S.setUser(x.userId,x.userAttributes),b.debug&&console.log("[TraceScout] ✓ Restored user metadata from session"))}return b.debug&&(console.log("[TraceScout] ✓ SDK Context initialized"),console.log(` Session ID: ${S.sessionId}`),console.log(` Project: ${S.projectId}`),console.log(` Environment: ${S.environment}`)),S}catch(S){throw console.error("[TraceScout] ❌ Failed to initialize SDKContext:",S),S}}#h(S){const b=this.#a,I={projectId:S.projectId,environment:S.environment,release:b.release,sourceName:b.sourceName,debug:b.debug||!1,apiBaseUrl:resolveApiBaseUrl(b),sampleRate:1,sessionChunkDuration:3e4,sessionMaxChunkSize:5e5,privacy:{maskAllInputs:!1,maskTextClass:"ts-mask",blockClass:"ts-block",ignoreClass:"ts-ignore",blockSelectors:[],maskImages:!1},network:(x=b.network,{isEnabled:!0,captureRequestHeaders:!0,captureResponseHeaders:!0,captureRequestBody:!0,captureResponseBody:!0,excludeEndpoints:[],maxBodyBytes:10240,requestSanitizer:null,responseSanitizer:null,sensitiveFields:[],...x&&"object"==typeof x&&!Array.isArray(x)?x:{}})};var x;return b.debug&&console.log("[TraceScout] ✓ Configuration built (SDK defaults)"),I}#p(){return{workspace:{name:"Unknown",id:null},project:{name:"Unknown"},configVersion:"sdk-defaults",features:{sessionRecording:{enabled:!0,sampleRate:1,captureNetwork:!0,captureConsole:!0,captureErrors:!0,networkSettings:{captureHeaders:!0,captureRequestBody:!0,captureResponseBody:!0},chunkDuration:3e4,maxChunkSize:5e5,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},performanceMonitoring:{enabled:!0,coreWebVitals:!0},logging:{enabled:!0,captureConsole:!0,minLevel:"debug",maxBufferSize:1e3,flushInterval:5e3,sampleRate:1}},telemetry:{}}}#d(S,b){const I=`${resolveApiBaseUrl(S)}/api/projects/${b.projectId}/telemetry`;return{send:async S=>{const x=Array.isArray(S)?S:[S];try{const S=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:x,context:{projectId:b.projectId,sessionId:b.sessionId,environment:b.environment}})});if(!S.ok)throw new Error(`Telemetry send failed: ${S.status}`);return await S.json()}catch(S){throw console.error("[TraceScout][TelemetryService] Send failed:",S),S}}}}#g(S){const b=new EventManager(S),I=new ServiceManager(S,this.#o),x=new UserProfileManager(S),R=new PerformanceMonitor(S);return S.debug&&console.log("[TraceScout] ✓ Core managers initialized"),{eventManager:b,serviceManager:I,userProfileManager:x,performanceMonitor:R}}}var me={environment:{type:"string",minLength:1,maxLength:64,default:"production"},release:{type:"string",minLength:1,maxLength:255},debug:{type:"boolean",default:!1},sourceName:{type:"string",minLength:1,maxLength:100,pattern:"^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$",default:"web-client",description:"S-2d.2 (step B): optional browser-source attribution. Defaults to 'web-client' when omitted. Emitted on every SDK v1 common envelope as `sourceName`. Pattern matches the API's envelope.schema.json SOURCE_NAME_PATTERN union. NOT named `source` to avoid collision with the existing js_error leaf `source` field (stack-frame URL, up to 2048 chars)."}};const ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ve=new Set(["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody","maxBodyBytes","excludeEndpoints","requestSanitizer","responseSanitizer","sensitiveFields"]),Se=["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody"];const we=/^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$/,be=new Set(Object.keys(me));function validateConfig(S,b){if(null!==S&&"object"==typeof S&&!Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_FIRST_ARG"};if(null==S||""===S||"string"!=typeof S)return{ok:!1,code:"CONFIG_PROJECT_ID_REQUIRED"};if(!ye.test(S))return{ok:!1,code:"CONFIG_PROJECT_ID_INVALID"};const I=b??{};if("object"!=typeof I||Array.isArray(I)||null===I)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:["(options must be a plain object)"]};const x=[];for(const S of Object.keys(I))"network"!==S&&(be.has(S)||x.push(S));if(x.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:x};if(void 0!==I.network){const S=function validateNetworkOptions(S){if("object"!=typeof S||null===S||Array.isArray(S))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["(network must be a plain object)"]};const b=[];for(const I of Object.keys(S))ve.has(I)||b.push(`network.${I}`);if(b.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:b};for(const b of Se)if(void 0!==S[b]&&"boolean"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};if(void 0!==S.maxBodyBytes){const b=S.maxBodyBytes;if("number"!=typeof b||!Number.isFinite(b)||b<0)return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.maxBodyBytes"]}}if(void 0!==S.excludeEndpoints){if(!Array.isArray(S.excludeEndpoints))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]};for(const b of S.excludeEndpoints)if("string"!=typeof b&&!(b instanceof RegExp))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.excludeEndpoints"]}}if(void 0!==S.sensitiveFields&&(!Array.isArray(S.sensitiveFields)||S.sensitiveFields.some(S=>"string"!=typeof S)))return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:["network.sensitiveFields"]};for(const b of["requestSanitizer","responseSanitizer"])if(void 0!==S[b]&&"function"!=typeof S[b])return{ok:!1,code:"CONFIG_INVALID_NETWORK",keys:[`network.${b}`]};return{ok:!0}}(I.network);if(!S.ok)return S}return void 0!==I.sourceName&&("string"!=typeof I.sourceName||I.sourceName.length<1||I.sourceName.length>100||!we.test(I.sourceName))?{ok:!1,code:"CONFIG_INVALID_SOURCE_NAME"}:{ok:!0,projectId:S,options:I}}function shouldSampleSession(S,b={}){const I=b.anonymousId??null,x=b.randomFn??Math.random;return null==S||"number"!=typeof S||(!!Number.isNaN(S)||(S>=1||!(S<=0)&&("string"==typeof I&&I.length>0?function hashToUnitInterval(S){let b=2166136261;for(let I=0;I<S.length;I++)b^=S.charCodeAt(I),b=Math.imul(b,16777619);return(b>>>0)/4294967296}(I)<S:x()<S)))}const Ce="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ulid(S=Date.now()){return function encodeTimestamp(S){let b="",I=S;for(let S=9;S>=0;S--)b=Ce[I%32]+b,I=Math.floor(I/32);return b}(S)+function encodeRandom(){let S="";const b=new Uint8Array(10);let I=!1;try{"undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&(crypto.getRandomValues(b),I=!0)}catch{}if(!I)for(let S=0;S<b.length;S++)b[S]=Math.floor(256*Math.random());let x=0,R=0;for(let I=0;I<b.length;I++)for(x=x<<8|b[I],R+=8;R>=5;)R-=5,S+=Ce[x>>R&31];return S}()}const ke=Object.freeze(["session_start","session_end","replay_chunk","page_view","route_change","network_request","console_event","js_error","performance_metric","custom_event","user_identified"]),Ie=new Set(ke);function wrapInEnvelope(S,b,I){if(!Ie.has(S))throw new Error(`wrapInEnvelope: unknown eventType "${S}"`);if(null===I||"object"!=typeof I)throw new Error("wrapInEnvelope: context is required");const x={eventId:ulid(),eventType:S,timestamp:Date.now(),contractVersion:"1.0.0",projectId:I.projectId,sessionId:I.sessionId,anonymousId:I.anonymousId,environment:I.environment,sdkVersion:I.sdkVersion};return isNonEmptyString$3(I.workspaceId)&&(x.workspaceId=I.workspaceId),isNonEmptyString$3(I.userId)&&(x.userId=I.userId),isNonEmptyString$3(I.userEmail)&&(x.userEmail=I.userEmail),isNonEmptyString$3(I.userName)&&(x.userName=I.userName),isNonEmptyString$3(I.release)&&(x.release=I.release),isNonEmptyString$3(I.sourceName)&&(x.sourceName=I.sourceName),isNonEmptyString$3(I.pageviewId)&&(x.pageviewId=I.pageviewId),isNonEmptyString$3(I.url)&&(x.url=I.url),isNonEmptyString$3(I.traceId)&&(x.traceId=I.traceId),isNonEmptyString$3(I.spanId)&&(x.spanId=I.spanId),{...x,...b}}function isNonEmptyString$3(S){return"string"==typeof S&&S.length>0}function mapInternalEndReason(S){switch(S){case"max_inactivity":case"inactivity":return"inactivity";case"max_duration":case"maxDuration":return"maxDuration";case"away_rule":case"allTabsClosed":return"allTabsClosed";case"manual":return"manual";default:return null}}function detectDeviceType$1(S){const b=(S&&"string"==typeof S.userAgent?S.userAgent:"")||("undefined"!=typeof navigator&&navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"");return b?/iPad|Tablet|PlayBook|Silk/i.test(b)||/Android/i.test(b)&&!/Mobile/i.test(b)?"tablet":/Mobi|iPhone|iPod|Android/i.test(b)?"mobile":"desktop":"desktop"}function buildDeviceField(){const S="undefined"!=typeof navigator?navigator:{},b="undefined"!=typeof window?window:{},I=b.screen||{};let x="UTC";try{x=Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch(S){}return{type:detectDeviceType$1(S),userAgent:"string"==typeof S.userAgent?S.userAgent:"",platform:"string"==typeof S.platform?S.platform:"",language:"string"==typeof S.language?S.language:"",timezone:x,viewport:{width:"number"==typeof b.innerWidth?b.innerWidth:0,height:"number"==typeof b.innerHeight?b.innerHeight:0},screen:{width:"number"==typeof I.width?I.width:0,height:"number"==typeof I.height?I.height:0,colorDepth:"number"==typeof I.colorDepth?I.colorDepth:0}}}function isNonEmptyString$2(S){return"string"==typeof S&&S.length>0}class SessionLifecycleEmitter{#f=!1;#m=!1;#y;#v;#S;#w;#b;#C;constructor(S){if(!S||"object"!=typeof S)throw new Error("SessionLifecycleEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("SessionLifecycleEmitter: addCustomEvent callback is required");if("function"!=typeof S.getContext)throw new Error("SessionLifecycleEmitter: getContext callback is required");if("function"!=typeof S.readGuard||"function"!=typeof S.writeGuard)throw new Error("SessionLifecycleEmitter: readGuard/writeGuard callbacks are required");this.#v=S.addCustomEvent,this.#C=S.getContext,this.#S=S.readGuard,this.#w=S.writeGuard,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{}}emitStart(S={}){if(this.#f)return!1;let b=null;try{b=this.#S()}catch(S){b=null}if(b&&!0===b.sessionStartEmitted)return this.#f=!0,!1;b||this.#b("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const I=this.#C(),x="undefined"!=typeof window?window:{},R="undefined"!=typeof document?document:{},A=isNonEmptyString$2(S.landingUrl)?S.landingUrl:"string"==typeof x.location?.href?x.location.href:"";if(!isNonEmptyString$2(A))return this.#b("[SDK lifecycle] session_start skipped — landingUrl unavailable"),!1;const _={device:buildDeviceField(),landingUrl:A},D=void 0!==S.referrer?S.referrer:"string"==typeof R.referrer?R.referrer:"";isNonEmptyString$2(D)&&(_.referrer=D);const L=void 0!==S.landingTitle?S.landingTitle:"string"==typeof R.title?R.title:"";let B;isNonEmptyString$2(L)&&(_.landingTitle=L),function isPlainObjectWithKeys(S){if(!S||"object"!=typeof S)return!1;for(const b in S)return!0;return!1}(S.userTraits)&&(_.userTraits=S.userTraits);try{B=this.#y("session_start",_,I)}catch(S){return this.#b("[SDK lifecycle] session_start envelope wrap failed:",S),!1}try{this.#v("tracescout.session_start",B)}catch(S){return this.#b("[SDK lifecycle] session_start addCustomEvent failed:",S),!1}this.#f=!0;try{this.#w({sessionStartEmitted:!0,startedAt:"number"==typeof B.timestamp?B.timestamp:Date.now()})}catch(S){}return!0}emitEnd(S){if(!S||"object"!=typeof S)return!1;if(this.#m)return!1;const b=mapInternalEndReason(S.reason);if(!b)return this.#b("[SDK lifecycle] session_end refused for non-logical reason:",S.reason),!1;let I=null;try{I=this.#S()}catch(S){I=null}if(I&&!0===I.sessionEndEmitted)return this.#m=!0,!1;I||this.#b("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const x=this.#C(),R=Date.now(),A=I&&"number"==typeof I.startedAt?I.startedAt:"number"==typeof x.sessionStartTime?x.sessionStartTime:R,_={endedAt:R,durationMs:Math.max(0,R-A),reason:b};let D;Number.isFinite(S.totalChunks)&&S.totalChunks>=0&&(_.totalChunks=Math.trunc(S.totalChunks)),Number.isFinite(S.totalEvents)&&S.totalEvents>=0&&(_.totalEvents=Math.trunc(S.totalEvents));try{D=this.#y("session_end",_,x)}catch(S){return this.#b("[SDK lifecycle] session_end envelope wrap failed:",S),!1}try{this.#v("tracescout.session_end",D)}catch(S){return this.#b("[SDK lifecycle] session_end addCustomEvent failed:",S),!1}this.#m=!0;try{this.#w({sessionEndEmitted:!0,endedAt:R,endReason:b})}catch(S){}return!0}get startEmitted(){return this.#f}get endEmitted(){return this.#m}}function isNonEmptyString$1(S){return"string"==typeof S&&S.length>0}function urlParts(S){if("string"!=typeof S||0===S.length)return{path:null,query:null,hash:null};try{const b=new URL(S);return{path:b.pathname,query:b.search||null,hash:b.hash||null}}catch(S){return{path:null,query:null,hash:null}}}class PageviewManager{#k;#I=!1;#E=null;#v;#x;#y;#b;constructor(S){if(!S||"object"!=typeof S)throw new Error("PageviewManager: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("PageviewManager: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("PageviewManager: getBaseContext callback is required");this.#v=S.addCustomEvent,this.#x=S.getBaseContext,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{},this.#k=uuidv4()}getCurrentPageviewId(){return this.#k}emitInitialPageView(S={}){if(this.#I)return!1;const b="undefined"!=typeof window?window:{},I="undefined"!=typeof document?document:{},x="string"==typeof b.location?.href?b.location.href:"";if(!isNonEmptyString$1(x))return this.#b("[SDK pageview] initial page_view skipped — url unavailable"),!1;const R=urlParts(x);if(!isNonEmptyString$1(R.path))return this.#b("[SDK pageview] initial page_view skipped — could not derive path"),!1;const A={url:x,path:R.path,isInitial:!0!==S.isResumed};isNonEmptyString$1(R.query)&&(A.query=R.query),isNonEmptyString$1(R.hash)&&(A.hash=R.hash),isNonEmptyString$1(I.title)&&(A.title=I.title),isNonEmptyString$1(I.referrer)&&(A.referrer=I.referrer);const _=this.#M(this.#k);let D;try{D=this.#y("page_view",A,_)}catch(S){return this.#b("[SDK pageview] initial page_view envelope wrap failed:",S),!1}try{this.#v("tracescout.page_view",D)}catch(S){return this.#b("[SDK pageview] initial page_view addCustomEvent failed:",S),!1}return this.#I=!0,this.#E=x,!0}recordNavigation(S,b,I){if(!isNonEmptyString$1(I))return this.#b("[SDK pageview] navigation skipped — toUrl unavailable"),!1;if(null!==this.#E&&this.#E===I)return!1;if(!["pushState","replaceState","popstate","hashchange"].includes(S))return this.#b("[SDK pageview] navigation skipped — unknown method:",S),!1;const x=isNonEmptyString$1(b)?b:I,R=urlParts(x),A=urlParts(I);if(!isNonEmptyString$1(A.path))return this.#b("[SDK pageview] navigation skipped — could not derive toPath"),!1;const _=this.#k,D=uuidv4(),L={fromUrl:x,toUrl:I,method:S,nextPageviewId:D};let B;isNonEmptyString$1(R.path)&&(L.fromPath=R.path),isNonEmptyString$1(A.path)&&(L.toPath=A.path);try{B=this.#y("route_change",L,this.#M(_))}catch(S){return this.#b("[SDK pageview] route_change envelope wrap failed:",S),!1}try{this.#v("tracescout.route_change",B)}catch(S){return this.#b("[SDK pageview] route_change addCustomEvent failed:",S),!1}this.#k=D,this.#E=I;const U="undefined"!=typeof document?document:{},$={url:I,path:A.path,isInitial:!1};let j;isNonEmptyString$1(A.query)&&($.query=A.query),isNonEmptyString$1(A.hash)&&($.hash=A.hash),isNonEmptyString$1(U.title)&&($.title=U.title),isNonEmptyString$1(x)&&($.referrer=x);try{j=this.#y("page_view",$,this.#M(D))}catch(S){return this.#b("[SDK pageview] post-nav page_view envelope wrap failed:",S),!1}try{this.#v("tracescout.page_view",j)}catch(S){return this.#b("[SDK pageview] post-nav page_view addCustomEvent failed:",S),!1}return!0}#M(S){const b=this.#x()||{};return Object.assign({},b,{pageviewId:S})}get initialEmitted(){return this.#I}get lastUrl(){return this.#E}}function normalizeRating(S){if("string"!=typeof S)return null;switch(S){case"good":return"good";case"needs-improvement":case"needsImprovement":return"needs-improvement";case"poor":return"poor";default:return null}}const Ee=new Set(["navigate","reload","back-forward","prerender","back-forward-cache","restore"]);function isNonEmptyString(S){return"string"==typeof S&&S.length>0}class WebVitalsEmitter{#R;#T;#A=new Set;#v;#x;#y;#b;constructor(S){if(!S||"object"!=typeof S)throw new Error("WebVitalsEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("WebVitalsEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("WebVitalsEmitter: getBaseContext callback is required");if(!isNonEmptyString(S.initialPageviewId))throw new Error("WebVitalsEmitter: initialPageviewId is required");if(!isNonEmptyString(S.initialUrl))throw new Error("WebVitalsEmitter: initialUrl is required");this.#v=S.addCustomEvent,this.#x=S.getBaseContext,this.#R=S.initialPageviewId,this.#T=S.initialUrl,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{}}emit(S,b){if(!b||"object"!=typeof b)return!1;const I=function normalizeMetricType(S){switch((S||"").toString().toLowerCase()){case"lcp":return"LCP";case"fid":return"FID";case"cls":return"CLS";case"inp":return"INP";case"ttfb":return"TTFB";case"fcp":return"FCP";default:return null}}(S);if(!I)return this.#b("[SDK web-vitals] emit refused — unknown metric type:",S),!1;if(this.#A.has(I))return!1;if(!function isPositiveFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)&&S>=0}(b.value))return this.#b("[SDK web-vitals] emit refused — invalid value for",I,b.value),!1;const x=normalizeRating(b.libRating)??normalizeRating(b.rating);if(!x)return this.#b("[SDK web-vitals] emit refused — invalid rating for",I,b.libRating,b.rating),!1;const R={metric:I,value:b.value,unit:(A=I,"CLS"===A?"score":"ms"),rating:x};var A;"string"==typeof b.navigationType&&Ee.has(b.navigationType)&&(R.navigationType=b.navigationType);const _=this.#x()||{},D=Object.assign({},_,{pageviewId:this.#R,url:this.#T});let L;try{L=this.#y("performance_metric",R,D)}catch(S){return this.#b("[SDK web-vitals] envelope wrap failed:",S),!1}try{this.#v("tracescout.performance_metric",L)}catch(S){return this.#b("[SDK web-vitals] addCustomEvent failed:",S),!1}return this.#A.add(I),!0}get emittedMetrics(){return new Set(this.#A)}get initialPageviewId(){return this.#R}get initialUrl(){return this.#T}}const xe=/^[a-zA-Z][a-zA-Z0-9_.-]*$/,Me=["_ts_","internal","system"],Re=["password","token","authorization","cookie","ssn","creditcard","secret","apikey"],Te=new Set(["__proto__","constructor","prototype"]);function isValidUserId(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isValidEmail(S){if("string"!=typeof S)return!1;if(0===S.length||S.length>320)return!1;if(/\s/.test(S))return!1;const b=S.indexOf("@");if(b<1||b!==S.lastIndexOf("@"))return!1;const I=S.slice(0,b),x=S.slice(b+1);if(0===I.length||x.length<3)return!1;if(I.startsWith(".")||I.endsWith("."))return!1;if(!x.includes("."))return!1;if(x.startsWith(".")||x.endsWith("."))return!1;if(x.includes("..")||I.includes(".."))return!1;const R=x.lastIndexOf("."),A=x.slice(R+1);return!(A.length<2||!/^[a-zA-Z]+$/.test(A))}function isValidUserName(S){return"string"==typeof S&&S.length>=1&&S.length<=256}function isFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)}function sanitizeScalarBag(S,b){const I={};if(!S||"object"!=typeof S||Array.isArray(S))return I;const x="function"==typeof b?b:()=>{};let R=0;for(const b of Object.keys(S)){if(R>=50){x("too-many-keys",b);continue}if("string"!=typeof b||0===b.length){x("invalid-key",String(b));continue}if(b.length>64){x("key-too-long",b);continue}if(Te.has(b)){x("pollution-key",b);continue}if(Me.some(S=>b.startsWith(S))){x("reserved-key",b);continue}const A=b.toLowerCase();if(Re.some(S=>A.includes(S))){x("sensitive-key",b);continue}const _=S[b];if(null===_){I[b]=null,R++;continue}const D=typeof _;if("string"!==D)if("number"!==D)"boolean"!==D?x(`invalid-type:${Array.isArray(_)?"array":D}`,b):(I[b]=_,R++);else{if(!isFiniteNumber(_)){x("non-finite-number",b);continue}I[b]=_,R++}else{if(_.length>1024){x("string-too-long",b);continue}I[b]=_,R++}}return I}class TrackIdentifyEmitter{#v;#x;#y;#b;constructor(S){if(!S||"object"!=typeof S)throw new Error("TrackIdentifyEmitter: opts is required");if("function"!=typeof S.addCustomEvent)throw new Error("TrackIdentifyEmitter: addCustomEvent callback is required");if("function"!=typeof S.getBaseContext)throw new Error("TrackIdentifyEmitter: getBaseContext callback is required");this.#v=S.addCustomEvent,this.#x=S.getBaseContext,this.#y=S.wrap||wrapInEnvelope,this.#b="function"==typeof S.debug?S.debug:()=>{}}emitCustomEvent(S,b){if(!function isValidEventName(S){return"string"==typeof S&&S.length>=1&&S.length<=128&&xe.test(S)}(S))return this.#b("[SDK track] emit refused — invalid event name:",S),!1;const I=[],x=sanitizeScalarBag(b,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#b("[SDK track] properties keys dropped:",I);const R={name:S};Object.keys(x).length>0&&(R.properties=x);const A=this.#x()||{};let _;try{_=this.#y("custom_event",R,A)}catch(S){return this.#b("[SDK track] envelope wrap failed:",S),!1}try{this.#v("tracescout.custom_event",_)}catch(S){return this.#b("[SDK track] addCustomEvent failed:",S),!1}return!0}emitUserIdentified(S){if(!S||"object"!=typeof S)return!1;if(!isValidUserId(S.userId))return this.#b("[SDK identify] emit refused — invalid userId"),!1;const b="set"===S.mode?"set":"merge",I=[],x=sanitizeScalarBag(S.traits,(S,b)=>I.push({reason:S,key:b}));I.length>0&&this.#b("[SDK identify] traits keys dropped:",I);const R={mode:b};Object.keys(x).length>0&&(R.traits=x);const A=this.#x()||{},_=Object.assign({},A,{userId:S.userId});let D;isValidEmail(S.userEmail)&&(_.userEmail=S.userEmail),isValidUserName(S.userName)&&(_.userName=S.userName);try{D=this.#y("user_identified",R,_)}catch(S){return this.#b("[SDK identify] envelope wrap failed:",S),!1}try{this.#v("tracescout.user_identified",D)}catch(S){return this.#b("[SDK identify] addCustomEvent failed:",S),!1}return!0}}class SessionRecordingFeature{#o=null;#_=null;#O=null;#a=null;#D=null;#F=null;#N=null;#L=null;#P=!1;#B=!1;#z=null;#U=0;#$=null;#j=null;#q=null;#W=null;constructor({logger:S,sdkContext:b,config:I,options:x}){this.#o=S,this.#_=b,this.#O=I,this.#a=x}async initialize(S,b){try{console.log("[TraceScout] Loading recording module..."),this.#D=await Promise.resolve().then(function(){return Rc});const{SessionStorage:I,UploadQueue:x,Recorder:R}=this.#D;return this.#N=new I({storageKey:"__tracescout_sessions_v2__",maxStorageSize:2097152,maxSessions:5,logger:this.#o}),console.log("[TraceScout] ✓ Session storage initialized"),this.#L=this.#H(x,S,b),console.log("[TraceScout] ✓ Upload queue initialized"),console.log(` Endpoint: /api/projects/${this.#_.projectId}/sessions/${this.#_.sessionId}/chunks`),this.#F=this.#V(R,S),console.log("[TraceScout] ✓ Session recorder initialized"),await this.#F.start(),console.log("[TraceScout] ✓ Session recording started"),this.#a.onSessionStart&&this.#a.onSessionStart(this.#_.sessionId),this.#P=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize session recording:",S),!1}}#H(S,b,I){return new S({sdkContext:this.#_,baseUrl:I?.baseUrl,batchSize:b.telemetry?.batchSize||5,maxRetries:3,retryDelay:2e3,enableCompression:!1!==b.telemetry?.enableCompression,enableOfflineQueue:!0,logger:this.#o,onUploadSuccess:(S,b)=>{this.#o?.log(`✅ Chunk ${S.chunkIndex} uploaded successfully`),this.#a.onChunkUploaded&&this.#a.onChunkUploaded(S,b)},onUploadError:(S,b)=>{if(b&&"QUOTA_EXCEEDED"===b.code)return console.error("[TraceScout] ⛔ QUOTA EXCEEDED - Stopping recording"),void this.#q?.(b);this.#o?.error(`❌ Chunk ${S?.chunkIndex} upload failed:`,b?.message)},onNetworkChange:S=>{this.#o?.log("Network status: "+(S?"online":"offline"))}})}#V(S,b){const I=b.features.sessionRecording;return new S({sdkContext:this.#_,serverSettings:I,emit:S=>this.#Q(S),onChunk:S=>{this.#K(S),this.#L&&this.#L.enqueue(S,"normal")},onSessionEnd:S=>{console.log(`[TraceScout] 🛑 Session ended: ${S.reason}`),console.log(` Session ID: ${S.sessionId}`),console.log(` Duration: ${Math.round(S.duration/6e4)}min`),console.log(` Total events: ${S.totalEvents}`),this.#B=!0,this.#z=S.reason,this.#a.onSessionEnd&&this.#a.onSessionEnd(S),this.#j?.(S)},chunkDuration:I.chunkDuration||3e4,maxChunkSize:I.maxChunkSize||5e5,blockClass:I.blockClass||"ts-block",ignoreClass:I.ignoreClass||"ts-ignore",maskTextClass:I.maskTextClass||"ts-mask",maskAllInputs:I.maskAllInputs||!1,recordCanvas:I.recordCanvas||!1,collectFonts:I.collectFonts||!1,inactivityTimeout:I.inactivityTimeout||3e5,maxInactivityDuration:I.maxInactivityDuration||18e5,maxSessionDuration:I.maxSessionDuration||36e5,enableInactivityDetection:!0,enableSampling:I.enableSampling||!1,enableDeduplication:I.enableDeduplication||!1,mousemoveSampling:I.mousemoveSampling||1,scrollSampling:I.scrollSampling||1,enableStorage:!0,enableCompression:!0,debug:this.#O.debug||!1,onSpaNavigation:(S,b,I)=>{"function"==typeof this.#W&&this.#W(S,b,I)}})}#Q(S){}#K(S){const b=Date.now();if(b-this.#U>=1e4){const I="number"==typeof S.size?S.size:S.compressedSize||0;this.#o?.log(`Session chunk created: ${S.chunkId} (${S.eventCount} events, ${I} bytes)`),this.#U=b}this.#N&&this.#N.storeChunk(S.sessionId,S),this.#$?.(S)}setCallbacks({onChunkCreated:S,onSessionEnd:b,onQuotaExceeded:I,onSpaNavigation:x}){this.#$=S,this.#j=b,this.#q=I,this.#W=x||null}get isAvailable(){return this.#P&&null!=this.#F}get isRecording(){return this.#F?.isRecording||!1}get sessionEnded(){return this.#B}get sessionEndReason(){return this.#z}get recorder(){return this.#F}get uploadQueue(){return this.#L}get sessionStorage(){return this.#N}async start(S={}){if(!this.#F)return this.#o?.warn("Session recording not enabled"),null;try{const b=this.#F.start(S),I=this.#F.getSessionId();return this.#o?.info("Session recording started:",I),{sessionId:I,startTime:Date.now(),status:"recording",stop:b}}catch(S){return this.#o?.error("Failed to start session recording:",S),null}}stop(){if(!this.#F)return this.#o?.warn("Session recording not enabled"),null;try{this.#F.stop();const S=this.#F.getEvents(),b=this.#F.getSessionId();return this.#o?.info("Session recording stopped:",b),{sessionId:b,startTime:this.#F.recordingStartTime,duration:Date.now()-this.#F.recordingStartTime,totalEvents:S.length,events:S,status:"stopped"}}catch(S){return this.#o?.error("Failed to stop session recording:",S),null}}addCustomEvent(S,b){if(!this.#F)return!1;try{return this.#F.addCustomEvent(S,b)}catch(S){return!1}}getStatus(){return this.#F?{available:!0,isRecording:this.#F.isRecording,sessionId:this.#F.getSessionId(),eventCount:this.#F.getEvents().length,startTime:this.#F.recordingStartTime}:{available:!1,error:"Session recording not enabled"}}getEvents(){return this.#F?.getEvents()||[]}getChunks(){return this.#F?.getChunks?.()||[]}getMetadata(){return this.#F?.getMetadata?.()||{}}getSessionId(){return this.#F?.getSessionId()}updateSessionId(S){this.#F&&(this.#F.sessionId=S),this.#B=!1,this.#z=null}updateUploadEndpoint(S){this.#L&&(this.#L.config.endpoint=S)}destroy(){if(this.#F){try{this.#F.stop()}catch(S){}this.#F=null}this.#N=null,this.#L=null,this.#D=null,this.#P=!1}}class LogManager{#o=null;#O=null;#_=null;#G=[];#J={};#X="debug";#Y=1e3;#Z=new Map;#ee=5e3;#te=null;#se=!0;static LOG_LEVELS={debug:0,info:1,warn:2,error:3,fatal:4};constructor(S={},b=null,I=null){this.#O=S,this.#_=b,this.#te=I,this.#o=new Logger("[LogManager]",S.debug),this.#se=!1!==S.logs?.enabled,this.#X=S.logs?.minLevel||"debug",this.#Y=S.logs?.maxBufferSize||1e3,this.#o.log("LogManager initialized",{enabled:this.#se,minLevel:this.#X,maxBufferSize:this.#Y})}log(S,b,I={}){if(!this.#se)return!1;if(!this.#re(S))return!1;try{const x=this.#ne(S,b,I);return!this.#ie(x)&&(this.#G.push(x),this.#G.length>=this.#Y&&this.flush(),"error"!==S&&"fatal"!==S||setTimeout(()=>this.flush(),0),!0)}catch(S){return this.#o.error("Failed to log message:",S),!1}}debug(S,b={}){return this.log("debug",S,b)}info(S,b={}){return this.log("info",S,b)}warn(S,b={}){return this.log("warn",S,b)}error(S,b={}){return this.log("error",S,b)}fatal(S,b={}){return this.log("fatal",S,b)}attachContext(S,b){"string"==typeof S?this.#J[S]=b:"object"==typeof S&&Object.assign(this.#J,S),this.#o.log("Context attached:",S)}clearContext(){this.#J={},this.#o.log("Context cleared")}setLogLevel(S){LogManager.LOG_LEVELS.hasOwnProperty(S)?(this.#X=S,this.#o.log("Log level set to:",S)):this.#o.warn("Invalid log level:",S)}getLogLevel(){return this.#X}setEnabled(S){this.#se=S,this.#o.log("Logging",S?"enabled":"disabled")}isEnabled(){return this.#se}flush(){if(0===this.#G.length)return[];const S=[...this.#G];if(this.#G=[],this.#o.log(`Flushing ${S.length} logs`),this.#te)try{this.#te(S)}catch(S){this.#o.error("Error in flush callback:",S)}return S}getQueueSize(){return this.#G.length}getQueue(){return[...this.#G]}clearQueue(){const S=this.#G.length;this.#G=[],this.#o.log(`Cleared ${S} logs from queue`)}getStats(){const S={queueSize:this.#G.length,byLevel:{},enabled:this.#se,minLevel:this.#X};return this.#G.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}#ne(S,b,I={}){const x=Date.now(),R=`log_${x}_${generateId()}`,A={source:"undefined"!=typeof process&&process.versions&&process.versions.node?"server":"client",timestamp:x,...this.#oe(),...this.#J};this.#_&&(A.sessionId=this.#_.sessionId,A.projectId=this.#_.projectId,A.environment=this.#_.environment,this.#_.userId&&(A.userId=this.#_.userId));const _=this.#ae(I);return"error"!==S&&"fatal"!==S||!1===this.#O.logs?.attachStackTrace||_.stack||(_.stack=this.#le()),{logId:R,timestamp:x,level:S,message:String(b),metadata:_,context:A}}#oe(){const S={};return"undefined"!=typeof window?(S.url=window.location?.href,S.userAgent=navigator?.userAgent,S.platform=navigator?.platform):"undefined"!=typeof process&&(S.platform=process.platform,S.nodeVersion=process.version,S.pid=process.pid),S}#ae(S){if(!S||"object"!=typeof S)return{};const b={};for(const[I,x]of Object.entries(S))if(x instanceof Error)b[I]={name:x.name,message:x.message,stack:x.stack,...x};else if("object"==typeof x&&null!==x)try{JSON.stringify(x),b[I]=x}catch(S){b[I]="[Circular Reference]"}else b[I]=x;return b}#le(){try{const S=(new Error).stack||"";return S.split("\n").slice(3).join("\n")}catch(S){return"Stack trace unavailable"}}#re(S){const b=LogManager.LOG_LEVELS[S],I=LogManager.LOG_LEVELS[this.#X];return void 0===b||void 0===I||b>=I}#ie(S){const b=`${S.level}:${S.message}`,I=Date.now(),x=this.#Z.get(b);return!!(x&&I-x<this.#ee)||(this.#Z.set(b,I),this.#Z.size>1e3&&this.#ce(),!1)}#ce(){const S=Date.now();for(const[b,I]of this.#Z.entries())S-I>this.#ee&&this.#Z.delete(b)}destroy(){this.flush(),this.#G=[],this.#J={},this.#Z.clear(),this.#te=null,this.#o.log("LogManager destroyed")}}class LogBuffer{#o=null;#O=null;#_=null;#ue=[];#he=null;#de=5e3;#ge=100;#pe=!1;#fe=null;#me=!0;#ye=0;static MAX_CONSECUTIVE_FAILURES=5;constructor(S={},b=null,I=null){this.#O=S,this.#_=b,this.#fe=I,this.#o=new Logger("[LogBuffer]",S.debug),this.#de=S.logs?.flushInterval||5e3,this.#ge=S.logs?.maxBatchSize||100,this.#me=!1!==S.telemetry?.enableCompression,this.#ve(),this.#o.log("LogBuffer initialized",{flushInterval:this.#de,maxBatchSize:this.#ge,compressionEnabled:this.#me})}add(S){Array.isArray(S)||(S=[S]),this.#ue.push(...S),this.#o.log(`Added ${S.length} logs to buffer. Buffer size: ${this.#ue.length}`),this.#ue.length>=this.#ge&&(this.#o.log("Buffer size threshold reached, flushing..."),this.flush())}async flush(){if(0===this.#ue.length)return{success:!0,sent:0};if(this.#pe)return this.#o.log("Already sending, skipping flush"),{success:!1,reason:"Already sending"};const S=this.#ue.splice(0,this.#ge);if(0===S.length)return{success:!0,sent:0};this.#o.log(`Flushing ${S.length} logs`);try{this.#pe=!0;const b=this.#Se(S);let I=b,x=!1;if(this.#me&&"function"==typeof this.#we)try{I=await this.#we(b),x=!0,this.#o.log(`Compressed batch from ${JSON.stringify(b).length} to ${I.length} bytes`)}catch(S){this.#o.warn("Compression failed, sending uncompressed:",S)}return this.#fe&&await this.#fe(I,x),this.#o.log(`Successfully sent batch with ${S.length} logs`),this.#ye=0,{success:!0,sent:S.length}}catch(b){return this.#ye++,this.#o.error(`Failed to flush logs (consecutive failures: ${this.#ye}):`,b),this.#ye>LogBuffer.MAX_CONSECUTIVE_FAILURES?(this.#o.warn(`Dropping batch of ${S.length} logs after ${this.#ye} consecutive failures`),{success:!1,dropped:S.length,error:b.message}):(this.#ue.unshift(...S),{success:!1,error:b.message})}finally{this.#pe=!1}}getConsecutiveFailures(){return this.#ye}async forceFlush(){this.#be();try{await this.flush()}finally{this.#ve()}}getBufferSize(){return this.#ue.length}getStats(){const S={bufferSize:this.#ue.length,isSending:this.#pe,flushInterval:this.#de,maxBatchSize:this.#ge,byLevel:{}};return this.#ue.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}clear(){const S=this.#ue.length;this.#ue=[],this.#o.log(`Cleared ${S} logs from buffer`)}destroy(){this.#be(),this.flush().catch(S=>{this.#o.error("Error during final flush:",S)}),this.clear(),this.#o.log("LogBuffer destroyed")}#Se(S){return{batchId:`batch_${Date.now()}_${generateId()}`,timestamp:Date.now(),projectId:this.#_?.projectId,count:S.length,logs:S}}async#we(S){const b=JSON.stringify(S);if("undefined"!=typeof CompressionStream)try{const S=new Blob([b]).stream().pipeThrough(new CompressionStream("gzip")),I=await new Response(S).blob(),x=await I.arrayBuffer();return Array.from(new Uint8Array(x))}catch(S){throw this.#o.warn("Browser compression failed:",S),S}throw new Error("Compression not available - CompressionStream not supported")}#ve(){this.#he||(this.#he=setInterval(()=>{this.#ue.length>0&&this.flush().catch(S=>{this.#o.error("Auto-flush failed:",S)})},this.#de),this.#o.log("Auto-flush started"))}#be(){this.#he&&(clearInterval(this.#he),this.#he=null,this.#o.log("Auto-flush stopped"))}}class LoggingFeature{#o=null;#_=null;#O=null;#Ce=null;#ke=null;#P=!1;constructor({logger:S,sdkContext:b,config:I}){this.#o=S,this.#_=b,this.#O=I}initialize(S){console.log("[TraceScout] Initializing logging system...");try{return this.#Ce=new LogManager(this.#O,this.#_,S=>{this.#ke&&this.#ke.add(S)}),this.#ke=new LogBuffer(this.#O,this.#_,async(S,b)=>this.#Ie(S,b)),console.log("[TraceScout] ✓ Logging system initialized"),this.#P=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize logging:",S),!1}}configure(S){try{const b={enabled:S.debug||!1,level:S.logLevel||"info",showTimestamps:!1!==S.showLogTimestamps,showServiceIcons:!1!==S.showServiceIcons};S.logging&&"object"==typeof S.logging&&(b.services=S.logging),_.configure(b),S.enabledLogServices&&Array.isArray(S.enabledLogServices)?_.enableServices(S.enabledLogServices,S.logLevel||"info"):S.debug&&_.enableServices(["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager"],S.logLevel||"info"),this.#o?.log("Logging system configured successfully")}catch(S){this.#o?.error("Failed to configure logging system:",S)}}async#Ie(S,b){if(!this.#_)throw new Error("SDK not initialized");const I=this.#_.projectId,x=`${resolveApiBaseUrl(this.#O)}/api/projects/${I}/logs/batch`;try{const I={};b?(I["Content-Type"]="application/octet-stream",I["Content-Encoding"]="gzip"):I["Content-Type"]="application/json";const R=await fetch(x,{method:"POST",headers:I,body:b?new Blob([new Uint8Array(S)]):JSON.stringify(S)});if(!R.ok)throw new Error(`HTTP ${R.status}: ${R.statusText}`);const A=await R.json();return this.#o?.log("Log batch sent successfully"),A}catch(S){throw this.#o?.error("Failed to send log batch:",S),S}}get isAvailable(){return this.#P&&null!=this.#Ce}get logManager(){return this.#Ce}get logBuffer(){return this.#ke}log(S,b,I={}){return!!this.#Ce&&this.#Ce.log(S,b,I)}debug(S,b={}){return this.#Ce?.debug(S,b)||!1}info(S,b={}){return this.#Ce?.info(S,b)||!1}warn(S,b={}){return this.#Ce?.warn(S,b)||!1}error(S,b={}){return this.#Ce?.error(S,b)||!1}fatal(S,b={}){return this.#Ce?.fatal(S,b)||!1}setContext(S,b){return!!this.#Ce&&(this.#Ce.attachContext(S,b),!0)}clearContext(){return!!this.#Ce&&(this.#Ce.clearContext(),!0)}setLogLevel(S){return!!this.#Ce&&(this.#Ce.setLogLevel(S),!0)}getStats(){return this.#Ce?{manager:this.#Ce.getStats(),buffer:this.#ke?this.#ke.getStats():null}:null}async flush(){if(!this.#ke)return!1;try{return await this.#ke.forceFlush(),!0}catch(S){return this.#o?.error("Failed to flush logs:",S),!1}}enableServices(S,b="info"){try{return _.enableServices(S,b),!0}catch(S){return this.#o?.error("Failed to enable logging:",S),!1}}disableServices(S){try{return _.disableServices(S),!0}catch(S){return this.#o?.error("Failed to disable logging:",S),!1}}enableAll(S="info"){try{return _.enableAll(S),!0}catch(S){return this.#o?.error("Failed to enable all logging:",S),!1}}disableAll(){try{return _.disableAll(),!0}catch(S){return this.#o?.error("Failed to disable all logging:",S),!1}}getConfig(){try{return _.getConfig()}catch(S){return this.#o?.error("Failed to get logging config:",S),null}}getEnabledServices(){try{return _.getEnabledServices()}catch(S){return[]}}getAvailableServices(){return["TraceScoutMonitoringCore","ConfigManager","EventManager","ServiceManager","UserProfileManager","PerformanceMonitor","FetchInterceptor","XHRInterceptor","ResourceInterceptor","PostMessageInterceptor","CoreWebVitalsMonitor","Recorder","SessionStorage","UploadQueue","CDN-Loader","Replayer","Validation","BaseService"]}destroy(){this.#ke&&(this.#ke.destroy(),this.#ke=null),this.#Ce&&(this.#Ce.destroy(),this.#Ce=null),this.#P=!1}}class ConsoleInterceptor{constructor(S,b={},I=null){this.eventManager=S,this.reporter=I,this.logManager=null,this.config={captureLog:!1!==b.captureLog,captureWarn:!1!==b.captureWarn,captureError:!1!==b.captureError,captureInfo:!1!==b.captureInfo,captureDebug:!1!==b.captureDebug,captureTrace:!1!==b.captureTrace,maxMessageLength:b.maxMessageLength||5e3,maxArgSize:b.maxArgSize||2e3,maxTotalArgsSize:b.maxTotalArgsSize||1e4,...b},this.logger=createLogger("ConsoleInterceptor"),this.originalMethods={},this.installed=!1}setLogManager(S){this.logManager=S,this.logger.debug("LogManager attached to ConsoleInterceptor")}install(){if(this.installed)return;const S=[];this.config.captureLog&&S.push("log"),this.config.captureWarn&&S.push("warn"),this.config.captureError&&S.push("error"),this.config.captureInfo&&S.push("info"),this.config.captureDebug&&S.push("debug"),this.config.captureTrace&&S.push("trace"),S.forEach(S=>{this.originalMethods[S]=console[S],console[S]=this.createInterceptor(S)}),this.installed=!0,this.logger.debug("Console interceptor installed")}uninstall(){this.installed&&(Object.keys(this.originalMethods).forEach(S=>{console[S]=this.originalMethods[S]}),this.originalMethods={},this.installed=!1,this.logger.debug("Console interceptor uninstalled"))}createInterceptor(S){const b=this;return function(...I){b.originalMethods[S].apply(console,I);const x=I[0];if("string"!=typeof x||!(x.includes("[TraceScout]")||x.includes("[Recorder]")||x.includes("[SDK]")||x.includes("[ConsoleInterceptor]")||x.includes("[NetworkInterceptor]")||x.includes("[FetchInterceptor]")||x.includes("[XHRInterceptor]")||x.includes("[SessionManager]")||x.includes("[UploadQueue]")||x.includes("[ErrorHandler]")||x.includes("TraceScoutMonitoringCore")))try{const x=b.formatMessage(I),R=Date.now(),A=b.getLevel(S),_=b.processArgs(I),D={method:S,args:_,source:"console"};if("error"!==S&&"trace"!==S||(D.stack=b.captureStackTrace()),b.logManager&&"function"==typeof b.logManager.log)try{const I=b.truncateMessage(x),R=b.mapToLogLevel(S);b.logManager.log(R,I,D)}catch(S){}const L={type:"console",category:"console",method:S,message:b.truncateMessage(x),timestamp:R,level:A,args:_};if("error"!==S&&"trace"!==S||(L.stack=b.captureStackTrace()),b.eventManager&&"function"==typeof b.eventManager.logEvent&&b.eventManager.logEvent("console",L),b.reporter&&b.reporter.addSessionCustomEvent&&"function"==typeof b.reporter.addSessionCustomEvent)try{b.reporter.addSessionCustomEvent("console",{method:S,message:L.message,args:L.args,level:L.level,stack:L.stack,timestamp:L.timestamp})}catch(S){}}catch(S){}}}formatMessage(S){return S.map(S=>{if(null===S)return"null";if(void 0===S)return"undefined";if("object"==typeof S)try{return safeStringify(S,5,this.config.maxArgSize)}catch{return"[Unserializable Object]"}return"string"==typeof S&&S.length>this.config.maxArgSize?S.substring(0,this.config.maxArgSize)+"... [truncated]":String(S)}).join(" ")}processArgs(S){if(this.config.captureArgs)return safeParseConsoleArgs(S,this.config.maxArgSize,this.config.maxTotalArgsSize)}truncateMessage(S){return S.length>this.config.maxMessageLength?S.substring(0,this.config.maxMessageLength)+"...":S}getLevel(S){return{log:"log",info:"info",warn:"warn",error:"error",debug:"debug",trace:"trace"}[S]||"log"}mapToLogLevel(S){return{log:"info",info:"info",warn:"warn",error:"error",debug:"debug",trace:"debug"}[S]||"info"}captureStackTrace(){return(new Error).stack||""}}const Ae=["authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-csrf-token","x-xsrf-token","api-key","apikey","x-amz-security-token","x-ms-client-principal","proxy-authorization","www-authenticate"],_e="[REDACTED]";function filterSensitiveHeaders(S,b=[]){if(!S)return{};const I={},x=new Set([...Ae,...b.map(S=>S.toLowerCase())]);if(S instanceof Headers||S.forEach&&"function"==typeof S.forEach)S.forEach((S,b)=>{const R=b.toLowerCase();I[b]=x.has(R)?_e:S});else if("object"==typeof S)for(const[b,R]of Object.entries(S)){const S=b.toLowerCase();I[b]=x.has(S)?_e:R}return I}const Oe=[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".woff",".woff2",".ttf",".eot",".ico",".webp",".avif"],De=["text/css","text/javascript","application/javascript","image/","font/","application/font","application/x-font"],Fe=[/\.(js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|ico|webp|avif)(\?|$)/i,/\/static\//i,/\/assets\//i,/\/images\//i,/\/fonts\//i,/\/_next\/static\//i,/\/webpack\//i,/\/node_modules\//i];function isStaticResource(S,b=""){if(!S)return!1;if(Oe.some(b=>S.toLowerCase().includes(b)))return!0;const I=De.some(S=>b.toLowerCase().startsWith(S));return!!I||Fe.some(b=>b.test(S))}function getResourceType(S,b=""){const I=S.toLowerCase(),x=b.toLowerCase();return I.includes(".js")||x.includes("javascript")?"script":I.includes(".css")||x.includes("text/css")?"stylesheet":/\.(woff2?|ttf|eot|otf)(\?|$)/i.test(S)||x.includes("font")?"font":/\.(png|jpg|jpeg|gif|svg|ico|webp|avif)(\?|$)/i.test(S)||x.includes("image")?"image":"other"}const Ne=1e4;function parseFormData(S){try{const b=new URLSearchParams(S),I={};for(const[S,x]of b)I[S]=x;return I}catch(S){return null}}function createTruncatedBody(S,b,I="body"){return{_truncated:!0,_originalSize:S.length,_message:`${I} body truncated (${S.length} bytes, limit ${b} bytes)`,_preview:S.substring(0,b)+"...",_tip:"Enable full body capture in project settings if needed"}}function handleRequestBody(S,b={}){const{maxSize:I=Ne,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Request");try{const S=JSON.parse(b),x=JSON.stringify(S);return x.length>I?createTruncatedBody(x,I,"Request"):S}catch{const S=parseFormData(b);return S||b}}else{if(b instanceof FormData){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if(b instanceof URLSearchParams){const S={};for(const[I,x]of b.entries())S[I]=x;return S}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Request"):b}}}catch(S){x("Failed to parse request data:",S)}return null}function handleResponseBody(S,b={}){const{maxSize:I=Ne,onWarn:x=()=>{}}=b;if(!S)return null;try{let b=S;if("string"==typeof b){if(b.length>I)return createTruncatedBody(b,I,"Response");try{b=JSON.parse(b)}catch{return b}}if("object"==typeof b){const S=JSON.stringify(b);return S.length>I?createTruncatedBody(S,I,"Response"):b}return b}catch(S){x("Failed to parse response data:",S)}return null}const Le="[REDACTED]",Pe=10240,Be=65536,ze=["password","passwd","pwd","secret","token","access_token","refresh_token","id_token","authorization","auth","api_key","apikey","x-api-key","cookie","session","sessionid","session_id","sid","jwt","bearer","credential","credentials","private_key","client_secret","card","cardnumber","card_number","cvv","cvc","pin","ssn","social_security","dob","date_of_birth","email","phone","address"];function utf8Bytes(S){return"string"!=typeof S||0===S.length?0:(new TextEncoder).encode(S).length}function truncateToBytes(S,b){const I=new TextEncoder,x=I.encode(S),R=x.length;if(R<=b)return{text:S,truncated:!1,capturedBytes:R,originalBytes:R};if(b<=0)return{text:"",truncated:!0,capturedBytes:0,originalBytes:R};const A=x.subarray(0,b);let _=new TextDecoder("utf-8",{fatal:!1}).decode(A);_.length&&65533===_.charCodeAt(_.length-1)&&(_=_.slice(0,-1));return{text:_,truncated:!0,capturedBytes:I.encode(_).length,originalBytes:R}}function safeMime(S){if(!S||"string"!=typeof S)return null;const b=S.split(";")[0].trim().toLowerCase();return b&&/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(b)?b.length>128?b.slice(0,128):b:null}function classifyMime(S){return S?"application/json"===S||"application/ld+json"===S||"application/graphql"===S||"application/graphql+json"===S||S.endsWith("+json")?"json":"application/x-www-form-urlencoded"===S?"form":"image/svg+xml"===S||"application/xml"===S||"text/xml"===S||"application/xhtml+xml"===S||"application/javascript"===S||"application/x-javascript"===S||"text/javascript"===S||S.startsWith("text/")?"text":S.startsWith("image/")||S.startsWith("audio/")||S.startsWith("video/")||S.startsWith("font/")||"application/octet-stream"===S||"application/zip"===S||"application/gzip"===S||"application/pdf"===S||"application/x-protobuf"===S||"application/protobuf"===S||S.startsWith("multipart/")?"binary":"unknown":"unknown"}function isTextualContentType(S){const b=classifyMime(safeMime(S));return"json"===b||"form"===b||"text"===b}function buildFieldDenylist(S=[]){const b=new Set(ze);if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.add(I.toLowerCase());return b}function isSensitiveField(S,b){const I=String(S).toLowerCase();for(const S of b)if(I.includes(S))return!0;return!1}function redactObject(S,b){let I=!1;const walk=S=>{if(Array.isArray(S))return S.map(walk);if(S&&"object"==typeof S){const x={};for(const R of Object.keys(S))isSensitiveField(R,b)?(x[R]=Le,I=!0):x[R]=walk(S[R]);return x}return S};return{value:walk(S),redacted:I}}function redactFormUrlEncoded(S,b){let I;try{I=new URLSearchParams(S)}catch{return{text:S,redacted:!1}}let x=!1;const R=[];for(const S of I.keys())R.push(S);const A=new Set;for(const S of R){if(A.has(S))continue;if(A.add(S),!isSensitiveField(S,b))continue;const R=I.getAll(S).length;I.delete(S);for(let b=0;b<R;b++)I.append(S,Le);x=!0}return{text:I.toString(),redacted:x}}function rawBodyBinarySize(S){return"undefined"!=typeof Blob&&S instanceof Blob&&"number"==typeof S.size?S.size:"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(S)?S.byteLength:null}function makeResult({state:S,contentType:b=null,originalBytes:I=null,redacted:x=!1}){return{text:null,state:S,redacted:!!x,truncated:!1,originalBytes:"number"==typeof I&&I>=0?I:null,capturedBytes:null,contentType:b||null}}function runSanitizer(S,b){try{return{threw:!1,value:S(b)}}catch{return{threw:!0}}}function safeToString(S){try{return"string"==typeof S?S:JSON.stringify(S)}catch{return String(S)}}function finalizeText(S,{mime:b,maxBytes:I,redacted:x}){const{text:R,truncated:A,capturedBytes:_,originalBytes:D}=truncateToBytes(S,I);let L;return L=A?"truncated":x?"redacted":"captured",{text:R,state:L,redacted:!!x,truncated:A,originalBytes:D,capturedBytes:_,contentType:b||null}}function finalizeStructured(S,{redacted:b,mime:I,maxBytes:x,sanitizer:R}){let A,_=S;if(R){const x=runSanitizer(R,S);if(x.threw)return makeResult({state:"failed",contentType:I,redacted:b});if(null===x.value||void 0===x.value)return makeResult({state:"excluded",contentType:I});_=x.value}try{A=JSON.stringify(_)}catch{return makeResult({state:"failed",contentType:I,redacted:b})}return void 0===A&&(A=""),finalizeText(A,{mime:I,maxBytes:x,redacted:b})}function captureText(S,{mime:b,maxBytes:I,sanitizer:x}){let R=S;if(x){const I=runSanitizer(x,S);if(I.threw)return makeResult({state:"failed",contentType:b});if(null===I.value||void 0===I.value)return makeResult({state:"excluded",contentType:b});R="string"==typeof I.value?I.value:safeToString(I.value)}return finalizeText(R,{mime:b,maxBytes:I,redacted:!1})}function captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const{text:A,redacted:_}=redactFormUrlEncoded(S,x);let D=A;if(R){const S=runSanitizer(R,D);if(S.threw)return makeResult({state:"failed",contentType:b,redacted:_});if(null===S.value||void 0===S.value)return makeResult({state:"excluded",contentType:b});D="string"==typeof S.value?S.value:safeToString(S.value)}return finalizeText(D,{mime:b,maxBytes:I,redacted:_})}function captureStringByMime(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R}){const A=classifyMime(b);if("binary"===A||"unknown"===A)return makeResult({state:"binary",contentType:b,originalBytes:utf8Bytes(S)});if("form"===A)return captureFormString(S,{mime:b,maxBytes:I,denylist:x,sanitizer:R});if("json"===A){let A;try{A=JSON.parse(S)}catch{return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}const{value:_,redacted:D}=redactObject(A,x);return finalizeStructured(_,{redacted:D,mime:b,maxBytes:I,sanitizer:R})}return captureText(S,{mime:b,maxBytes:I,sanitizer:R})}function normalizeOpts(S){let b="number"==typeof S.maxBytes&&S.maxBytes>=0?S.maxBytes:Pe;return b>Be&&(b=Be),{maxBytes:b,denylist:S.denylist instanceof Set?S.denylist:buildFieldDenylist(S.sensitiveFields),sanitizer:"function"==typeof S.sanitizer?S.sanitizer:null,captureEnabled:!1!==S.captureEnabled,excluded:!0===S.excluded}}function captureRequestBody(S,b={}){const I=safeMime(b.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(null==S||""===S)return makeResult({state:"unavailable",contentType:I});try{if("undefined"!=typeof FormData&&S instanceof FormData){const{obj:b,redacted:_}=function sanitizeFormData(S,b){let I=!1;const x={};for(const[R,A]of S.entries()){let S;"undefined"!=typeof File&&A instanceof File||"undefined"!=typeof Blob&&A instanceof Blob?S={_type:"file",mime:safeMime(A.type)||null,bytes:"number"==typeof A.size?A.size:null}:isSensitiveField(R,b)?(S=Le,I=!0):S=String(A),Object.prototype.hasOwnProperty.call(x,R)?Array.isArray(x[R])?x[R].push(S):x[R]=[x[R],S]:x[R]=S}return{obj:x,redacted:I}}(S,R);return finalizeStructured(b,{redacted:_,mime:I||"multipart/form-data",maxBytes:x,sanitizer:A})}if("undefined"!=typeof URLSearchParams&&S instanceof URLSearchParams)return captureFormString(S.toString(),{mime:I||"application/x-www-form-urlencoded",maxBytes:x,denylist:R,sanitizer:A});if(function isBinaryRawBody(S){return"undefined"!=typeof Blob&&S instanceof Blob||"undefined"!=typeof ArrayBuffer&&S instanceof ArrayBuffer||!("undefined"==typeof ArrayBuffer||!ArrayBuffer.isView||!ArrayBuffer.isView(S))||"undefined"!=typeof ReadableStream&&S instanceof ReadableStream}(S))return makeResult({state:"binary",contentType:I||(L=S,"undefined"!=typeof Blob&&L instanceof Blob&&L.type?safeMime(L.type):null),originalBytes:rawBodyBinarySize(S)});if("string"==typeof S)return captureStringByMime(S,{mime:I,maxBytes:x,denylist:R,sanitizer:A});if("object"==typeof S){const{value:b,redacted:_}=redactObject(S,R);return finalizeStructured(b,{redacted:_,mime:I||"application/json",maxBytes:x,sanitizer:A})}return captureStringByMime(String(S),{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}var L}function captureResponseBody(S={},b={}){const I=safeMime(S.contentTypeHeader),{maxBytes:x,denylist:R,sanitizer:A,captureEnabled:_,excluded:D}=normalizeOpts(b);if(!_||D)return makeResult({state:"excluded",contentType:I});if(S.opaque)return makeResult({state:"inaccessible",contentType:I});if(S.readError)return makeResult({state:"failed",contentType:I});if(S.binary){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}const L=classifyMime(I);if("binary"===L||"unknown"===L){return makeResult({state:"binary",contentType:I,originalBytes:"number"==typeof S.knownSize&&S.knownSize>=0?S.knownSize:null})}if(S.empty||null===S.text||void 0===S.text||""===S.text)return makeResult({state:"unavailable",contentType:I});try{return captureStringByMime(S.text,{mime:I,maxBytes:x,denylist:R,sanitizer:A})}catch{return makeResult({state:"failed",contentType:I})}}const Ue="[REDACTED]",$e=["token","access_token","refresh_token","id_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","ssid","password","passwd","pwd","secret","jwt","bearer","credential","credentials","private_token","private_key","client_secret","pin","cvv","cvc","ssn","email"];function buildTokens(S=[]){const b=[...$e];if(Array.isArray(S))for(const I of S)"string"==typeof I&&I.trim()&&b.push(I.toLowerCase());return b}function isSensitiveParam(S,b){const I=String(S).toLowerCase();return b.some(S=>I.includes(S))}function scrubSearchParams(S,b,I){let x=!1;const R=[];for(const b of S.keys())R.push(b);const A=new Set;for(const _ of R)if(!A.has(_)&&(A.add(_),isSensitiveParam(_,b)))if(x=!0,"delete"===I)S.delete(_);else{const b=S.getAll(_).length;S.delete(_);for(let I=0;I<b;I++)S.append(_,Ue)}return x}function splitSanitizedUrl(S,b={}){const{extraParams:I=[],mode:x="redact"}=b;if(!S)return{url:"",path:"",query:""};const R=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);scrubSearchParams(I.searchParams,R,x);const A=I.searchParams.toString();return{url:I.toString(),path:I.pathname||"",query:A}}catch{const I=function sanitizeUrl$1(S,b={}){const{extraParams:I=[],mode:x="redact",stripHash:R=!1}=b;if(!S)return S||"";const A=buildTokens(I);try{const b="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,I=new URL(S,b);return scrubSearchParams(I.searchParams,A,x),R&&(I.hash=""),I.toString()}catch{let b=S.replace(/([?&][^=&]*(?:token|key|secret|password|passwd|pwd|auth|jwt|bearer|session|sid|credential|pin|cvv|cvc|ssn|email)[^=&]*=)[^&#]*/gi,`$1${Ue}`);return b.length>2048&&(b=b.substring(0,2048)),b}}(S,b),x=I.indexOf("?");return-1===x?{url:I,path:I,query:""}:{url:I,path:I.substring(0,x),query:I.substring(x+1).split("#")[0]}}}class InterceptorLogger{constructor(S,b=!1){let I=S.replace(/^\[|\]$/g,"").replace(":","");I="xhrinterceptor"===I.toLowerCase()?"XHRInterceptor":I.charAt(0).toUpperCase()+I.slice(1),this.serviceLogger=createLogger(I),this.prefix=S,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class BaseInterceptor{constructor(S,b){this.reporter=S,this.interceptorName=b,this.logger=new InterceptorLogger(`[${this.interceptorName}Interceptor]`,this.reporter.config?.debug||!1)}updateDebugMode(S){this.logger.updateDebugMode(S)}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!1}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isStaticResource(S,b=""){return isStaticResource(S,b)}isResourceUrl(S,b=""){return isStaticResource(S,b)}getResourceType(S,b=""){return getResourceType(S,b)}extractRequestDetails(S,b,I,x,R){const A=parseUrl(S);return{method:b.toUpperCase(),url:S,domain:A.hostname,path:A.pathname,status:I,statusText:x,response:R,interceptor:this.interceptorName}}logEvent(S){const b=S?.url||S?.request?.url;if(b&&isInternalSdkEndpoint(b))return;if(this.reporter?._sessionRecorder?.isRecording||this.reporter?.sessionRecording?.isRecording)return;const I={id:generateId(),timestamp:Date.now(),...S};this.reporter.logEvent&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(I)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("string"==typeof S&&0===S.indexOf("network")){const S=this.reporter.config&&this.reporter.config.network;if(S&&!1===S.isEnabled)return!1}const I=b?.url||b?.request?.url;if(I&&isInternalSdkEndpoint(I))return!1;if(!this.reporter.addSessionCustomEvent)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateUserProfileFromContext({url:S,source:b,data:I}){try{if(this.reporter.extractUserContextFromBody&&"function"==typeof this.reporter.extractUserContextFromBody){const x=this.reporter.extractUserContextFromBody({url:S,source:b,data:I});if(Object.keys(x).length>0){let S={};this.reporter._getUserProfile&&"function"==typeof this.reporter._getUserProfile?S=this.reporter._getUserProfile():this.reporter.getUserProfile&&"function"==typeof this.reporter.getUserProfile&&(S=this.reporter.getUserProfile());const b={...S,...x};JSON.stringify(S)!==JSON.stringify(b)&&this.reporter.setUserProfile&&"function"==typeof this.reporter.setUserProfile&&this.reporter.setUserProfile(b)}}}catch(S){this.logger.warn("Failed to update user profile context:",S)}}getNetworkConfig(){const S=this.reporter&&this.reporter.config&&this.reporter.config.network||{};let b="number"==typeof S.maxBodyBytes?S.maxBodyBytes:Pe;b>=0||(b=Pe),b>Be&&(b=Be);const I=Array.isArray(S.sensitiveFields)?S.sensitiveFields:[];return{isEnabled:!1!==S.isEnabled,captureRequestHeaders:!1!==S.captureRequestHeaders,captureResponseHeaders:!1!==S.captureResponseHeaders,captureRequestBody:!1!==S.captureRequestBody,captureResponseBody:!1!==S.captureResponseBody,maxBodyBytes:b,excludeEndpoints:Array.isArray(S.excludeEndpoints)?S.excludeEndpoints:[],requestSanitizer:"function"==typeof S.requestSanitizer?S.requestSanitizer:null,responseSanitizer:"function"==typeof S.responseSanitizer?S.responseSanitizer:null,sensitiveFields:I,_denylist:buildFieldDenylist(I)}}isEndpointExcluded(S,b){const I=b&&b.excludeEndpoints||[],x=String(S||"");for(const S of I)try{if(S instanceof RegExp){if(S.test(x))return!0}else if("string"==typeof S&&S&&x.includes(S))return!0}catch{}return!1}sanitizeRequestUrlFields(S,b){try{return splitSanitizedUrl(S,{extraParams:b&&b.sensitiveFields||[]})}catch{return{url:String(S||""),path:"",query:""}}}mapCaptureToFields(S,b){const I={};return I[`${b}Body`]="string"==typeof S.text?S.text:null,I[`${b}BodyState`]=S.state,I[`${b}BodyRedacted`]=!!S.redacted,I[`${b}BodyTruncated`]=!!S.truncated,"number"==typeof S.originalBytes&&(I[`${b}BodySize`]=S.originalBytes),"number"==typeof S.capturedBytes&&(I[`${b}BodyCapturedBytes`]=S.capturedBytes),S.contentType&&(I[`${b}BodyContentType`]=S.contentType),I}buildRequestBodyFields(S,b,I,x){const R=captureRequestBody(S,{contentTypeHeader:b,maxBytes:I.maxBodyBytes,denylist:I._denylist,sanitizer:I.requestSanitizer,captureEnabled:I.captureRequestBody,excluded:x});return this.mapCaptureToFields(R,"request")}buildResponseBodyFields(S,b,I){const x=captureResponseBody(S,{maxBytes:b.maxBodyBytes,denylist:b._denylist,sanitizer:b.responseSanitizer,captureEnabled:b.captureResponseBody,excluded:I});return this.mapCaptureToFields(x,"response")}handleRequestData(S,b){return handleRequestBody(b,{maxSize:Ne,onWarn:(...S)=>this.logger.warn(...S)})}handleResponseData(S,b){return handleResponseBody(b,{maxSize:Ne,onWarn:(...S)=>this.logger.warn(...S)})}createEvent(S,b,I,x,R,A=null,_=null,D={}){const L={type:S,context:{url:b,method:I.toUpperCase(),status:x,statusText:R,requestData:this.handleRequestData(b,A),responseData:this.handleResponseData(b,_),isMonitored:this.shouldMonitor(b),...D}};return this.shouldExtractFields(b,"response")&&_&&this.updateUserProfileFromContext({url:b,source:"response",data:_}),L}logErrorEvent(S,b,I,x,R=null,A=null,_={}){const D={type:_.errorType||`${this.interceptorName}_http_error`,request:this.extractRequestDetails(S,b,I,x,A),extraData:_,context:{isMonitored:this.shouldMonitor(S),forceLog:I>=400,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}handleSilentLoginFailure(S,b,I,x,R,A){S.toLowerCase().includes("/myava/login")&&(I>=200&&I<300)&&null==R?.LoginToken&&this.logEvent({type:A,request:this.extractRequestDetails(S,b,I,x,R),extraData:R})}logCustomApiError(S,b,I,x,R,A,_={}){const D={type:"custom_api_error",request:this.extractRequestDetails(S,b,I,x,R),extraData:{errorCondition:A,..._},context:{isMonitored:this.shouldMonitor(S),forceLog:!0,url:S,method:b,status:I,statusText:x}};this.logEvent(D)}logUnknownError(S,b,I,x={}){const R={type:"unknown_error",request:{method:b||"UNKNOWN",url:S||"unknown",domain:S?this.extractDomain(S):"unknown",path:S?this.extractPath(S):"unknown",status:0,statusText:"Unknown Error",response:{error:I?.message||"Unknown error occurred",stack:I?.stack||""},interceptor:this.interceptorName},extraData:{errorType:I?.name||"UnknownError",errorMessage:I?.message||"Unknown error",...x},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logEvent(R)}extractDomain(S){try{return new URL(S,window.location.origin).hostname}catch{return"unknown"}}extractPath(S){try{return new URL(S,window.location.origin).pathname}catch{return"unknown"}}destroy(){this.reporter=null,this.logger=null}}function getHeader(S,b){if(!S)return null;const I=b.toLowerCase();if(S instanceof Headers)return S.get(I);for(const b in S)if(b.toLowerCase()===I)return S[b];return null}function setHeader(S,b,I){if(!S)return;if(S instanceof Headers)return void S.set(b,I);const x=b.toLowerCase();for(const b in S)b.toLowerCase()===x&&delete S[b];S[b]=I}function hasHeader(S,b){if(!S)return!1;const I=b.toLowerCase();if(S instanceof Headers)return S.has(I);for(const b in S)if(b.toLowerCase()===I)return!0;return!1}const je=/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/,qe=/^0+$/;function readTraceContextFromHeaders(S){return function parseTraceparent(S){if("string"!=typeof S)return null;const b=S.match(je);if(!b)return null;const I=b[1],x=b[2];return qe.test(I)||qe.test(x)?null:{traceId:I,spanId:x}}(function readTraceparentFromHeaders(S){if(!S)return null;if("undefined"!=typeof Headers&&S instanceof Headers){const b=S.get("traceparent");return"string"==typeof b?b:null}if("object"==typeof S)for(const b of Object.keys(S))if("traceparent"===b.toLowerCase()){const I=S[b];return"string"==typeof I?I:null}return null}(S))}function isSameOrigin(S,b,I){const x=function resolveOrigin(S,b){try{const I=b||"undefined"!=typeof window&&window.location&&window.location.href||void 0;return new URL(S,I).origin}catch{return null}}(S,I),R=function currentOrigin(S){return S||("undefined"!=typeof window&&window.location?window.location.origin:null)}(b);return null!==x&&null!==R&&x===R}function tracePropagationDecision(S,b={}){const{pageOrigin:I,pageHref:x}=b;return"string"==typeof S&&isInternalSdkEndpoint(S)?{traceparent:!1,baggage:!1,reason:"sdk_ingest_excluded"}:isSameOrigin(S,I,x)?{traceparent:!0,baggage:!0,reason:"same_origin"}:{traceparent:!1,baggage:!1,reason:"third_party"}}const We="undefined"!=typeof window&&window.fetch?window.fetch.bind(window):void 0;class FetchInterceptor extends BaseInterceptor{constructor(S){super(S,"fetch"),this.originalFetch=We}setup(){this.logger.log("Initializing Fetch interceptor...");const S=this;window._apiReporter_originalFetch||(window._apiReporter_originalFetch=this.originalFetch),window.fetch=async function(...b){const I=(b=S.injectCorrelationHeaders(b))[0]instanceof Request?b[0].url:String(b[0]),x=b[1]||{},R=x.method||(b[0]instanceof Request?b[0].method:"GET"),A=x.body;let _={};b[0]instanceof Request?b[0].headers.forEach((S,b)=>{_[b]=S}):x.headers&&(x.headers instanceof Headers?x.headers.forEach((S,b)=>{_[b]=S}):Object.assign(_,x.headers));const D=filterSensitiveHeaders(_),L=S.shouldMonitor(I),B=S.isStaticResource(I);let U=null;L&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&(U=S.reporter.performanceMonitor.generateRequestId(),S.reporter.performanceMonitor.startTracking(U,I,R));const $=Date.now();if(!B){const b=S.getNetworkConfig(),x=S.isEndpointExcluded(I,b),L=S.sanitizeRequestUrlFields(I,b),B=getHeader(_,"content-type"),U=S.buildRequestBodyFields(A,B,b,x),j={interceptor:"fetch",method:R,url:L.url,requestHeaders:b.captureRequestHeaders?D:{},timestamp:$,...U};L.path&&(j.requestPath=L.path),L.query&&(j.requestQuery=L.query);const W=readTraceContextFromHeaders(_);W&&(j.traceId=W.traceId,j.spanId=W.spanId),S.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing API request:",{url:L.url,hasHeaders:!!D&&Object.keys(D).length>0,bodyState:U.requestBodyState}),S.addToSessionReplay("network_request",j)}try{const x=await S.originalFetch.apply(window,b);let A=null;return U&&(A=S.reporter.performanceMonitor.endTracking(U,x.status)),await S.handleResponse(x,I,R,A),x}catch(b){throw U&&S.reporter.performanceMonitor.endTracking(U,0),S.handleNetworkError(I,R,b,"fetch_network_error"),b}},this.logger.log("Fetch interceptor setup complete")}async handleResponse(S,b,I,x){const R=this.getNetworkConfig(),A=this.isEndpointExcluded(b,R);let _=null,D=!1;try{_=S.clone()}catch{D=!0}const L="opaque"===S.type,B=_&&_.headers&&_.headers.get("content-type")||"",U={};_&&_.headers&&_.headers.forEach((S,b)=>{U[b]=S});const $=R.captureResponseHeaders?filterSensitiveHeaders(U):{},j=_&&_.headers?_.headers.get("content-length"):null,W=j?parseInt(j,10):null;let H=null,V=!1,Q=null;const G=!L&&!D&&isTextualContentType(B);if(G){try{H=await _.text()}catch{V=!0}if(!V&&null!=H){const S=safeMime(B);if(S&&"json"===classifyMime(S))try{Q=JSON.parse(H)}catch{Q=H}else Q=H}}else D&&!L&&(V=!0);const J=this.buildResponseBodyFields({opaque:L,readError:V,text:G?H:null,contentTypeHeader:B,knownSize:W},R,A),X=this.isStaticResource(b,B);!X&&x?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,Q,x),x?.performanceAlert&&this.logPerformanceAlert(x.metrics),X?this.handleStaticResource(b,I,S.status,S.statusText,B,x,_||S):this.handleApiResponse(b,I,S.status,S.statusText,Q,x,$,J,R)}handleStaticResource(S,b,I,x,R,A,_){const D=_.headers?.get("content-length"),L=D?parseInt(D,10):null,B={interceptor:"fetch",method:b,url:S,status:I,statusText:x,resourceType:this.getResourceType(S,R),size:L,duration:A?.duration||null,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing static resource:",{url:S,status:I,resourceType:B.resourceType,size:L}),this.addToSessionReplay("network_resource",B),I>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(S,b,I,x,null,null,{errorType:"resource_load_error",contentType:R,resourceType:B.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"fetch",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing response:",{url:U.url,status:I,hasHeaders:!!_&&Object.keys(_).length>0,bodyState:$.responseBodyState}),this.addToSessionReplay("network_response",$),I>=400?this.logErrorEvent(S,b,I,x,null,R,{errorType:"fetch_http_error",performanceData:A}):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"fetch_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"fetch_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logger.log(`Slow request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"fetch",method:b,url:R.url,status:0,statusText:"Network Error",errorMessage:I.message||"Network request failed",errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,"Network Error",null,null,{errorType:x,errorMessage:I.message||"Network request failed",errorStack:I.stack})}destroy(){window._apiReporter_originalFetch&&(window.fetch=window._apiReporter_originalFetch,delete window._apiReporter_originalFetch),super.destroy()}injectCorrelationHeaders(S){const b=SDKContext.getInstance();if(!b||!b.sessionId)return S;const I=tracePropagationDecision(S[0]instanceof Request?S[0].url:String(S[0]));if(!I.traceparent&&!I.baggage)return S;const x=[];if(I.baggage&&(b.sessionId&&x.push(`sessionId=${encodeURIComponent(b.sessionId)}`),b.userId&&x.push(`userId=${encodeURIComponent(b.userId)}`),b.projectId&&x.push(`projectId=${encodeURIComponent(b.projectId)}`)),S[0]instanceof Request){const b=S[0],R=S[1]||{},A=new Headers(b.headers);if(R.headers)if(R.headers instanceof Headers)R.headers.forEach((S,b)=>A.set(b,S));else for(const S in R.headers)A.set(S,R.headers[S]);const _=hasHeader(A,"traceparent");I.baggage&&x.length>0&&!getHeader(A,"baggage")&&setHeader(A,"baggage",x.join(",")),I.traceparent&&!_&&setHeader(A,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`);const D={...R};delete D.headers;return[new Request(b,{...D,headers:A})]}const R=S[0],A=S[1]||{};if(A.headers=A.headers||{},A.headers instanceof Headers){const S={};A.headers.forEach((b,I)=>{S[I]=b}),A.headers=S}const _=hasHeader(A.headers,"traceparent");return I.baggage&&x.length>0&&!getHeader(A.headers,"baggage")&&setHeader(A.headers,"baggage",x.join(",")),I.traceparent&&!_&&setHeader(A.headers,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`),[R,A]}generateW3CTraceId(){const S=new Uint8Array(16);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=new Uint8Array(8);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}}class XHRInterceptor extends BaseInterceptor{constructor(S){super(S,"xhr"),this.originalOpen=XMLHttpRequest.prototype.open,this.originalSend=XMLHttpRequest.prototype.send}setup(){this.logger.log("Initializing XHR interceptor...");const S=this;XMLHttpRequest.prototype.open=function(b,I,...x){return this._apiReporterUrl=I,this._apiReporterMethod=b.toUpperCase(),this._apiReporterRequestHeaders={},this._apiReporterUserSetHeaders=new Set,this._apiReporterHeadersInjected=!1,S.originalOpen.call(this,b,I,...x)};const b=XMLHttpRequest.prototype.setRequestHeader;XMLHttpRequest.prototype.setRequestHeader=function(S,I){return this._apiReporterRequestHeaders||(this._apiReporterRequestHeaders={}),this._apiReporterUserSetHeaders||(this._apiReporterUserSetHeaders=new Set),this._apiReporterUserSetHeaders.add(S.toLowerCase()),setHeader(this._apiReporterRequestHeaders,S,I),b.call(this,S,I)},XMLHttpRequest.prototype.send=function(...b){const I=this;if(!I._apiReporterHeadersInjected){const b=I._apiReporterUserSetHeaders?.has("traceparent");S.injectXHRCorrelationHeaders(I,b),I._apiReporterHeadersInjected=!0}const{_apiReporterUrl:x,_apiReporterMethod:R,_apiReporterRequestHeaders:A}=I,_=filterSensitiveHeaders(A||{}),D=S.shouldMonitor(x),L=S.isStaticResource(x),B=b[0],U=Date.now();I._apiReporterStartTime=U,S.logger.log(`XHR Request: ${R} ${x}, shouldMonitor: ${D}, isResource: ${L}`);let $=null;if(D&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&($=S.reporter.performanceMonitor.generateRequestId(),I._apiReporterRequestId=$,S.reporter.performanceMonitor.startTracking($,x,R)),!L){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(x,b),D=S.sanitizeRequestUrlFields(x,b),L=getHeader(A||{},"content-type"),$=S.buildRequestBodyFields(B,L,b,I),j={interceptor:"xhr",method:R,url:D.url,requestHeaders:b.captureRequestHeaders&&_||{},timestamp:U,...$};D.path&&(j.requestPath=D.path),D.query&&(j.requestQuery=D.query);const W=readTraceContextFromHeaders(A);W&&(j.traceId=W.traceId,j.spanId=W.spanId),S.addToSessionReplay("network_request",j)}return I.addEventListener("load",()=>S.handleXHRLoad(I,x,R,L)),I.addEventListener("error",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Network error"),"xhr_network_error")}),I.addEventListener("timeout",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request timed out"),"xhr_timeout_error")}),I.addEventListener("abort",()=>{I._apiReporterRequestId&&S.reporter.performanceMonitor.endTracking(I._apiReporterRequestId,0),L||S.handleNetworkError(x,R,new Error("Request aborted"),"xhr_aborted_error")}),S.originalSend.apply(I,b)},this.logger.log("XHR interceptor setup complete")}handleXHRLoad(S,b,I,x){let R=null;S._apiReporterRequestId&&(R=this.reporter.performanceMonitor.endTracking(S._apiReporterRequestId,S.status));const A=S.getResponseHeader("content-type")||"",_=R?.duration||(S._apiReporterStartTime?Date.now()-S._apiReporterStartTime:null);if(x)return void this.handleStaticResource(S,b,I,A,_);const D=this.getNetworkConfig(),L=this.isEndpointExcluded(b,D);let B=null,U=null;try{const b=S.responseType;if(""===b||"text"===b){const b=S.responseText||null;if(B={text:b,contentTypeHeader:A},b){const S=safeMime(A);if(S&&"json"===classifyMime(S))try{U=JSON.parse(b)}catch{U=b}else U=b}}else if("json"===b){const b=S.response;U=b;let I=null;try{I=null==b?null:JSON.stringify(b)}catch{I=null}B={text:I,contentTypeHeader:A||"application/json"}}else{const I=S.getResponseHeader("content-length");B={binary:!0,contentTypeHeader:A,knownSize:I?parseInt(I,10):null},U=`[${String(b).toUpperCase()} data]`}}catch(S){this.logger.warn(`Failed to read XHR response for ${b}`),B={readError:!0,contentTypeHeader:A},U={error:"Failed to read response",originalError:S.message}}const $=this.parseXHRResponseHeaders(S.getAllResponseHeaders?.()),j=D.captureResponseHeaders?filterSensitiveHeaders($):{},W=this.buildResponseBodyFields(B,D,L);R?.isSlowRequest&&S.status>=200&&S.status<300&&this.logSlowRequest(b,I,S.status,S.statusText,U,R),R?.performanceAlert&&this.logPerformanceAlert(R.metrics),this.handleApiResponse(b,I,S.status,S.statusText,U,R,j,W,D)}parseXHRResponseHeaders(S){const b={};if(!S||"string"!=typeof S)return b;for(const I of S.trim().split(/[\r\n]+/)){const S=I.indexOf(":");if(-1===S)continue;const x=I.slice(0,S).trim(),R=I.slice(S+1).trim();x&&(b[x]=R)}return b}handleStaticResource(S,b,I,x,R){const A=S.getResponseHeader("content-length"),_=A?parseInt(A,10):null,D={interceptor:"xhr",method:I,url:b,status:S.status,statusText:S.statusText,resourceType:this.getResourceType(b,x),size:_,duration:R,timestamp:Date.now()};this.reporter?.config?.debug&&console.log("[XHRInterceptor] Capturing static resource:",{url:b,status:S.status,resourceType:D.resourceType,size:_}),this.addToSessionReplay("network_resource",D),S.status>=400&&this.reporter.config?.logResourceErrors&&this.logErrorEvent(b,I,S.status,S.statusText,null,null,{errorType:"resource_load_error",contentType:x,resourceType:D.resourceType})}handleApiResponse(S,b,I,x,R,A,_,D,L){this.logger.log(`Handling API response: ${b} ${S}, status: ${I}`);const B=L||this.getNetworkConfig(),U=this.sanitizeRequestUrlFields(S,B),$={interceptor:"xhr",method:b,url:U.url,status:I,statusText:x,responseHeaders:B.captureResponseHeaders&&_||{},duration:A?.duration,timing:A?{dns:A.dns,tcp:A.tcp,request:A.request,response:A.response,total:A.duration}:null,timestamp:Date.now(),...D||{}};U.path&&($.requestPath=U.path),U.query&&($.requestQuery=U.query),this.addToSessionReplay("network_response",$),I>=400?(this.logger.log(`Logging error event for: ${S} with status ${I}`),this.logErrorEvent(S,b,I,x,null,R,{errorType:"xhr_http_error",performanceData:A})):I>=200&&I<300&&this.handleSilentLoginFailure(S,b,I,x,R,"xhr_silent_login_failure")}logSlowRequest(S,b,I,x,R,A){const _={type:"xhr_slow_request",request:this.extractRequestDetails(S,b,I,x,R),performance:{duration:A.duration,durationSeconds:A.durationSeconds,threshold:this.reporter.config?.slowRequestThreshold||2e3,endpoint:A.endpoint},context:{isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logger.log(`Slow XHR request detected: ${S} took ${A.durationSeconds}s`),this.logEvent(_)}logPerformanceAlert(S){const b={type:S.type||"performance_degradation_alert",severity:S.severity||"warning",metrics:{currentAverage:S.averageSeconds,currentMedian:S.medianSeconds,threshold:2.5,sessionRequests:S.totalRequests,slowRequestCount:S.slowRequests,slowRequestPercentage:S.slowRequestPercentage,slowestEndpoints:S.slowestEndpoints},message:S.message,context:{forceLog:!0,isMonitored:!0,timestamp:S.timestamp,interceptor:this.interceptorName}};this.logEvent(b)}handleNetworkError(S,b,I,x){const R=this.sanitizeRequestUrlFields(S,this.getNetworkConfig());this.addToSessionReplay("network_error",{interceptor:"xhr",method:b,url:R.url,status:0,statusText:I.message||"Network Error",errorMessage:I.message,errorStack:I.stack,timestamp:Date.now()}),this.logErrorEvent(S,b,0,I.message,null,null,{errorType:x,errorMessage:I.message,errorStack:I.stack})}destroy(){XMLHttpRequest.prototype.open=this.originalOpen,XMLHttpRequest.prototype.send=this.originalSend,super.destroy()}injectXHRCorrelationHeaders(S,b){const I=SDKContext.getInstance();if(!I||!I.sessionId)return;const x=tracePropagationDecision(String(S._apiReporterUrl||""));if(x.traceparent||x.baggage){if(x.baggage&&!getHeader(S._apiReporterRequestHeaders,"baggage")){const b=[];I.sessionId&&b.push(`sessionId=${encodeURIComponent(I.sessionId)}`),I.userId&&b.push(`userId=${encodeURIComponent(I.userId)}`),I.projectId&&b.push(`projectId=${encodeURIComponent(I.projectId)}`),b.length>0&&S.setRequestHeader("baggage",b.join(","))}if(x.traceparent&&!b){const b=`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`;S.setRequestHeader("traceparent",b)}}}generateW3CTraceId(){const S=new Uint8Array(16);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=new Uint8Array(8);return crypto.getRandomValues(S),Array.from(S,S=>S.toString(16).padStart(2,"0")).join("")}}const He=["token","access_token","auth","authorization","api_key","apikey","key","session","sessionid","session_id","sid","password","pwd","secret","email","jwt","bearer","refresh_token","id_token"];class LRUDedupeCache{constructor(S=5e3){this.maxSize=S,this.cache=new Map}has(S){if(this.cache.has(S)){const b=this.cache.get(S);return this.cache.delete(S),this.cache.set(S,b),!0}return!1}add(S){if(this.cache.has(S))this.cache.delete(S);else if(this.cache.size>=this.maxSize){const S=this.cache.keys().next().value;this.cache.delete(S)}this.cache.set(S,!0)}clear(){this.cache.clear()}get size(){return this.cache.size}}class PerformanceResourceObserver{constructor(S,b={}){this.reporter=S,this.logger=createLogger("PerformanceResourceObserver"),this.config={captureResources:!1!==b.captureResources,captureNavigation:!1!==b.captureNavigation,maxDedupeEntries:b.maxDedupeEntries||5e3,filterOtherInitiator:!1!==b.filterOtherInitiator,debug:b.debug||this.reporter?.config?.debug||!1,maxResourceEntriesPerSession:b.maxResourceEntriesPerSession||2e3,resourceAllowlist:b.resourceAllowlist||null,resourceBlocklist:b.resourceBlocklist||null},this.allowlistRegexes=this.compilePatterns(this.config.resourceAllowlist),this.blocklistRegexes=this.compilePatterns(this.config.resourceBlocklist),this.resourceObserver=null,this.navigationObserver=null,this.processedEntries=new LRUDedupeCache(this.config.maxDedupeEntries),this.isDestroyed=!1,this.sessionResourceCount=0,this.sessionCapReached=!1,this.eventCount=0,this.eventCountResetTime=Date.now(),this.maxEventsPerMinute=this.reporter?.config?.maxEventsPerMinute||500}compilePatterns(S){if(!S||!Array.isArray(S)||0===S.length)return null;try{return S.map(S=>new RegExp(S,"i"))}catch(S){return this.logger?.warn?.("Invalid regex pattern in allowlist/blocklist:",S.message),null}}passesUrlFilters(S){if(this.blocklistRegexes)for(const b of this.blocklistRegexes)if(b.test(S))return!1;if(this.allowlistRegexes){for(const b of this.allowlistRegexes)if(b.test(S))return!0;return!1}return!0}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed PerformanceResourceObserver"):"undefined"!=typeof PerformanceObserver?(this.config.captureResources&&this.setupResourceObserver(),this.config.captureNavigation&&this.setupNavigationObserver(),this.logger.log("PerformanceResourceObserver setup complete",{captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation})):this.logger.warn("PerformanceObserver not supported in this browser")}setupResourceObserver(){try{this.resourceObserver=new PerformanceObserver(S=>{for(const b of S.getEntries())this.processResourceEntry(b)}),this.resourceObserver.observe({type:"resource",buffered:!0}),this.logger.log("Resource observer initialized")}catch(S){this.logger.warn("Failed to setup resource observer:",S.message)}}setupNavigationObserver(){try{this.navigationObserver=new PerformanceObserver(S=>{for(const b of S.getEntries())this.processNavigationEntry(b)}),this.navigationObserver.observe({type:"navigation",buffered:!0}),this.logger.log("Navigation observer initialized")}catch(S){this.logger.warn("Failed to setup navigation observer:",S.message)}}processResourceEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(this.sessionResourceCount>=this.config.maxResourceEntriesPerSession)return void(this.sessionCapReached||(this.sessionCapReached=!0,this.logger.warn(`Session resource cap reached (${this.config.maxResourceEntriesPerSession}). Stopping resource capture.`)));if(!this.checkRateLimit())return;const b=S.initiatorType;if("fetch"===b||"xmlhttprequest"===b)return;if(this.config.filterOtherInitiator&&"other"===b){const b=(S.transferSize||S.encodedBodySize||S.decodedBodySize)>0,I=S.duration>10;if(!b&&!I)return}if(!this.passesUrlFilters(S.name))return;const I=`${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(I))return;this.processedEntries.add(I);const x=this.sanitizeUrl(S.name),R=this.mapInitiatorType(b,S.name),A=this.extractTimingPhases(S),_={interceptor:"performance",method:"GET",url:x,status:this.getResponseStatus(S),resourceType:R,initiatorType:b,duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:A,timestamp:Math.round(performance.timeOrigin+S.startTime)};this.addToSessionReplay("network_resource",_)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured resource:",{url:x.substring(0,80),type:R,duration:_.duration,cached:_.cached,sessionCount:this.sessionResourceCount})}processNavigationEntry(S){if(this.isDestroyed)return;if(this.sessionCapReached)return;if(!this.checkRateLimit())return;const b=`nav-${S.name}-${Math.round(S.startTime)}`;if(this.processedEntries.has(b))return;this.processedEntries.add(b);const I=this.sanitizeUrl(S.name),x=this.extractTimingPhases(S),R={dns:x.dns,tcp:x.tcp,ssl:x.ssl,ttfb:Math.round(S.responseStart-S.requestStart),download:Math.round(S.responseEnd-S.responseStart),domInteractive:Math.round(S.domInteractive-S.responseEnd),domContentLoaded:Math.round(S.domContentLoadedEventEnd-S.responseEnd),loadComplete:Math.round(S.loadEventEnd-S.startTime)},A={interceptor:"performance",method:"GET",url:I,status:this.getResponseStatus(S),resourceType:"document",initiatorType:"navigation",duration:Math.round(S.duration),size:S.transferSize||S.encodedBodySize||null,cached:this.isCached(S),timing:R,navigationType:S.type,timestamp:Math.round(performance.timeOrigin+S.startTime)};this.addToSessionReplay("network_resource",A)&&this.sessionResourceCount++,this.config.debug&&this.logger.log("Captured navigation:",{url:I.substring(0,80),type:S.type,loadTime:R.loadComplete,sessionCount:this.sessionResourceCount})}sanitizeUrl(S){if(!S)return S;try{const b=new URL(S);for(const S of He){b.searchParams.has(S)&&b.searchParams.delete(S);for(const[I]of b.searchParams.entries())I.toLowerCase()===S.toLowerCase()&&b.searchParams.delete(I)}return b.hash="",b.toString()}catch(b){return S.length>500?S.substring(0,500):S}}mapInitiatorType(S,b=""){const I={script:"script",link:"stylesheet",css:"stylesheet",img:"image",image:"image",font:"font",video:"media",audio:"media",iframe:"document",navigation:"document",beacon:"beacon"};if(I[S]){if("link"===S){const S=b.toLowerCase();return S.includes(".css")?"stylesheet":S.includes(".woff")||S.includes(".ttf")||S.includes(".eot")?"font":"stylesheet"}return I[S]}return getResourceType(b,"")}extractTimingPhases(S){return{dns:Math.max(0,Math.round(S.domainLookupEnd-S.domainLookupStart)),tcp:Math.max(0,Math.round(S.connectEnd-S.connectStart)),ssl:S.secureConnectionStart>0?Math.max(0,Math.round(S.connectEnd-S.secureConnectionStart)):0,ttfb:Math.max(0,Math.round(S.responseStart-S.requestStart)),download:Math.max(0,Math.round(S.responseEnd-S.responseStart)),total:Math.round(S.duration)}}getResponseStatus(S){return"number"==typeof S.responseStatus?S.responseStatus:0===S.duration&&0===S.transferSize&&0===S.decodedBodySize?0:200}isCached(S){return 0===S.transferSize&&S.decodedBodySize>0||S.domainLookupEnd===S.domainLookupStart&&S.connectEnd===S.connectStart&&S.requestStart>0}checkRateLimit(){const S=Date.now();return S-this.eventCountResetTime>6e4&&(this.eventCount=0,this.eventCountResetTime=S),!(this.eventCount>=this.maxEventsPerMinute)&&(this.eventCount++,!0)}addToSessionReplay(S,b){if(!this.reporter)return!1;if("function"!=typeof this.reporter.addSessionCustomEvent)return!1;try{return this.reporter.addSessionCustomEvent(S,b)}catch(S){return this.logger.warn("Failed to add event to session replay:",S),!1}}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}updateConfig(S){void 0!==S.captureResources&&S.captureResources!==this.config.captureResources&&(this.config.captureResources=S.captureResources,S.captureResources&&!this.resourceObserver?this.setupResourceObserver():!S.captureResources&&this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null)),void 0!==S.captureNavigation&&S.captureNavigation!==this.config.captureNavigation&&(this.config.captureNavigation=S.captureNavigation,S.captureNavigation&&!this.navigationObserver?this.setupNavigationObserver():!S.captureNavigation&&this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null)),void 0!==S.debug&&(this.config.debug=S.debug),void 0!==S.maxDedupeEntries&&(this.config.maxDedupeEntries=S.maxDedupeEntries),void 0!==S.filterOtherInitiator&&(this.config.filterOtherInitiator=S.filterOtherInitiator)}getStats(){return{dedupeEntriesCount:this.processedEntries.size,maxDedupeEntries:this.config.maxDedupeEntries,eventsThisMinute:this.eventCount,maxEventsPerMinute:this.maxEventsPerMinute,captureResources:this.config.captureResources,captureNavigation:this.config.captureNavigation,resourceObserverActive:!!this.resourceObserver,navigationObserverActive:!!this.navigationObserver,sessionResourceCount:this.sessionResourceCount,maxResourceEntriesPerSession:this.config.maxResourceEntriesPerSession,sessionCapReached:this.sessionCapReached,hasAllowlist:!!this.allowlistRegexes,hasBlocklist:!!this.blocklistRegexes}}destroy(){this.isDestroyed?this.logger.warn("PerformanceResourceObserver already destroyed"):(this.isDestroyed=!0,this.resourceObserver&&(this.resourceObserver.disconnect(),this.resourceObserver=null),this.navigationObserver&&(this.navigationObserver.disconnect(),this.navigationObserver=null),this.processedEntries.clear(),this.reporter=null,this.logger.log("PerformanceResourceObserver destroyed"))}}class ErrorFingerprint{constructor(S={}){this.maxUniqueErrors=S.maxUniqueErrors||100,this.throttleWindow=S.throttleWindow||6e4,this.maxPerFingerprint=S.maxPerFingerprint||5,this.seenFingerprints=new Map,this.cleanupInterval=null,this.startCleanup()}generateFingerprint(S){if(!S)return"unknown_error";return`${this.getErrorName(S)}::${this.normalizeMessage(this.getErrorMessage(S))}::${this.getFirstMeaningfulStackLine(S.stack)}`}getErrorName(S){return S.name?S.name:S.constructor&&S.constructor.name?S.constructor.name:S.type?S.type:"Error"}getErrorMessage(S){return"string"==typeof S?S:S.message?S.message:S.reason?String(S.reason):String(S)}normalizeMessage(S){return S&&"string"==typeof S?S.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"[UUID]").replace(/\b(0x)?[0-9a-f]{8,}\b/gi,"[HEX]").replace(/\b\d+\b/g,"[N]").replace(/https?:\/\/[^\s'"]+/gi,"[URL]").replace(/\/[\w./-]+\.(js|ts|jsx|tsx|mjs|cjs)/gi,"[PATH]").replace(/"[^"]*"/g,"[STR]").replace(/'[^']*'/g,"[STR]").replace(/[\w.+-]+@[\w.-]+\.\w+/gi,"[EMAIL]").replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,"[IP]").replace(/\s+/g," ").substring(0,200).trim():""}getFirstMeaningfulStackLine(S){if(!S||"string"!=typeof S)return"unknown";const b=[/tracescout/i,/rrweb/i,/node_modules/,/<anonymous>/,/native code/i,/eval at/i,/^\s*at\s*$/],I=S.split("\n");for(const S of I){if(!S.trim()||S.match(/^[\w]*Error:/))continue;if(b.some(b=>b.test(S)))continue;const I=S.match(/(?:at\s+)?(?:[\w.<>[\]]+\s+\()?([^()\s]+):(\d+):(\d+)\)?/);if(I){const[,S,b,x]=I;return`${S.split("/").pop().split("\\").pop()}:${b}:${x}`}const x=S.match(/@([^@]+):(\d+):(\d+)/);if(x){const[,S,b,I]=x;return`${S.split("/").pop().split("\\").pop()}:${b}:${I}`}}return"unknown"}shouldCapture(S){const b=Date.now(),I=this.seenFingerprints.get(S);if(!I)return this.seenFingerprints.set(S,{count:1,firstSeen:b,lastSeen:b,windowStart:b}),this.seenFingerprints.size>this.maxUniqueErrors&&this.evictOldest(),{shouldCapture:!0,count:1,isFirst:!0};if(b-I.windowStart>this.throttleWindow)return I.count=1,I.windowStart=b,I.lastSeen=b,{shouldCapture:!0,count:1,isFirst:!1};I.count++,I.lastSeen=b;const x=I.count<=this.maxPerFingerprint;return{shouldCapture:x,count:I.count,isFirst:!1,throttled:!x}}getStats(S){return this.seenFingerprints.get(S)||null}getAllStats(){const S=[];return this.seenFingerprints.forEach((b,I)=>{S.push({fingerprint:I,...b})}),S.sort((S,b)=>b.count-S.count)}evictOldest(){let S=null,b=1/0;this.seenFingerprints.forEach((I,x)=>{I.lastSeen<b&&(b=I.lastSeen,S=x)}),S&&this.seenFingerprints.delete(S)}startCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanup()},3e5)}cleanup(){const S=Date.now(),b=2*this.throttleWindow;this.seenFingerprints.forEach((I,x)=>{S-I.lastSeen>b&&this.seenFingerprints.delete(x)})}reset(){this.seenFingerprints.clear()}destroy(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.seenFingerprints.clear()}}class ErrorHandler{constructor(S,b={},I=null){this.eventManager=S,this.reporter=I,this.config={captureErrors:!1!==b.captureErrors,captureUnhandledRejections:!1!==b.captureUnhandledRejections,maxStackTraceLength:b.maxStackTraceLength||5e3,filterErrors:b.filterErrors||[],enableFingerprinting:!1!==b.enableFingerprinting,maxUniqueErrors:b.maxUniqueErrors||100,throttleWindow:b.throttleWindow||6e4,maxPerFingerprint:b.maxPerFingerprint||5,...b},this.logger=createLogger("ErrorHandler"),this.originalHandlers={},this.installed=!1,this.config.enableFingerprinting&&(this.fingerprinter=new ErrorFingerprint({maxUniqueErrors:this.config.maxUniqueErrors,throttleWindow:this.config.throttleWindow,maxPerFingerprint:this.config.maxPerFingerprint}))}install(){this.installed||(this.config.captureErrors&&(this.originalHandlers.onerror=window.onerror,window.onerror=this.handleError.bind(this)),this.config.captureUnhandledRejections&&(this.originalHandlers.onunhandledrejection=window.onunhandledrejection,window.addEventListener("unhandledrejection",this.handleUnhandledRejection.bind(this))),this.installed=!0,this.logger.debug("Error handler installed"))}uninstall(){this.installed&&(this.originalHandlers.onerror&&(window.onerror=this.originalHandlers.onerror),this.originalHandlers.onunhandledrejection&&(window.removeEventListener("unhandledrejection",this.handleUnhandledRejection),this.originalHandlers.onunhandledrejection&&(window.onunhandledrejection=this.originalHandlers.onunhandledrejection)),this.fingerprinter&&this.fingerprinter.destroy(),this.originalHandlers={},this.installed=!1,this.logger.debug("Error handler uninstalled"))}handleError(S,b,I,x,R){try{if(this.shouldFilterError(S,R))return;let A=null,_=null;if(this.fingerprinter&&(A=this.fingerprinter.generateFingerprint(R||{message:S,stack:`at ${b}:${I}:${x}`}),_=this.fingerprinter.shouldCapture(A),!_.shouldCapture))return _.count===this.config.maxPerFingerprint+1&&this.logger.debug(`Error throttled: "${S.substring(0,50)}..." (${_.count} occurrences)`),this.originalHandlers.onerror?this.originalHandlers.onerror(S,b,I,x,R):void 0;SDKContext.getInstance()?.recordError();const D={type:"error",category:"error",message:String(S),source:b,lineno:I,colno:x,stack:this.getStackTrace(R),timestamp:Date.now(),userAgent:navigator.userAgent,url:window.location.href,fingerprint:A,occurrenceCount:_?.count||1,isFirstOccurrence:_?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",D),console.log("[TraceScout][ErrorHandler] Checking reporter:",{hasReporter:!!this.reporter,hasMethod:!(!this.reporter||!this.reporter.addSessionCustomEvent),isFunction:!(!this.reporter||"function"!=typeof this.reporter.addSessionCustomEvent)}),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{console.log("[TraceScout][ErrorHandler] Adding error to session replay:",D.message),this.reporter.addSessionCustomEvent("error",{message:D.message,stack:D.stack,fingerprint:D.fingerprint,source:D.source,lineno:D.lineno,colno:D.colno,timestamp:D.timestamp,url:D.url,userAgent:D.userAgent,occurrenceCount:D.occurrenceCount,isFirstOccurrence:D.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture error:",S)}if(this.originalHandlers.onerror)return this.originalHandlers.onerror(S,b,I,x,R)}handleUnhandledRejection(S){try{const b=S.reason;let I=null,x=null;if(this.fingerprinter&&(I=this.fingerprinter.generateFingerprint(b||{message:"Unhandled Promise Rejection"}),x=this.fingerprinter.shouldCapture(I),!x.shouldCapture)){if(x.count===this.config.maxPerFingerprint+1){const S=b?String(b).substring(0,50):"Promise rejection";this.logger.debug(`Promise rejection throttled: "${S}..." (${x.count} occurrences)`)}return void(this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S))}SDKContext.getInstance()?.recordError();const R={type:"unhandledRejection",category:"error",message:b?String(b):"Unhandled Promise Rejection",stack:this.getStackTrace(b),promiseState:"rejected",timestamp:Date.now(),userAgent:navigator.userAgent,url:window.location.href,fingerprint:I,occurrenceCount:x?.count||1,isFirstOccurrence:x?.isFirst??!0};if(this.eventManager&&"function"==typeof this.eventManager.logEvent&&this.eventManager.logEvent("error",R),this.reporter&&this.reporter.addSessionCustomEvent&&"function"==typeof this.reporter.addSessionCustomEvent)try{this.reporter.addSessionCustomEvent("unhandledRejection",{message:R.message,stack:R.stack,fingerprint:R.fingerprint,timestamp:R.timestamp,url:R.url,userAgent:R.userAgent,occurrenceCount:R.occurrenceCount,isFirstOccurrence:R.isFirstOccurrence})}catch(S){}}catch(S){this.logger.error("Failed to capture unhandled rejection:",S)}this.originalHandlers.onunhandledrejection&&this.originalHandlers.onunhandledrejection(S)}shouldFilterError(S,b){return this.config.filterErrors.some(I=>"string"==typeof I?S.includes(I):I instanceof RegExp?I.test(S):"function"==typeof I&&I(S,b))}getStackTrace(S){if(!S)return"";let b="";return S.stack?b=S.stack:S instanceof Error&&(b=S.toString()),b.length>this.config.maxStackTraceLength&&(b=b.substring(0,this.config.maxStackTraceLength)+"..."),b}getErrorStats(){return this.fingerprinter?this.fingerprinter.getAllStats():[]}resetErrorTracking(){this.fingerprinter&&this.fingerprinter.reset()}}class PostMessageInterceptor{constructor(S){this.reporter=S,this.logger=createLogger("PostMessageInterceptor"),this.originalPostMessage=window.postMessage,this.boundMessageHandler=this.handleMessage.bind(this),this.messageCounter=0,this.suspiciousOrigins=[],this.errorCount=0,this.isDestroyed=!1,this.config=null,this.whitelist=[]}setup(){if(this.isDestroyed)return void this.logger.warn("Attempted to setup destroyed PostMessageMonitor");this.logger.log("Initializing PostMessage monitor...");const S=this;this.config=this.reporter.config?.monitorPostMessages||{},this.whitelist=this.config.postMessageOriginWhitelist||[],window.postMessage=function(b,I,...x){const R=window.location.origin;if(S.shouldMonitor(I,"outgoing",b)){const x=S.getEventType(b);S.logger.log(`Outgoing PostMessage [${x}]: ${R} -> ${I}`),S.logPostMessage({direction:"outgoing",message:b,targetOrigin:I,sourceOrigin:R,eventType:x})}return S.originalPostMessage.call(this,b,I,...x)},window.addEventListener("message",this.boundMessageHandler),this.logger.log("PostMessage monitor setup complete")}handleMessage(S){if(!this.isDestroyed)try{if(this.shouldMonitor(S.origin,"incoming",S.data)){const b=this.getEventType(S.data);this.logger.log(`Incoming PostMessage [${b}]: ${S.origin} -> ${window.location.origin}`),this.logPostMessage({direction:"incoming",message:S.data,sourceOrigin:S.origin,targetOrigin:window.location.origin,source:this.getSourceInfo(S.source),eventType:b}),this.shouldExtractFields("postmessage","message")&&this.extractUserData(S.origin,S.data)}}catch(b){this.logger.error("Error handling message:",b),this.logPostMessageError(S,b)}}shouldMonitor(S,b,I){if(!this.config||"object"!=typeof this.config)return!1;if(this.whitelist.length>0&&!this.isOriginWhitelisted(S))return!1;const x=this.getEventType(I),R=(this.config.excludePostMessagesEvents||[]).includes(x),A=this.config.monitorSpecificPostMessagesEvents||[];return!R&&(0===A.length||A.includes(x))}shouldExtractFields(S,b){return this.reporter.shouldExtractFields?.(S,b)||!1}isOriginWhitelisted(S){if(this.whitelist.includes("*"))return!0;if("null"===S&&this.whitelist.includes("null"))return!0;try{const b=new URL(S).hostname.toLowerCase();return this.whitelist.some(I=>{const x=I.toLowerCase();return x.includes("://")?S.toLowerCase()===x:b===x||b.endsWith(`.${x}`)})}catch{return this.whitelist.includes(S)}}getEventType(S){if(null==S)return"null_message";let b=S;if("string"==typeof S)try{b=JSON.parse(S)}catch{return"string_message"}if("object"!=typeof b)return typeof b+"_message";const I=["event_type","type","action","event","command","method"];for(const S of I)if(b[S])return String(b[S]);return!0===b.init?"init":!0===b.ready?"ready":b.resize?"resize":void 0!==b.height?"height_update":"object_message"}getSourceInfo(S){try{return S===window?"same-window":S===window.parent?"parent-window":S===window.opener?"opener-window":S===window.top?"top-window":S instanceof Window?"other-window":S instanceof MessagePort?"message-port":S instanceof ServiceWorker?"service-worker":"unknown-source"}catch{return"unknown-source"}}logPostMessage(S){const b=this.parseMessage(S.message),I=S.sourceOrigin!==S.targetOrigin,x=this.getSize(S.message),R=x>1e4,A=this.isSuspiciousOrigin(S.sourceOrigin);let _="postmessage_communication";I&&(_="postmessage_cross_origin"),R&&(_="postmessage_large_payload"),A&&(_="postmessage_suspicious_origin",this.trackSuspiciousOrigin(S.sourceOrigin));const D={type:_,request:{method:"POSTMESSAGE",url:"outgoing"===S.direction?S.targetOrigin:S.sourceOrigin,domain:this.getDomain("outgoing"===S.direction?S.targetOrigin:S.sourceOrigin),path:null,status:null,statusText:null,response:b,interceptor:"postMessage"},extraData:{messageId:`pm_${S.direction}_${Date.now()}_${++this.messageCounter}`,direction:S.direction,sourceOrigin:S.sourceOrigin,targetOrigin:S.targetOrigin,messageSize:x,messageType:typeof S.message,detectedEventType:S.eventType,source:S.source||"unknown",isCrossOrigin:I,isLargePayload:R,isSuspicious:A,hasTransferables:S.transferables?.length>0||!1},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(D)}logPostMessageError(S,b){const I={type:"postmessage_error",request:{method:"POSTMESSAGE",url:S?.origin||"unknown",domain:this.getDomain(S?.origin||"unknown"),path:null,status:0,statusText:"PostMessage Error",response:{error:b.message,stack:b.stack},interceptor:"postMessage"},extraData:{errorCount:++this.errorCount,sourceOrigin:S?.origin||"unknown",targetOrigin:window.location.origin,errorType:b.name||"Error",errorMessage:b.message,errorStack:b.stack},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logEvent(I)}logEvent(S){this.reporter&&this.reporter.logEvent?this.reporter.logEvent(S):this.logger.error("Could not log event - reporter.logEvent not available")}parseMessage(S){if("string"==typeof S)try{return JSON.parse(S)}catch{return S.length>1e3?S.substring(0,1e3)+"...":S}try{return JSON.stringify(S),S}catch{return"[Circular or Complex Object]"}}getSize(S){try{return"string"==typeof S?S.length:JSON.stringify(S).length}catch{return-1}}getDomain(S){try{return"*"===S||"null"===S||"file://"===S?S:new URL(S).hostname}catch{return"unknown"}}isSuspiciousOrigin(S){if(!S||"null"===S||"file://"===S)return!0;if(this.whitelist.length>0&&!this.whitelist.includes("*")&&!this.isOriginWhitelisted(S))return!0;if("https:"===window.location.protocol&&"https://localhost"!==S&&!S.startsWith("https://"))return!0;const b=this.suspiciousOrigins.filter(b=>b===S).length;return b>100}trackSuspiciousOrigin(S){this.suspiciousOrigins.push(S),this.suspiciousOrigins.length>1e3&&(this.suspiciousOrigins=this.suspiciousOrigins.slice(-1e3))}extractUserData(S,b){try{const I=this.parseMessage(b);I&&"object"==typeof I&&this.reporter.updateUserProfileFromContext&&this.reporter.updateUserProfileFromContext({url:`postmessage://${S}`,source:"message",data:I})}catch(S){this.logger.warn("Failed to extract user data:",S)}}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}destroy(){this.isDestroyed?this.logger.warn("PostMessageMonitor already destroyed"):(this.isDestroyed=!0,this.originalPostMessage&&(window.postMessage=this.originalPostMessage),window.removeEventListener("message",this.boundMessageHandler),this.reporter=null,this.boundMessageHandler=null,this.suspiciousOrigins=[],this.logger.log("PostMessage monitor destroyed"))}}class InterceptorFeature{#o=null;#O=null;#Ee=null;#xe=null;#Me=null;#P=!1;constructor({logger:S,config:b,monitoringCore:I,eventManager:x}){this.#o=S,this.#O=b,this.#Ee=I,this.#xe=x}initialize(S,b=null){try{this.#Me={};return S&&S.isRecording?(console.log("[TraceScout] 🔌 Setting up session recording interceptors bundle..."),this.#Re(),this.#Te(),this.#Ae(),this.#_e(b),this.#Oe(),this.#De(),console.log("[TraceScout] ✅ Session recording bundle complete (DOM + Network + Console + Errors)"),this.#o?.log("Interceptors setup complete"),this.#P=!0,!0):(console.log("[TraceScout] ⏭️ Interceptors skipped (bundled with session recording - not active)"),!1)}catch(S){return this.#o?.error("Failed to setup interceptors:",S),!1}}#Re(){console.log("[TraceScout] 📡 Setting up FetchInterceptor..."),this.#Me.fetch=new FetchInterceptor(this.#Ee),this.#Me.fetch.setup?.()||this.#Me.fetch.install?.(),console.log("[TraceScout] ✅ FetchInterceptor active")}#Te(){console.log("[TraceScout] 📡 Setting up XHRInterceptor..."),this.#Me.xhr=new XHRInterceptor(this.#Ee),this.#Me.xhr.setup?.()||this.#Me.xhr.install?.(),console.log("[TraceScout] ✅ XHRInterceptor active")}#Ae(){const S=!1!==this.#O?.captureResources,b=!1!==this.#O?.captureNavigation;if(S||b)try{console.log("[TraceScout] 📊 Setting up PerformanceResourceObserver...",{captureResources:S,captureNavigation:b,maxResourceEntriesPerSession:this.#O?.maxResourceEntriesPerSession||2e3}),this.#Me.performanceResource=new PerformanceResourceObserver(this.#Ee,{captureResources:S,captureNavigation:b,debug:this.#O?.debug||!1,maxDedupeEntries:this.#O?.maxDedupeEntries||5e3,filterOtherInitiator:!1!==this.#O?.filterOtherInitiator,maxResourceEntriesPerSession:this.#O?.maxResourceEntriesPerSession||2e3,resourceAllowlist:this.#O?.resourceAllowlist||null,resourceBlocklist:this.#O?.resourceBlocklist||null}),this.#Me.performanceResource.setup(),console.log("[TraceScout] ✅ PerformanceResourceObserver active")}catch(S){console.warn("[TraceScout] ⚠️ PerformanceResourceObserver setup failed:",S.message)}else console.log("[TraceScout] ⏭️ PerformanceResourceObserver disabled via config")}#_e(S){console.log("[TraceScout] 💬 Setting up ConsoleInterceptor..."),this.#Me.console=new ConsoleInterceptor(this.#xe,this.#O,this.#Ee),S&&this.#Me.console.setLogManager(S),this.#Me.console.install?.(),console.log("[TraceScout] ✅ ConsoleInterceptor active")}#Oe(){try{console.log("[TraceScout] 🚨 Setting up ErrorHandler..."),this.#Me.errors=new ErrorHandler(this.#xe,this.#O,this.#Ee),console.log("[TraceScout] ErrorHandler created, installing...",{hasInstall:"function"==typeof this.#Me.errors?.install,hasReporter:!!this.#Ee}),this.#Me.errors.install?.(),console.log("[TraceScout] ✅ ErrorHandler active")}catch(S){console.error("[TraceScout] ❌ ErrorHandler setup failed:",S)}}#De(){this.#O?.monitorPostMessages&&"object"==typeof this.#O.monitorPostMessages&&(this.#Me.postMessage=new PostMessageInterceptor(this.#Ee),this.#Me.postMessage.setup?.()||this.#Me.postMessage.install?.())}get isInitialized(){return this.#P}get interceptors(){return this.#Me}getInterceptor(S){return this.#Me?.[S]||null}updateDebugMode(S){this.#Me&&Object.values(this.#Me).forEach(b=>{b&&b.updateDebugMode&&b.updateDebugMode(S)})}destroy(){this.#Me&&(Object.values(this.#Me).forEach(S=>{S?.destroy?.()||S?.uninstall?.()}),this.#Me=null),this.#P=!1}}class EventLifecycleFeature{#o=null;#O=null;#Fe=null;#Ne=null;#Le=null;#Pe=null;#Be=null;#ze=null;#Ue=null;#$e=null;#P=!1;#je=!1;constructor({logger:S,config:b}){this.#o=S,this.#O=b}setCallbacks({onCustomApiError:S,onBeforeUnload:b,onUserActivity:I,onVisibilityChange:x}){this.#Be=S,this.#ze=b,this.#Ue=I,this.#$e=x}initialize(){try{return this.#Fe=this.#qe.bind(this),this.#Ne=this.#We.bind(this),this.#Le=this.#He.bind(this),this.#Pe=this.#Ve.bind(this),document.addEventListener("custom-api-error",this.#Fe),window.addEventListener("beforeunload",this.#Ne),document.addEventListener("click",this.#Le,{passive:!0,capture:!0}),document.addEventListener("keydown",this.#Le,{passive:!0,capture:!0}),document.addEventListener("scroll",this.#Le,{passive:!0,capture:!0}),document.addEventListener("visibilitychange",this.#Pe),this.#o?.log("Event listeners setup complete"),this.#P=!0,!0}catch(S){return this.#o?.error("Failed to setup event listeners:",S),!1}}#qe(S){this.#Be?.(S)}#We(S){this.#ze?.(S)}#He(){this.#je||this.#Ue?.()}#Ve(){this.#je||("visible"===document.visibilityState?this.#$e?.("visible"):this.#$e?.("hidden"))}get isInitialized(){return this.#P}setQuotaExceeded(S){this.#je=S,S&&this.#Qe()}#Qe(){this.#Le&&(document.removeEventListener("click",this.#Le,{capture:!0}),document.removeEventListener("keydown",this.#Le,{capture:!0}),document.removeEventListener("scroll",this.#Le,{capture:!0}),this.#Le=null),this.#Pe&&(document.removeEventListener("visibilitychange",this.#Pe),this.#Pe=null)}destroy(){try{document.removeEventListener("custom-api-error",this.#Fe),window.removeEventListener("beforeunload",this.#Ne),this.#Qe(),this.#Fe=null,this.#Ne=null,this.#P=!1}catch(S){this.#o?.error("Failed to cleanup event listeners:",S)}}}class TraceScoutMonitoringCore{#P=!1;#o=null;#Ke=null;#xe=null;#Ge=null;#Je=null;#Xe=null;#Ye=null;#_=null;#Ze=null;#et=null;#tt=null;#st=null;#Me=null;#rt=null;#nt=null;#it=null;#ot=null;#at=null;#lt=null;#ct=null;#ut=null;#ht=null;_consecutiveFailures=0;#je=!1;#dt=null;#gt=!1;static#pt=null;static#ft=!1;constructor(){this.config=R.defaults({retryIntervalMs:R.get(A,"RETRY_INTERVAL_MS",5e3),deduplicationWindowMs:R.get(A,"DEDUPLICATION_WINDOW_MS",3e4),maxQueueSize:R.get(A,"MAX_QUEUE_SIZE",1e3),maxRetries:R.get(A,"MAX_RETRIES",3),batchSize:R.get(A,"BATCH_SIZE",10),debug:!1,logPreflight:!1,logResourceErrors:!1},{}),this.#o=new Logger("[TraceScoutMonitoringCore]",this.config.debug),"function"!=typeof this.#o.debug&&(this.#o.debug=(...S)=>this.#o.info(...S));try{this.#Ke=new ConfigManager(this.config)}catch(S){this.#o.error("Failed to initialize ConfigManager:",S)}this.appContext={appVersion:"1.0.0",environment:"unknown"},"function"==typeof this.sendEvents&&(this.#ct=throttle$1(this.sendEvents.bind(this),1e3))}static setTransport(S){TraceScoutMonitoringCore.#ft?console.error("[TraceScout] setTransport() must be called before init()"):"object"==typeof S&&null!==S?"string"==typeof S.apiBaseUrl&&S.apiBaseUrl?TraceScoutMonitoringCore.#pt=S:console.error("[TraceScout] setTransport() requires a non-empty apiBaseUrl string"):console.error("[TraceScout] setTransport() requires an object with apiBaseUrl")}async init(S,b={}){if(this.#gt)return this.#o.warn("TraceScoutMonitoringCore already initialized"),{sampled:this.#dt??!1,sdkVersion:"2.0.0",projectId:"",environment:""};const I=validateConfig(S,b);if(!I.ok){return function surfaceConfigError(S,b){if(b)try{console.error("[TraceScout] init() refused — invalid arguments:",S)}catch{}}(I.keys?{code:I.code,keys:I.keys}:{code:I.code},b?.debug||!1),{sampled:!1,sdkVersion:"2.0.0",projectId:"",environment:""}}this.#gt=!0,TraceScoutMonitoringCore.#ft=!0;const x=TraceScoutMonitoringCore.#pt,R={projectId:I.projectId,environment:I.options.environment||"production",release:I.options.release,sourceName:I.options.sourceName??"web-client",debug:I.options.debug||!1,apiBaseUrl:x?.apiBaseUrl,...void 0!==I.options.network?{network:I.options.network}:{}},A=peekAnonymousId();if(this.#dt=shouldSampleSession(1,{anonymousId:A}),!this.#dt)return R.debug&&console.log("[TraceScout] Session not sampled — SDK will not instrument this page-load."),{sampled:!1,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment};try{R.debug&&(console.log("[TraceScout] ============================================"),console.log("[TraceScout] Initializing SDK v2.0..."),console.log("[TraceScout] ============================================"));const S=new InitializationPipeline(this.#o),I=await S.run(R);this.#Ye=I.sessionManager.sessionManager,this.#_=I.sdkContext,this.#Ze=I.remoteConfigService,this.config=I.config,this.#et=R,this.#xe=I.managers.eventManager,this.#Ge=I.managers.serviceManager,this.#Je=I.managers.userProfileManager,this.#Xe=I.managers.performanceMonitor,this.config.appName&&(this.appContext.appName=this.config.appName),I.serverConfig?.project?.name&&(this.appContext.appName=I.serverConfig.project.name),this.#o&&"function"==typeof this.#o.updateDebugMode&&this.#o.updateDebugMode(this.config.debug),this.#st=new LoggingFeature({logger:this.#o,sdkContext:this.#_,config:this.config}),this.#st.initialize(I.serverConfig),this.#st.configure(this.config);const x=I.serverConfig?.features?.performanceMonitoring?.enabled;x&&(this.#lt=new CoreWebVitalsMonitor(this.config),console.log("[TraceScout] ✓ Performance monitoring initialized")),this.#tt=new SessionRecordingFeature({logger:this.#o,sdkContext:this.#_,config:this.config,options:b}),this.#tt.setCallbacks({onChunkCreated:S=>this.#K(S),onSessionEnd:S=>this.#mt(S),onQuotaExceeded:S=>this.#yt(S),onSpaNavigation:(S,b,I)=>{this.#it?.recordNavigation(S,b,I)}});const A=await this.#tt.initialize(I.serverConfig,this.#Ze);if(this.#it=new PageviewManager({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getBaseContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#_.setPageviewManager(this.#it),this.#nt=new SessionLifecycleEmitter({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),readGuard:()=>this.#Ye?.getLifecycleGuard?.()??null,writeGuard:S=>this.#Ye?.setLifecycleGuard?.(S),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Ye&&(this.#Ye.onLifecycleEnd=({reason:S})=>{this.#nt?.emitEnd({reason:S})}),A&&this.#lt){const S=this.#it.getCurrentPageviewId(),b="undefined"!=typeof window&&"string"==typeof window.location?.href?window.location.href:"";b&&(this.#ot=new WebVitalsEmitter({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getBaseContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),initialPageviewId:S,initialUrl:b,debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#lt.addCallback?.((S,b)=>{this.#ot?.emit(S,b)}),this.#lt.metrics&&"function"==typeof this.#lt.metrics.forEach&&this.#lt.metrics.forEach(S=>{this.#ot?.emit(S.type,S)}))}if(A&&(this.#at=new TrackIdentifyEmitter({addCustomEvent:(S,b)=>this.#tt?.addCustomEvent(S,b),getBaseContext:()=>this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}})),A){const S=!0===this.#Ye?.isResumedSession?.();this.#it.emitInitialPageView({isResumed:S})}return A&&this.#Ye&&!this.#Ye.isResumedSession?.()&&!this.#Ye.getLifecycleGuard?.()?.sessionStartEmitted&&this.#nt.emitStart({}),A?(this.#Me=new InterceptorFeature({logger:this.#o,config:this.config,monitoringCore:this,eventManager:this.#xe}),this.#Me.initialize(this.#tt.recorder,this.#st.logManager),console.log("[TraceScout] ✓ Session recording bundle initialized (DOM + Network + Console + Errors)")):console.log("[TraceScout] ⏭️ Skipping interceptors (bundled with session recording)"),this.#rt=new EventLifecycleFeature({logger:this.#o,config:this.config}),this.#rt.setCallbacks({onCustomApiError:S=>this.#qe(S),onBeforeUnload:S=>this.#We(S),onUserActivity:()=>this.#He(),onVisibilityChange:S=>this.#Ve(S)}),this.#rt.initialize(),this.#vt(),this.#xe&&this.#xe.loadFromLocal(),this.#Je&&this.#Je.ensureProfile(),this.#P=!0,this.#St(I.serverConfig),{sampled:!0,sdkVersion:"2.0.0",projectId:R.projectId,environment:R.environment}}catch(S){throw console.error("[TraceScout] ❌ Initialization failed:",S),this.#o.error("Failed to initialize TraceScoutMonitoringCore:",S),S}}#St(S){console.log("[TraceScout] ============================================"),console.log("[TraceScout] ✅ SDK Initialized Successfully"),console.log("[TraceScout] ============================================"),console.log(` Workspace: ${S.workspace.name}`),console.log(` Project: ${S.project.name}`),console.log(` Session: ${this.#_.sessionId}`),console.log(` Environment: ${this.#_.environment}`),console.log(` Config Version: ${S.configVersion}`);const b=Object.keys(S.features||{}).filter(b=>S.features[b].enabled);console.log(` Features: ${b.join(", ")||"none"}`),console.log("[TraceScout] ============================================"),this.#o.info("TraceScoutMonitoringCore initialized successfully",{configSource:"server",configVersion:S.configVersion,workspace:S.workspace.name,project:S.project.name,sessionId:this.#_.sessionId})}#wt(S,b){try{const I=Object.keys(b.features||{}).filter(S=>b.features[S].enabled);S({sessionId:this.#_.sessionId,workspace:b.workspace.name,project:b.project.name,environment:this.#_.environment,featuresEnabled:I,configVersion:b.configVersion})}catch(S){this.#o.error("Error in onReady callback:",S)}}#K(S){this.#Ye&&(this.#Ye.incrementChunkCount(),this.#Ye.incrementEventCount(S.eventCount||0))}#mt(S){if(!S||"object"!=typeof S)return;const b=mapInternalEndReason(S.reason);b&&this.#nt?.emitEnd({reason:b,totalChunks:"number"==typeof S.totalChunks?S.totalChunks:void 0,totalEvents:"number"==typeof S.totalEvents?S.totalEvents:void 0})}#qe(S){}#We(S){}#He(){this.#je||this.#tt?.sessionEnded&&!this.#tt?.isRecording&&(console.log("[TraceScout] 🔄 User activity detected after session end - starting new session"),this.forceNewSession("activity_after_"+this.#tt.sessionEndReason))}#Ve(S){this.#je||"visible"===S&&this.#tt?.sessionEnded&&!this.#tt?.isRecording&&(console.log("[TraceScout] 🔄 Tab visible after session end - starting new session"),this.forceNewSession("tab_focus_after_"+this.#tt.sessionEndReason))}#yt(S){this.#je||(this.#je=!0,console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been permanently stopped.","color: #ff4444;"),console.error("%c[TraceScout] Your workspace has reached its monthly session limit.","color: #ff4444;"),S?.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions (${S.usage.percentage}%)`,"color: #ff4444;"),console.error("%c[TraceScout] To continue recording, upgrade your plan at: /billing","color: #ff4444;"),this.#rt?.setQuotaExceeded(!0),this.#tt?.stop(),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:recording_stopped",{detail:{reason:"quota_exceeded",usage:S?.usage,message:S?.message||"Session quota exceeded"}})))}#vt(){"development"===this.config.environment||this.config.debug?this.#o.log("⚠️ Auto-retry DISABLED (development mode) - reduces API spam"):(this.#ut=setInterval(()=>{this.#bt()},this.config.retryIntervalMs),this.#o.log("Auto-retry enabled (production mode)")),this.#ht=setInterval(()=>{this.#Ct()},6e4),this.#o.log("Background processes started")}#kt(){this.#ut&&(clearInterval(this.#ut),this.#ut=null),this.#ht&&(clearInterval(this.#ht),this.#ht=null)}async#bt(){try{if(this.#Ge?.isSending)return;const S=this.#xe?.getQueueSize();if(S>0){if(this._consecutiveFailures>=10)return this.#o.warn(`⛔ Stopped retrying after ${this._consecutiveFailures} consecutive failures`),this.#o.warn(`⛔ Clearing ${S} queued events to prevent infinite loop`),this.#xe.clearEvents(),void(this._consecutiveFailures=0);this.#o.info(`🔄 Retrying ${S} queued events (attempt ${this._consecutiveFailures+1}/10)`);await this.sendEvents()?(this.#o.info("✅ Retry succeeded - resetting failure counter"),this._consecutiveFailures=0):(this._consecutiveFailures++,this.#o.warn(`❌ Retry failed (${this._consecutiveFailures}/10)`))}else this._consecutiveFailures>0&&(this.#o.info("✅ Queue empty - resetting failure counter"),this._consecutiveFailures=0)}catch(S){this.#o.error("Error during retry:",S),this._consecutiveFailures++}}#Ct(){try{if(this.#xe){const S=this.config.eventMaxAge||864e5;this.#xe.cleanupOldEvents(S)}}catch(S){this.#o.error("Error during cleanup:",S)}}#It(){return"evt_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}destroy(){if(this.#P)try{this.#st?.destroy(),this.#Me?.destroy(),this.#tt?.destroy(),this.#rt?.destroy(),this.#kt(),this.#Ye&&this.#Ye.destroy(),this.#P=!1,this.#o.info("TraceScoutMonitoringCore destroyed successfully")}catch(S){this.#o.error("Error during destruction:",S)}}logEvent(S,b={},I={}){if(this.#P)try{let x;"object"==typeof S&&S.type?(x={id:S.id||this.#It(),timestamp:S.timestamp||Date.now(),...S},x.context||(x.context={}),void 0===x.context.isMonitored&&(x.context.isMonitored=!0),void 0===x.context.forceLog&&(x.context.forceLog=x.type?.includes("error")||x.type?.includes("alert")||x.type?.includes("p1_incident")||"critical"===x.severity)):x={id:this.#It(),type:S,data:b,context:{isMonitored:!0,forceLog:I.forceLog||!1,status:I.status||"success",...I.context},timestamp:Date.now()};if(this.#xe.addEvent(x)){this.#o.log("Event logged:",x.type);this.#xe.getQueueSize()>=this.config.batchSize&&this.sendEvents()}}catch(S){this.#o.error("Failed to log event:",S)}else this.#o.warn("TraceScoutMonitoringCore not initialized")}async sendEvents(S=null){if(!this.#Ge||!this.#xe)return this.#o.warn("ServiceManager or EventManager not available"),!1;try{const b=S||this.#xe.getEvents();if(!b||0===b.length)return!0;this.#o.info(`📤 Attempting to send ${b.length} events`);const I=await this.#Ge.sendEvents(b);this.#o.info(`📊 Send results: ${I.length} results received`);const x=I.filter(S=>S.success).map(S=>S.event.id);x.length>0&&(this.#xe.removeEvents(x),this.#o.info(`✅ Successfully sent ${x.length}/${b.length} events`));const R=I.filter(S=>!S.success).length;if(R>0){this.#o.warn(`❌ Failed to send ${R}/${b.length} events - will retry`);const S=I.find(S=>!S.success);S&&S.error&&this.#o.error("First failure reason:",S.error.message||S.error)}return 0===x.length&&I.length>0&&this.#o.warn(`⚠️ 0 events succeeded out of ${b.length} - all failed`),0===R}catch(S){return this.#o.error("❌ Failed to send events:",S),!1}}clearEvents(){this.#xe?(this.#xe.clearEvents(),this.#o.log("Event queue cleared")):this.#o.warn("EventManager not available")}isMonitoredEndpoint(S){if("string"!=typeof S||R.isEmpty(S))return!1;try{const b=this.config.endpoints||[],I=this.config.domainsToTrack||[];if(b.includes("*")||"*"===b)return!0;const x=S.toLowerCase();let A;try{A=new URL(x)}catch{return!1}if(!R.isEmpty(I)){const S=A.hostname;if(I.some(b=>S===b.toLowerCase()||S.endsWith(`.${b.toLowerCase()}`)))return!0}const _=A.pathname;return b.some(S=>_.includes(S.toLowerCase()))}catch(S){return this.#o?.warn("Error checking monitored endpoint:",S),!1}}shouldExtractFields(S,b){return"string"==typeof S&&!R.isEmpty(S)&&(!!R.isArray(this.config.fieldsToExtract)&&this.config.fieldsToExtract.some(I=>{const x=R.toLower(R.get(I,"api","")),A=R.get(I,"source","");return("*"===x||S.toLowerCase().includes(x))&&("*"===A||A===b)}))}extractUserContextFromBody({data:S,source:b="response",url:I=""}){if(!this.#Je)return{};try{return this.#Je.extractContextFromData({data:S,source:b,url:I})}catch(S){return this.#o.error("Failed to extract user context:",S),{}}}async startSessionRecording(S={}){return this.#tt?.start(S)||null}stopSessionRecording(){return this.#tt?.stop()||null}addSessionCustomEvent(S,b){if(this.#_&&"object"==typeof b&&null!==b){const I=this.#Et(S);if(I){let x;try{const S=this.#_.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"});"string"==typeof b.traceId&&b.traceId.length>0&&(S.traceId=b.traceId),"string"==typeof b.spanId&&b.spanId.length>0&&(S.spanId=b.spanId);x=wrapInEnvelope(I,this.#xt(I,b),S)}catch(S){if(this.config?.debug&&this.#o.warn?.("addSessionCustomEvent: envelope build failed; skipping v1 emit:",S),"function"==typeof this.#et?.onError)try{this.#et.onError(S)}catch(S){}return!1}return this.#tt?.addCustomEvent(S,x)||!1}}return this.#tt?.addCustomEvent(S,b)||!1}#Et(S){switch(S){case"network_request":case"network_response":case"network_error":case"network_resource":return"network_request";case"console":return"console_event";case"error":case"unhandledRejection":return"js_error";default:return null}}#xt(S,b){switch(S){case"console_event":{const S=Array.isArray(b.args)?b.args.map(S=>"object"==typeof S&&null!==S&&"type"in S?S:{type:"string"==typeof S?"string":"object",preview:String(S).slice(0,2e3)}):void 0,I={level:b.level||b.method||"log",message:"string"==typeof b.message?b.message:String(b.message??"")};return void 0!==S&&(I.args=S),void 0!==b.stack&&null!==b.stack&&(I.stack=b.stack),"number"==typeof b.timestamp&&(I.timestamp=b.timestamp),I}case"js_error":{const S={handled:b.handled||"window.onerror",message:"string"==typeof b.message?b.message:String(b.message??""),fingerprint:b.fingerprint,occurrenceCount:b.occurrenceCount||1,severity:b.severity||"error"},I=b.errorName??b.name;return null!=I&&(S.errorName=I),void 0!==b.stack&&null!==b.stack&&(S.stack=b.stack),void 0!==b.source&&null!==b.source&&(S.source=b.source),"number"==typeof b.lineno&&(S.lineno=b.lineno),"number"==typeof b.colno&&(S.colno=b.colno),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}case"network_request":{const S={initiator:"xhr"===b.interceptor?"xhr":"fetch",method:(b.method||"GET").toUpperCase(),requestUrl:b.url||b.requestUrl||"",status:"number"==typeof b.status?b.status:0,durationMs:"number"==typeof b.duration?Math.round(b.duration):0,errored:"number"!=typeof b.status||(b.status>=400||0===b.status)};return void 0!==b.statusText&&null!==b.statusText&&(S.statusText=b.statusText),"string"==typeof b.requestPath&&b.requestPath.length>0&&(S.requestPath=b.requestPath),"string"==typeof b.requestQuery&&b.requestQuery.length>0&&(S.requestQuery=b.requestQuery),b.requestHeaders&&"object"==typeof b.requestHeaders&&(S.requestHeaders=b.requestHeaders),b.responseHeaders&&"object"==typeof b.responseHeaders&&(S.responseHeaders=b.responseHeaders),"requestBody"in b&&(S.requestBody="string"==typeof b.requestBody?b.requestBody:null),"responseBody"in b&&(S.responseBody="string"==typeof b.responseBody?b.responseBody:null),"string"==typeof b.requestBodyState&&(S.requestBodyState=b.requestBodyState),"string"==typeof b.responseBodyState&&(S.responseBodyState=b.responseBodyState),"boolean"==typeof b.requestBodyRedacted&&(S.requestBodyRedacted=b.requestBodyRedacted),"boolean"==typeof b.responseBodyRedacted&&(S.responseBodyRedacted=b.responseBodyRedacted),"boolean"==typeof b.requestBodyTruncated&&(S.requestBodyTruncated=b.requestBodyTruncated),"boolean"==typeof b.responseBodyTruncated&&(S.responseBodyTruncated=b.responseBodyTruncated),"number"==typeof b.requestBodySize&&(S.requestBodySize=b.requestBodySize),"number"==typeof b.responseBodySize&&(S.responseBodySize=b.responseBodySize),"number"==typeof b.requestBodyCapturedBytes&&(S.requestBodyCapturedBytes=b.requestBodyCapturedBytes),"number"==typeof b.responseBodyCapturedBytes&&(S.responseBodyCapturedBytes=b.responseBodyCapturedBytes),"string"==typeof b.requestBodyContentType&&(S.requestBodyContentType=b.requestBodyContentType),"string"==typeof b.responseBodyContentType&&(S.responseBodyContentType=b.responseBodyContentType),"number"==typeof b.requestSize&&(S.requestSize=b.requestSize),"number"==typeof b.responseSize&&(S.responseSize=b.responseSize),"number"==typeof b.timestamp&&(S.timestamp=b.timestamp),S}default:return{...b}}}getSessionRecordingStatus(){return this.#tt?.getStatus()||{available:!1,error:"Session recording not enabled"}}async getSessionEvents(S){return this.#tt?.getEvents()||[]}exportSessionData(S="json"){if(!this.#tt?.isAvailable)return this.#o.warn("Session recording not enabled"),null;try{const b=this.#tt.getEvents(),I=this.#tt.getChunks(),x=this.#tt.getMetadata(),R=this.#tt.getSessionId();let A=b;(!b||0===b.length)&&I&&I.length>0&&(A=[],I.forEach(S=>{S.events&&Array.isArray(S.events)&&A.push(...S.events)}));const _=JSON.stringify(A).length,D=_>5e6,L={sessionId:R,startTime:this.#tt.recorder?.recordingStartTime,endTime:this.#tt.isRecording?null:Date.now(),duration:this.#tt.recorder?.recordingStartTime?Date.now()-this.#tt.recorder.recordingStartTime:0,eventCount:A.length,chunkCount:I.length,totalSize:_,isLarge:D,metadata:x,events:D?[]:A,chunks:I,userAgent:navigator.userAgent,url:window.location.href,timestamp:Date.now(),...D&&{warning:"Session data is large. Use exportChunk() to get individual chunks for replay."}};return"json"===S?JSON.stringify(L,null,2):"object"===S?L:"blob"===S?new Blob([JSON.stringify(L,null,2)],{type:"application/json"}):L}catch(S){return this.#o.error("Failed to export session data:",S),null}}getSessionChunks(){return this.#tt?.getChunks()||[]}listChunks(){return(this.#tt?.getChunks()||[]).map((S,b)=>({index:b,chunkId:S.chunkId,eventCount:S.events?.length||0,size:JSON.stringify(S.events||[]).length,sizeKB:Math.round(JSON.stringify(S.events||[]).length/1024),startTime:S.startTime,endTime:S.endTime,duration:(S.endTime||0)-(S.startTime||0)}))}getUploadQueueStats(){return this.#tt?.uploadQueue?.getStats()||null}getUploadQueue(){return this.#tt?.uploadQueue?.getQueue()||null}pauseUploads(){return this.#tt?.uploadQueue?.pause(),!0}resumeUploads(){return this.#tt?.uploadQueue?.resume(),!0}getSessionStorageStats(){return this.#tt?.sessionStorage?.getStorageStats()||null}getStoredSessions(){return this.#tt?.sessionStorage?.getSessions()||{}}clearSessionStorage(){return this.#tt?.sessionStorage?.clearAll()||!1}log(S,b,I={}){return this.#st?.log(S,b,I)||!1}debug(S,b={}){return this.#st?.debug(S,b)||!1}info(S,b={}){return this.#st?.info(S,b)||!1}warn(S,b={}){return this.#st?.warn(S,b)||!1}error(S,b={}){return this.#st?.error(S,b)||!1}fatal(S,b={}){return this.#st?.fatal(S,b)||!1}setLogContext(S,b){return this.#st?.setContext(S,b)||!1}clearLogContext(){return this.#st?.clearContext()||!1}setLogLevel(S){return this.#st?.setLogLevel(S)||!1}getLogStats(){return this.#st?.getStats()||null}async flushLogs(){return this.#st?.flush()||!1}enableLogging(S,b="info"){return this.#st?.enableServices(S,b)||!1}disableLogging(S){return this.#st?.disableServices(S)||!1}enableAllLogging(S="info"){return this.#st?.enableAll(S)||!1}disableAllLogging(){return this.#st?.disableAll()||!1}getLoggingConfig(){return this.#st?.getConfig()||null}getEnabledLogServices(){return this.#st?.getEnabledServices()||[]}getAvailableLogServices(){return this.#st?.getAvailableServices()||[]}setUserProfile(S){if(!this.#Je)return this.#o.warn("UserProfileManager not available"),!1;let b=!1;try{b=!0===this.#Je.setProfile(S)}catch(S){return this.#o.error("Failed to set user profile:",S),!1}if(S&&"object"==typeof S&&isValidUserId(S.userId)){const{userId:b,...I}=S;try{this.#Mt(b,I,{mode:"merge"},{skipUserProfileWrite:!0})}catch(S){this.#o.warn?.("Failed to route setUserProfile through identify:",S)}}return b}getUserProfile(){if(!this.#Je)return{};try{return this.#Je.getProfile()}catch(S){return this.#o.error("Failed to get user profile:",S),{}}}getSdkContext(){return!1===this.#dt?{sampled:!1}:this.#_}setUserMetadata(S,b={}){return this.identify(S,b,{mode:"merge"})}clearUserMetadata(){return!!this.#_&&(this.#_.clearUser(),this.#Ye&&this.#Ye.clearUserMetadata(),!0)}identify(S,b={},I={}){return this.#Mt(S,b,I,{skipUserProfileWrite:!1})}#Mt(S,b={},I={},x={}){if(!isValidUserId(S))return this.#o.error("identify: userId is required and must be a non-empty string (≤256 chars)"),!1;if(!this.#_)return this.#o.warn("Cannot identify — SDK not initialized"),!1;const R=I&&"set"===I.mode?"set":"merge",A=[],onDrop=(S,b)=>A.push({reason:S,key:b}),{userEmail:_,userName:D,traits:L}=function extractIdentityFromTraits(S,b){const I="function"==typeof b?b:()=>{};if(!S||"object"!=typeof S||Array.isArray(S))return{userEmail:null,userName:null,traits:{}};const x=Object.assign({},S),R=void 0!==x.userEmail?x.userEmail:x.email;delete x.email,delete x.userEmail;let A=null;null!=R&&(isValidEmail(R)?A=R:I("invalid-email","email"));const _=void 0!==x.userName?x.userName:x.name;delete x.name,delete x.userName;let D=null;return null!=_&&(isValidUserName(_)?D=_:I("invalid-name","name")),{userEmail:A,userName:D,traits:x}}(b||{},onDrop),B=sanitizeScalarBag(L,onDrop);this.config?.debug&&A.length>0&&this.#o.warn?.("identify: dropped invalid trait entries:",A);const U=this.#_.userAttributes||{},$="set"===R?{}:{...U};null!==_&&($.email=_),null!==D&&($.name=D);const j=Object.assign({},$,B);if(this.#_.setUser(S,j),this.#Ye)try{this.#Ye.updateUserMetadata(S,j)}catch(S){this.#o.warn?.("SessionManager.updateUserMetadata threw:",S)}if(!x.skipUserProfileWrite&&this.#Je)try{this.#Je.setProfile({userId:S,...j})}catch(S){this.#o.warn?.("UserProfileManager.setProfile threw:",S)}return this.#at?this.#at.emitUserIdentified({userId:S,userEmail:_,userName:D,traits:B,mode:R}):this.config?.debug&&this.#o.warn?.("identify: emitter not available (recording disabled?) — context updated but no v1 envelope emitted"),!0}track(S,b={}){if(!this.#P)return this.#o.warn("SDK not initialized"),!1;try{this.logEvent({type:`custom.${S}`,category:"custom",severity:"info",data:b,timestamp:Date.now()})}catch(S){}return this.#at?this.#at.emitCustomEvent(S,b):(this.config?.debug&&this.#o.warn?.("track: v1 emitter not available (recording disabled?) — legacy event emitted, no v1 envelope"),!1)}captureException(S,b={}){return this.#P?(this.logEvent({type:"error.captured",category:"error",severity:"error",data:{message:S.message,stack:S.stack,name:S.name,...b},timestamp:Date.now()}),!0):(this.#o.warn("SDK not initialized"),!1)}getStatus(){const S=this.#Ye?.getSessionInfo?.()||{};return{initialized:this.#P,recording:this.#tt?.isRecording||!1,sessionId:this.#_?.sessionId||null,eventQueueSize:this.#xe?.getQueueSize()||0,session:{id:S.sessionId,duration:S.durationMinutes,events:S.eventCount,chunks:S.chunkCount,pages:S.pageCount,expiresIn:S.willExpireInMinutes}}}forceNewSession(S="manual"){if(!this.#P)return this.#o.warn("SDK not initialized"),null;if(this.#je)return console.warn("[TraceScout] Cannot start new session - quota exceeded."),null;console.log("[TraceScout] 🔄 Forcing new session, reason:",S),this.#tt?.stop(),this.#Ye&&this.#Ye.forceNewSession(S);const b=this.#Ye?.getOrCreateSession({projectId:this.#_.projectId,environment:this.#_.environment,userId:this.#_.userId});if(this.#_&&b&&(this.#_.sessionId=b,this.#_.sessionStartTime=Date.now()),this.#tt&&b){this.#tt.updateSessionId(b);const S=this.config.apiBaseUrl||"http://localhost:3001";this.#tt.updateUploadEndpoint(`${S}/api/projects/${this.#_.projectId}/sessions/${b}/chunks`),this.#tt.recorder?.start()}return b}debugMode(S){this.config.debug=S,this.#o.updateDebugMode(S),this.#Ge&&this.#Ge.updateDebugMode(S),this.#Me?.updateDebugMode(S),this.#o.log("Debug mode "+(S?"enabled":"disabled"))}getQueueStatus(){return{queueSize:this.#xe?this.#xe.getQueueSize():0,isSending:!!this.#Ge&&this.#Ge.isSending,isInitialized:this.#P,service:this.#Ge?this.#Ge.getServiceName():"none",configSource:this.config?.configSource||"local",configVersion:this.config?.configVersion||"local"}}getPerformanceMetrics(){return this.#Xe?.getMetrics()||null}getCoreWebVitalsMonitor(){return this.#lt}getCoreWebVitalsMetrics(){return this.#lt?.getAllMetrics()||null}getCoreWebVitalsInsights(){return this.#lt?.getPerformanceInsights()||null}generateCoreWebVitalsReport(){return this.#lt?.generateReport()||null}updateCoreWebVitalsThresholds(S){this.#lt?this.#lt.updateThresholds(S):this.#o.warn("Core Web Vitals monitor not available")}}let Ve;try{Ve=new TraceScoutMonitoringCore}catch(S){Ve={init:()=>Promise.reject(new Error("TraceScoutMonitoringCore failed to initialize")),logEvent:()=>{},destroy:()=>{},debugMode:()=>{},setUserProfile:()=>{},getUserProfile:()=>({}),getQueueStatus:()=>({error:"Not available"}),getPerformanceMetrics:()=>null,getCoreWebVitalsMonitor:()=>null,getCoreWebVitalsMetrics:()=>null,getCoreWebVitalsInsights:()=>null,generateCoreWebVitalsReport:()=>null,updateCoreWebVitalsThresholds:()=>{},getSessionRecorder:()=>null,startSessionRecording:()=>Promise.resolve(null),stopSessionRecording:()=>!1,getSessionRecordingStatus:()=>({available:!1,error:"Not available"}),getStatus:()=>({initialized:!1,error:"Not available"}),forceNewSession:()=>null}}if("undefined"!=typeof window)try{window.monitoringCore=Ve}catch(S){}var Qe=Ve;var Ke,Ge=Object.defineProperty,__publicField=(S,b,I)=>((S,b,I)=>b in S?Ge(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),Je=Object.defineProperty,__publicField$1=(S,b,I)=>((S,b,I)=>b in S?Je(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),Xe=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(Xe||{});const Ye={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Ze={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},et={};function getUntaintedPrototype$1(S){if(et[S])return et[S];const b=globalThis[S],I=b.prototype,x=S in Ye?Ye[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in Ze?Ze[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return et[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?et[S]=A:I}catch{return I}}const tt={};function getUntaintedAccessor$1(S,b,I){var x;const R=`${S}.${String(I)}`;if(tt[R])return tt[R].call(b);const A=getUntaintedPrototype$1(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(tt[R]=_,_.call(b)):b[I]}const st={};function getUntaintedMethod$1(S,b,I){const x=`${S}.${String(I)}`;if(st[x])return st[x].bind(b);const R=getUntaintedPrototype$1(S)[I];return"function"!=typeof R?b[I]:(st[x]=R,R.bind(b))}const rt={childNodes:function childNodes$1(S){return getUntaintedAccessor$1("Node",S,"childNodes")},parentNode:function parentNode$1(S){return getUntaintedAccessor$1("Node",S,"parentNode")},parentElement:function parentElement$1(S){return getUntaintedAccessor$1("Node",S,"parentElement")},textContent:function textContent$1(S){return getUntaintedAccessor$1("Node",S,"textContent")},contains:function contains$1(S,b){return getUntaintedMethod$1("Node",S,"contains")(b)},getRootNode:function getRootNode$1(S){return getUntaintedMethod$1("Node",S,"getRootNode")()},host:function host$1(S){return S&&"host"in S?getUntaintedAccessor$1("ShadowRoot",S,"host"):null},styleSheets:function styleSheets$1(S){return S.styleSheets},shadowRoot:function shadowRoot$1(S){return S&&"shadowRoot"in S?getUntaintedAccessor$1("Element",S,"shadowRoot"):null},querySelector:function querySelector$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll$1(S,b){return getUntaintedAccessor$1("Element",S,"querySelectorAll")(b)},mutationObserver:function mutationObserverCtor$1(){return getUntaintedPrototype$1("MutationObserver").constructor}};function isElement(S){return S.nodeType===S.ELEMENT_NODE}function isShadowRoot(S){const b=S&&"host"in S&&"mode"in S&&rt.host(S)||null;return Boolean(b&&"shadowRoot"in b&&rt.shadowRoot(b)===S)}function isNativeShadowDom(S){return"[object ShadowRoot]"===Object.prototype.toString.call(S)}function stringifyStylesheet(S){try{const b=S.rules||S.cssRules;if(!b)return null;let I=S.href;!I&&S.ownerNode&&S.ownerNode.ownerDocument&&(I=S.ownerNode.ownerDocument.location.href);return function fixBrowserCompatibilityIssuesInCSS(S){return S.includes(" background-clip: text;")&&!S.includes(" -webkit-background-clip: text;")&&(S=S.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),S}(Array.from(b,S=>stringifyRule(S,I)).join(""))}catch(S){return null}}function stringifyRule(S,b){if(function isCSSImportRule(S){return"styleSheet"in S}(S)){let b;try{b=stringifyStylesheet(S.styleSheet)||function escapeImportStatement(S){const{cssText:b}=S;if(b.split('"').length<3)return b;const I=["@import",`url(${JSON.stringify(S.href)})`];return""===S.layerName?I.push("layer"):S.layerName&&I.push(`layer(${S.layerName})`),S.supportsText&&I.push(`supports(${S.supportsText})`),S.media.length&&I.push(S.media.mediaText),I.join(" ")+";"}(S)}catch(I){b=S.cssText}return S.styleSheet.href?absolutifyURLs(b,S.styleSheet.href):b}{let I=S.cssText;return function isCSSStyleRule(S){return"selectorText"in S}(S)&&S.selectorText.includes(":")&&(I=function fixSafariColons(S){const b=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return S.replace(b,"$1\\$2")}(I)),b?absolutifyURLs(I,b):I}}class Mirror{constructor(){__publicField$1(this,"idNodeMap",new Map),__publicField$1(this,"nodeMetaMap",new WeakMap)}getId(S){var b;if(!S)return-1;return(null==(b=this.getMeta(S))?void 0:b.id)??-1}getNode(S){return this.idNodeMap.get(S)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(S){return this.nodeMetaMap.get(S)||null}removeNodeFromMap(S){const b=this.getId(S);this.idNodeMap.delete(b),S.childNodes&&S.childNodes.forEach(S=>this.removeNodeFromMap(S))}has(S){return this.idNodeMap.has(S)}hasNode(S){return this.nodeMetaMap.has(S)}add(S,b){const I=b.id;this.idNodeMap.set(I,S),this.nodeMetaMap.set(S,b)}replace(S,b){const I=this.getNode(S);if(I){const S=this.nodeMetaMap.get(I);S&&this.nodeMetaMap.set(b,S)}this.idNodeMap.set(S,b)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function maskInputValue({element:S,maskInputOptions:b,tagName:I,type:x,value:R,maskInputFn:A}){let _=R||"";const D=x&&toLowerCase(x);return(b[I.toLowerCase()]||D&&b[D])&&(_=A?A(_,S):"*".repeat(_.length)),_}function toLowerCase(S){return S.toLowerCase()}const nt="__rrweb_original__";function getInputType(S){const b=S.type;return S.hasAttribute("data-rr-is-password")?"password":b?toLowerCase(b):null}function extractFileExtension(S,b){let I;try{I=new URL(S,b??window.location.href)}catch(S){return null}const x=I.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==x?void 0:x[1])??null}const it=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,ot=/^(?:[a-z+]+:)?\/\//i,at=/^www\..*/i,lt=/^(data:)([^,]*),(.*)/i;function absolutifyURLs(S,b){return(S||"").replace(it,(S,I,x,R,A,_)=>{const D=x||A||_,L=I||R||"";if(!D)return S;if(ot.test(D)||at.test(D))return`url(${L}${D}${L})`;if(lt.test(D))return`url(${L}${D}${L})`;if("/"===D[0])return`url(${L}${function extractOrigin(S){let b="";return b=S.indexOf("//")>-1?S.split("/").slice(0,3).join("/"):S.split("/")[0],b=b.split("?")[0],b}(b)+D}${L})`;const B=b.split("/"),U=D.split("/");B.pop();for(const S of U)"."!==S&&(".."===S?B.pop():B.push(S));return`url(${L}${B.join("/")}${L})`})}function normalizeCssString(S){return S.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"")}function markCssSplits(S,b){return function splitCssText(S,b){const I=Array.from(b.childNodes),x=[];if(I.length>1&&S&&"string"==typeof S){const b=normalizeCssString(S);for(let R=1;R<I.length;R++)if(I[R].textContent&&"string"==typeof I[R].textContent){const A=normalizeCssString(I[R].textContent);for(let I=3;I<A.length;I++){const R=A.substring(0,I);if(2===b.split(R).length){const I=b.indexOf(R);for(let b=I;b<S.length;b++)if(normalizeCssString(S.substring(0,b)).length===I){x.push(S.substring(0,b)),S=S.substring(b);break}break}}}}return x.push(S),x}(S,b).join("/* rr_split */")}let ct=1;const ut=new RegExp("[^a-z0-9-_:]");function genId(){return ct++}let ht,dt;const gt=/^[^ \t\n\r\u000c]+/,pt=/^[, \t\n\r\u000c]+/;const ft=new WeakMap;function absoluteToDoc(S,b){return b&&""!==b.trim()?getHref(S,b):b}function isSVGElement(S){return Boolean("svg"===S.tagName||S.ownerSVGElement)}function getHref(S,b){let I=ft.get(S);if(I||(I=S.createElement("a"),ft.set(S,I)),b){if(b.startsWith("blob:")||b.startsWith("data:"))return b}else b="";return I.setAttribute("href",b),I.href}function transformAttribute(S,b,I,x){return x?"src"===I||"href"===I&&("use"!==b||"#"!==x[0])||"xlink:href"===I&&"#"!==x[0]?absoluteToDoc(S,x):"background"!==I||"table"!==b&&"td"!==b&&"th"!==b?"srcset"===I?function getAbsoluteSrcsetString(S,b){if(""===b.trim())return b;let I=0;function collectCharacters(S){let x;const R=S.exec(b.substring(I));return R?(x=R[0],I+=x.length,x):""}const x=[];for(;collectCharacters(pt),!(I>=b.length);){let R=collectCharacters(gt);if(","===R.slice(-1))R=absoluteToDoc(S,R.substring(0,R.length-1)),x.push(R);else{let A="";R=absoluteToDoc(S,R);let _=!1;for(;;){const S=b.charAt(I);if(""===S){x.push((R+A).trim());break}if(_)")"===S&&(_=!1);else{if(","===S){I+=1,x.push((R+A).trim());break}"("===S&&(_=!0)}A+=S,I+=1}}}return x.join(", ")}(S,x):"style"===I?absolutifyURLs(x,getHref(S)):"object"===b&&"data"===I?absoluteToDoc(S,x):x:absoluteToDoc(S,x):x}function ignoreAttribute(S,b,I){return("video"===S||"audio"===S)&&"autoplay"===b}function classMatchesRegex(S,b,I){if(!S)return!1;if(S.nodeType!==S.ELEMENT_NODE)return!!I&&classMatchesRegex(rt.parentNode(S),b,I);for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}return!!I&&classMatchesRegex(rt.parentNode(S),b,I)}function needMaskingText(S,b,I,x){let R;if(isElement(S)){if(R=S,!rt.childNodes(R).length)return!1}else{if(null===rt.parentElement(S))return!1;R=rt.parentElement(S)}try{if("string"==typeof b){if(x){if(R.closest(`.${b}`))return!0}else if(R.classList.contains(b))return!0}else if(classMatchesRegex(R,b,x))return!0;if(I)if(x){if(R.closest(I))return!0}else if(R.matches(I))return!0}catch(S){}return!1}function serializeNode(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:_,inlineStylesheet:D,maskInputOptions:L={},maskTextFn:B,maskInputFn:U,dataURLOptions:$={},inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V=!1,cssCaptured:Q=!1}=b,G=function getRootId(S,b){if(!b.hasNode(S))return;const I=b.getId(S);return 1===I?void 0:I}(I,x);switch(S.nodeType){case S.DOCUMENT_NODE:return"CSS1Compat"!==S.compatMode?{type:Xe.Document,childNodes:[],compatMode:S.compatMode}:{type:Xe.Document,childNodes:[]};case S.DOCUMENT_TYPE_NODE:return{type:Xe.DocumentType,name:S.name,publicId:S.publicId,systemId:S.systemId,rootId:G};case S.ELEMENT_NODE:return function serializeElementNode(S,b){const{doc:I,blockClass:x,blockSelector:R,inlineStylesheet:A,maskInputOptions:_={},maskInputFn:D,dataURLOptions:L={},inlineImages:B,recordCanvas:U,keepIframeSrcFn:$,newlyAddedElement:j=!1,rootId:W}=b,H=function _isBlockedElement(S,b,I){try{if("string"==typeof b){if(S.classList.contains(b))return!0}else for(let I=S.classList.length;I--;){const x=S.classList[I];if(b.test(x))return!0}if(I)return S.matches(I)}catch(S){}return!1}(S,x,R),V=function getValidTagName$1(S){if(S instanceof HTMLFormElement)return"form";const b=toLowerCase(S.tagName);return ut.test(b)?"div":b}(S);let Q={};const G=S.attributes.length;for(let b=0;b<G;b++){const x=S.attributes[b];ignoreAttribute(V,x.name)||(Q[x.name]=transformAttribute(I,V,toLowerCase(x.name),x.value))}if("link"===V&&A){const b=Array.from(I.styleSheets).find(b=>b.href===S.href);let x=null;b&&(x=stringifyStylesheet(b)),x&&(delete Q.rel,delete Q.href,Q._cssText=x)}if("style"===V&&S.sheet){let b=stringifyStylesheet(S.sheet);b&&(S.childNodes.length>1&&(b=markCssSplits(b,S)),Q._cssText=b)}if("input"===V||"textarea"===V||"select"===V){const b=S.value,I=S.checked;"radio"!==Q.type&&"checkbox"!==Q.type&&"submit"!==Q.type&&"button"!==Q.type&&b?Q.value=maskInputValue({element:S,type:getInputType(S),tagName:V,value:b,maskInputOptions:_,maskInputFn:D}):I&&(Q.checked=I)}"option"===V&&(S.selected&&!_.select?Q.selected=!0:delete Q.selected);"dialog"===V&&S.open&&(Q.rr_open_mode=S.matches("dialog:modal")?"modal":"non-modal");if("canvas"===V&&U)if("2d"===S.__context)(function is2DCanvasBlank(S){const b=S.getContext("2d");if(!b)return!0;for(let I=0;I<S.width;I+=50)for(let x=0;x<S.height;x+=50){const R=b.getImageData,A=nt in R?R[nt]:R;if(new Uint32Array(A.call(b,I,x,Math.min(50,S.width-I),Math.min(50,S.height-x)).data.buffer).some(S=>0!==S))return!1}return!0})(S)||(Q.rr_dataURL=S.toDataURL(L.type,L.quality));else if(!("__context"in S)){const b=S.toDataURL(L.type,L.quality),x=I.createElement("canvas");x.width=S.width,x.height=S.height;b!==x.toDataURL(L.type,L.quality)&&(Q.rr_dataURL=b)}if("img"===V&&B){ht||(ht=I.createElement("canvas"),dt=ht.getContext("2d"));const b=S,x=b.currentSrc||b.getAttribute("src")||"<unknown-src>",R=b.crossOrigin,recordInlineImage=()=>{b.removeEventListener("load",recordInlineImage);try{ht.width=b.naturalWidth,ht.height=b.naturalHeight,dt.drawImage(b,0,0),Q.rr_dataURL=ht.toDataURL(L.type,L.quality)}catch(S){if("anonymous"!==b.crossOrigin)return b.crossOrigin="anonymous",void(b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage));console.warn(`Cannot inline img src=${x}! Error: ${S}`)}"anonymous"===b.crossOrigin&&(R?Q.crossOrigin=R:b.removeAttribute("crossorigin"))};b.complete&&0!==b.naturalWidth?recordInlineImage():b.addEventListener("load",recordInlineImage)}if("audio"===V||"video"===V){const b=Q;b.rr_mediaState=S.paused?"paused":"played",b.rr_mediaCurrentTime=S.currentTime,b.rr_mediaPlaybackRate=S.playbackRate,b.rr_mediaMuted=S.muted,b.rr_mediaLoop=S.loop,b.rr_mediaVolume=S.volume}j||(S.scrollLeft&&(Q.rr_scrollLeft=S.scrollLeft),S.scrollTop&&(Q.rr_scrollTop=S.scrollTop));if(H){const{width:b,height:I}=S.getBoundingClientRect();Q={class:Q.class,rr_width:`${b}px`,rr_height:`${I}px`}}"iframe"!==V||$(Q.src)||(S.contentDocument||(Q.rr_src=Q.src),delete Q.src);let J;try{customElements.get(V)&&(J=!0)}catch(S){}return{type:Xe.Element,tagName:V,attributes:Q,childNodes:[],isSVG:isSVGElement(S)||void 0,needBlock:H,rootId:W,isCustom:J}}(S,{doc:I,blockClass:R,blockSelector:A,inlineStylesheet:D,maskInputOptions:L,maskInputFn:U,dataURLOptions:$,inlineImages:j,recordCanvas:W,keepIframeSrcFn:H,newlyAddedElement:V,rootId:G});case S.TEXT_NODE:return function serializeTextNode(S,b){const{needsMask:I,maskTextFn:x,rootId:R,cssCaptured:A}=b,_=rt.parentNode(S),D=_&&_.tagName;let L="";const B="STYLE"===D||void 0,U="SCRIPT"===D||void 0;U?L="SCRIPT_PLACEHOLDER":A||(L=rt.textContent(S),B&&L&&(L=absolutifyURLs(L,getHref(b.doc))));!B&&!U&&L&&I&&(L=x?x(L,rt.parentElement(S)):L.replace(/[\S]/g,"*"));return{type:Xe.Text,textContent:L||"",rootId:R}}(S,{doc:I,needsMask:_,maskTextFn:B,rootId:G,cssCaptured:Q});case S.CDATA_SECTION_NODE:return{type:Xe.CDATA,textContent:"",rootId:G};case S.COMMENT_NODE:return{type:Xe.Comment,textContent:rt.textContent(S)||"",rootId:G};default:return!1}}function lowerIfExists(S){return null==S?"":S.toLowerCase()}function serializeNodeWithId(S,b){const{doc:I,mirror:x,blockClass:R,blockSelector:A,maskTextClass:_,maskTextSelector:D,skipChild:L=!1,inlineStylesheet:B=!0,maskInputOptions:U={},maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H={},inlineImages:V=!1,recordCanvas:Q=!1,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X=5e3,onStylesheetLoad:Y,stylesheetLoadTimeout:ee=5e3,keepIframeSrcFn:te=()=>!1,newlyAddedElement:se=!1,cssCaptured:re=!1}=b;let{needsMask:ne}=b,{preserveWhiteSpace:ie=!0}=b;if(!ne){ne=needMaskingText(S,_,D,void 0===ne)}const oe=serializeNode(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,dataURLOptions:H,inlineImages:V,recordCanvas:Q,keepIframeSrcFn:te,newlyAddedElement:se,cssCaptured:re});if(!oe)return console.warn(S,"not serialized"),null;let ae;ae=x.hasNode(S)?x.getId(S):function slimDOMExcluded(S,b){if(b.comment&&S.type===Xe.Comment)return!0;if(S.type===Xe.Element){if(b.script&&("script"===S.tagName||"link"===S.tagName&&("preload"===S.attributes.rel||"modulepreload"===S.attributes.rel)&&"script"===S.attributes.as||"link"===S.tagName&&"prefetch"===S.attributes.rel&&"string"==typeof S.attributes.href&&"js"===extractFileExtension(S.attributes.href)))return!0;if(b.headFavicon&&("link"===S.tagName&&"shortcut icon"===S.attributes.rel||"meta"===S.tagName&&(lowerIfExists(S.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===lowerIfExists(S.attributes.name)||"icon"===lowerIfExists(S.attributes.rel)||"apple-touch-icon"===lowerIfExists(S.attributes.rel)||"shortcut icon"===lowerIfExists(S.attributes.rel))))return!0;if("meta"===S.tagName){if(b.headMetaDescKeywords&&lowerIfExists(S.attributes.name).match(/^description|keywords$/))return!0;if(b.headMetaSocial&&(lowerIfExists(S.attributes.property).match(/^(og|twitter|fb):/)||lowerIfExists(S.attributes.name).match(/^(og|twitter):/)||"pinterest"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaRobots&&("robots"===lowerIfExists(S.attributes.name)||"googlebot"===lowerIfExists(S.attributes.name)||"bingbot"===lowerIfExists(S.attributes.name)))return!0;if(b.headMetaHttpEquiv&&void 0!==S.attributes["http-equiv"])return!0;if(b.headMetaAuthorship&&("author"===lowerIfExists(S.attributes.name)||"generator"===lowerIfExists(S.attributes.name)||"framework"===lowerIfExists(S.attributes.name)||"publisher"===lowerIfExists(S.attributes.name)||"progid"===lowerIfExists(S.attributes.name)||lowerIfExists(S.attributes.property).match(/^article:/)||lowerIfExists(S.attributes.property).match(/^product:/)))return!0;if(b.headMetaVerification&&("google-site-verification"===lowerIfExists(S.attributes.name)||"yandex-verification"===lowerIfExists(S.attributes.name)||"csrf-token"===lowerIfExists(S.attributes.name)||"p:domain_verify"===lowerIfExists(S.attributes.name)||"verify-v1"===lowerIfExists(S.attributes.name)||"verification"===lowerIfExists(S.attributes.name)||"shopify-checkout-api-token"===lowerIfExists(S.attributes.name)))return!0}}return!1}(oe,W)||!ie&&oe.type===Xe.Text&&!oe.textContent.replace(/^\s+|\s+$/gm,"").length?-2:genId();const le=Object.assign(oe,{id:ae});if(x.add(S,le),-2===ae)return null;G&&G(S);let ce=!L;if(le.type===Xe.Element){ce=ce&&!le.needBlock,delete le.needBlock;const b=rt.shadowRoot(S);b&&isNativeShadowDom(b)&&(le.isShadowHost=!0)}if((le.type===Xe.Document||le.type===Xe.Element)&&ce){W.headWhitespace&&le.type===Xe.Element&&"head"===le.tagName&&(ie=!1);const b={doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:L,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te,cssCaptured:!1};if(le.type===Xe.Element&&"textarea"===le.tagName&&void 0!==le.attributes.value);else{le.type===Xe.Element&&void 0!==le.attributes._cssText&&"string"==typeof le.attributes._cssText&&(b.cssCaptured=!0);for(const I of Array.from(rt.childNodes(S))){const S=serializeNodeWithId(I,b);S&&le.childNodes.push(S)}}let se=null;if(isElement(S)&&(se=rt.shadowRoot(S)))for(const S of Array.from(rt.childNodes(se))){const I=serializeNodeWithId(S,b);I&&(isNativeShadowDom(se)&&(I.isShadow=!0),le.childNodes.push(I))}}const ue=rt.parentNode(S);return ue&&isShadowRoot(ue)&&isNativeShadowDom(ue)&&(le.isShadow=!0),le.type===Xe.Element&&"iframe"===le.tagName&&function onceIframeLoaded(S,b,I){const x=S.contentWindow;if(!x)return;let R,A=!1;try{R=x.document.readyState}catch(S){return}if("complete"!==R){const x=setTimeout(()=>{A||(b(),A=!0)},I);return void S.addEventListener("load",()=>{clearTimeout(x),A=!0,b()})}const _="about:blank";if(x.location.href!==_||S.src===_||""===S.src)return setTimeout(b,0),S.addEventListener("load",b);S.addEventListener("load",b)}(S,()=>{const b=S.contentDocument;if(b&&J){const I=serializeNodeWithId(b,{doc:b,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});I&&J(S,I)}},X),le.type===Xe.Element&&"link"===le.tagName&&"string"==typeof le.attributes.rel&&("stylesheet"===le.attributes.rel||"preload"===le.attributes.rel&&"string"==typeof le.attributes.href&&"css"===extractFileExtension(le.attributes.href))&&function onceStylesheetLoaded(S,b,I){let x,R=!1;try{x=S.sheet}catch(S){return}if(x)return;const A=setTimeout(()=>{R||(b(),R=!0)},I);S.addEventListener("load",()=>{clearTimeout(A),R=!0,b()})}(S,()=>{if(Y){const b=serializeNodeWithId(S,{doc:I,mirror:x,blockClass:R,blockSelector:A,needsMask:ne,maskTextClass:_,maskTextSelector:D,skipChild:!1,inlineStylesheet:B,maskInputOptions:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:W,dataURLOptions:H,inlineImages:V,recordCanvas:Q,preserveWhiteSpace:ie,onSerialize:G,onIframeLoad:J,iframeLoadTimeout:X,onStylesheetLoad:Y,stylesheetLoadTimeout:ee,keepIframeSrcFn:te});b&&Y(S,b)}},ee),le}function getAugmentedNamespace$1(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var mt={exports:{}},yt=String,create$1=function(){return{isColorSupported:!1,reset:yt,bold:yt,dim:yt,italic:yt,underline:yt,inverse:yt,hidden:yt,strikethrough:yt,black:yt,red:yt,green:yt,yellow:yt,blue:yt,magenta:yt,cyan:yt,white:yt,gray:yt,bgBlack:yt,bgRed:yt,bgGreen:yt,bgYellow:yt,bgBlue:yt,bgMagenta:yt,bgCyan:yt,bgWhite:yt}};mt.exports=create$1(),mt.exports.createColors=create$1;var vt=mt.exports;const St=getAugmentedNamespace$1(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let wt=vt,bt=St,Ct=class CssSyntaxError extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=wt.isColorSupported),bt&&S&&(b=bt(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=wt.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var kt=Ct;Ct.default=Ct;var It={};It.isClean=Symbol("isClean"),It.my=Symbol("my");const Et={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let xt=class Stringifier{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return Et[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize$1(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=Et[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var Mt=xt;xt.default=xt;let Rt=Mt;function stringify$4$1(S,b){new Rt(b).stringify(S)}var Tt=stringify$4$1;stringify$4$1.default=stringify$4$1;let{isClean:At,my:_t}=It,Ot=kt,Dt=Mt,Ft=Tt;function cloneNode$1(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode$1(S,I)):("object"===A&&null!==R&&(R=cloneNode$1(R)),I[x]=R)}return I}let Nt=class Node2{constructor(S={}){this.raws={},this[At]=!1,this[_t]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode$1(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new Ot(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[At]){this[At]=!1;let S=this;for(;S=S.parent;)S[At]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new Dt).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=Ft){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var Lt=Nt;Nt.default=Nt;let Pt=Lt,Bt=class Declaration extends Pt{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var zt=Bt;Bt.default=Bt;var Ut={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:$t,SourceMapGenerator:jt}=St,{existsSync:qt,readFileSync:Wt}=St,{dirname:Ht,join:Vt}=St;let Qt=class PreviousMap{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=Ht(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new $t(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64$1(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=Ht(S),qt(S))return this.mapFile=S,Wt(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof $t)return jt.fromSourceMap(b).toString();if(b instanceof jt)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=Vt(Ht(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var Kt=Qt;Qt.default=Qt;let{SourceMapConsumer:Gt,SourceMapGenerator:Jt}=St,{fileURLToPath:Xt,pathToFileURL:Yt}=St,{isAbsolute:Zt,resolve:es}=St,{nanoid:ts}=Ut,ss=St,rs=kt,ns=Kt,is=Symbol("fromOffsetCache"),os=Boolean(Gt&&Jt),as=Boolean(es&&Zt),ls=class Input{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||""===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!as||/^\w+:\/\//.test(b.from)||Zt(b.from)?this.file=b.from:this.file=es(b.from)),as&&os){let S=new ns(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+ts(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new rs(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new rs(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(Yt&&(R.input.url=Yt(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[is])I=this[is];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[is]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:es(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=Zt(D.source)?Yt(D.source):new URL(D.source,this.map.consumer().sourceRoot||Yt(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!Xt)throw new Error("file: protocol is not available in this PostCSS build");L.file=Xt(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var cs=ls;ls.default=ls,ss&&ss.registerInput&&ss.registerInput(ls);let{SourceMapConsumer:us,SourceMapGenerator:hs}=St,{dirname:ds,relative:gs,resolve:ps,sep:fs}=St,{pathToFileURL:ms}=St,ys=cs,vs=Boolean(us&&hs),Ss=Boolean(ds&&ps&&gs&&fs);var ws=class MapGenerator{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||ds(S.file);!1===this.mapOpts.sourcesContent?(b=new us(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),Ss&&vs&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=hs.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new hs({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new hs({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?ds(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=ds(ps(I,this.mapOpts.annotation)));let x=gs(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new ys(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(ms){let b=ms(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===fs&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let bs=Lt,Cs=class Comment extends bs{constructor(S){super(S),this.type="comment"}};var ks=Cs;Cs.default=Cs;let Is,Es,xs,Ms,{isClean:Rs,my:Ts}=It,As=zt,_s=ks,Os=Lt;function cleanSource$1(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource$1(S.nodes)),delete S.source,S))}function markDirtyUp$1(S){if(S[Rs]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp$1(b)}let Ds=class Container extends Os{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource$1(Is(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new As(S)]}else if(S.selector)S=[new Es(S)];else if(S.name)S=[new xs(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new _s(S)]}return S.map(S=>(S[Ts]||Container.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[Rs]&&markDirtyUp$1(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Ds.registerParse=S=>{Is=S},Ds.registerRule=S=>{Es=S},Ds.registerAtRule=S=>{xs=S},Ds.registerRoot=S=>{Ms=S};var Fs=Ds;Ds.default=Ds,Ds.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,xs.prototype):"rule"===S.type?Object.setPrototypeOf(S,Es.prototype):"decl"===S.type?Object.setPrototypeOf(S,As.prototype):"comment"===S.type?Object.setPrototypeOf(S,_s.prototype):"root"===S.type&&Object.setPrototypeOf(S,Ms.prototype),S[Ts]=!0,S.nodes&&S.nodes.forEach(S=>{Ds.rebuild(S)})};let Ns,Ls,Ps=Fs,Bs=class Document2 extends Ps{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Ns(new Ls,this,S).stringify()}};Bs.registerLazyResult=S=>{Ns=S},Bs.registerProcessor=S=>{Ls=S};var zs=Bs;Bs.default=Bs;let Us=class Warning{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var $s=Us;Us.default=Us;let js=$s,qs=class Result{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new js(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var Ws=qs;qs.default=qs;const Hs="'".charCodeAt(0),Vs='"'.charCodeAt(0),Qs="\\".charCodeAt(0),Ks="/".charCodeAt(0),Gs="\n".charCodeAt(0),Js=" ".charCodeAt(0),Xs="\f".charCodeAt(0),Ys="\t".charCodeAt(0),Zs="\r".charCodeAt(0),er="[".charCodeAt(0),tr="]".charCodeAt(0),sr="(".charCodeAt(0),rr=")".charCodeAt(0),nr="{".charCodeAt(0),ir="}".charCodeAt(0),or=";".charCodeAt(0),ar="*".charCodeAt(0),lr=":".charCodeAt(0),cr="@".charCodeAt(0),ur=/[\t\n\f\r "#'()/;[\\\]{}]/g,hr=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,dr=/.[\r\n"'(/\\]/,gr=/[\da-f]/i;let pr=Fs,fr=class AtRule extends pr{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var mr=fr;fr.default=fr,pr.registerAtRule(fr);let yr,vr,Sr=Fs,wr=class Root extends Sr{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new yr(new vr,this,S).stringify()}};wr.registerLazyResult=S=>{yr=S},wr.registerProcessor=S=>{vr=S};var br=wr;wr.default=wr,Sr.registerRoot(wr);let Cr={comma:S=>Cr.split(S,[","],!0),space:S=>Cr.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var kr=Cr;Cr.default=Cr;let Ir=Fs,Er=kr,xr=class Rule extends Ir{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Er.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var Mr=xr;xr.default=xr,Ir.registerRule(xr);let Rr=zt,Tr=function tokenizer(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case Gs:case Js:case Ys:case Zs:case Xs:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===Js||I===Gs||I===Ys||I===Zs||I===Xs);$=["space",j.slice(V,x)],V=x-1;break;case er:case tr:case nr:case ir:case lr:case or:case rr:{let S=String.fromCharCode(I);$=[S,S,V];break}case sr:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==Hs&&U!==Vs&&U!==Js&&U!==Gs&&U!==Ys&&U!==Xs&&U!==Zs){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===Qs;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||dr.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case Hs:case Vs:R=I===Hs?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===Qs;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case cr:ur.lastIndex=V+1,ur.test(j),x=0===ur.lastIndex?j.length-1:ur.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case Qs:for(x=V,_=!0;j.charCodeAt(x+1)===Qs;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==Ks&&I!==Js&&I!==Gs&&I!==Ys&&I!==Zs&&I!==Xs&&(x+=1,gr.test(j.charAt(x)))){for(;gr.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===Js&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===Ks&&j.charCodeAt(V+1)===ar?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(hr.lastIndex=V+1,hr.test(j),x=0===hr.lastIndex?j.length-1:hr.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},Ar=ks,_r=mr,Or=br,Dr=Mr;const Fr={empty:!0,space:!0};var Nr=class Parser{constructor(S){this.input=S,this.root=new Or,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new _r;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new Ar;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=Tr(this.input)}decl(S,b){let I=new Rr;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition$1(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new Dr;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",Fr[D]||Fr[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new Dr;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let Lr=Fs,Pr=Nr,Br=cs;function parse$3$1(S,b){let I=new Br(S,b),x=new Pr(I);try{x.parse()}catch(S){throw S}return x.root}var zr=parse$3$1;parse$3$1.default=parse$3$1,Lr.registerParse(parse$3$1);let{isClean:Ur,my:$r}=It,jr=ws,qr=Tt,Wr=Fs,Hr=zs,Vr=Ws,Qr=zr,Kr=br;const Gr={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},Jr={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Xr={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise$1(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents$1(S){let b=!1,I=Gr[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack$1(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents$1(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks$1(S){return S[Ur]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks$1(S)),S}let Yr={},Zr=class LazyResult{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult||b instanceof Vr)x=cleanMarks$1(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=Qr;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[$r]&&Wr.rebuild(x)}else x=cleanMarks$1(b);this.result=new Vr(S,x,I),this.helpers={...Yr,postcss:Yr,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!Jr[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Xr[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise$1(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[Ur];){S[Ur]=!0;let b=[toStack$1(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise$1(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise$1(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=qr;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new jr(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise$1(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[Ur];)S[Ur]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise$1(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[Ur])return x[Ur]=!0,void S.push(toStack$1(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[Ur]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[Ur]=!0;let b=getEvents$1(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[Ur]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Zr.registerPostcss=S=>{Yr=S};var en=Zr;Zr.default=Zr,Kr.registerLazyResult(Zr),Hr.registerLazyResult(Zr);let tn=ws,sn=Tt,rn=zr;const nn=Ws;let an=class NoWorkResult{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=sn;this.result=new nn(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new tn(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=rn;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var cn=an;an.default=an;let un=cn,hn=en,dn=zs,gn=br,pn=class Processor{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new hn(this,S,b):new un(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var fn=pn;pn.default=pn,gn.registerProcessor(pn),dn.registerProcessor(pn);let mn=zt,yn=Kt,vn=ks,Sn=mr,wn=cs,bn=br,Cn=Mr;function fromJSON$1$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:wn.prototype};I.map&&(I.map={...I.map,__proto__:yn.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new bn(x);if("decl"===x.type)return new mn(x);if("rule"===x.type)return new Cn(x);if("comment"===x.type)return new vn(x);if("atrule"===x.type)return new Sn(x);throw new Error("Unknown node type: "+S.type)}var kn=fromJSON$1$1;fromJSON$1$1.default=fromJSON$1$1;let In=kt,En=zt,xn=en,Mn=Fs,Rn=fn,Tn=Tt,An=kn,_n=zs,On=$s,Dn=ks,Fn=mr,Nn=Ws,Ln=cs,Pn=zr,Bn=kr,zn=Mr,Un=br,$n=Lt;function postcss$3(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new Rn(S)}postcss$3.plugin=function plugin(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new Rn).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss$3([creator(I)]).process(S,b)},creator},postcss$3.stringify=Tn,postcss$3.parse=Pn,postcss$3.fromJSON=An,postcss$3.list=Bn,postcss$3.comment=S=>new Dn(S),postcss$3.atRule=S=>new Fn(S),postcss$3.decl=S=>new En(S),postcss$3.rule=S=>new zn(S),postcss$3.root=S=>new Un(S),postcss$3.document=S=>new _n(S),postcss$3.CssSyntaxError=In,postcss$3.Declaration=En,postcss$3.Container=Mn,postcss$3.Processor=Rn,postcss$3.Document=_n,postcss$3.Comment=Dn,postcss$3.Warning=On,postcss$3.AtRule=Fn,postcss$3.Result=Nn,postcss$3.Input=Ln,postcss$3.Rule=zn,postcss$3.Root=Un,postcss$3.Node=$n,xn.registerPostcss(postcss$3),postcss$3.default=postcss$3;var jn=Object.defineProperty,__publicField2=(S,b,I)=>((S,b,I)=>b in S?jn(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I);function getAugmentedNamespace(S){if(S.__esModule)return S;var b=S.default;if("function"==typeof b){var I=function a22(){return this instanceof a22?Reflect.construct(b,arguments,this.constructor):b.apply(this,arguments)};I.prototype=b.prototype}else I={};return Object.defineProperty(I,"__esModule",{value:!0}),Object.keys(S).forEach(function(b){var x=Object.getOwnPropertyDescriptor(S,b);Object.defineProperty(I,b,x.get?x:{enumerable:!0,get:function(){return S[b]}})}),I}var qn={exports:{}},Wn=String,create=function(){return{isColorSupported:!1,reset:Wn,bold:Wn,dim:Wn,italic:Wn,underline:Wn,inverse:Wn,hidden:Wn,strikethrough:Wn,black:Wn,red:Wn,green:Wn,yellow:Wn,blue:Wn,magenta:Wn,cyan:Wn,white:Wn,gray:Wn,bgBlack:Wn,bgRed:Wn,bgGreen:Wn,bgYellow:Wn,bgBlue:Wn,bgMagenta:Wn,bgCyan:Wn,bgWhite:Wn}};qn.exports=create(),qn.exports.createColors=create;var Hn=qn.exports;const Vn=getAugmentedNamespace(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Qn=Hn,Kn=Vn,Gn=class CssSyntaxError2 extends Error{constructor(S,b,I,x,R,A){super(S),this.name="CssSyntaxError",this.reason=S,R&&(this.file=R),x&&(this.source=x),A&&(this.plugin=A),void 0!==b&&void 0!==I&&("number"==typeof b?(this.line=b,this.column=I):(this.line=b.line,this.column=b.column,this.endLine=I.line,this.endColumn=I.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,CssSyntaxError2)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(S){if(!this.source)return"";let b=this.source;null==S&&(S=Qn.isColorSupported),Kn&&S&&(b=Kn(b));let I,x,R=b.split(/\r?\n/),A=Math.max(this.line-3,0),_=Math.min(this.line+2,R.length),D=String(_).length;if(S){let{bold:S,gray:b,red:R}=Qn.createColors(!0);I=b=>S(R(b)),x=S=>b(S)}else I=x=S=>S;return R.slice(A,_).map((S,b)=>{let R=A+1+b,_=" "+(" "+R).slice(-D)+" | ";if(R===this.line){let b=x(_.replace(/\d/g," "))+S.slice(0,this.column-1).replace(/[^\t]/g," ");return I(">")+x(_)+S+"\n "+b+I("^")}return" "+x(_)+S}).join("\n")}toString(){let S=this.showSourceCode();return S&&(S="\n\n"+S+"\n"),this.name+": "+this.message+S}};var Jn=Gn;Gn.default=Gn;var Xn={};Xn.isClean=Symbol("isClean"),Xn.my=Symbol("my");const Yn={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Zn=class Stringifier2{constructor(S){this.builder=S}atrule(S,b){let I="@"+S.name,x=S.params?this.rawValue(S,"params"):"";if(void 0!==S.raws.afterName?I+=S.raws.afterName:x&&(I+=" "),S.nodes)this.block(S,I+x);else{let R=(S.raws.between||"")+(b?";":"");this.builder(I+x+R,S)}}beforeAfter(S,b){let I;I="decl"===S.type?this.raw(S,null,"beforeDecl"):"comment"===S.type?this.raw(S,null,"beforeComment"):"before"===b?this.raw(S,null,"beforeRule"):this.raw(S,null,"beforeClose");let x=S.parent,R=0;for(;x&&"root"!==x.type;)R+=1,x=x.parent;if(I.includes("\n")){let b=this.raw(S,null,"indent");if(b.length)for(let S=0;S<R;S++)I+=b}return I}block(S,b){let I,x=this.raw(S,"between","beforeOpen");this.builder(b+x+"{",S,"start"),S.nodes&&S.nodes.length?(this.body(S),I=this.raw(S,"after")):I=this.raw(S,"after","emptyBody"),I&&this.builder(I),this.builder("}",S,"end")}body(S){let b=S.nodes.length-1;for(;b>0&&"comment"===S.nodes[b].type;)b-=1;let I=this.raw(S,"semicolon");for(let x=0;x<S.nodes.length;x++){let R=S.nodes[x],A=this.raw(R,"before");A&&this.builder(A),this.stringify(R,b!==x||I)}}comment(S){let b=this.raw(S,"left","commentLeft"),I=this.raw(S,"right","commentRight");this.builder("/*"+b+S.text+I+"*/",S)}decl(S,b){let I=this.raw(S,"between","colon"),x=S.prop+I+this.rawValue(S,"value");S.important&&(x+=S.raws.important||" !important"),b&&(x+=";"),this.builder(x,S)}document(S){this.body(S)}raw(S,b,I){let x;if(I||(I=b),b&&(x=S.raws[b],void 0!==x))return x;let R=S.parent;if("before"===I){if(!R||"root"===R.type&&R.first===S)return"";if(R&&"document"===R.type)return""}if(!R)return Yn[I];let A=S.root();if(A.rawCache||(A.rawCache={}),void 0!==A.rawCache[I])return A.rawCache[I];if("before"===I||"after"===I)return this.beforeAfter(S,I);{let R="raw"+function capitalize(S){return S[0].toUpperCase()+S.slice(1)}(I);this[R]?x=this[R](A,S):A.walk(S=>{if(x=S.raws[b],void 0!==x)return!1})}return void 0===x&&(x=Yn[I]),A.rawCache[I]=x,x}rawBeforeClose(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length>0&&void 0!==S.raws.after)return b=S.raws.after,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawBeforeComment(S,b){let I;return S.walkComments(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeDecl"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeDecl(S,b){let I;return S.walkDecls(S=>{if(void 0!==S.raws.before)return I=S.raws.before,I.includes("\n")&&(I=I.replace(/[^\n]+$/,"")),!1}),void 0===I?I=this.raw(b,null,"beforeRule"):I&&(I=I.replace(/\S/g,"")),I}rawBeforeOpen(S){let b;return S.walk(S=>{if("decl"!==S.type&&(b=S.raws.between,void 0!==b))return!1}),b}rawBeforeRule(S){let b;return S.walk(I=>{if(I.nodes&&(I.parent!==S||S.first!==I)&&void 0!==I.raws.before)return b=I.raws.before,b.includes("\n")&&(b=b.replace(/[^\n]+$/,"")),!1}),b&&(b=b.replace(/\S/g,"")),b}rawColon(S){let b;return S.walkDecls(S=>{if(void 0!==S.raws.between)return b=S.raws.between.replace(/[^\s:]/g,""),!1}),b}rawEmptyBody(S){let b;return S.walk(S=>{if(S.nodes&&0===S.nodes.length&&(b=S.raws.after,void 0!==b))return!1}),b}rawIndent(S){if(S.raws.indent)return S.raws.indent;let b;return S.walk(I=>{let x=I.parent;if(x&&x!==S&&x.parent&&x.parent===S&&void 0!==I.raws.before){let S=I.raws.before.split("\n");return b=S[S.length-1],b=b.replace(/\S/g,""),!1}}),b}rawSemicolon(S){let b;return S.walk(S=>{if(S.nodes&&S.nodes.length&&"decl"===S.last.type&&(b=S.raws.semicolon,void 0!==b))return!1}),b}rawValue(S,b){let I=S[b],x=S.raws[b];return x&&x.value===I?x.raw:I}root(S){this.body(S),S.raws.after&&this.builder(S.raws.after)}rule(S){this.block(S,this.rawValue(S,"selector")),S.raws.ownSemicolon&&this.builder(S.raws.ownSemicolon,S,"end")}stringify(S,b){if(!this[S.type])throw new Error("Unknown AST node type "+S.type+". Maybe you need to change PostCSS stringifier.");this[S.type](S,b)}};var ei=Zn;Zn.default=Zn;let ti=ei;function stringify$4(S,b){new ti(b).stringify(S)}var si=stringify$4;stringify$4.default=stringify$4;let{isClean:ri,my:ni}=Xn,ii=Jn,oi=ei,ai=si;function cloneNode(S,b){let I=new S.constructor;for(let x in S){if(!Object.prototype.hasOwnProperty.call(S,x))continue;if("proxyCache"===x)continue;let R=S[x],A=typeof R;"parent"===x&&"object"===A?b&&(I[x]=b):"source"===x?I[x]=R:Array.isArray(R)?I[x]=R.map(S=>cloneNode(S,I)):("object"===A&&null!==R&&(R=cloneNode(R)),I[x]=R)}return I}let li=class Node3{constructor(S={}){this.raws={},this[ri]=!1,this[ni]=!0;for(let b in S)if("nodes"===b){this.nodes=[];for(let I of S[b])"function"==typeof I.clone?this.append(I.clone()):this.append(I)}else this[b]=S[b]}addToError(S){if(S.postcssNode=this,S.stack&&this.source&&/\n\s{4}at /.test(S.stack)){let b=this.source;S.stack=S.stack.replace(/\n\s{4}at /,`$&${b.input.from}:${b.start.line}:${b.start.column}$&`)}return S}after(S){return this.parent.insertAfter(this,S),this}assign(S={}){for(let b in S)this[b]=S[b];return this}before(S){return this.parent.insertBefore(this,S),this}cleanRaws(S){delete this.raws.before,delete this.raws.after,S||delete this.raws.between}clone(S={}){let b=cloneNode(this);for(let I in S)b[I]=S[I];return b}cloneAfter(S={}){let b=this.clone(S);return this.parent.insertAfter(this,b),b}cloneBefore(S={}){let b=this.clone(S);return this.parent.insertBefore(this,b),b}error(S,b={}){if(this.source){let{end:I,start:x}=this.rangeBy(b);return this.source.input.error(S,{column:x.column,line:x.line},{column:I.column,line:I.line},b)}return new ii(S)}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:"root"===b?()=>S.root().toProxy():S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"prop"!==b&&"value"!==b&&"name"!==b&&"params"!==b&&"important"!==b&&"text"!==b||S.markDirty()),!0)}}markDirty(){if(this[ri]){this[ri]=!1;let S=this;for(;S=S.parent;)S[ri]=!1}}next(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S+1]}positionBy(S,b){let I=this.source.start;if(S.index)I=this.positionInside(S.index,b);else if(S.word){let x=(b=this.toString()).indexOf(S.word);-1!==x&&(I=this.positionInside(x,b))}return I}positionInside(S,b){let I=b||this.toString(),x=this.source.start.column,R=this.source.start.line;for(let b=0;b<S;b++)"\n"===I[b]?(x=1,R+=1):x+=1;return{column:x,line:R}}prev(){if(!this.parent)return;let S=this.parent.index(this);return this.parent.nodes[S-1]}rangeBy(S){let b={column:this.source.start.column,line:this.source.start.line},I=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:b.column+1,line:b.line};if(S.word){let x=this.toString(),R=x.indexOf(S.word);-1!==R&&(b=this.positionInside(R,x),I=this.positionInside(R+S.word.length,x))}else S.start?b={column:S.start.column,line:S.start.line}:S.index&&(b=this.positionInside(S.index)),S.end?I={column:S.end.column,line:S.end.line}:"number"==typeof S.endIndex?I=this.positionInside(S.endIndex):S.index&&(I=this.positionInside(S.index+1));return(I.line<b.line||I.line===b.line&&I.column<=b.column)&&(I={column:b.column+1,line:b.line}),{end:I,start:b}}raw(S,b){return(new oi).raw(this,S,b)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...S){if(this.parent){let b=this,I=!1;for(let x of S)x===this?I=!0:I?(this.parent.insertAfter(b,x),b=x):this.parent.insertBefore(b,x);I||this.remove()}return this}root(){let S=this;for(;S.parent&&"document"!==S.parent.type;)S=S.parent;return S}toJSON(S,b){let I={},x=null==b;b=b||new Map;let R=0;for(let S in this){if(!Object.prototype.hasOwnProperty.call(this,S))continue;if("parent"===S||"proxyCache"===S)continue;let x=this[S];if(Array.isArray(x))I[S]=x.map(S=>"object"==typeof S&&S.toJSON?S.toJSON(null,b):S);else if("object"==typeof x&&x.toJSON)I[S]=x.toJSON(null,b);else if("source"===S){let A=b.get(x.input);null==A&&(A=R,b.set(x.input,R),R++),I[S]={end:x.end,inputId:A,start:x.start}}else I[S]=x}return x&&(I.inputs=[...b.keys()].map(S=>S.toJSON())),I}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(S=ai){S.stringify&&(S=S.stringify);let b="";return S(this,S=>{b+=S}),b}warn(S,b,I){let x={node:this};for(let S in I)x[S]=I[S];return S.warn(b,x)}get proxyOf(){return this}};var ci=li;li.default=li;let ui=ci,hi=class Declaration2 extends ui{constructor(S){S&&void 0!==S.value&&"string"!=typeof S.value&&(S={...S,value:String(S.value)}),super(S),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var di=hi;hi.default=hi;var gi={nanoid:(S=21)=>{let b="",I=S;for(;I--;)b+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return b},customAlphabet:(S,b=21)=>(I=b)=>{let x="",R=I;for(;R--;)x+=S[Math.random()*S.length|0];return x}};let{SourceMapConsumer:pi,SourceMapGenerator:fi}=Vn,{existsSync:mi,readFileSync:yi}=Vn,{dirname:vi,join:Si}=Vn;let wi=class PreviousMap2{constructor(S,b){if(!1===b.map)return;this.loadAnnotation(S),this.inline=this.startWith(this.annotation,"data:");let I=b.map?b.map.prev:void 0,x=this.loadMap(b.from,I);!this.mapFile&&b.from&&(this.mapFile=b.from),this.mapFile&&(this.root=vi(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new pi(this.text)),this.consumerCache}decodeInline(S){if(/^data:application\/json;charset=utf-?8,/.test(S)||/^data:application\/json,/.test(S))return decodeURIComponent(S.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(S)||/^data:application\/json;base64,/.test(S))return function fromBase64(S){return Buffer?Buffer.from(S,"base64").toString():window.atob(S)}(S.substr(RegExp.lastMatch.length));let b=S.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+b)}getAnnotationURL(S){return S.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(S){return"object"==typeof S&&("string"==typeof S.mappings||"string"==typeof S._mappings||Array.isArray(S.sections))}loadAnnotation(S){let b=S.match(/\/\*\s*# sourceMappingURL=/gm);if(!b)return;let I=S.lastIndexOf(b.pop()),x=S.indexOf("*/",I);I>-1&&x>-1&&(this.annotation=this.getAnnotationURL(S.substring(I,x)))}loadFile(S){if(this.root=vi(S),mi(S))return this.mapFile=S,yi(S,"utf-8").toString().trim()}loadMap(S,b){if(!1===b)return!1;if(b){if("string"==typeof b)return b;if("function"!=typeof b){if(b instanceof pi)return fi.fromSourceMap(b).toString();if(b instanceof fi)return b.toString();if(this.isMap(b))return JSON.stringify(b);throw new Error("Unsupported previous source map format: "+b.toString())}{let I=b(S);if(I){let S=this.loadFile(I);if(!S)throw new Error("Unable to load previous source map: "+I.toString());return S}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let b=this.annotation;return S&&(b=Si(vi(S),b)),this.loadFile(b)}}}startWith(S,b){return!!S&&S.substr(0,b.length)===b}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var bi=wi;wi.default=wi;let{SourceMapConsumer:Ci,SourceMapGenerator:ki}=Vn,{fileURLToPath:Ii,pathToFileURL:Ei}=Vn,{isAbsolute:xi,resolve:Mi}=Vn,{nanoid:Ri}=gi,Ti=Vn,Ai=Jn,_i=bi,Oi=Symbol("fromOffsetCache"),Di=Boolean(Ci&&ki),Fi=Boolean(Mi&&xi),Ni=class Input2{constructor(S,b={}){if(null==S||"object"==typeof S&&!S.toString)throw new Error(`PostCSS received ${S} instead of CSS string`);if(this.css=S.toString(),"\ufeff"===this.css[0]||""===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,b.from&&(!Fi||/^\w+:\/\//.test(b.from)||xi(b.from)?this.file=b.from:this.file=Mi(b.from)),Fi&&Di){let S=new _i(this.css,b);if(S.text){this.map=S;let b=S.consumer().file;!this.file&&b&&(this.file=this.mapResolve(b))}}this.file||(this.id="<input css "+Ri(6)+">"),this.map&&(this.map.file=this.from)}error(S,b,I,x={}){let R,A,_;if(b&&"object"==typeof b){let S=b,x=I;if("number"==typeof S.offset){let x=this.fromOffset(S.offset);b=x.line,I=x.col}else b=S.line,I=S.column;if("number"==typeof x.offset){let S=this.fromOffset(x.offset);A=S.line,_=S.col}else A=x.line,_=x.column}else if(!I){let S=this.fromOffset(b);b=S.line,I=S.col}let D=this.origin(b,I,A,_);return R=D?new Ai(S,void 0===D.endLine?D.line:{column:D.column,line:D.line},void 0===D.endLine?D.column:{column:D.endColumn,line:D.endLine},D.source,D.file,x.plugin):new Ai(S,void 0===A?b:{column:I,line:b},void 0===A?I:{column:_,line:A},this.css,this.file,x.plugin),R.input={column:I,endColumn:_,endLine:A,line:b,source:this.css},this.file&&(Ei&&(R.input.url=Ei(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[Oi])I=this[Oi];else{let S=this.css.split("\n");I=new Array(S.length);let b=0;for(let x=0,R=S.length;x<R;x++)I[x]=b,b+=S[x].length+1;this[Oi]=I}b=I[I.length-1];let x=0;if(S>=b)x=I.length-1;else{let b,R=I.length-2;for(;x<R;)if(b=x+(R-x>>1),S<I[b])R=b-1;else{if(!(S>=I[b+1])){x=b;break}x=b+1}}return{col:S-I[x]+1,line:x+1}}mapResolve(S){return/^\w+:\/\//.test(S)?S:Mi(this.map.consumer().sourceRoot||this.map.root||".",S)}origin(S,b,I,x){if(!this.map)return!1;let R,A,_=this.map.consumer(),D=_.originalPositionFor({column:b,line:S});if(!D.source)return!1;"number"==typeof I&&(R=_.originalPositionFor({column:x,line:I})),A=xi(D.source)?Ei(D.source):new URL(D.source,this.map.consumer().sourceRoot||Ei(this.map.mapFile));let L={column:D.column,endColumn:R&&R.column,endLine:R&&R.line,line:D.line,url:A.toString()};if("file:"===A.protocol){if(!Ii)throw new Error("file: protocol is not available in this PostCSS build");L.file=Ii(A)}let B=_.sourceContentFor(D.source);return B&&(L.source=B),L}toJSON(){let S={};for(let b of["hasBOM","css","file","id"])null!=this[b]&&(S[b]=this[b]);return this.map&&(S.map={...this.map},S.map.consumerCache&&(S.map.consumerCache=void 0)),S}get from(){return this.file||this.id}};var Li=Ni;Ni.default=Ni,Ti&&Ti.registerInput&&Ti.registerInput(Ni);let{SourceMapConsumer:Pi,SourceMapGenerator:Bi}=Vn,{dirname:zi,relative:Ui,resolve:$i,sep:ji}=Vn,{pathToFileURL:qi}=Vn,Wi=Li,Hi=Boolean(Pi&&Bi),Vi=Boolean(zi&&$i&&Ui&&ji);var Qi=class MapGenerator2{constructor(S,b,I,x){this.stringify=S,this.mapOpts=I.map||{},this.root=b,this.opts=I,this.css=x,this.originalCSS=x,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let S;S=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let b="\n";this.css.includes("\r\n")&&(b="\r\n"),this.css+=b+"/*# sourceMappingURL="+S+" */"}applyPrevMaps(){for(let S of this.previous()){let b,I=this.toUrl(this.path(S.file)),x=S.root||zi(S.file);!1===this.mapOpts.sourcesContent?(b=new Pi(S.text),b.sourcesContent&&(b.sourcesContent=null)):b=S.consumer(),this.map.applySourceMap(b,I,this.toUrl(this.path(x)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let S;for(let b=this.root.nodes.length-1;b>=0;b--)S=this.root.nodes[b],"comment"===S.type&&0===S.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(b)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),Vi&&Hi&&this.isMap())return this.generateMap();{let S="";return this.stringify(this.root,b=>{S+=b}),[S]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let S=this.previous()[0].consumer();S.file=this.outputFile(),this.map=Bi.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Bi({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Bi({file:this.outputFile(),ignoreInvalidMapping:!0});let S,b,I=1,x=1,R="<no source>",A={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(_,D,L)=>{if(this.css+=_,D&&"end"!==L&&(A.generated.line=I,A.generated.column=x-1,D.source&&D.source.start?(A.source=this.sourcePath(D),A.original.line=D.source.start.line,A.original.column=D.source.start.column-1,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,this.map.addMapping(A))),S=_.match(/\n/g),S?(I+=S.length,b=_.lastIndexOf("\n"),x=_.length-b):x+=_.length,D&&"start"!==L){let S=D.parent||{raws:{}};("decl"===D.type||"atrule"===D.type&&!D.nodes)&&D===S.last&&!S.raws.semicolon||(D.source&&D.source.end?(A.source=this.sourcePath(D),A.original.line=D.source.end.line,A.original.column=D.source.end.column-1,A.generated.line=I,A.generated.column=x-2,this.map.addMapping(A)):(A.source=R,A.original.line=1,A.original.column=0,A.generated.line=I,A.generated.column=x-1,this.map.addMapping(A)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(S=>S.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let S=this.mapOpts.annotation;return(void 0===S||!0===S)&&(!this.previous().length||this.previous().some(S=>S.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(S=>S.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(S){if(this.mapOpts.absolute)return S;if(60===S.charCodeAt(0))return S;if(/^\w+:\/\//.test(S))return S;let b=this.memoizedPaths.get(S);if(b)return b;let I=this.opts.to?zi(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=zi($i(I,this.mapOpts.annotation)));let x=Ui(I,S);return this.memoizedPaths.set(S,x),x}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(S=>{if(S.source&&S.source.input.map){let b=S.source.input.map;this.previousMaps.includes(b)||this.previousMaps.push(b)}});else{let S=new Wi(this.originalCSS,this.opts);S.map&&this.previousMaps.push(S.map)}return this.previousMaps}setSourcesContent(){let S={};if(this.root)this.root.walk(b=>{if(b.source){let I=b.source.input.from;if(I&&!S[I]){S[I]=!0;let x=this.usesFileUrls?this.toFileUrl(I):this.toUrl(this.path(I));this.map.setSourceContent(x,b.source.input.css)}}});else if(this.css){let S=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(S,this.css)}}sourcePath(S){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(S.source.input.from):this.toUrl(this.path(S.source.input.from))}toBase64(S){return Buffer?Buffer.from(S).toString("base64"):window.btoa(unescape(encodeURIComponent(S)))}toFileUrl(S){let b=this.memoizedFileURLs.get(S);if(b)return b;if(qi){let b=qi(S).toString();return this.memoizedFileURLs.set(S,b),b}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(S){let b=this.memoizedURLs.get(S);if(b)return b;"\\"===ji&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let Ki=ci,Gi=class Comment2 extends Ki{constructor(S){super(S),this.type="comment"}};var Ji=Gi;Gi.default=Gi;let Xi,Yi,Zi,eo,{isClean:to,my:so}=Xn,ro=di,no=Ji,io=ci;function cleanSource(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource(S.nodes)),delete S.source,S))}function markDirtyUp(S){if(S[to]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp(b)}let oo=class Container2 extends io{append(...S){for(let b of S){let S=this.normalize(b,this.last);for(let b of S)this.proxyOf.nodes.push(b)}return this.markDirty(),this}cleanRaws(S){if(super.cleanRaws(S),this.nodes)for(let b of this.nodes)b.cleanRaws(S)}each(S){if(!this.proxyOf.nodes)return;let b,I,x=this.getIterator();for(;this.indexes[x]<this.proxyOf.nodes.length&&(b=this.indexes[x],I=S(this.proxyOf.nodes[b],b),!1!==I);)this.indexes[x]+=1;return delete this.indexes[x],I}every(S){return this.nodes.every(S)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let S=this.lastEach;return this.indexes[S]=0,S}getProxyProcessor(){return{get:(S,b)=>"proxyOf"===b?S:S[b]?"each"===b||"string"==typeof b&&b.startsWith("walk")?(...I)=>S[b](...I.map(S=>"function"==typeof S?(b,I)=>S(b.toProxy(),I):S)):"every"===b||"some"===b?I=>S[b]((S,...b)=>I(S.toProxy(),...b)):"root"===b?()=>S.root().toProxy():"nodes"===b?S.nodes.map(S=>S.toProxy()):"first"===b||"last"===b?S[b].toProxy():S[b]:S[b],set:(S,b,I)=>(S[b]===I||(S[b]=I,"name"!==b&&"params"!==b&&"selector"!==b||S.markDirty()),!0)}}index(S){return"number"==typeof S?S:(S.proxyOf&&(S=S.proxyOf),this.proxyOf.nodes.indexOf(S))}insertAfter(S,b){let I,x=this.index(S),R=this.normalize(b,this.proxyOf.nodes[x]).reverse();x=this.index(S);for(let S of R)this.proxyOf.nodes.splice(x+1,0,S);for(let S in this.indexes)I=this.indexes[S],x<I&&(this.indexes[S]=I+R.length);return this.markDirty(),this}insertBefore(S,b){let I,x=this.index(S),R=0===x&&"prepend",A=this.normalize(b,this.proxyOf.nodes[x],R).reverse();x=this.index(S);for(let S of A)this.proxyOf.nodes.splice(x,0,S);for(let S in this.indexes)I=this.indexes[S],x<=I&&(this.indexes[S]=I+A.length);return this.markDirty(),this}normalize(S,b){if("string"==typeof S)S=cleanSource(Xi(S).nodes);else if(void 0===S)S=[];else if(Array.isArray(S)){S=S.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if("root"===S.type&&"document"!==this.type){S=S.nodes.slice(0);for(let b of S)b.parent&&b.parent.removeChild(b,"ignore")}else if(S.type)S=[S];else if(S.prop){if(void 0===S.value)throw new Error("Value field is missed in node creation");"string"!=typeof S.value&&(S.value=String(S.value)),S=[new ro(S)]}else if(S.selector)S=[new Yi(S)];else if(S.name)S=[new Zi(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new no(S)]}return S.map(S=>(S[so]||Container2.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[to]&&markDirtyUp(S),void 0===S.raws.before&&b&&void 0!==b.raws.before&&(S.raws.before=b.raws.before.replace(/\S/g,"")),S.parent=this.proxyOf,S))}prepend(...S){S=S.reverse();for(let b of S){let S=this.normalize(b,this.first,"prepend").reverse();for(let b of S)this.proxyOf.nodes.unshift(b);for(let b in this.indexes)this.indexes[b]=this.indexes[b]+S.length}return this.markDirty(),this}push(S){return S.parent=this,this.proxyOf.nodes.push(S),this}removeAll(){for(let S of this.proxyOf.nodes)S.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(S){let b;S=this.index(S),this.proxyOf.nodes[S].parent=void 0,this.proxyOf.nodes.splice(S,1);for(let I in this.indexes)b=this.indexes[I],b>=S&&(this.indexes[I]=b-1);return this.markDirty(),this}replaceValues(S,b,I){return I||(I=b,b={}),this.walkDecls(x=>{b.props&&!b.props.includes(x.prop)||b.fast&&!x.value.includes(b.fast)||(x.value=x.value.replace(S,I))}),this.markDirty(),this}some(S){return this.nodes.some(S)}walk(S){return this.each((b,I)=>{let x;try{x=S(b,I)}catch(S){throw b.addToError(S)}return!1!==x&&b.walk&&(x=b.walk(S)),x})}walkAtRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("atrule"===I.type&&S.test(I.name))return b(I,x)}):this.walk((I,x)=>{if("atrule"===I.type&&I.name===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("atrule"===S.type)return b(S,I)}))}walkComments(S){return this.walk((b,I)=>{if("comment"===b.type)return S(b,I)})}walkDecls(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("decl"===I.type&&S.test(I.prop))return b(I,x)}):this.walk((I,x)=>{if("decl"===I.type&&I.prop===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("decl"===S.type)return b(S,I)}))}walkRules(S,b){return b?S instanceof RegExp?this.walk((I,x)=>{if("rule"===I.type&&S.test(I.selector))return b(I,x)}):this.walk((I,x)=>{if("rule"===I.type&&I.selector===S)return b(I,x)}):(b=S,this.walk((S,I)=>{if("rule"===S.type)return b(S,I)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};oo.registerParse=S=>{Xi=S},oo.registerRule=S=>{Yi=S},oo.registerAtRule=S=>{Zi=S},oo.registerRoot=S=>{eo=S};var ao=oo;oo.default=oo,oo.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,Zi.prototype):"rule"===S.type?Object.setPrototypeOf(S,Yi.prototype):"decl"===S.type?Object.setPrototypeOf(S,ro.prototype):"comment"===S.type?Object.setPrototypeOf(S,no.prototype):"root"===S.type&&Object.setPrototypeOf(S,eo.prototype),S[so]=!0,S.nodes&&S.nodes.forEach(S=>{oo.rebuild(S)})};let lo,co,uo=ao,ho=class Document23 extends uo{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new lo(new co,this,S).stringify()}};ho.registerLazyResult=S=>{lo=S},ho.registerProcessor=S=>{co=S};var go=ho;ho.default=ho;let po=class Warning2{constructor(S,b={}){if(this.type="warning",this.text=S,b.node&&b.node.source){let S=b.node.rangeBy(b);this.line=S.start.line,this.column=S.start.column,this.endLine=S.end.line,this.endColumn=S.end.column}for(let S in b)this[S]=b[S]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var fo=po;po.default=po;let mo=fo,yo=class Result2{constructor(S,b,I){this.processor=S,this.messages=[],this.root=b,this.opts=I,this.css=void 0,this.map=void 0}toString(){return this.css}warn(S,b={}){b.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(b.plugin=this.lastPlugin.postcssPlugin);let I=new mo(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var vo=yo;yo.default=yo;const So="'".charCodeAt(0),wo='"'.charCodeAt(0),bo="\\".charCodeAt(0),Co="/".charCodeAt(0),ko="\n".charCodeAt(0),Io=" ".charCodeAt(0),Eo="\f".charCodeAt(0),xo="\t".charCodeAt(0),Mo="\r".charCodeAt(0),Ro="[".charCodeAt(0),To="]".charCodeAt(0),Ao="(".charCodeAt(0),_o=")".charCodeAt(0),Oo="{".charCodeAt(0),Do="}".charCodeAt(0),Fo=";".charCodeAt(0),No="*".charCodeAt(0),Lo=":".charCodeAt(0),Po="@".charCodeAt(0),Bo=/[\t\n\f\r "#'()/;[\\\]{}]/g,zo=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Uo=/.[\r\n"'(/\\]/,$o=/[\da-f]/i;let jo=ao,qo=class AtRule2 extends jo{constructor(S){super(S),this.type="atrule"}append(...S){return this.proxyOf.nodes||(this.nodes=[]),super.append(...S)}prepend(...S){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...S)}};var Wo=qo;qo.default=qo,jo.registerAtRule(qo);let Ho,Vo,Qo=ao,Ko=class Root2 extends Qo{constructor(S){super(S),this.type="root",this.nodes||(this.nodes=[])}normalize(S,b,I){let x=super.normalize(S);if(b)if("prepend"===I)this.nodes.length>1?b.raws.before=this.nodes[1].raws.before:delete b.raws.before;else if(this.first!==b)for(let S of x)S.raws.before=b.raws.before;return x}removeChild(S,b){let I=this.index(S);return!b&&0===I&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[I].raws.before),super.removeChild(S)}toResult(S={}){return new Ho(new Vo,this,S).stringify()}};Ko.registerLazyResult=S=>{Ho=S},Ko.registerProcessor=S=>{Vo=S};var Go=Ko;Ko.default=Ko,Qo.registerRoot(Ko);let Jo={comma:S=>Jo.split(S,[","],!0),space:S=>Jo.split(S,[" ","\n","\t"]),split(S,b,I){let x=[],R="",A=!1,_=0,D=!1,L="",B=!1;for(let I of S)B?B=!1:"\\"===I?B=!0:D?I===L&&(D=!1):'"'===I||"'"===I?(D=!0,L=I):"("===I?_+=1:")"===I?_>0&&(_-=1):0===_&&b.includes(I)&&(A=!0),A?(""!==R&&x.push(R.trim()),R="",A=!1):R+=I;return(I||""!==R)&&x.push(R.trim()),x}};var Xo=Jo;Jo.default=Jo;let Yo=ao,Zo=Xo,ea=class Rule2 extends Yo{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Zo.comma(this.selector)}set selectors(S){let b=this.selector?this.selector.match(/,\s*/):null,I=b?b[0]:","+this.raw("between","beforeOpen");this.selector=S.join(I)}};var ta=ea;ea.default=ea,Yo.registerRule(ea);let sa=di,ra=function tokenizer2(S,b={}){let I,x,R,A,_,D,L,B,U,$,j=S.css.valueOf(),W=b.ignoreErrors,H=j.length,V=0,Q=[],G=[];function unclosed(b){throw S.error("Unclosed "+b,V)}return{back:function back(S){G.push(S)},endOfFile:function endOfFile(){return 0===G.length&&V>=H},nextToken:function nextToken(S){if(G.length)return G.pop();if(V>=H)return;let b=!!S&&S.ignoreUnclosed;switch(I=j.charCodeAt(V),I){case ko:case Io:case xo:case Mo:case Eo:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===Io||I===ko||I===xo||I===Mo||I===Eo);$=["space",j.slice(V,x)],V=x-1;break;case Ro:case To:case Oo:case Do:case Lo:case Fo:case _o:{let S=String.fromCharCode(I);$=[S,S,V];break}case Ao:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==So&&U!==wo&&U!==Io&&U!==ko&&U!==xo&&U!==Eo&&U!==Mo){x=V;do{if(D=!1,x=j.indexOf(")",x+1),-1===x){if(W||b){x=V;break}unclosed("bracket")}for(L=x;j.charCodeAt(L-1)===bo;)L-=1,D=!D}while(D);$=["brackets",j.slice(V,x+1),V,x],V=x}else x=j.indexOf(")",V+1),A=j.slice(V,x+1),-1===x||Uo.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case So:case wo:R=I===So?"'":'"',x=V;do{if(D=!1,x=j.indexOf(R,x+1),-1===x){if(W||b){x=V+1;break}unclosed("string")}for(L=x;j.charCodeAt(L-1)===bo;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Po:Bo.lastIndex=V+1,Bo.test(j),x=0===Bo.lastIndex?j.length-1:Bo.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case bo:for(x=V,_=!0;j.charCodeAt(x+1)===bo;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==Co&&I!==Io&&I!==ko&&I!==xo&&I!==Mo&&I!==Eo&&(x+=1,$o.test(j.charAt(x)))){for(;$o.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===Io&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===Co&&j.charCodeAt(V+1)===No?(x=j.indexOf("*/",V+2)+1,0===x&&(W||b?x=j.length:unclosed("comment")),$=["comment",j.slice(V,x+1),V,x],V=x):(zo.lastIndex=V+1,zo.test(j),x=0===zo.lastIndex?j.length-1:zo.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},na=Ji,ia=Wo,oa=Go,aa=ta;const la={empty:!0,space:!0};var ca=class Parser2{constructor(S){this.input=S,this.root=new oa,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:S,start:{column:1,line:1,offset:0}}}atrule(S){let b,I,x,R=new ia;R.name=S[1].slice(1),""===R.name&&this.unnamedAtrule(R,S),this.init(R,S[2]);let A=!1,_=!1,D=[],L=[];for(;!this.tokenizer.endOfFile();){if(b=(S=this.tokenizer.nextToken())[0],"("===b||"["===b?L.push("("===b?")":"]"):"{"===b&&L.length>0?L.push("}"):b===L[L.length-1]&&L.pop(),0===L.length){if(";"===b){R.source.end=this.getPosition(S[2]),R.source.end.offset++,this.semicolon=!0;break}if("{"===b){_=!0;break}if("}"===b){if(D.length>0){for(x=D.length-1,I=D[x];I&&"space"===I[0];)I=D[--x];I&&(R.source.end=this.getPosition(I[3]||I[2]),R.source.end.offset++)}this.end(S);break}D.push(S)}else D.push(S);if(this.tokenizer.endOfFile()){A=!0;break}}R.raws.between=this.spacesAndCommentsFromEnd(D),D.length?(R.raws.afterName=this.spacesAndCommentsFromStart(D),this.raw(R,"params",D),A&&(S=D[D.length-1],R.source.end=this.getPosition(S[3]||S[2]),R.source.end.offset++,this.spaces=R.raws.between,R.raws.between="")):(R.raws.afterName="",R.params=""),_&&(R.nodes=[],this.current=R)}checkMissedSemicolon(S){let b=this.colon(S);if(!1===b)return;let I,x=0;for(let R=b-1;R>=0&&(I=S[R],"space"===I[0]||(x+=1,2!==x));R--);throw this.input.error("Missed semicolon","word"===I[0]?I[3]+1:I[2])}colon(S){let b,I,x,R=0;for(let[A,_]of S.entries()){if(b=_,I=b[0],"("===I&&(R+=1),")"===I&&(R-=1),0===R&&":"===I){if(x){if("word"===x[0]&&"progid"===x[1])continue;return A}this.doubleColon(b)}x=b}return!1}comment(S){let b=new na;this.init(b,S[2]),b.source.end=this.getPosition(S[3]||S[2]),b.source.end.offset++;let I=S[1].slice(2,-2);if(/^\s*$/.test(I))b.text="",b.raws.left=I,b.raws.right="";else{let S=I.match(/^(\s*)([^]*\S)(\s*)$/);b.text=S[2],b.raws.left=S[1],b.raws.right=S[3]}}createTokenizer(){this.tokenizer=ra(this.input)}decl(S,b){let I=new sa;this.init(I,S[0][2]);let x,R=S[S.length-1];for(";"===R[0]&&(this.semicolon=!0,S.pop()),I.source.end=this.getPosition(R[3]||R[2]||function findLastWithPosition(S){for(let b=S.length-1;b>=0;b--){let I=S[b],x=I[3]||I[2];if(x)return x}}(S)),I.source.end.offset++;"word"!==S[0][0];)1===S.length&&this.unknownWord(S),I.raws.before+=S.shift()[1];for(I.source.start=this.getPosition(S[0][2]),I.prop="";S.length;){let b=S[0][0];if(":"===b||"space"===b||"comment"===b)break;I.prop+=S.shift()[1]}for(I.raws.between="";S.length;){if(x=S.shift(),":"===x[0]){I.raws.between+=x[1];break}"word"===x[0]&&/\w/.test(x[1])&&this.unknownWord([x]),I.raws.between+=x[1]}"_"!==I.prop[0]&&"*"!==I.prop[0]||(I.raws.before+=I.prop[0],I.prop=I.prop.slice(1));let A,_=[];for(;S.length&&(A=S[0][0],"space"===A||"comment"===A);)_.push(S.shift());this.precheckMissedSemicolon(S);for(let b=S.length-1;b>=0;b--){if(x=S[b],"!important"===x[1].toLowerCase()){I.important=!0;let x=this.stringFrom(S,b);x=this.spacesFromEnd(S)+x," !important"!==x&&(I.raws.important=x);break}if("important"===x[1].toLowerCase()){let x=S.slice(0),R="";for(let S=b;S>0;S--){let b=x[S][0];if(0===R.trim().indexOf("!")&&"space"!==b)break;R=x.pop()[1]+R}0===R.trim().indexOf("!")&&(I.important=!0,I.raws.important=R,S=x)}if("space"!==x[0]&&"comment"!==x[0])break}S.some(S=>"space"!==S[0]&&"comment"!==S[0])&&(I.raws.between+=_.map(S=>S[1]).join(""),_=[]),this.raw(I,"value",_.concat(S),b),I.value.includes(":")&&!b&&this.checkMissedSemicolon(S)}doubleColon(S){throw this.input.error("Double colon",{offset:S[2]},{offset:S[2]+S[1].length})}emptyRule(S){let b=new aa;this.init(b,S[2]),b.selector="",b.raws.between="",this.current=b}end(S){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(S[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(S)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(S){if(this.spaces+=S[1],this.current.nodes){let S=this.current.nodes[this.current.nodes.length-1];S&&"rule"===S.type&&!S.raws.ownSemicolon&&(S.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(S){let b=this.input.fromOffset(S);return{column:b.col,line:b.line,offset:S}}init(S,b){this.current.push(S),S.source={input:this.input,start:this.getPosition(b)},S.raws.before=this.spaces,this.spaces="","comment"!==S.type&&(this.semicolon=!1)}other(S){let b=!1,I=null,x=!1,R=null,A=[],_=S[1].startsWith("--"),D=[],L=S;for(;L;){if(I=L[0],D.push(L),"("===I||"["===I)R||(R=L),A.push("("===I?")":"]");else if(_&&x&&"{"===I)R||(R=L),A.push("}");else if(0===A.length){if(";"===I){if(x)return void this.decl(D,_);break}if("{"===I)return void this.rule(D);if("}"===I){this.tokenizer.back(D.pop()),b=!0;break}":"===I&&(x=!0)}else I===A[A.length-1]&&(A.pop(),0===A.length&&(R=null));L=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(b=!0),A.length>0&&this.unclosedBracket(R),b&&x){if(!_)for(;D.length&&(L=D[D.length-1][0],"space"===L||"comment"===L);)this.tokenizer.back(D.pop());this.decl(D,_)}else this.unknownWord(D)}parse(){let S;for(;!this.tokenizer.endOfFile();)switch(S=this.tokenizer.nextToken(),S[0]){case"space":this.spaces+=S[1];break;case";":this.freeSemicolon(S);break;case"}":this.end(S);break;case"comment":this.comment(S);break;case"at-word":this.atrule(S);break;case"{":this.emptyRule(S);break;default:this.other(S)}this.endFile()}precheckMissedSemicolon(){}raw(S,b,I,x){let R,A,_,D,L=I.length,B="",U=!0;for(let S=0;S<L;S+=1)R=I[S],A=R[0],"space"!==A||S!==L-1||x?"comment"===A?(D=I[S-1]?I[S-1][0]:"empty",_=I[S+1]?I[S+1][0]:"empty",la[D]||la[_]||","===B.slice(-1)?U=!1:B+=R[1]):B+=R[1]:U=!1;if(!U){let x=I.reduce((S,b)=>S+b[1],"");S.raws[b]={raw:x,value:B}}S[b]=B}rule(S){S.pop();let b=new aa;this.init(b,S[0][2]),b.raws.between=this.spacesAndCommentsFromEnd(S),this.raw(b,"selector",S),this.current=b}spacesAndCommentsFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b||"comment"===b);)I=S.pop()[1]+I;return I}spacesAndCommentsFromStart(S){let b,I="";for(;S.length&&(b=S[0][0],"space"===b||"comment"===b);)I+=S.shift()[1];return I}spacesFromEnd(S){let b,I="";for(;S.length&&(b=S[S.length-1][0],"space"===b);)I=S.pop()[1]+I;return I}stringFrom(S,b){let I="";for(let x=b;x<S.length;x++)I+=S[x][1];return S.splice(b,S.length-b),I}unclosedBlock(){let S=this.current.source.start;throw this.input.error("Unclosed block",S.line,S.column)}unclosedBracket(S){throw this.input.error("Unclosed bracket",{offset:S[2]},{offset:S[2]+1})}unexpectedClose(S){throw this.input.error("Unexpected }",{offset:S[2]},{offset:S[2]+1})}unknownWord(S){throw this.input.error("Unknown word",{offset:S[0][2]},{offset:S[0][2]+S[0][1].length})}unnamedAtrule(S,b){throw this.input.error("At-rule without name",{offset:b[2]},{offset:b[2]+b[1].length})}};let ua=ao,ha=ca,da=Li;function parse$3(S,b){let I=new da(S,b),x=new ha(I);try{x.parse()}catch(S){throw S}return x.root}var ga=parse$3;parse$3.default=parse$3,ua.registerParse(parse$3);let{isClean:pa,my:fa}=Xn,ma=Qi,ya=si,va=ao,Sa=go,wa=vo,ba=ga,Ca=Go;const ka={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},Ia={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Ea={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents(S){let b=!1,I=ka[S.type];return"decl"===S.type?b=S.prop.toLowerCase():"atrule"===S.type&&(b=S.name.toLowerCase()),b&&S.append?[I,I+"-"+b,0,I+"Exit",I+"Exit-"+b]:b?[I,I+"-"+b,I+"Exit",I+"Exit-"+b]:S.append?[I,0,I+"Exit"]:[I,I+"Exit"]}function toStack(S){let b;return b="document"===S.type?["Document",0,"DocumentExit"]:"root"===S.type?["Root",0,"RootExit"]:getEvents(S),{eventIndex:0,events:b,iterator:0,node:S,visitorIndex:0,visitors:[]}}function cleanMarks(S){return S[pa]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks(S)),S}let xa={},Ma=class LazyResult2{constructor(S,b,I){let x;if(this.stringified=!1,this.processed=!1,"object"!=typeof b||null===b||"root"!==b.type&&"document"!==b.type)if(b instanceof LazyResult2||b instanceof wa)x=cleanMarks(b.root),b.map&&(void 0===I.map&&(I.map={}),I.map.inline||(I.map.inline=!1),I.map.prev=b.map);else{let S=ba;I.syntax&&(S=I.syntax.parse),I.parser&&(S=I.parser),S.parse&&(S=S.parse);try{x=S(b,I)}catch(S){this.processed=!0,this.error=S}x&&!x[fa]&&va.rebuild(x)}else x=cleanMarks(b);this.result=new wa(S,x,I),this.helpers={...xa,postcss:xa,result:this.result},this.plugins=this.processor.plugins.map(S=>"object"==typeof S&&S.prepare?{...S,...S.prepare(this.result)}:S)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(S,b){let I=this.result.lastPlugin;try{b&&b.addToError(S),this.error=S,"CssSyntaxError"!==S.name||S.plugin||(S.plugin=I.postcssPlugin,S.setMessage())}catch(S){console&&console.error&&console.error(S)}return S}prepareVisitors(){this.listeners={};let add=(S,b,I)=>{this.listeners[b]||(this.listeners[b]=[]),this.listeners[b].push([S,I])};for(let S of this.plugins)if("object"==typeof S)for(let b in S){if(!Ia[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Ea[b])if("object"==typeof S[b])for(let I in S[b])add(S,"*"===I?b:b+"-"+I.toLowerCase(),S[b][I]);else"function"==typeof S[b]&&add(S,b,S[b])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let S=0;S<this.plugins.length;S++){let b=this.plugins[S],I=this.runOnRoot(b);if(isPromise(I))try{await I}catch(S){throw this.handleError(S)}}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[pa];){S[pa]=!0;let b=[toStack(S)];for(;b.length>0;){let S=this.visitTick(b);if(isPromise(S))try{await S}catch(S){let I=b[b.length-1].node;throw this.handleError(S,I)}}}if(this.listeners.OnceExit)for(let[b,I]of this.listeners.OnceExit){this.result.lastPlugin=b;try{if("document"===S.type){let b=S.nodes.map(S=>I(S,this.helpers));await Promise.all(b)}else await I(S,this.helpers)}catch(S){throw this.handleError(S)}}}return this.processed=!0,this.stringify()}runOnRoot(S){this.result.lastPlugin=S;try{if("object"==typeof S&&S.Once){if("document"===this.result.root.type){let b=this.result.root.nodes.map(b=>S.Once(b,this.helpers));return isPromise(b[0])?Promise.all(b):b}return S.Once(this.result.root,this.helpers)}if("function"==typeof S)return S(this.result.root,this.result)}catch(S){throw this.handleError(S)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let S=this.result.opts,b=ya;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new ma(b,this.result.root,this.result.opts).generate();return this.result.css=I[0],this.result.map=I[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let S of this.plugins){if(isPromise(this.runOnRoot(S)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let S=this.result.root;for(;!S[pa];)S[pa]=!0,this.walkSync(S);if(this.listeners.OnceExit)if("document"===S.type)for(let b of S.nodes)this.visitSync(this.listeners.OnceExit,b);else this.visitSync(this.listeners.OnceExit,S)}return this.result}then(S,b){return this.async().then(S,b)}toString(){return this.css}visitSync(S,b){for(let[I,x]of S){let S;this.result.lastPlugin=I;try{S=x(b,this.helpers)}catch(S){throw this.handleError(S,b.proxyOf)}if("root"!==b.type&&"document"!==b.type&&!b.parent)return!0;if(isPromise(S))throw this.getAsyncError()}}visitTick(S){let b=S[S.length-1],{node:I,visitors:x}=b;if("root"!==I.type&&"document"!==I.type&&!I.parent)return void S.pop();if(x.length>0&&b.visitorIndex<x.length){let[S,R]=x[b.visitorIndex];b.visitorIndex+=1,b.visitorIndex===x.length&&(b.visitors=[],b.visitorIndex=0),this.result.lastPlugin=S;try{return R(I.toProxy(),this.helpers)}catch(S){throw this.handleError(S,I)}}if(0!==b.iterator){let x,R=b.iterator;for(;x=I.nodes[I.indexes[R]];)if(I.indexes[R]+=1,!x[pa])return x[pa]=!0,void S.push(toStack(x));b.iterator=0,delete I.indexes[R]}let R=b.events;for(;b.eventIndex<R.length;){let S=R[b.eventIndex];if(b.eventIndex+=1,0===S)return void(I.nodes&&I.nodes.length&&(I[pa]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[pa]=!0;let b=getEvents(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[pa]||this.walkSync(S)});else{let b=this.listeners[I];if(b&&this.visitSync(b,S.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Ma.registerPostcss=S=>{xa=S};var Ra=Ma;Ma.default=Ma,Ca.registerLazyResult(Ma),Sa.registerLazyResult(Ma);let Ta=Qi,Aa=si,_a=ga;const Oa=vo;let Da=class NoWorkResult2{constructor(S,b,I){let x;b=b.toString(),this.stringified=!1,this._processor=S,this._css=b,this._opts=I,this._map=void 0;let R=Aa;this.result=new Oa(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new Ta(R,x,this._opts,b);if(_.isMap()){let[S,b]=_.generate();S&&(this.result.css=S),b&&(this.result.map=b)}else _.clearAnnotation(),this.result.css=_.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(S){return this.async().catch(S)}finally(S){return this.async().then(S,S)}sync(){if(this.error)throw this.error;return this.result}then(S,b){return this.async().then(S,b)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let S,b=_a;try{S=b(this._css,this._opts)}catch(S){this.error=S}if(this.error)throw this.error;return this._root=S,S}get[Symbol.toStringTag](){return"NoWorkResult"}};var Fa=Da;Da.default=Da;let Na=Fa,La=Ra,Pa=go,Ba=Go,za=class Processor2{constructor(S=[]){this.version="8.4.38",this.plugins=this.normalize(S)}normalize(S){let b=[];for(let I of S)if(!0===I.postcss?I=I():I.postcss&&(I=I.postcss),"object"==typeof I&&Array.isArray(I.plugins))b=b.concat(I.plugins);else if("object"==typeof I&&I.postcssPlugin)b.push(I);else if("function"==typeof I)b.push(I);else if("object"!=typeof I||!I.parse&&!I.stringify)throw new Error(I+" is not a PostCSS plugin");return b}process(S,b={}){return this.plugins.length||b.parser||b.stringifier||b.syntax?new La(this,S,b):new Na(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var Ua=za;za.default=za,Ba.registerProcessor(za),Pa.registerProcessor(za);let $a=di,ja=bi,qa=Ji,Wa=Wo,Ha=Li,Va=Go,Qa=ta;function fromJSON$1(S,b){if(Array.isArray(S))return S.map(S=>fromJSON$1(S));let{inputs:I,...x}=S;if(I){b=[];for(let S of I){let I={...S,__proto__:Ha.prototype};I.map&&(I.map={...I.map,__proto__:ja.prototype}),b.push(I)}}if(x.nodes&&(x.nodes=S.nodes.map(S=>fromJSON$1(S,b))),x.source){let{inputId:S,...I}=x.source;x.source=I,null!=S&&(x.source.input=b[S])}if("root"===x.type)return new Va(x);if("decl"===x.type)return new $a(x);if("rule"===x.type)return new Qa(x);if("comment"===x.type)return new qa(x);if("atrule"===x.type)return new Wa(x);throw new Error("Unknown node type: "+S.type)}var Ka=fromJSON$1;fromJSON$1.default=fromJSON$1;let Ga=Jn,Ja=di,Xa=Ra,Ya=ao,Za=Ua,el=si,tl=Ka,sl=go,rl=fo,nl=Ji,il=Wo,ol=vo,al=Li,ll=ga,cl=Xo,ul=ta,hl=Go,dl=ci;function postcss(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new Za(S)}postcss.plugin=function plugin2(S,b){let I,x=!1;function creator(...I){console&&console.warn&&!x&&(x=!0,console.warn(S+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"));let R=b(...I);return R.postcssPlugin=S,R.postcssVersion=(new Za).version,R}return Object.defineProperty(creator,"postcss",{get:()=>(I||(I=creator()),I)}),creator.process=function(S,b,I){return postcss([creator(I)]).process(S,b)},creator},postcss.stringify=el,postcss.parse=ll,postcss.fromJSON=tl,postcss.list=cl,postcss.comment=S=>new nl(S),postcss.atRule=S=>new il(S),postcss.decl=S=>new Ja(S),postcss.rule=S=>new ul(S),postcss.root=S=>new hl(S),postcss.document=S=>new sl(S),postcss.CssSyntaxError=Ga,postcss.Declaration=Ja,postcss.Container=Ya,postcss.Processor=Za,postcss.Document=sl,postcss.Comment=nl,postcss.Warning=rl,postcss.AtRule=il,postcss.Result=ol,postcss.Input=al,postcss.Rule=ul,postcss.Root=hl,postcss.Node=dl,Xa.registerPostcss(postcss),postcss.default=postcss;class BaseRRNode{constructor(...S){__publicField2(this,"parentElement",null),__publicField2(this,"parentNode",null),__publicField2(this,"ownerDocument"),__publicField2(this,"firstChild",null),__publicField2(this,"lastChild",null),__publicField2(this,"previousSibling",null),__publicField2(this,"nextSibling",null),__publicField2(this,"ELEMENT_NODE",1),__publicField2(this,"TEXT_NODE",3),__publicField2(this,"nodeType"),__publicField2(this,"nodeName"),__publicField2(this,"RRNodeType")}get childNodes(){const S=[];let b=this.firstChild;for(;b;)S.push(b),b=b.nextSibling;return S}contains(S){if(!(S instanceof BaseRRNode))return!1;if(S.ownerDocument!==this.ownerDocument)return!1;if(S===this)return!0;for(;S.parentNode;){if(S.parentNode===this)return!0;S=S.parentNode}return!1}appendChild(S){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(S,b){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(S){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}}const gl={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},pl={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},fl={};function getUntaintedPrototype(S){if(fl[S])return fl[S];const b=globalThis[S],I=b.prototype,x=S in gl?gl[S]:void 0,R=Boolean(x&&x.every(S=>{var b,x;return Boolean(null==(x=null==(b=Object.getOwnPropertyDescriptor(I,S))?void 0:b.get)?void 0:x.toString().includes("[native code]"))})),A=S in pl?pl[S]:void 0,_=Boolean(A&&A.every(S=>{var b;return"function"==typeof I[S]&&(null==(b=I[S])?void 0:b.toString().includes("[native code]"))}));if(R&&_&&!globalThis.Zone)return fl[S]=b.prototype,b.prototype;try{const x=document.createElement("iframe");document.body.appendChild(x);const R=x.contentWindow;if(!R)return b.prototype;const A=R[S].prototype;return document.body.removeChild(x),A?fl[S]=A:I}catch{return I}}const ml={};function getUntaintedAccessor(S,b,I){var x;const R=`${S}.${String(I)}`;if(ml[R])return ml[R].call(b);const A=getUntaintedPrototype(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(ml[R]=_,_.call(b)):b[I]}const yl={};function getUntaintedMethod(S,b,I){const x=`${S}.${String(I)}`;if(yl[x])return yl[x].bind(b);const R=getUntaintedPrototype(S)[I];return"function"!=typeof R?b[I]:(yl[x]=R,R.bind(b))}function mutationObserverCtor(){return getUntaintedPrototype("MutationObserver").constructor}const vl={childNodes:function childNodes(S){return getUntaintedAccessor("Node",S,"childNodes")},parentNode:function parentNode(S){return getUntaintedAccessor("Node",S,"parentNode")},parentElement:function parentElement(S){return getUntaintedAccessor("Node",S,"parentElement")},textContent:function textContent(S){return getUntaintedAccessor("Node",S,"textContent")},contains:function contains(S,b){return getUntaintedMethod("Node",S,"contains")(b)},getRootNode:function getRootNode(S){return getUntaintedMethod("Node",S,"getRootNode")()},host:function host(S){return S&&"host"in S?getUntaintedAccessor("ShadowRoot",S,"host"):null},styleSheets:function styleSheets(S){return S.styleSheets},shadowRoot:function shadowRoot(S){return S&&"shadowRoot"in S?getUntaintedAccessor("Element",S,"shadowRoot"):null},querySelector:function querySelector(S,b){return getUntaintedAccessor("Element",S,"querySelector")(b)},querySelectorAll:function querySelectorAll(S,b){return getUntaintedAccessor("Element",S,"querySelectorAll")(b)},mutationObserver:mutationObserverCtor};function on(S,b,I=document){const x={capture:!0,passive:!0};return I.addEventListener(S,b,x),()=>I.removeEventListener(S,b,x)}const Sl="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 wl={map:{},getId:()=>(console.error(Sl),-1),getNode:()=>(console.error(Sl),null),removeNodeFromMap(){console.error(Sl)},has:()=>(console.error(Sl),!1),reset(){console.error(Sl)}};function throttle(S,b,I={}){let x=null,R=0;return function(...A){const _=Date.now();R||!1!==I.leading||(R=_);const D=b-(_-R),L=this;D<=0||D>b?(x&&(clearTimeout(x),x=null),R=_,S.apply(L,A)):x||!1===I.trailing||(x=setTimeout(()=>{R=!1===I.leading?0:Date.now(),x=null,S.apply(L,A)},D))}}function hookSetter(S,b,I,x,R=window){const A=R.Object.getOwnPropertyDescriptor(S,b);return R.Object.defineProperty(S,b,x?I:{set(S){setTimeout(()=>{I.set.call(this,S)},0),A&&A.set&&A.set.call(this,S)}}),()=>hookSetter(S,b,A||{},!0)}function patch(S,b,I){try{if(!(b in S))return()=>{};const x=S[b],R=I(x);return"function"==typeof R&&(R.prototype=R.prototype||{},Object.defineProperties(R,{__rrweb_original__:{enumerable:!1,value:x}})),S[b]=R,()=>{S[b]=x}}catch{return()=>{}}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(wl=new Proxy(wl,{get:(S,b,I)=>("map"===b&&console.error(Sl),Reflect.get(S,b,I))}));let bl=Date.now;function getWindowScroll(S){var b,I,x,R;const A=S.document;return{left:A.scrollingElement?A.scrollingElement.scrollLeft:void 0!==S.pageXOffset?S.pageXOffset:A.documentElement.scrollLeft||(null==A?void 0:A.body)&&(null==(b=vl.parentElement(A.body))?void 0:b.scrollLeft)||(null==(I=null==A?void 0:A.body)?void 0:I.scrollLeft)||0,top:A.scrollingElement?A.scrollingElement.scrollTop:void 0!==S.pageYOffset?S.pageYOffset:(null==A?void 0:A.documentElement.scrollTop)||(null==A?void 0:A.body)&&(null==(x=vl.parentElement(A.body))?void 0:x.scrollTop)||(null==(R=null==A?void 0:A.body)?void 0:R.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(S){if(!S)return null;return S.nodeType===S.ELEMENT_NODE?S:vl.parentElement(S)}function isBlocked(S,b,I,x){if(!S)return!1;const R=closestElementOfNode(S);if(!R)return!1;try{if("string"==typeof b){if(R.classList.contains(b))return!0;if(x&&null!==R.closest("."+b))return!0}else if(classMatchesRegex(R,b,x))return!0}catch(S){}if(I){if(R.matches(I))return!0;if(x&&null!==R.closest(I))return!0}return!1}function isIgnored(S,b,I){return!("TITLE"!==S.tagName||!I.headTitleMutations)||-2===b.getId(S)}function isAncestorRemoved(S,b){if(isShadowRoot(S))return!1;const I=b.getId(S);if(!b.has(I))return!0;const x=vl.parentNode(S);return(!x||x.nodeType!==S.DOCUMENT_NODE)&&(!x||isAncestorRemoved(x,b))}function legacy_isTouchEvent(S){return Boolean(S.changedTouches)}function isSerializedIframe(S,b){return Boolean("IFRAME"===S.nodeName&&b.getMeta(S))}function isSerializedStylesheet(S,b){return Boolean("LINK"===S.nodeName&&S.nodeType===S.ELEMENT_NODE&&S.getAttribute&&"stylesheet"===S.getAttribute("rel")&&b.getMeta(S))}function hasShadowRoot(S){return!!S&&(S instanceof BaseRRNode&&"shadowRoot"in S?Boolean(S.shadowRoot):Boolean(vl.shadowRoot(S)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(bl=()=>(new Date).getTime());class StyleSheetMirror{constructor(){__publicField(this,"id",1),__publicField(this,"styleIDMap",new WeakMap),__publicField(this,"idStyleMap",new Map)}getId(S){return this.styleIDMap.get(S)??-1}has(S){return this.styleIDMap.has(S)}add(S,b){if(this.has(S))return this.getId(S);let I;return I=void 0===b?this.id++:b,this.styleIDMap.set(S,I),this.idStyleMap.set(I,S),I}getStyle(S){return this.idStyleMap.get(S)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function getShadowHost(S){var b;let I=null;return"getRootNode"in S&&(null==(b=vl.getRootNode(S))?void 0:b.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&vl.host(vl.getRootNode(S))&&(I=vl.host(vl.getRootNode(S))),I}function shadowHostInDom(S){const b=S.ownerDocument;if(!b)return!1;const I=function getRootShadowHost(S){let b,I=S;for(;b=getShadowHost(I);)I=b;return I}(S);return vl.contains(b,I)}function inDom(S){const b=S.ownerDocument;return!!b&&(vl.contains(b,S)||shadowHostInDom(S))}var Cl=(S=>(S[S.DomContentLoaded=0]="DomContentLoaded",S[S.Load=1]="Load",S[S.FullSnapshot=2]="FullSnapshot",S[S.IncrementalSnapshot=3]="IncrementalSnapshot",S[S.Meta=4]="Meta",S[S.Custom=5]="Custom",S[S.Plugin=6]="Plugin",S))(Cl||{}),kl=(S=>(S[S.Mutation=0]="Mutation",S[S.MouseMove=1]="MouseMove",S[S.MouseInteraction=2]="MouseInteraction",S[S.Scroll=3]="Scroll",S[S.ViewportResize=4]="ViewportResize",S[S.Input=5]="Input",S[S.TouchMove=6]="TouchMove",S[S.MediaInteraction=7]="MediaInteraction",S[S.StyleSheetRule=8]="StyleSheetRule",S[S.CanvasMutation=9]="CanvasMutation",S[S.Font=10]="Font",S[S.Log=11]="Log",S[S.Drag=12]="Drag",S[S.StyleDeclaration=13]="StyleDeclaration",S[S.Selection=14]="Selection",S[S.AdoptedStyleSheet=15]="AdoptedStyleSheet",S[S.CustomElement=16]="CustomElement",S))(kl||{}),Il=(S=>(S[S.MouseUp=0]="MouseUp",S[S.MouseDown=1]="MouseDown",S[S.Click=2]="Click",S[S.ContextMenu=3]="ContextMenu",S[S.DblClick=4]="DblClick",S[S.Focus=5]="Focus",S[S.Blur=6]="Blur",S[S.TouchStart=7]="TouchStart",S[S.TouchMove_Departed=8]="TouchMove_Departed",S[S.TouchEnd=9]="TouchEnd",S[S.TouchCancel=10]="TouchCancel",S))(Il||{}),El=(S=>(S[S.Mouse=0]="Mouse",S[S.Pen=1]="Pen",S[S.Touch=2]="Touch",S))(El||{}),xl=(S=>(S[S["2D"]=0]="2D",S[S.WebGL=1]="WebGL",S[S.WebGL2=2]="WebGL2",S))(xl||{}),Ml=(S=>(S[S.Play=0]="Play",S[S.Pause=1]="Pause",S[S.Seeked=2]="Seeked",S[S.VolumeChange=3]="VolumeChange",S[S.RateChange=4]="RateChange",S))(Ml||{}),Rl=(S=>(S[S.Document=0]="Document",S[S.DocumentType=1]="DocumentType",S[S.Element=2]="Element",S[S.Text=3]="Text",S[S.CDATA=4]="CDATA",S[S.Comment=5]="Comment",S))(Rl||{});function isNodeInLinkedList(S){return"__ln"in S}class DoubleLinkedList{constructor(){__publicField(this,"length",0),__publicField(this,"head",null),__publicField(this,"tail",null)}get(S){if(S>=this.length)throw new Error("Position outside of list range");let b=this.head;for(let I=0;I<S;I++)b=(null==b?void 0:b.next)||null;return b}addNode(S){const b={value:S,previous:null,next:null};if(S.__ln=b,S.previousSibling&&isNodeInLinkedList(S.previousSibling)){const I=S.previousSibling.__ln.next;b.next=I,b.previous=S.previousSibling.__ln,S.previousSibling.__ln.next=b,I&&(I.previous=b)}else if(S.nextSibling&&isNodeInLinkedList(S.nextSibling)&&S.nextSibling.__ln.previous){const I=S.nextSibling.__ln.previous;b.previous=I,b.next=S.nextSibling.__ln,S.nextSibling.__ln.previous=b,I&&(I.next=b)}else this.head&&(this.head.previous=b),b.next=this.head,this.head=b;null===b.next&&(this.tail=b),this.length++}removeNode(S){const b=S.__ln;this.head&&(b.previous?(b.previous.next=b.next,b.next?b.next.previous=b.previous:this.tail=b.previous):(this.head=b.next,this.head?this.head.previous=null:this.tail=null),S.__ln&&delete S.__ln,this.length--)}}const moveKey=(S,b)=>`${S}@${b}`;class MutationBuffer{constructor(){__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"texts",[]),__publicField(this,"attributes",[]),__publicField(this,"attributeMap",new WeakMap),__publicField(this,"removes",[]),__publicField(this,"mapRemoves",[]),__publicField(this,"movedMap",{}),__publicField(this,"addedSet",new Set),__publicField(this,"movedSet",new Set),__publicField(this,"droppedSet",new Set),__publicField(this,"removesSubTreeCache",new Set),__publicField(this,"mutationCb"),__publicField(this,"blockClass"),__publicField(this,"blockSelector"),__publicField(this,"maskTextClass"),__publicField(this,"maskTextSelector"),__publicField(this,"inlineStylesheet"),__publicField(this,"maskInputOptions"),__publicField(this,"maskTextFn"),__publicField(this,"maskInputFn"),__publicField(this,"keepIframeSrcFn"),__publicField(this,"recordCanvas"),__publicField(this,"inlineImages"),__publicField(this,"slimDOMOptions"),__publicField(this,"dataURLOptions"),__publicField(this,"doc"),__publicField(this,"mirror"),__publicField(this,"iframeManager"),__publicField(this,"stylesheetManager"),__publicField(this,"shadowDomManager"),__publicField(this,"canvasManager"),__publicField(this,"processedNodeManager"),__publicField(this,"unattachedDoc"),__publicField(this,"processMutations",S=>{S.forEach(this.processMutation),this.emit()}),__publicField(this,"emit",()=>{if(this.frozen||this.locked)return;const S=[],b=new Set,I=new DoubleLinkedList,getNextId=S=>{let b=S,I=-2;for(;-2===I;)b=b&&b.nextSibling,I=b&&this.mirror.getId(b);return I},pushAdd=x=>{const R=vl.parentNode(x);if(!R||!inDom(x))return;let A=!1;if(x.nodeType===Node.TEXT_NODE){const S=R.tagName;if("TEXTAREA"===S)return;"STYLE"===S&&this.addedSet.has(R)&&(A=!0)}const _=isShadowRoot(R)?this.mirror.getId(getShadowHost(x)):this.mirror.getId(R),D=getNextId(x);if(-1===_||-1===D)return I.addNode(x);const L=serializeNodeWithId(x,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:S=>{isSerializedIframe(S,this.mirror)&&this.iframeManager.addIframe(S),isSerializedStylesheet(S,this.mirror)&&this.stylesheetManager.trackLinkElement(S),hasShadowRoot(x)&&this.shadowDomManager.addShadowRoot(vl.shadowRoot(x),this.doc)},onIframeLoad:(S,b)=>{this.iframeManager.attachIframe(S,b),this.shadowDomManager.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{this.stylesheetManager.attachLinkElement(S,b)},cssCaptured:A});L&&(S.push({parentId:_,nextId:D,node:L}),b.add(L.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const S of this.movedSet)isParentRemoved(this.removesSubTreeCache,S)&&!this.movedSet.has(vl.parentNode(S))||pushAdd(S);for(const S of this.addedSet)isAncestorInSet(this.droppedSet,S)||isParentRemoved(this.removesSubTreeCache,S)?isAncestorInSet(this.movedSet,S)?pushAdd(S):this.droppedSet.add(S):pushAdd(S);let x=null;for(;I.length;){let S=null;if(x){const b=this.mirror.getId(vl.parentNode(x.value)),I=getNextId(x.value);-1!==b&&-1!==I&&(S=x)}if(!S){let b=I.tail;for(;b;){const I=b;if(b=b.previous,I){const b=this.mirror.getId(vl.parentNode(I.value));if(-1===getNextId(I.value))continue;if(-1!==b){S=I;break}{const b=I.value,x=vl.parentNode(b);if(x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const b=vl.host(x);if(-1!==this.mirror.getId(b)){S=I;break}}}}}}if(!S){for(;I.head;)I.removeNode(I.head.value);break}x=S.previous,I.removeNode(S.value),pushAdd(S.value)}const R={texts:this.texts.map(S=>{const b=S.node,I=vl.parentNode(b);return I&&"TEXTAREA"===I.tagName&&this.genTextAreaValueMutation(I),{id:this.mirror.getId(b),value:S.value}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),attributes:this.attributes.map(S=>{const{attributes:b}=S;if("string"==typeof b.style){const I=JSON.stringify(S.styleDiff),x=JSON.stringify(S._unchangedStyles);I.length<b.style.length&&(I+x).split("var(").length===b.style.split("var(").length&&(b.style=S.styleDiff)}return{id:this.mirror.getId(S.node),attributes:b}}).filter(S=>!b.has(S.id)).filter(S=>this.mirror.has(S.id)),removes:this.removes,adds:S};(R.texts.length||R.attributes.length||R.removes.length||R.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.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(R))}),__publicField(this,"genTextAreaValueMutation",S=>{let b=this.attributeMap.get(S);b||(b={node:S,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(b),this.attributeMap.set(S,b)),b.attributes.value=Array.from(vl.childNodes(S),S=>vl.textContent(S)||"").join("")}),__publicField(this,"processMutation",S=>{if(!isIgnored(S.target,this.mirror,this.slimDOMOptions))switch(S.type){case"characterData":{const b=vl.textContent(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||b===S.oldValue||this.texts.push({value:needMaskingText(S.target,this.maskTextClass,this.maskTextSelector,!0)&&b?this.maskTextFn?this.maskTextFn(b,closestElementOfNode(S.target)):b.replace(/[\S]/g,"*"):b,node:S.target});break}case"attributes":{const b=S.target;let I=S.attributeName,x=S.target.getAttribute(I);if("value"===I){const S=getInputType(b);x=maskInputValue({element:b,maskInputOptions:this.maskInputOptions,tagName:b.tagName,type:S,value:x,maskInputFn:this.maskInputFn})}if(isBlocked(S.target,this.blockClass,this.blockSelector,!1)||x===S.oldValue)return;let R=this.attributeMap.get(S.target);if("IFRAME"===b.tagName&&"src"===I&&!this.keepIframeSrcFn(x)){if(b.contentDocument)return;I="rr_src"}if(R||(R={node:S.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(R),this.attributeMap.set(S.target,R)),"type"===I&&"INPUT"===b.tagName&&"password"===(S.oldValue||"").toLowerCase()&&b.setAttribute("data-rr-is-password","true"),!ignoreAttribute(b.tagName,I))if(R.attributes[I]=transformAttribute(this.doc,toLowerCase(b.tagName),toLowerCase(I),x),"style"===I){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(S){this.unattachedDoc=this.doc}const I=this.unattachedDoc.createElement("span");S.oldValue&&I.setAttribute("style",S.oldValue);for(const S of Array.from(b.style)){const x=b.style.getPropertyValue(S),A=b.style.getPropertyPriority(S);x!==I.style.getPropertyValue(S)||A!==I.style.getPropertyPriority(S)?R.styleDiff[S]=""===A?x:[x,A]:R._unchangedStyles[S]=[x,A]}for(const S of Array.from(I.style))""===b.style.getPropertyValue(S)&&(R.styleDiff[S]=!1)}else"open"===I&&"DIALOG"===b.tagName&&(b.matches("dialog:modal")?R.attributes.rr_open_mode="modal":R.attributes.rr_open_mode="non-modal");break}case"childList":if(isBlocked(S.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===S.target.tagName)return void this.genTextAreaValueMutation(S.target);S.addedNodes.forEach(b=>this.genAdds(b,S.target)),S.removedNodes.forEach(b=>{const I=this.mirror.getId(b),x=isShadowRoot(S.target)?this.mirror.getId(vl.host(S.target)):this.mirror.getId(S.target);isBlocked(S.target,this.blockClass,this.blockSelector,!1)||isIgnored(b,this.mirror,this.slimDOMOptions)||!function isSerialized(S,b){return-1!==b.getId(S)}(b,this.mirror)||(this.addedSet.has(b)?(deepDelete(this.addedSet,b),this.droppedSet.add(b)):this.addedSet.has(S.target)&&-1===I||isAncestorRemoved(S.target,this.mirror)||(this.movedSet.has(b)&&this.movedMap[moveKey(I,x)]?deepDelete(this.movedSet,b):(this.removes.push({parentId:x,id:I,isShadow:!(!isShadowRoot(S.target)||!isNativeShadowDom(S.target))||void 0}),function processRemoves(S,b){const I=[S];for(;I.length;){const S=I.pop();b.has(S)||(b.add(S),vl.childNodes(S).forEach(S=>I.push(S)))}return}(b,this.removesSubTreeCache))),this.mapRemoves.push(b))})}}),__publicField(this,"genAdds",(S,b)=>{if(!this.processedNodeManager.inOtherBuffer(S,this)&&!this.addedSet.has(S)&&!this.movedSet.has(S)){if(this.mirror.hasNode(S)){if(isIgnored(S,this.mirror,this.slimDOMOptions))return;this.movedSet.add(S);let I=null;b&&this.mirror.hasNode(b)&&(I=this.mirror.getId(b)),I&&-1!==I&&(this.movedMap[moveKey(this.mirror.getId(S),I)]=!0)}else this.addedSet.add(S),this.droppedSet.delete(S);isBlocked(S,this.blockClass,this.blockSelector,!1)||(vl.childNodes(S).forEach(S=>this.genAdds(S)),hasShadowRoot(S)&&vl.childNodes(vl.shadowRoot(S)).forEach(b=>{this.processedNodeManager.add(b,this),this.genAdds(b,S)}))}})}init(S){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(b=>{this[b]=S[b]})}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(S,b){S.delete(b),vl.childNodes(b).forEach(b=>deepDelete(S,b))}function isParentRemoved(S,b,I){return 0!==S.size&&function _isParentRemoved(S,b,I){const x=vl.parentNode(b);return!!x&&S.has(x)}(S,b)}function isAncestorInSet(S,b){return 0!==S.size&&_isAncestorInSet(S,b)}function _isAncestorInSet(S,b){const I=vl.parentNode(b);return!!I&&(!!S.has(I)||_isAncestorInSet(S,I))}let Tl;const callbackWrapper=S=>{if(!Tl)return S;return(...b)=>{try{return S(...b)}catch(S){if(Tl&&!0===Tl(S))return;throw S}}},Al=[];function getEventTarget(S){try{if("composedPath"in S){const b=S.composedPath();if(b.length)return b[0]}else if("path"in S&&S.path.length)return S.path[0]}catch{}return S&&S.target}function initMutationObserver(S,b){const I=new MutationBuffer;Al.push(I),I.init(S);const x=new(mutationObserverCtor())(callbackWrapper(I.processMutations.bind(I)));return x.observe(b,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),x}function initMouseInteractionObserver({mouseInteractionCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){if(!1===A.mouseInteraction)return()=>{};const _=!0===A.mouseInteraction||void 0===A.mouseInteraction?{}:A.mouseInteraction,D=[];let L=null;return Object.keys(Il).filter(S=>Number.isNaN(Number(S))&&!S.endsWith("_Departed")&&!1!==_[S]).forEach(A=>{let _=toLowerCase(A);const B=(b=>A=>{const _=getEventTarget(A);if(isBlocked(_,x,R,!0))return;let D=null,B=b;if("pointerType"in A){switch(A.pointerType){case"mouse":D=El.Mouse;break;case"touch":D=El.Touch;break;case"pen":D=El.Pen}D===El.Touch&&(Il[b]===Il.MouseDown?B="TouchStart":Il[b]===Il.MouseUp&&(B="TouchEnd"))}else legacy_isTouchEvent(A)&&(D=El.Touch);null!==D?(L=D,(B.startsWith("Touch")&&D===El.Touch||B.startsWith("Mouse")&&D===El.Mouse)&&(D=null)):Il[b]===Il.Click&&(D=L,L=null);const U=legacy_isTouchEvent(A)?A.changedTouches[0]:A;if(!U)return;const $=I.getId(_),{clientX:j,clientY:W}=U;callbackWrapper(S)({type:Il[B],id:$,x:j,y:W,...null!==D&&{pointerType:D}})})(A);if(window.PointerEvent)switch(Il[A]){case Il.MouseDown:case Il.MouseUp:_=_.replace("mouse","pointer");break;case Il.TouchStart:case Il.TouchEnd:return}D.push(on(_,B,b))}),callbackWrapper(()=>{D.forEach(S=>S())})}function initScrollObserver({scrollCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,sampling:A}){return on("scroll",callbackWrapper(throttle(callbackWrapper(A=>{const _=getEventTarget(A);if(!_||isBlocked(_,x,R,!0))return;const D=I.getId(_);if(_===b&&b.defaultView){const I=getWindowScroll(b.defaultView);S({id:D,x:I.left,y:I.top})}else S({id:D,x:_.scrollLeft,y:_.scrollTop})}),A.scroll||100)),b)}const _l=["INPUT","TEXTAREA","SELECT"],Ol=new WeakMap;function getNestedCSSRulePositions(S){return function recurse(S,b){if(hasNestedCSSRule("CSSGroupingRule")&&S.parentRule instanceof CSSGroupingRule||hasNestedCSSRule("CSSMediaRule")&&S.parentRule instanceof CSSMediaRule||hasNestedCSSRule("CSSSupportsRule")&&S.parentRule instanceof CSSSupportsRule||hasNestedCSSRule("CSSConditionRule")&&S.parentRule instanceof CSSConditionRule){const I=Array.from(S.parentRule.cssRules).indexOf(S);b.unshift(I)}else if(S.parentStyleSheet){const I=Array.from(S.parentStyleSheet.cssRules).indexOf(S);b.unshift(I)}return b}(S,[])}function getIdAndStyleId(S,b,I){let x,R;return S?(S.ownerNode?x=b.getId(S.ownerNode):R=I.getId(S),{styleId:R,id:x}):{}}function initAdoptedStyleSheetObserver({mirror:S,stylesheetManager:b},I){var x,R,A;let _=null;_="#document"===I.nodeName?S.getId(I):S.getId(vl.host(I));const D="#document"===I.nodeName?null==(x=I.defaultView)?void 0:x.Document:null==(A=null==(R=I.ownerDocument)?void 0:R.defaultView)?void 0:A.ShadowRoot,L=(null==D?void 0:D.prototype)?Object.getOwnPropertyDescriptor(null==D?void 0:D.prototype,"adoptedStyleSheets"):void 0;return null!==_&&-1!==_&&D&&L?(Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get(){var S;return null==(S=L.get)?void 0:S.call(this)},set(S){var I;const x=null==(I=L.set)?void 0:I.call(this,S);if(null!==_&&-1!==_)try{b.adoptStyleSheets(S,_)}catch(S){}return x}}),callbackWrapper(()=>{Object.defineProperty(I,"adoptedStyleSheets",{configurable:L.configurable,enumerable:L.enumerable,get:L.get,set:L.set})})):()=>{}}function initObservers(S,b={}){const I=S.doc.defaultView;if(!I)return()=>{};let x;!function mergeHooks(S,b){const{mutationCb:I,mousemoveCb:x,mouseInteractionCb:R,scrollCb:A,viewportResizeCb:_,inputCb:D,mediaInteractionCb:L,styleSheetRuleCb:B,styleDeclarationCb:U,canvasMutationCb:$,fontCb:j,selectionCb:W,customElementCb:H}=S;S.mutationCb=(...S)=>{b.mutation&&b.mutation(...S),I(...S)},S.mousemoveCb=(...S)=>{b.mousemove&&b.mousemove(...S),x(...S)},S.mouseInteractionCb=(...S)=>{b.mouseInteraction&&b.mouseInteraction(...S),R(...S)},S.scrollCb=(...S)=>{b.scroll&&b.scroll(...S),A(...S)},S.viewportResizeCb=(...S)=>{b.viewportResize&&b.viewportResize(...S),_(...S)},S.inputCb=(...S)=>{b.input&&b.input(...S),D(...S)},S.mediaInteractionCb=(...S)=>{b.mediaInteaction&&b.mediaInteaction(...S),L(...S)},S.styleSheetRuleCb=(...S)=>{b.styleSheetRule&&b.styleSheetRule(...S),B(...S)},S.styleDeclarationCb=(...S)=>{b.styleDeclaration&&b.styleDeclaration(...S),U(...S)},S.canvasMutationCb=(...S)=>{b.canvasMutation&&b.canvasMutation(...S),$(...S)},S.fontCb=(...S)=>{b.font&&b.font(...S),j(...S)},S.selectionCb=(...S)=>{b.selection&&b.selection(...S),W(...S)},S.customElementCb=(...S)=>{b.customElement&&b.customElement(...S),H(...S)}}(S,b),S.recordDOM&&(x=initMutationObserver(S,S.doc));const R=function initMoveObserver({mousemoveCb:S,sampling:b,doc:I,mirror:x}){if(!1===b.mousemove)return()=>{};const R="number"==typeof b.mousemove?b.mousemove:50,A="number"==typeof b.mousemoveCallback?b.mousemoveCallback:500;let _,D=[];const L=throttle(callbackWrapper(b=>{const I=Date.now()-_;S(D.map(S=>(S.timeOffset-=I,S)),b),D=[],_=null}),A),B=callbackWrapper(throttle(callbackWrapper(S=>{const b=getEventTarget(S),{clientX:I,clientY:R}=legacy_isTouchEvent(S)?S.changedTouches[0]:S;_||(_=bl()),D.push({x:I,y:R,id:x.getId(b),timeOffset:bl()-_}),L("undefined"!=typeof DragEvent&&S instanceof DragEvent?kl.Drag:S instanceof MouseEvent?kl.MouseMove:kl.TouchMove)}),R,{trailing:!1})),U=[on("mousemove",B,I),on("touchmove",B,I),on("drag",B,I)];return callbackWrapper(()=>{U.forEach(S=>S())})}(S),A=initMouseInteractionObserver(S),_=initScrollObserver(S),D=function initViewportResizeObserver({viewportResizeCb:S},{win:b}){let I=-1,x=-1;return on("resize",callbackWrapper(throttle(callbackWrapper(()=>{const b=getWindowHeight(),R=getWindowWidth();I===b&&x===R||(S({width:Number(R),height:Number(b)}),I=b,x=R)}),200)),b)}(S,{win:I}),L=function initInputObserver({inputCb:S,doc:b,mirror:I,blockClass:x,blockSelector:R,ignoreClass:A,ignoreSelector:_,maskInputOptions:D,maskInputFn:L,sampling:B,userTriggeredOnInput:U}){function eventHandler(S){let I=getEventTarget(S);const B=S.isTrusted,$=I&&I.tagName;if(I&&"OPTION"===$&&(I=vl.parentElement(I)),!I||!$||_l.indexOf($)<0||isBlocked(I,x,R,!0))return;if(I.classList.contains(A)||_&&I.matches(_))return;let j=I.value,W=!1;const H=getInputType(I)||"";"radio"===H||"checkbox"===H?W=I.checked:(D[$.toLowerCase()]||D[H])&&(j=maskInputValue({element:I,maskInputOptions:D,tagName:$,type:H,value:j,maskInputFn:L})),cbWithDedup(I,U?{text:j,isChecked:W,userTriggered:B}:{text:j,isChecked:W});const V=I.name;"radio"===H&&V&&W&&b.querySelectorAll(`input[type="radio"][name="${V}"]`).forEach(S=>{if(S!==I){const b=S.value;cbWithDedup(S,U?{text:b,isChecked:!W,userTriggered:!1}:{text:b,isChecked:!W})}})}function cbWithDedup(b,x){const R=Ol.get(b);if(!R||R.text!==x.text||R.isChecked!==x.isChecked){Ol.set(b,x);const R=I.getId(b);callbackWrapper(S)({...x,id:R})}}const $=("last"===B.input?["change"]:["input","change"]).map(S=>on(S,callbackWrapper(eventHandler),b)),j=b.defaultView;if(!j)return()=>{$.forEach(S=>S())};const W=j.Object.getOwnPropertyDescriptor(j.HTMLInputElement.prototype,"value"),H=[[j.HTMLInputElement.prototype,"value"],[j.HTMLInputElement.prototype,"checked"],[j.HTMLSelectElement.prototype,"value"],[j.HTMLTextAreaElement.prototype,"value"],[j.HTMLSelectElement.prototype,"selectedIndex"],[j.HTMLOptionElement.prototype,"selected"]];return W&&W.set&&$.push(...H.map(S=>hookSetter(S[0],S[1],{set(){callbackWrapper(eventHandler)({target:this,isTrusted:!1})}},!1,j))),callbackWrapper(()=>{$.forEach(S=>S())})}(S),B=function initMediaInteractionObserver({mediaInteractionCb:S,blockClass:b,blockSelector:I,mirror:x,sampling:R,doc:A}){const _=callbackWrapper(A=>throttle(callbackWrapper(R=>{const _=getEventTarget(R);if(!_||isBlocked(_,b,I,!0))return;const{currentTime:D,volume:L,muted:B,playbackRate:U,loop:$}=_;S({type:A,id:x.getId(_),currentTime:D,volume:L,muted:B,playbackRate:U,loop:$})}),R.media||500)),D=[on("play",_(Ml.Play),A),on("pause",_(Ml.Pause),A),on("seeked",_(Ml.Seeked),A),on("volumechange",_(Ml.VolumeChange),A),on("ratechange",_(Ml.RateChange),A)];return callbackWrapper(()=>{D.forEach(S=>S())})}(S);let styleSheetObserver=()=>{},adoptedStyleSheetObserver=()=>{},styleDeclarationObserver=()=>{},fontObserver=()=>{};S.recordDOM&&(styleSheetObserver=function initStyleSheetObserver({styleSheetRuleCb:S,mirror:b,stylesheetManager:I},{win:x}){if(!x.CSSStyleSheet||!x.CSSStyleSheet.prototype)return()=>{};const R=x.CSSStyleSheet.prototype.insertRule;x.CSSStyleSheet.prototype.insertRule=new Proxy(R,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:D}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.addRule=function(S,b,I=this.cssRules.length){const R=`${S} { ${b} }`;return x.CSSStyleSheet.prototype.insertRule.apply(this,[R,I])};const A=x.CSSStyleSheet.prototype.deleteRule;let _,D;x.CSSStyleSheet.prototype.deleteRule=new Proxy(A,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:_}]}),x.apply(R,A)})}),x.CSSStyleSheet.prototype.removeRule=function(S){return x.CSSStyleSheet.prototype.deleteRule.apply(this,[S])},x.CSSStyleSheet.prototype.replace&&(_=x.CSSStyleSheet.prototype.replace,x.CSSStyleSheet.prototype.replace=new Proxy(_,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replace:_}),x.apply(R,A)})})),x.CSSStyleSheet.prototype.replaceSync&&(D=x.CSSStyleSheet.prototype.replaceSync,x.CSSStyleSheet.prototype.replaceSync=new Proxy(D,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,replaceSync:_}),x.apply(R,A)})}));const L={};canMonkeyPatchNestedCSSRule("CSSGroupingRule")?L.CSSGroupingRule=x.CSSGroupingRule:(canMonkeyPatchNestedCSSRule("CSSMediaRule")&&(L.CSSMediaRule=x.CSSMediaRule),canMonkeyPatchNestedCSSRule("CSSConditionRule")&&(L.CSSConditionRule=x.CSSConditionRule),canMonkeyPatchNestedCSSRule("CSSSupportsRule")&&(L.CSSSupportsRule=x.CSSSupportsRule));const B={};return Object.entries(L).forEach(([x,R])=>{B[x]={insertRule:R.prototype.insertRule,deleteRule:R.prototype.deleteRule},R.prototype.insertRule=new Proxy(B[x].insertRule,{apply:callbackWrapper((x,R,A)=>{const[_,D]=A,{id:L,styleId:B}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(L&&-1!==L||B&&-1!==B)&&S({id:L,styleId:B,adds:[{rule:_,index:[...getNestedCSSRulePositions(R),D||0]}]}),x.apply(R,A)})}),R.prototype.deleteRule=new Proxy(B[x].deleteRule,{apply:callbackWrapper((x,R,A)=>{const[_]=A,{id:D,styleId:L}=getIdAndStyleId(R.parentStyleSheet,b,I.styleMirror);return(D&&-1!==D||L&&-1!==L)&&S({id:D,styleId:L,removes:[{index:[...getNestedCSSRulePositions(R),_]}]}),x.apply(R,A)})})}),callbackWrapper(()=>{x.CSSStyleSheet.prototype.insertRule=R,x.CSSStyleSheet.prototype.deleteRule=A,_&&(x.CSSStyleSheet.prototype.replace=_),D&&(x.CSSStyleSheet.prototype.replaceSync=D),Object.entries(L).forEach(([S,b])=>{b.prototype.insertRule=B[S].insertRule,b.prototype.deleteRule=B[S].deleteRule})})}(S,{win:I}),adoptedStyleSheetObserver=initAdoptedStyleSheetObserver(S,S.doc),styleDeclarationObserver=function initStyleDeclarationObserver({styleDeclarationCb:S,mirror:b,ignoreCSSAttributes:I,stylesheetManager:x},{win:R}){const A=R.CSSStyleDeclaration.prototype.setProperty;R.CSSStyleDeclaration.prototype.setProperty=new Proxy(A,{apply:callbackWrapper((R,_,D)=>{var L;const[B,U,$]=D;if(I.has(B))return A.apply(_,[B,U,$]);const{id:j,styleId:W}=getIdAndStyleId(null==(L=_.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(j&&-1!==j||W&&-1!==W)&&S({id:j,styleId:W,set:{property:B,value:U,priority:$},index:getNestedCSSRulePositions(_.parentRule)}),R.apply(_,D)})});const _=R.CSSStyleDeclaration.prototype.removeProperty;return R.CSSStyleDeclaration.prototype.removeProperty=new Proxy(_,{apply:callbackWrapper((R,A,D)=>{var L;const[B]=D;if(I.has(B))return _.apply(A,[B]);const{id:U,styleId:$}=getIdAndStyleId(null==(L=A.parentRule)?void 0:L.parentStyleSheet,b,x.styleMirror);return(U&&-1!==U||$&&-1!==$)&&S({id:U,styleId:$,remove:{property:B},index:getNestedCSSRulePositions(A.parentRule)}),R.apply(A,D)})}),callbackWrapper(()=>{R.CSSStyleDeclaration.prototype.setProperty=A,R.CSSStyleDeclaration.prototype.removeProperty=_})}(S,{win:I}),S.collectFonts&&(fontObserver=function initFontObserver({fontCb:S,doc:b}){const I=b.defaultView;if(!I)return()=>{};const x=[],R=new WeakMap,A=I.FontFace;I.FontFace=function FontFace2(S,b,I){const x=new A(S,b,I);return R.set(x,{family:S,buffer:"string"!=typeof b,descriptors:I,fontSource:"string"==typeof b?b:JSON.stringify(Array.from(new Uint8Array(b)))}),x};const _=patch(b.fonts,"add",function(b){return function(I){return setTimeout(callbackWrapper(()=>{const b=R.get(I);b&&(S(b),R.delete(I))}),0),b.apply(this,[I])}});return x.push(()=>{I.FontFace=A}),x.push(_),callbackWrapper(()=>{x.forEach(S=>S())})}(S)));const U=function initSelectionObserver(S){const{doc:b,mirror:I,blockClass:x,blockSelector:R,selectionCb:A}=S;let _=!0;const D=callbackWrapper(()=>{const S=b.getSelection();if(!S||_&&(null==S?void 0:S.isCollapsed))return;_=S.isCollapsed||!1;const D=[],L=S.rangeCount||0;for(let b=0;b<L;b++){const A=S.getRangeAt(b),{startContainer:_,startOffset:L,endContainer:B,endOffset:U}=A;isBlocked(_,x,R,!0)||isBlocked(B,x,R,!0)||D.push({start:I.getId(_),startOffset:L,end:I.getId(B),endOffset:U})}A({ranges:D})});return D(),on("selectionchange",D)}(S),$=function initCustomElementObserver({doc:S,customElementCb:b}){const I=S.defaultView;return I&&I.customElements?patch(I.customElements,"define",function(S){return function(I,x,R){try{b({define:{name:I}})}catch(S){console.warn(`Custom element callback failed for ${I}`)}return S.apply(this,[I,x,R])}}):()=>{}}(S),j=[];for(const b of S.plugins)j.push(b.observer(b.callback,I,b.options));return callbackWrapper(()=>{Al.forEach(S=>S.reset()),null==x||x.disconnect(),R(),A(),_(),D(),L(),B(),styleSheetObserver(),adoptedStyleSheetObserver(),styleDeclarationObserver(),fontObserver(),U(),$(),j.forEach(S=>S())})}function hasNestedCSSRule(S){return void 0!==window[S]}function canMonkeyPatchNestedCSSRule(S){return Boolean(void 0!==window[S]&&window[S].prototype&&"insertRule"in window[S].prototype&&"deleteRule"in window[S].prototype)}class CrossOriginIframeMirror{constructor(S){__publicField(this,"iframeIdToRemoteIdMap",new WeakMap),__publicField(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=S}getId(S,b,I,x){const R=I||this.getIdToRemoteIdMap(S),A=x||this.getRemoteIdToIdMap(S);let _=R.get(b);return _||(_=this.generateIdFn(),R.set(b,_),A.set(_,b)),_}getIds(S,b){const I=this.getIdToRemoteIdMap(S),x=this.getRemoteIdToIdMap(S);return b.map(b=>this.getId(S,b,I,x))}getRemoteId(S,b,I){const x=I||this.getRemoteIdToIdMap(S);if("number"!=typeof b)return b;const R=x.get(b);return R||-1}getRemoteIds(S,b){const I=this.getRemoteIdToIdMap(S);return b.map(b=>this.getRemoteId(S,b,I))}reset(S){if(!S)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(S),this.iframeRemoteIdToIdMap.delete(S)}getIdToRemoteIdMap(S){let b=this.iframeIdToRemoteIdMap.get(S);return b||(b=new Map,this.iframeIdToRemoteIdMap.set(S,b)),b}getRemoteIdToIdMap(S){let b=this.iframeRemoteIdToIdMap.get(S);return b||(b=new Map,this.iframeRemoteIdToIdMap.set(S,b)),b}}class IframeManager{constructor(S){__publicField(this,"iframes",new WeakMap),__publicField(this,"crossOriginIframeMap",new WeakMap),__publicField(this,"crossOriginIframeMirror",new CrossOriginIframeMirror(genId)),__publicField(this,"crossOriginIframeStyleMirror"),__publicField(this,"crossOriginIframeRootIdMap",new WeakMap),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"wrappedEmit"),__publicField(this,"loadListener"),__publicField(this,"stylesheetManager"),__publicField(this,"recordCrossOriginIframes"),this.mutationCb=S.mutationCb,this.wrappedEmit=S.wrappedEmit,this.stylesheetManager=S.stylesheetManager,this.recordCrossOriginIframes=S.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=S.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(S){this.iframes.set(S,!0),S.contentWindow&&this.crossOriginIframeMap.set(S.contentWindow,S)}addLoadListener(S){this.loadListener=S}attachIframe(S,b){var I,x;this.mutationCb({adds:[{parentId:this.mirror.getId(S),nextId:null,node:b}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(I=S.contentWindow)||I.addEventListener("message",this.handleMessage.bind(this))),null==(x=this.loadListener)||x.call(this,S),S.contentDocument&&S.contentDocument.adoptedStyleSheets&&S.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(S.contentDocument.adoptedStyleSheets,this.mirror.getId(S.contentDocument))}handleMessage(S){const b=S;if("rrweb"!==b.data.type||b.origin!==b.data.origin)return;if(!S.source)return;const I=this.crossOriginIframeMap.get(S.source);if(!I)return;const x=this.transformCrossOriginEvent(I,b.data.event);x&&this.wrappedEmit(x,b.data.isCheckout)}transformCrossOriginEvent(S,b){var I;switch(b.type){case Cl.FullSnapshot:{this.crossOriginIframeMirror.reset(S),this.crossOriginIframeStyleMirror.reset(S),this.replaceIdOnNode(b.data.node,S);const I=b.data.node.id;return this.crossOriginIframeRootIdMap.set(S,I),this.patchRootIdOnNode(b.data.node,I),{timestamp:b.timestamp,type:Cl.IncrementalSnapshot,data:{source:kl.Mutation,adds:[{parentId:this.mirror.getId(S),nextId:null,node:b.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Cl.Meta:case Cl.Load:case Cl.DomContentLoaded:return!1;case Cl.Plugin:return b;case Cl.Custom:return this.replaceIds(b.data.payload,S,["id","parentId","previousId","nextId"]),b;case Cl.IncrementalSnapshot:switch(b.data.source){case kl.Mutation:return b.data.adds.forEach(b=>{this.replaceIds(b,S,["parentId","nextId","previousId"]),this.replaceIdOnNode(b.node,S);const I=this.crossOriginIframeRootIdMap.get(S);I&&this.patchRootIdOnNode(b.node,I)}),b.data.removes.forEach(b=>{this.replaceIds(b,S,["parentId","id"])}),b.data.attributes.forEach(b=>{this.replaceIds(b,S,["id"])}),b.data.texts.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case kl.Drag:case kl.TouchMove:case kl.MouseMove:return b.data.positions.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case kl.ViewportResize:return!1;case kl.MediaInteraction:case kl.MouseInteraction:case kl.Scroll:case kl.CanvasMutation:case kl.Input:return this.replaceIds(b.data,S,["id"]),b;case kl.StyleSheetRule:case kl.StyleDeclaration:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleId"]),b;case kl.Font:return b;case kl.Selection:return b.data.ranges.forEach(b=>{this.replaceIds(b,S,["start","end"])}),b;case kl.AdoptedStyleSheet:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleIds"]),null==(I=b.data.styles)||I.forEach(b=>{this.replaceStyleIds(b,S,["styleId"])}),b}}return!1}replace(S,b,I,x){for(const R of x)(Array.isArray(b[R])||"number"==typeof b[R])&&(Array.isArray(b[R])?b[R]=S.getIds(I,b[R]):b[R]=S.getId(I,b[R]));return b}replaceIds(S,b,I){return this.replace(this.crossOriginIframeMirror,S,b,I)}replaceStyleIds(S,b,I){return this.replace(this.crossOriginIframeStyleMirror,S,b,I)}replaceIdOnNode(S,b){this.replaceIds(S,b,["id","rootId"]),"childNodes"in S&&S.childNodes.forEach(S=>{this.replaceIdOnNode(S,b)})}patchRootIdOnNode(S,b){S.type===Rl.Document||S.rootId||(S.rootId=b),"childNodes"in S&&S.childNodes.forEach(S=>{this.patchRootIdOnNode(S,b)})}}class ShadowDomManager{constructor(S){__publicField(this,"shadowDoms",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"scrollCb"),__publicField(this,"bypassOptions"),__publicField(this,"mirror"),__publicField(this,"restoreHandlers",[]),this.mutationCb=S.mutationCb,this.scrollCb=S.scrollCb,this.bypassOptions=S.bypassOptions,this.mirror=S.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(S,b){if(!isNativeShadowDom(S))return;if(this.shadowDoms.has(S))return;this.shadowDoms.add(S);const I=initMutationObserver({...this.bypassOptions,doc:b,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},S);this.restoreHandlers.push(()=>I.disconnect()),this.restoreHandlers.push(initScrollObserver({...this.bypassOptions,scrollCb:this.scrollCb,doc:S,mirror:this.mirror})),setTimeout(()=>{S.adoptedStyleSheets&&S.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(S.adoptedStyleSheets,this.mirror.getId(vl.host(S))),this.restoreHandlers.push(initAdoptedStyleSheetObserver({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},S))},0)}observeAttachShadow(S){S.contentWindow&&S.contentDocument&&this.patchAttachShadow(S.contentWindow.Element,S.contentDocument)}patchAttachShadow(S,b){const I=this;this.restoreHandlers.push(patch(S.prototype,"attachShadow",function(S){return function(x){const R=S.call(this,x),A=vl.shadowRoot(this);return A&&inDom(this)&&I.addShadowRoot(A,b),R}}))}reset(){this.restoreHandlers.forEach(S=>{try{S()}catch(S){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}for(var Dl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Fl="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Nl=0;Nl<64;Nl++)Fl[Dl.charCodeAt(Nl)]=Nl;const Ll=new Map;const saveWebGLVar=(S,b,I)=>{if(!S||!isInstanceOfWebGLObject(S,b)&&"object"!=typeof S)return;const x=function variableListFor$1(S,b){let I=Ll.get(S);return I||(I=new Map,Ll.set(S,I)),I.has(b)||I.set(b,[]),I.get(b)}(I,S.constructor.name);let R=x.indexOf(S);return-1===R&&(R=x.length,x.push(S)),R};function serializeArg(S,b,I){if(S instanceof Array)return S.map(S=>serializeArg(S,b,I));if(null===S)return S;if(S instanceof Float32Array||S instanceof Float64Array||S instanceof Int32Array||S instanceof Uint32Array||S instanceof Uint8Array||S instanceof Uint16Array||S instanceof Int16Array||S instanceof Int8Array||S instanceof Uint8ClampedArray){return{rr_type:S.constructor.name,args:[Object.values(S)]}}if(S instanceof ArrayBuffer){return{rr_type:S.constructor.name,base64:function(S){var b,I=new Uint8Array(S),x=I.length,R="";for(b=0;b<x;b+=3)R+=Dl[I[b]>>2],R+=Dl[(3&I[b])<<4|I[b+1]>>4],R+=Dl[(15&I[b+1])<<2|I[b+2]>>6],R+=Dl[63&I[b+2]];return x%3==2?R=R.substring(0,R.length-1)+"=":x%3==1&&(R=R.substring(0,R.length-2)+"=="),R}(S)}}if(S instanceof DataView){return{rr_type:S.constructor.name,args:[serializeArg(S.buffer,b,I),S.byteOffset,S.byteLength]}}if(S instanceof HTMLImageElement){const b=S.constructor.name,{src:I}=S;return{rr_type:b,src:I}}if(S instanceof HTMLCanvasElement){return{rr_type:"HTMLImageElement",src:S.toDataURL()}}if(S instanceof ImageData){return{rr_type:S.constructor.name,args:[serializeArg(S.data,b,I),S.width,S.height]}}if(isInstanceOfWebGLObject(S,b)||"object"==typeof S){return{rr_type:S.constructor.name,index:saveWebGLVar(S,b,I)}}return S}const serializeArgs=(S,b,I)=>S.map(S=>serializeArg(S,b,I)),isInstanceOfWebGLObject=(S,b)=>{const I=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(S=>"function"==typeof b[S]);return Boolean(I.find(I=>S instanceof b[I]))};function initCanvasContextObserver(S,b,I,x){const R=[];try{const A=patch(S.HTMLCanvasElement.prototype,"getContext",function(S){return function(R,...A){if(!isBlocked(this,b,I,!0)){const S=function getNormalizedContextName(S){return"experimental-webgl"===S?"webgl":S}(R);if("__context"in this||(this.__context=S),x&&["webgl","webgl2"].includes(S))if(A[0]&&"object"==typeof A[0]){const S=A[0];S.preserveDrawingBuffer||(S.preserveDrawingBuffer=!0)}else A.splice(0,1,{preserveDrawingBuffer:!0})}return S.apply(this,[R,...A])}});R.push(A)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{R.forEach(S=>S())}}function patchGLPrototype(S,b,I,x,R,A){const _=[],D=Object.getOwnPropertyNames(S);for(const L of D)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(L))try{if("function"!=typeof S[L])continue;const D=patch(S,L,function(S){return function(..._){const D=S.apply(this,_);if(saveWebGLVar(D,A,this),"tagName"in this.canvas&&!isBlocked(this.canvas,x,R,!0)){const S=serializeArgs(_,A,this),x={type:b,property:L,args:S};I(this.canvas,x)}return D}});_.push(D)}catch{const x=hookSetter(S,L,{set(S){I(this.canvas,{type:b,property:L,args:[S],setter:!0})}});_.push(x)}return _}const Pl="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Bl="undefined"!=typeof window&&window.Blob&&new Blob([(zl=Pl,Uint8Array.from(atob(zl),S=>S.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});var zl;function WorkerWrapper(S){let b;try{if(b=Bl&&(window.URL||window.webkitURL).createObjectURL(Bl),!b)throw"";const I=new Worker(b,{name:null==S?void 0:S.name});return I.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(b)}),I}catch(b){return new Worker("data:text/javascript;base64,"+Pl,{name:null==S?void 0:S.name})}finally{b&&(window.URL||window.webkitURL).revokeObjectURL(b)}}class CanvasManager{constructor(S){__publicField(this,"pendingCanvasMutations",new Map),__publicField(this,"rafStamps",{latestId:0,invokeId:null}),__publicField(this,"mirror"),__publicField(this,"mutationCb"),__publicField(this,"resetObservers"),__publicField(this,"frozen",!1),__publicField(this,"locked",!1),__publicField(this,"processMutation",(S,b)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(S)||this.pendingCanvasMutations.set(S,[]),this.pendingCanvasMutations.get(S).push(b)});const{sampling:b="all",win:I,blockClass:x,blockSelector:R,recordCanvas:A,dataURLOptions:_}=S;this.mutationCb=S.mutationCb,this.mirror=S.mirror,A&&"all"===b&&this.initCanvasMutationObserver(I,x,R),A&&"number"==typeof b&&this.initCanvasFPSObserver(b,I,x,R,{dataURLOptions:_})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(S,b,I,x,R){const A=initCanvasContextObserver(b,I,x,!0),_=new Map,D=new WorkerWrapper;D.onmessage=S=>{const{id:b}=S.data;if(_.set(b,!1),!("base64"in S.data))return;const{base64:I,type:x,width:R,height:A}=S.data;this.mutationCb({id:b,type:xl["2D"],commands:[{property:"clearRect",args:[0,0,R,A]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:I}],type:x}]},0,0]}]})};const L=1e3/S;let B,U=0;const takeCanvasSnapshots=S=>{U&&S-U<L||(U=S,(()=>{const S=[];return b.document.querySelectorAll("canvas").forEach(b=>{isBlocked(b,I,x,!0)||S.push(b)}),S})().forEach(async S=>{var b;const I=this.mirror.getId(S);if(_.get(I))return;if(0===S.width||0===S.height)return;if(_.set(I,!0),["webgl","webgl2"].includes(S.__context)){const I=S.getContext(S.__context);!1===(null==(b=null==I?void 0:I.getContextAttributes())?void 0:b.preserveDrawingBuffer)&&I.clear(I.COLOR_BUFFER_BIT)}const x=await createImageBitmap(S);D.postMessage({id:I,bitmap:x,width:S.width,height:S.height,dataURLOptions:R.dataURLOptions},[x])})),B=requestAnimationFrame(takeCanvasSnapshots)};B=requestAnimationFrame(takeCanvasSnapshots),this.resetObservers=()=>{A(),cancelAnimationFrame(B)}}initCanvasMutationObserver(S,b,I){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const x=initCanvasContextObserver(S,b,I,!1),R=function initCanvas2DMutationObserver(S,b,I,x){const R=[],A=Object.getOwnPropertyNames(b.CanvasRenderingContext2D.prototype);for(const _ of A)try{if("function"!=typeof b.CanvasRenderingContext2D.prototype[_])continue;const A=patch(b.CanvasRenderingContext2D.prototype,_,function(R){return function(...A){return isBlocked(this.canvas,I,x,!0)||setTimeout(()=>{const I=serializeArgs(A,b,this);S(this.canvas,{type:xl["2D"],property:_,args:I})},0),R.apply(this,A)}});R.push(A)}catch{const I=hookSetter(b.CanvasRenderingContext2D.prototype,_,{set(b){S(this.canvas,{type:xl["2D"],property:_,args:[b],setter:!0})}});R.push(I)}return()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I),A=function initCanvasWebGLMutationObserver(S,b,I,x){const R=[];return R.push(...patchGLPrototype(b.WebGLRenderingContext.prototype,xl.WebGL,S,I,x,b)),void 0!==b.WebGL2RenderingContext&&R.push(...patchGLPrototype(b.WebGL2RenderingContext.prototype,xl.WebGL2,S,I,x,b)),()=>{R.forEach(S=>S())}}(this.processMutation.bind(this),S,b,I);this.resetObservers=()=>{x(),R(),A()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const setLatestRAFTimestamp=S=>{this.rafStamps.latestId=S,requestAnimationFrame(setLatestRAFTimestamp)};requestAnimationFrame(setLatestRAFTimestamp)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((S,b)=>{const I=this.mirror.getId(b);this.flushPendingCanvasMutationFor(b,I)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(S,b){if(this.frozen||this.locked)return;const I=this.pendingCanvasMutations.get(S);if(!I||-1===b)return;const x=I.map(S=>{const{type:b,...I}=S;return I}),{type:R}=I[0];this.mutationCb({id:b,type:R,commands:x}),this.pendingCanvasMutations.delete(S)}}class StylesheetManager{constructor(S){__publicField(this,"trackedLinkElements",new WeakSet),__publicField(this,"mutationCb"),__publicField(this,"adoptedStyleSheetCb"),__publicField(this,"styleMirror",new StyleSheetMirror),this.mutationCb=S.mutationCb,this.adoptedStyleSheetCb=S.adoptedStyleSheetCb}attachLinkElement(S,b){"_cssText"in b.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:b.id,attributes:b.attributes}]}),this.trackLinkElement(S)}trackLinkElement(S){this.trackedLinkElements.has(S)||(this.trackedLinkElements.add(S),this.trackStylesheetInLinkElement(S))}adoptStyleSheets(S,b){if(0===S.length)return;const I={id:b,styleIds:[]},x=[];for(const b of S){let S;this.styleMirror.has(b)?S=this.styleMirror.getId(b):(S=this.styleMirror.add(b),x.push({styleId:S,rules:Array.from(b.rules||CSSRule,(S,I)=>({rule:stringifyRule(S,b.href),index:I}))})),I.styleIds.push(S)}x.length>0&&(I.styles=x),this.adoptedStyleSheetCb(I)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(S){}}class ProcessedNodeManager{constructor(){__publicField(this,"nodeMap",new WeakMap),__publicField(this,"active",!1)}inOtherBuffer(S,b){const I=this.nodeMap.get(S);return I&&Array.from(I).some(S=>S!==b)}add(S,b){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(S,(this.nodeMap.get(S)||new Set).add(b))}destroy(){}}let Ul,$l,jl,ql=!1;try{if(2!==Array.from([1],S=>2*S)[0]){const S=document.createElement("iframe");document.body.appendChild(S),Array.from=(null==(Ke=S.contentWindow)?void 0:Ke.Array.from)||Array.from,document.body.removeChild(S)}}catch(err){console.debug("Unable to override Array.from",err)}const Wl=function createMirror$2(){return new Mirror}();function record(S={}){const{emit:b,checkoutEveryNms:I,checkoutEveryNth:x,blockClass:R="rr-block",blockSelector:A=null,ignoreClass:_="rr-ignore",ignoreSelector:D=null,maskTextClass:L="rr-mask",maskTextSelector:B=null,inlineStylesheet:U=!0,maskAllInputs:$,maskInputOptions:j,slimDOMOptions:W,maskInputFn:H,maskTextFn:V,hooks:Q,packFn:G,sampling:J={},dataURLOptions:X={},mousemoveWait:Y,recordDOM:ee=!0,recordCanvas:te=!1,recordCrossOriginIframes:se=!1,recordAfter:re=("DOMContentLoaded"===S.recordAfter?S.recordAfter:"load"),userTriggeredOnInput:ne=!1,collectFonts:ie=!1,inlineImages:oe=!1,plugins:ae,keepIframeSrcFn:le=()=>!1,ignoreCSSAttributes:ce=new Set([]),errorHandler:ue}=S;!function registerErrorHandler(S){Tl=S}(ue);const he=!se||window.parent===window;let de=!1;if(!he)try{window.parent.document&&(de=!1)}catch(S){de=!0}if(he&&!b)throw new Error("emit function is required");if(!he&&!de)return()=>{};void 0!==Y&&void 0===J.mousemove&&(J.mousemove=Y),Wl.reset();const ge=!0===$?{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,password:!0}:void 0!==j?j:{password:!0},pe=!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===W,headMetaDescKeywords:"all"===W,headTitleMutations:"all"===W}:W||{};let fe;!function polyfill$1(S=window){"NodeList"in S&&!S.NodeList.prototype.forEach&&(S.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in S&&!S.DOMTokenList.prototype.forEach&&(S.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let me=0;const eventProcessor=S=>{for(const b of ae||[])b.eventProcessor&&(S=b.eventProcessor(S));return G&&!de&&(S=G(S)),S};Ul=(S,R)=>{var A;const _=S;if(_.timestamp=bl(),!(null==(A=Al[0])?void 0:A.isFrozen())||_.type===Cl.FullSnapshot||_.type===Cl.IncrementalSnapshot&&_.data.source===kl.Mutation||Al.forEach(S=>S.unfreeze()),he)null==b||b(eventProcessor(_),R);else if(de){const S={type:"rrweb",event:eventProcessor(_),origin:window.location.origin,isCheckout:R};window.parent.postMessage(S,"*")}if(_.type===Cl.FullSnapshot)fe=_,me=0;else if(_.type===Cl.IncrementalSnapshot){if(_.data.source===kl.Mutation&&_.data.isAttachIframe)return;me++;const S=x&&me>=x,b=I&&_.timestamp-fe.timestamp>I;(S||b)&&$l(!0)}};const wrappedMutationEmit=S=>{Ul({type:Cl.IncrementalSnapshot,data:{source:kl.Mutation,...S}})},wrappedScrollEmit=S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.Scroll,...S}}),wrappedCanvasMutationEmit=S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.CanvasMutation,...S}}),ye=new StylesheetManager({mutationCb:wrappedMutationEmit,adoptedStyleSheetCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.AdoptedStyleSheet,...S}})}),ve=new IframeManager({mirror:Wl,mutationCb:wrappedMutationEmit,stylesheetManager:ye,recordCrossOriginIframes:se,wrappedEmit:Ul});for(const S of ae||[])S.getMirror&&S.getMirror({nodeMirror:Wl,crossOriginIframeMirror:ve.crossOriginIframeMirror,crossOriginIframeStyleMirror:ve.crossOriginIframeStyleMirror});const Se=new ProcessedNodeManager;jl=new CanvasManager({recordCanvas:te,mutationCb:wrappedCanvasMutationEmit,win:window,blockClass:R,blockSelector:A,mirror:Wl,sampling:J.canvas,dataURLOptions:X});const we=new ShadowDomManager({mutationCb:wrappedMutationEmit,scrollCb:wrappedScrollEmit,bypassOptions:{blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskInputOptions:ge,dataURLOptions:X,maskTextFn:V,maskInputFn:H,recordCanvas:te,inlineImages:oe,sampling:J,slimDOMOptions:pe,iframeManager:ve,stylesheetManager:ye,canvasManager:jl,keepIframeSrcFn:le,processedNodeManager:Se},mirror:Wl});$l=(S=!1)=>{if(!ee)return;Ul({type:Cl.Meta,data:{href:window.location.href,width:getWindowWidth(),height:getWindowHeight()}},S),ye.reset(),we.init(),Al.forEach(S=>S.lock());const b=function snapshot(S,b){const{mirror:I=new Mirror,blockClass:x="rr-block",blockSelector:R=null,maskTextClass:A="rr-mask",maskTextSelector:_=null,inlineStylesheet:D=!0,inlineImages:L=!1,recordCanvas:B=!1,maskAllInputs:U=!1,maskTextFn:$,maskInputFn:j,slimDOM:W=!1,dataURLOptions:H,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee=()=>!1}=b||{};return serializeNodeWithId(S,{doc:S,mirror:I,blockClass:x,blockSelector:R,maskTextClass:A,maskTextSelector:_,skipChild:!1,inlineStylesheet:D,maskInputOptions:!0===U?{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,password:!0}:!1===U?{password:!0}:U,maskTextFn:$,maskInputFn:j,slimDOMOptions:!0===W||"all"===W?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===W,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===W?{}:W,dataURLOptions:H,inlineImages:L,recordCanvas:B,preserveWhiteSpace:V,onSerialize:Q,onIframeLoad:G,iframeLoadTimeout:J,onStylesheetLoad:X,stylesheetLoadTimeout:Y,keepIframeSrcFn:ee,newlyAddedElement:!1})}(document,{mirror:Wl,blockClass:R,blockSelector:A,maskTextClass:L,maskTextSelector:B,inlineStylesheet:U,maskAllInputs:ge,maskTextFn:V,maskInputFn:H,slimDOM:pe,dataURLOptions:X,recordCanvas:te,inlineImages:oe,onSerialize:S=>{isSerializedIframe(S,Wl)&&ve.addIframe(S),isSerializedStylesheet(S,Wl)&&ye.trackLinkElement(S),hasShadowRoot(S)&&we.addShadowRoot(vl.shadowRoot(S),document)},onIframeLoad:(S,b)=>{ve.attachIframe(S,b),we.observeAttachShadow(S)},onStylesheetLoad:(S,b)=>{ye.attachLinkElement(S,b)},keepIframeSrcFn:le});if(!b)return console.warn("Failed to snapshot the document");Ul({type:Cl.FullSnapshot,data:{node:b,initialOffset:getWindowScroll(window)}},S),Al.forEach(S=>S.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ye.adoptStyleSheets(document.adoptedStyleSheets,Wl.getId(document))};try{const S=[],observe=S=>{var b;return callbackWrapper(initObservers)({mutationCb:wrappedMutationEmit,mousemoveCb:(S,b)=>Ul({type:Cl.IncrementalSnapshot,data:{source:b,positions:S}}),mouseInteractionCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.MouseInteraction,...S}}),scrollCb:wrappedScrollEmit,viewportResizeCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.ViewportResize,...S}}),inputCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.Input,...S}}),mediaInteractionCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.MediaInteraction,...S}}),styleSheetRuleCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.StyleSheetRule,...S}}),styleDeclarationCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.StyleDeclaration,...S}}),canvasMutationCb:wrappedCanvasMutationEmit,fontCb:S=>Ul({type:Cl.IncrementalSnapshot,data:{source:kl.Font,...S}}),selectionCb:S=>{Ul({type:Cl.IncrementalSnapshot,data:{source:kl.Selection,...S}})},customElementCb:S=>{Ul({type:Cl.IncrementalSnapshot,data:{source:kl.CustomElement,...S}})},blockClass:R,ignoreClass:_,ignoreSelector:D,maskTextClass:L,maskTextSelector:B,maskInputOptions:ge,inlineStylesheet:U,sampling:J,recordDOM:ee,recordCanvas:te,inlineImages:oe,userTriggeredOnInput:ne,collectFonts:ie,doc:S,maskInputFn:H,maskTextFn:V,keepIframeSrcFn:le,blockSelector:A,slimDOMOptions:pe,dataURLOptions:X,mirror:Wl,iframeManager:ve,stylesheetManager:ye,shadowDomManager:we,processedNodeManager:Se,canvasManager:jl,ignoreCSSAttributes:ce,plugins:(null==(b=null==ae?void 0:ae.filter(S=>S.observer))?void 0:b.map(S=>({observer:S.observer,options:S.options,callback:b=>Ul({type:Cl.Plugin,data:{plugin:S.name,payload:b}})})))||[]},Q)};ve.addLoadListener(b=>{try{S.push(observe(b.contentDocument))}catch(S){console.warn(S)}});const init=()=>{$l(),S.push(observe(document)),ql=!0};return"interactive"===document.readyState||"complete"===document.readyState?init():(S.push(on("DOMContentLoaded",()=>{Ul({type:Cl.DomContentLoaded,data:{}}),"DOMContentLoaded"===re&&init()})),S.push(on("load",()=>{Ul({type:Cl.Load,data:{}}),"load"===re&&init()},window))),()=>{S.forEach(S=>S()),Se.destroy(),ql=!1,function unregisterErrorHandler(){Tl=void 0}()}}catch(S){console.warn(S)}}var Hl,Vl;record.addCustomEvent=(S,b)=>{if(!ql)throw new Error("please add custom event after start recording");Ul({type:Cl.Custom,data:{tag:S,payload:b}})},record.freezePage=()=>{Al.forEach(S=>S.freeze())},record.takeFullSnapshot=S=>{if(!ql)throw new Error("please take full snapshot after start recording");$l(S)},record.mirror=Wl,(Vl=Hl||(Hl={}))[Vl.NotStarted=0]="NotStarted",Vl[Vl.Running=1]="Running",Vl[Vl.Stopped=2]="Stopped";const Ql=createLogger("RRWeb-Loader");let Kl=null,Gl=null;try{record?(Kl=record,Gl={record:record,addCustomEvent:record.addCustomEvent,freezePage:record.freezePage,takeFullSnapshot:record.takeFullSnapshot,mirror:record.mirror},console.log("%c[TraceScout] ✅ rrweb RECORD bundled","color: #00aa00; font-weight: bold;"),Ql.log("rrweb record() statically imported and ready")):console.error("[TraceScout] ❌ rrweb record import found but not a function")}catch(D){console.error("[TraceScout] ❌ Static rrweb record import failed:",D.message),Ql.warn("Static rrweb record import failed:",D.message)}async function loadRRWeb(){if(!Gl||!Gl.record)throw new Error("rrweb record not available - bundling failed");return Gl}function getRRWeb(){return Gl}function getRecord(){return Kl}function isRRWebLoaded(){return!!Gl}function getRRWebSource(){return{isBundled:!0,source:"bundled",details:"@rrweb/record bundled with SDK",isRecordOnly:!0}}var Jl=Uint8Array,Xl=Uint16Array,Yl=Int32Array,Zl=new Jl([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]),ec=new Jl([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]),tc=new Jl([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(S,b){for(var I=new Xl(31),x=0;x<31;++x)I[x]=b+=1<<S[x-1];var R=new Yl(I[30]);for(x=1;x<30;++x)for(var A=I[x];A<I[x+1];++A)R[A]=A-I[x]<<5|x;return{b:I,r:R}},sc=freb(Zl,2),rc=sc.b,nc=sc.r;rc[28]=258,nc[258]=28;for(var ic=freb(ec,0),oc=ic.b,ac=ic.r,cc=new Xl(32768),uc=0;uc<32768;++uc){var hc=(43690&uc)>>1|(21845&uc)<<1;hc=(61680&(hc=(52428&hc)>>2|(13107&hc)<<2))>>4|(3855&hc)<<4,cc[uc]=((65280&hc)>>8|(255&hc)<<8)>>1}var hMap=function(S,b,I){for(var x=S.length,R=0,A=new Xl(b);R<x;++R)S[R]&&++A[S[R]-1];var _,D=new Xl(b);for(R=1;R<b;++R)D[R]=D[R-1]+A[R-1]<<1;if(I){_=new Xl(1<<b);var L=15-b;for(R=0;R<x;++R)if(S[R])for(var B=R<<4|S[R],U=b-S[R],$=D[S[R]-1]++<<U,j=$|(1<<U)-1;$<=j;++$)_[cc[$]>>L]=B}else for(_=new Xl(x),R=0;R<x;++R)S[R]&&(_[R]=cc[D[S[R]-1]++]>>15-S[R]);return _},dc=new Jl(288);for(uc=0;uc<144;++uc)dc[uc]=8;for(uc=144;uc<256;++uc)dc[uc]=9;for(uc=256;uc<280;++uc)dc[uc]=7;for(uc=280;uc<288;++uc)dc[uc]=8;var gc=new Jl(32);for(uc=0;uc<32;++uc)gc[uc]=5;var pc=hMap(dc,9,0),fc=hMap(dc,9,1),mc=hMap(gc,5,0),yc=hMap(gc,5,1),max=function(S){for(var b=S[0],I=1;I<S.length;++I)S[I]>b&&(b=S[I]);return b},bits=function(S,b,I){var x=b/8|0;return(S[x]|S[x+1]<<8)>>(7&b)&I},bits16=function(S,b){var I=b/8|0;return(S[I]|S[I+1]<<8|S[I+2]<<16)>>(7&b)},shft=function(S){return(S+7)/8|0},slc=function(S,b,I){return(null==b||b<0)&&(b=0),(null==I||I>S.length)&&(I=S.length),new Jl(S.subarray(b,I))},vc=["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"],err=function(S,b,I){var x=new Error(b||vc[S]);if(x.code=S,Error.captureStackTrace&&Error.captureStackTrace(x,err),!I)throw x;return x},wbits=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8},wbits16=function(S,b,I){I<<=7&b;var x=b/8|0;S[x]|=I,S[x+1]|=I>>8,S[x+2]|=I>>16},hTree=function(S,b){for(var I=[],x=0;x<S.length;++x)S[x]&&I.push({s:x,f:S[x]});var R=I.length,A=I.slice();if(!R)return{t:wc,l:0};if(1==R){var _=new Jl(I[0].s+1);return _[I[0].s]=1,{t:_,l:1}}I.sort(function(S,b){return S.f-b.f}),I.push({s:-1,f:25001});var D=I[0],L=I[1],B=0,U=1,$=2;for(I[0]={s:-1,f:D.f+L.f,l:D,r:L};U!=R-1;)D=I[I[B].f<I[$].f?B++:$++],L=I[B!=U&&I[B].f<I[$].f?B++:$++],I[U++]={s:-1,f:D.f+L.f,l:D,r:L};var j=A[0].s;for(x=1;x<R;++x)A[x].s>j&&(j=A[x].s);var W=new Xl(j+1),H=ln(I[U-1],W,0);if(H>b){x=0;var V=0,Q=H-b,G=1<<Q;for(A.sort(function(S,b){return W[b.s]-W[S.s]||S.f-b.f});x<R;++x){var J=A[x].s;if(!(W[J]>b))break;V+=G-(1<<H-W[J]),W[J]=b}for(V>>=Q;V>0;){var X=A[x].s;W[X]<b?V-=1<<b-W[X]++-1:++x}for(;x>=0&&V;--x){var Y=A[x].s;W[Y]==b&&(--W[Y],++V)}H=b}return{t:new Jl(W),l:H}},ln=function(S,b,I){return-1==S.s?Math.max(ln(S.l,b,I+1),ln(S.r,b,I+1)):b[S.s]=I},lc=function(S){for(var b=S.length;b&&!S[--b];);for(var I=new Xl(++b),x=0,R=S[0],A=1,w=function(S){I[x++]=S},_=1;_<=b;++_)if(S[_]==R&&_!=b)++A;else{if(!R&&A>2){for(;A>138;A-=138)w(32754);A>2&&(w(A>10?A-11<<5|28690:A-3<<5|12305),A=0)}else if(A>3){for(w(R),--A;A>6;A-=6)w(8304);A>2&&(w(A-3<<5|8208),A=0)}for(;A--;)w(R);A=1,R=S[_]}return{c:I.subarray(0,x),n:b}},clen=function(S,b){for(var I=0,x=0;x<b.length;++x)I+=S[x]*b[x];return I},wfblk=function(S,b,I){var x=I.length,R=shft(b+2);S[R]=255&x,S[R+1]=x>>8,S[R+2]=255^S[R],S[R+3]=255^S[R+1];for(var A=0;A<x;++A)S[R+A+4]=I[A];return 8*(R+4+x)},wblk=function(S,b,I,x,R,A,_,D,L,B,U){wbits(b,U++,I),++R[256];for(var $=hTree(R,15),j=$.t,W=$.l,H=hTree(A,15),V=H.t,Q=H.l,G=lc(j),J=G.c,X=G.n,Y=lc(V),ee=Y.c,te=Y.n,se=new Xl(19),re=0;re<J.length;++re)++se[31&J[re]];for(re=0;re<ee.length;++re)++se[31&ee[re]];for(var ne=hTree(se,7),ie=ne.t,oe=ne.l,ae=19;ae>4&&!ie[tc[ae-1]];--ae);var le,ce,ue,he,de=B+5<<3,ge=clen(R,dc)+clen(A,gc)+_,pe=clen(R,j)+clen(A,V)+_+14+3*ae+clen(se,ie)+2*se[16]+3*se[17]+7*se[18];if(L>=0&&de<=ge&&de<=pe)return wfblk(b,U,S.subarray(L,L+B));if(wbits(b,U,1+(pe<ge)),U+=2,pe<ge){le=hMap(j,W,0),ce=j,ue=hMap(V,Q,0),he=V;var fe=hMap(ie,oe,0);wbits(b,U,X-257),wbits(b,U+5,te-1),wbits(b,U+10,ae-4),U+=14;for(re=0;re<ae;++re)wbits(b,U+3*re,ie[tc[re]]);U+=3*ae;for(var me=[J,ee],ye=0;ye<2;++ye){var ve=me[ye];for(re=0;re<ve.length;++re){var Se=31&ve[re];wbits(b,U,fe[Se]),U+=ie[Se],Se>15&&(wbits(b,U,ve[re]>>5&127),U+=ve[re]>>12)}}}else le=pc,ce=dc,ue=mc,he=gc;for(re=0;re<D;++re){var we=x[re];if(we>255){wbits16(b,U,le[(Se=we>>18&31)+257]),U+=ce[Se+257],Se>7&&(wbits(b,U,we>>23&31),U+=Zl[Se]);var be=31&we;wbits16(b,U,ue[be]),U+=he[be],be>3&&(wbits16(b,U,we>>5&8191),U+=ec[be])}else wbits16(b,U,le[we]),U+=ce[we]}return wbits16(b,U,le[256]),U+ce[256]},Sc=new Yl([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),wc=new Jl(0),adler=function(){var S=1,b=0;return{p:function(I){for(var x=S,R=b,A=0|I.length,_=0;_!=A;){for(var D=Math.min(_+2655,A);_<D;++_)R+=x+=I[_];x=(65535&x)+15*(x>>16),R=(65535&R)+15*(R>>16)}S=x,b=R},d:function(){return(255&(S%=65521))<<24|(65280&S)<<8|(255&(b%=65521))<<8|b>>8}}},dopt=function(S,b,I,x,R){if(!R&&(R={l:1},b.dictionary)){var A=b.dictionary.subarray(-32768),_=new Jl(A.length+S.length);_.set(A),_.set(S,A.length),S=_,R.w=A.length}return function(S,b,I,x,R,A){var _=A.z||S.length,D=new Jl(x+_+5*(1+Math.ceil(_/7e3))+R),L=D.subarray(x,D.length-R),B=A.l,U=7&(A.r||0);if(b){U&&(L[0]=A.r>>3);for(var $=Sc[b-1],j=$>>13,W=8191&$,H=(1<<I)-1,V=A.p||new Xl(32768),Q=A.h||new Xl(H+1),G=Math.ceil(I/3),J=2*G,hsh=function(b){return(S[b]^S[b+1]<<G^S[b+2]<<J)&H},X=new Yl(25e3),Y=new Xl(288),ee=new Xl(32),te=0,se=0,re=A.i||0,ne=0,ie=A.w||0,oe=0;re+2<_;++re){var ae=hsh(re),le=32767&re,ce=Q[ae];if(V[le]=ce,Q[ae]=le,ie<=re){var ue=_-re;if((te>7e3||ne>24576)&&(ue>423||!B)){U=wblk(S,L,0,X,Y,ee,se,ne,oe,re-oe,U),ne=te=se=0,oe=re;for(var he=0;he<286;++he)Y[he]=0;for(he=0;he<30;++he)ee[he]=0}var de=2,ge=0,pe=W,fe=le-ce&32767;if(ue>2&&ae==hsh(re-fe))for(var me=Math.min(j,ue)-1,ye=Math.min(32767,re),ve=Math.min(258,ue);fe<=ye&&--pe&&le!=ce;){if(S[re+de]==S[re+de-fe]){for(var Se=0;Se<ve&&S[re+Se]==S[re+Se-fe];++Se);if(Se>de){if(de=Se,ge=fe,Se>me)break;var we=Math.min(fe,Se-2),be=0;for(he=0;he<we;++he){var Ce=re-fe+he&32767,ke=Ce-V[Ce]&32767;ke>be&&(be=ke,ce=Ce)}}}fe+=(le=ce)-(ce=V[le])&32767}if(ge){X[ne++]=268435456|nc[de]<<18|ac[ge];var Ie=31&nc[de],Ee=31&ac[ge];se+=Zl[Ie]+ec[Ee],++Y[257+Ie],++ee[Ee],ie=re+de,++te}else X[ne++]=S[re],++Y[S[re]]}}for(re=Math.max(re,ie);re<_;++re)X[ne++]=S[re],++Y[S[re]];U=wblk(S,L,B,X,Y,ee,se,ne,oe,re-oe,U),B||(A.r=7&U|L[U/8|0]<<3,U-=7,A.h=Q,A.p=V,A.i=re,A.w=ie)}else{for(re=A.w||0;re<_+B;re+=65535){var xe=re+65535;xe>=_&&(L[U/8|0]=B,xe=_),U=wfblk(L,U+1,S.subarray(re,xe))}A.i=_}return slc(D,0,x+shft(U)+R)}(S,null==b.level?6:b.level,null==b.mem?R.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(S.length)))):20:12+b.mem,I,x,R)},wbytes=function(S,b,I){for(;I;++b)S[b]=I,I>>>=8};function zlibSync(S,b){b||(b={});var I=adler();I.p(S);var x=dopt(S,b,b.dictionary?6:2,4);return function(S,b){var I=b.level,x=0==I?0:I<6?1:9==I?3:2;if(S[0]=120,S[1]=x<<6|(b.dictionary&&32),S[1]|=31-(S[0]<<8|S[1])%31,b.dictionary){var R=adler();R.p(b.dictionary),wbytes(S,2,R.d())}}(x,b),wbytes(x,x.length-4,I.d()),x}function unzlibSync(S,b){return function(S,b,I,x){var R=S.length,A=x?x.length:0;if(!R||b.f&&!b.l)return I||new Jl(0);var _=!I,D=_||2!=b.i,L=b.i;_&&(I=new Jl(3*R));var cbuf=function(S){var b=I.length;if(S>b){var x=new Jl(Math.max(2*b,S));x.set(I),I=x}},B=b.f||0,U=b.p||0,$=b.b||0,j=b.l,W=b.d,H=b.m,V=b.n,Q=8*R;do{if(!j){B=bits(S,U,1);var G=bits(S,U+1,3);if(U+=3,!G){var J=S[(le=shft(U)+4)-4]|S[le-3]<<8,X=le+J;if(X>R){L&&err(0);break}D&&cbuf($+J),I.set(S.subarray(le,X),$),b.b=$+=J,b.p=U=8*X,b.f=B;continue}if(1==G)j=fc,W=yc,H=9,V=5;else if(2==G){var Y=bits(S,U,31)+257,ee=bits(S,U+10,15)+4,te=Y+bits(S,U+5,31)+1;U+=14;for(var se=new Jl(te),re=new Jl(19),ne=0;ne<ee;++ne)re[tc[ne]]=bits(S,U+3*ne,7);U+=3*ee;var ie=max(re),oe=(1<<ie)-1,ae=hMap(re,ie,1);for(ne=0;ne<te;){var le,ce=ae[bits(S,U,oe)];if(U+=15&ce,(le=ce>>4)<16)se[ne++]=le;else{var ue=0,he=0;for(16==le?(he=3+bits(S,U,3),U+=2,ue=se[ne-1]):17==le?(he=3+bits(S,U,7),U+=3):18==le&&(he=11+bits(S,U,127),U+=7);he--;)se[ne++]=ue}}var de=se.subarray(0,Y),ge=se.subarray(Y);H=max(de),V=max(ge),j=hMap(de,H,1),W=hMap(ge,V,1)}else err(1);if(U>Q){L&&err(0);break}}D&&cbuf($+131072);for(var pe=(1<<H)-1,fe=(1<<V)-1,me=U;;me=U){var ye=(ue=j[bits16(S,U)&pe])>>4;if((U+=15&ue)>Q){L&&err(0);break}if(ue||err(2),ye<256)I[$++]=ye;else{if(256==ye){me=U,j=null;break}var ve=ye-254;if(ye>264){var Se=Zl[ne=ye-257];ve=bits(S,U,(1<<Se)-1)+rc[ne],U+=Se}var we=W[bits16(S,U)&fe],be=we>>4;if(we||err(3),U+=15&we,ge=oc[be],be>3&&(Se=ec[be],ge+=bits16(S,U)&(1<<Se)-1,U+=Se),U>Q){L&&err(0);break}D&&cbuf($+131072);var Ce=$+ve;if($<ge){var ke=A-ge,Ie=Math.min(ge,Ce);for(ke+$<0&&err(3);$<Ie;++$)I[$]=x[ke+$]}for(;$<Ce;++$)I[$]=I[$-ge]}}b.l=j,b.p=me,b.b=$,b.f=B,j&&(B=1,b.m=H,b.d=W,b.n=V)}while(!B);return $!=I.length&&_?slc(I,0,$):I.subarray(0,$)}(S.subarray(function(S,b){return(8!=(15&S[0])||S[0]>>4>7||(S[0]<<8|S[1])%31)&&err(6,"invalid zlib data"),(S[1]>>5&1)==+!b&&err(6,"invalid zlib data: "+(32&S[1]?"need":"unexpected")+" dictionary"),2+(S[1]>>3&4)}(S,b&&b.dictionary),-4),{i:2},b&&b.out,b&&b.dictionary)}var bc="undefined"!=typeof TextEncoder&&new TextEncoder,Cc="undefined"!=typeof TextDecoder&&new TextDecoder;try{Cc.decode(wc,{stream:!0})}catch(D){}function strToU8(S,b){if(b){for(var I=new Jl(S.length),x=0;x<S.length;++x)I[x]=S.charCodeAt(x);return I}if(bc)return bc.encode(S);var R=S.length,A=new Jl(S.length+(S.length>>1)),_=0,w=function(S){A[_++]=S};for(x=0;x<R;++x){if(_+5>A.length){var D=new Jl(_+8+(R-x<<1));D.set(A),A=D}var L=S.charCodeAt(x);L<128||b?w(L):L<2048?(w(192|L>>6),w(128|63&L)):L>55295&&L<57344?(w(240|(L=65536+(1047552&L)|1023&S.charCodeAt(++x))>>18),w(128|L>>12&63),w(128|L>>6&63),w(128|63&L)):(w(224|L>>12),w(128|L>>6&63),w(128|63&L))}return slc(A,0,_)}function strFromU8(S,b){if(b){for(var I="",x=0;x<S.length;x+=16384)I+=String.fromCharCode.apply(null,S.subarray(x,x+16384));return I}if(Cc)return Cc.decode(S);var R=function(S){for(var b="",I=0;;){var x=S[I++],R=(x>127)+(x>223)+(x>239);if(I+R>S.length)return{s:b,r:slc(S,I-1)};R?3==R?(x=((15&x)<<18|(63&S[I++])<<12|(63&S[I++])<<6|63&S[I++])-65536,b+=String.fromCharCode(55296|x>>10,56320|1023&x)):b+=1&R?String.fromCharCode((31&x)<<6|63&S[I++]):String.fromCharCode((15&x)<<12|(63&S[I++])<<6|63&S[I++]):b+=String.fromCharCode(x)}}(S),A=R.s;return(I=R.r).length&&err(8),A}const kc=["token","key","secret","password","auth","api_key","apikey","access_token","refresh_token","jwt","bearer","credential","session_id","session","sid","ssid","private_token"];function sanitizeUrl(S){if(!S)return"";try{const b=new URL(S);for(const S of kc)b.searchParams.delete(S),b.searchParams.delete(S.toLowerCase()),b.searchParams.delete(S.toUpperCase());return b.toString()}catch{return S.replace(/[?&](token|key|secret|password|auth|api_key|apikey|access_token|jwt)=[^&]*/gi,"$1=[REDACTED]")}}function hashCode(S){let b=0;for(let I=0;I<S.length;I++){b=(b<<5)-b+S.charCodeAt(I),b&=b}return Math.abs(b).toString(36)}function generateNetworkId(S,b,I,x){return`net_${b}_${hashCode(sanitizeUrl(x))}`}function generateConsoleId(S,b,I){return`log_${b}_${hashCode(String(I||"").substring(0,100))}`}function generateResourceId(S,b){return`res_${S}_${hashCode(b)}`}function flatNetworkFields(S){const b=S||{},I=b.requestUrl||b.url||"";return{method:b.method,url:I,status:"number"==typeof b.status?b.status:b.statusCode,duration:"number"==typeof b.durationMs?b.durationMs:b.duration,size:"number"==typeof b.responseSize?b.responseSize:b.size,error:b.error||b.errorMessage,resourceType:b.resourceType||(I?getResourceType(I):void 0)}}function extractNetworkRef(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=flatNetworkFields(S.data?.payload),R=sanitizeUrl(x.url),A={networkId:generateNetworkId(0,S.timestamp,x.method,R),timestamp:S.timestamp,method:x.method||"GET",url:R,status:x.status,duration:x.duration,size:x.size,type:I.replace("network_","")};return"network_resource"===I&&x.resourceType&&(A.resourceType=x.resourceType),A}function extractConsoleRef(S,b){if(5!==S.type)return null;if("console"!==S.data?.tag)return null;const I=S.data?.payload||{};let x="";I.args&&Array.isArray(I.args)?x=JSON.stringify(I.args).substring(0,100):I.message&&(x=String(I.message).substring(0,100));const R=generateConsoleId(0,S.timestamp,x);let A="";return I.message?(A=String(I.message).slice(0,100),I.message.length>100&&(A+="...")):I.args&&Array.isArray(I.args)&&(A=I.args.map(S=>String(S)).join(" ").slice(0,100),A.length>=100&&(A+="...")),{consoleId:R,timestamp:S.timestamp,level:I.level||"log",preview:A}}function extractResourceRef(S){if(5!==S.type)return null;if("network_resource"!==S.data?.tag)return null;const b=S.data?.payload||{};return{resourceId:generateResourceId(S.timestamp,b.url||""),timestamp:S.timestamp,method:b.method||"GET",url:b.url||"",status:b.status||0,resourceType:b.resourceType||"other",size:b.size||null,duration:b.duration||null}}function extractNetworkFull(S,b){if(5!==S.type)return null;const I=S.data?.tag;if(!I||!I.startsWith("network_"))return null;const x=S.data?.payload||{},R=flatNetworkFields(x),A=sanitizeUrl(R.url);return{id:generateNetworkId(0,S.timestamp,R.method,A),timestamp:S.timestamp,method:R.method||"GET",url:A,requestHeaders:x.requestHeaders||{},requestBody:x.requestBody||null,status:R.status,statusText:x.statusText,responseHeaders:x.responseHeaders||{},responseBody:x.responseBody||null,duration:R.duration,size:R.size,timing:x.timing,error:R.error}}function stripNetworkPayload(S){if(5!==S.type)return S;const b=S.data?.tag;if(!b||!b.startsWith("network_"))return S;const I=flatNetworkFields(S.data?.payload);return{...S,data:{tag:S.data.tag,payload:{method:I.method,url:I.url,status:I.status,duration:I.duration,size:I.size,resourceType:I.resourceType,error:I.error}}}}function extractVersion(S,b){const I=S.match(b);return I?I[1]:"unknown"}function parseBrowserInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";return b.includes("edg/")?(I="Edge",x=extractVersion(S,/edg\/(\d+(\.\d+)?)/i)):b.includes("chrome")&&!b.includes("chromium")?(I="Chrome",x=extractVersion(S,/chrome\/(\d+(\.\d+)?)/i)):b.includes("firefox")?(I="Firefox",x=extractVersion(S,/firefox\/(\d+(\.\d+)?)/i)):b.includes("safari")&&!b.includes("chrome")?(I="Safari",x=extractVersion(S,/version\/(\d+(\.\d+)?)/i)):b.includes("opera")||b.includes("opr")?(I="Opera",x=extractVersion(S,/(?:opera|opr)\/(\d+(\.\d+)?)/i)):(b.includes("msie")||b.includes("trident"))&&(I="IE",x=extractVersion(S,/(?:msie |rv:)(\d+(\.\d+)?)/i)),{name:I,version:x}}function parseOSInfo(S){if(!S)return{name:"unknown",version:"unknown"};const b=S.toLowerCase();let I="unknown",x="unknown";if(b.includes("windows"))I="Windows",b.includes("windows nt 10")?x="10":b.includes("windows nt 6.3")?x="8.1":b.includes("windows nt 6.2")?x="8":b.includes("windows nt 6.1")&&(x="7");else if(b.includes("mac os x")){I="macOS";const b=S.match(/mac os x (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else if(b.includes("android"))I="Android",x=extractVersion(S,/android (\d+(\.\d+)?)/i);else if(b.includes("iphone")||b.includes("ipad")||b.includes("ipod")){I="iOS";const b=S.match(/os (\d+[._]\d+)/i);b&&(x=b[1].replace("_","."))}else b.includes("linux")&&(I="Linux");return{name:I,version:x}}function detectDeviceType(S){if(!S)return"desktop";const b=S.toLowerCase();return/mobile|android|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(b)?/ipad|tablet/i.test(b)||b.includes("android")&&!b.includes("mobile")?"tablet":"mobile":"desktop"}function detectTouchCapability(){return"undefined"!=typeof window&&("ontouchstart"in window||"undefined"!=typeof navigator&&navigator.maxTouchPoints>0)}function getConnectionInfo(){if("undefined"==typeof navigator||!navigator.connection)return null;const S=navigator.connection;return{effectiveType:S.effectiveType||null,downlink:S.downlink||null,rtt:S.rtt||null,saveData:S.saveData||!1}}function getMemoryInfo(){return"undefined"!=typeof navigator&&navigator.deviceMemory?{deviceMemory:navigator.deviceMemory}:null}function collectDeviceMetadata(){const S="undefined"!=typeof navigator?navigator.userAgent:null;return{screen:{width:"undefined"!=typeof screen?screen.width:null,height:"undefined"!=typeof screen?screen.height:null,colorDepth:"undefined"!=typeof screen?screen.colorDepth:null,pixelRatio:"undefined"!=typeof window?window.devicePixelRatio:null},viewport:{width:"undefined"!=typeof window?window.innerWidth:null,height:"undefined"!=typeof window?window.innerHeight:null},userAgent:S,language:"undefined"!=typeof navigator?navigator.language:null,languages:"undefined"!=typeof navigator?navigator.languages:null,platform:"undefined"!=typeof navigator?navigator.platform:null,connection:getConnectionInfo(),deviceType:detectDeviceType(S),touchCapable:detectTouchCapability(),memory:getMemoryInfo(),browser:parseBrowserInfo(S),os:parseOSInfo(S)}}function analyzeSnapshotsInEvents(S){const b=[];let I=-1;for(let x=0;x<S.length;x++){const R=S[x];2===R.type&&(b.push(R.timestamp),-1===I&&(I=x))}return{hasSnapshot:b.length>0,snapshotCount:b.length,snapshotTimestamps:b,firstSnapshotIndex:I}}function buildSnapshotIndex(S){const b=[];for(const I of S)if(I.snapshotInfo?.hasSnapshot)for(let S=0;S<I.events.length;S++){const x=I.events[S];2===x.type&&b.push({chunkSequence:I.sequence,timestamp:x.timestamp,eventIndex:S})}return b.sort((S,b)=>S.timestamp-b.timestamp),b}function findNearestSnapshotBefore(S,b){if(!S||0===S.length)return null;let I=0,x=S.length-1,R=null;for(;I<=x;){const A=Math.floor((I+x)/2),_=S[A];_.timestamp<=b?(R=_,I=A+1):x=A-1}return R}function getEventsAfterSnapshot(S,b,I){if(!S||!S.events)return[];const x=[];for(let R=b;R<S.events.length;R++){const b=S.events[R];if(!(b.timestamp<=I))break;x.push(b)}return x}function chunkHasSnapshot(S){return!0===S?.snapshotInfo?.hasSnapshot}function getSnapshotTimestamps(S){return S?.snapshotInfo?.snapshotTimestamps||[]}function createChunk(S){const{sequence:b,sessionId:I,events:x=[],networkRefs:R=[],consoleRefs:A=[],networkFullData:_=[],metadata:D={},isFirstChunk:L=!1,isLastChunk:B=!1}=S,U=x.map(S=>S.timestamp).filter(S=>"number"==typeof S),$=U.length>0?Math.min(...U):Date.now(),j=U.length>0?Math.max(...U):Date.now(),W=analyzeSnapshotsInEvents(x);return{version:4,chunkId:I?`${I}_chunk_${b}`:`chunk_${b}_${Date.now()}`,sequence:b,sessionId:I,startTimestamp:$,endTimestamp:j,eventCount:x.length,events:x,networkRefs:R,consoleRefs:A,networkFullData:_,snapshotInfo:{hasSnapshot:W.hasSnapshot,snapshotCount:W.snapshotCount,snapshotTimestamps:W.snapshotTimestamps,firstSnapshotIndex:W.firstSnapshotIndex},metadata:{...D,createdAt:Date.now(),isFirstChunk:L,isLastChunk:B,hasSnapshotInChunk:W.hasSnapshot}}}function isCompatibleVersion(S){return 4===S.version}class InactivityManager{constructor(S={}){this.inactivityTimeout=S.inactivityTimeout||3e5,this.maxInactivityDuration=S.maxInactivityDuration||18e5,this.maxSessionDuration=S.maxSessionDuration||36e5,this.enabled=!1!==S.enableInactivityDetection,this.lastActivityTime=Date.now(),this.isPaused=!1,this.pauseStartTime=null,this.totalPausedTime=0,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.inactivityTimer=null,this.sessionEndTimer=null,this.onPause=S.onPause||(()=>{}),this.onResume=S.onResume||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.enabled&&(this.lastActivityTime=Date.now(),this.sessionStartTime=Date.now(),this.totalPausedTime=0,this.isPaused=!1,this.sessionEnded=!1,this.sessionEndReason=null,this.resetInactivityTimer(),this.logger.info?.(`[Inactivity] Detection enabled: pause after ${this.inactivityTimeout/1e3}s, end session after ${this.maxInactivityDuration/1e3}s`))}stop(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null)}trackActivity(S){if(!this.enabled)return;this.isUserActivityEvent(S)&&(this.lastActivityTime=Date.now(),this.isPaused&&this.resumeFromInactivity(),this.resetInactivityTimer())}isUserActivityEvent(S){if(3===S.type&&S.data){return[1,2,3,5,6,7].includes(S.data.source)}return!1}resetInactivityTimer(){if(Date.now()-this.sessionStartTime>this.maxSessionDuration)return this.logger.warn?.(`[Inactivity] Max session duration (${Math.round(this.maxSessionDuration/6e4)}min) exceeded - ending session`),void this.onMaxSessionDurationReached();this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout(()=>{this.onInactivityTimeout()},this.inactivityTimeout)}onInactivityTimeout(){if(this.isPaused)return;const S=Date.now()-this.lastActivityTime;this.logger.info?.(`[Inactivity] User inactive for ${Math.round(S/1e3)}s - pausing recording`),this.pauseForInactivity(),this.sessionEndTimer=setTimeout(()=>{this.onMaxInactivityReached()},this.maxInactivityDuration-this.inactivityTimeout)}pauseForInactivity(){this.isPaused||(this.isPaused=!0,this.pauseStartTime=Date.now(),this.onAddCustomEvent("inactivity",{action:"pause",inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}),this.logger.info?.("[Inactivity] Recording paused - waiting for user activity"),this.onPause({inactiveFor:Date.now()-this.lastActivityTime,timestamp:Date.now()}))}resumeFromInactivity(){if(!this.isPaused)return;const S=Date.now()-this.pauseStartTime;this.totalPausedTime+=S;const b=Date.now()-this.sessionStartTime;if(b>this.maxSessionDuration)return this.logger.warn?.("[Inactivity] Max session duration exceeded during pause - ending session"),void this.onMaxSessionDurationReached();this.isPaused=!1,this.pauseStartTime=null,this.sessionEndTimer&&(clearTimeout(this.sessionEndTimer),this.sessionEndTimer=null),this.onAddCustomEvent("inactivity",{action:"resume",pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()}),this.logger.info?.(`[Inactivity] Recording resumed after ${Math.round(S/1e3)}s pause (session: ${Math.round(b/6e4)}min)`),this.onResume({pauseDuration:S,totalPausedTime:this.totalPausedTime,sessionDuration:b,timestamp:Date.now()})}onMaxInactivityReached(){const S=Date.now()-this.lastActivityTime,b=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Inactivity] Max inactivity (${Math.round(S/1e3)}s) reached - ending session`),this.onAddCustomEvent("inactivity",{action:"session_ended",reason:"max_inactivity",inactiveFor:S,sessionDuration:b,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_inactivity")}onMaxSessionDurationReached(){const S=Date.now()-this.sessionStartTime;this.logger.warn?.(`[Session] Max duration (${Math.round(S/6e4)}min) reached - ending session`),this.onAddCustomEvent("session_lifecycle",{action:"session_ended",reason:"max_duration",sessionDuration:S,totalPausedTime:this.totalPausedTime,timestamp:Date.now()}),this.endSession("max_duration")}endSession(S="manual"){this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.onSessionEnd({reason:S,duration:Date.now()-this.sessionStartTime,totalPausedTime:this.totalPausedTime})}shouldRecordEvent(S){return!this.isPaused||5===S.type}getState(){return{enabled:this.enabled,isPaused:this.isPaused,sessionEnded:this.sessionEnded,sessionEndReason:this.sessionEndReason,lastActivityTime:this.lastActivityTime,totalPausedTime:this.totalPausedTime,sessionDuration:Date.now()-this.sessionStartTime,timeSinceLastActivity:Date.now()-this.lastActivityTime}}updateConfig(S){void 0!==S.inactivityTimeout&&(this.inactivityTimeout=S.inactivityTimeout),void 0!==S.maxInactivityDuration&&(this.maxInactivityDuration=S.maxInactivityDuration),void 0!==S.maxSessionDuration&&(this.maxSessionDuration=S.maxSessionDuration),void 0!==S.enableInactivityDetection&&(this.enabled=S.enableInactivityDetection)}destroy(){this.stop(),this.onPause=null,this.onResume=null,this.onSessionEnd=null,this.onAddCustomEvent=null,this.logger=null}}class PageLifecycleManager{constructor(S={}){this.onFlush=S.onFlush||(()=>{}),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.onSendBeacon=S.onSendBeacon||(()=>{}),this.getIsRecording=S.getIsRecording||(()=>!1),this.getCurrentChunkLength=S.getCurrentChunkLength||(()=>0),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.logger=S.logger||console,this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this._pageCloseFlushAttempted=!1}setup(){"undefined"!=typeof window&&(this._pageCloseFlushAttempted=!1,this._boundBeforeUnload=this._handleBeforeUnload.bind(this),this._boundPageHide=this._handlePageHide.bind(this),this._boundVisibilityChange=this._handleVisibilityChange.bind(this),window.addEventListener("beforeunload",this._boundBeforeUnload),window.addEventListener("pagehide",this._boundPageHide),document.addEventListener("visibilitychange",this._boundVisibilityChange),this.logger.info?.("[PageLifecycle] Page close handlers installed"))}remove(){"undefined"!=typeof window&&(this._boundBeforeUnload&&window.removeEventListener("beforeunload",this._boundBeforeUnload),this._boundPageHide&&window.removeEventListener("pagehide",this._boundPageHide),this._boundVisibilityChange&&document.removeEventListener("visibilitychange",this._boundVisibilityChange),this._boundBeforeUnload=null,this._boundPageHide=null,this._boundVisibilityChange=null,this.logger.info?.("[PageLifecycle] Page close handlers removed"))}_handleBeforeUnload(S){this._flushOnPageClose("beforeunload")}_handlePageHide(S){this._flushOnPageClose("pagehide",S.persisted)}_handleVisibilityChange(){"hidden"===document.visibilityState&&this._flushOnPageClose("visibilitychange")}_flushOnPageClose(S,b=!1){if(this._pageCloseFlushAttempted)return void this.logger.log?.(`[PageLifecycle] Flush already attempted, skipping duplicate (${S})`);const I=this.getIsRecording(),x=this.getCurrentChunkLength();if(!I||0===x)return void this.logger.log?.(`[PageLifecycle] No pending events to flush on ${S}`);this._pageCloseFlushAttempted=!0,this.logger.log?.(`[PageLifecycle] Flushing ${x} events on ${S}`),this.onAddCustomEvent("session_lifecycle",{action:"page_close",trigger:S,persisted:b,timestamp:Date.now(),pendingEvents:x,sessionDuration:Date.now()-this.getSessionStartTime(),totalChunks:this.getChunkCounter()});const R=this.onFlush();R&&(R.metadata=R.metadata||{},R.metadata.isLastChunk=!0,R.metadata.closeTrigger=S,R.metadata.sessionEndedGracefully=!0,this.onSendBeacon(R,S))}resetFlushGuard(){this._pageCloseFlushAttempted=!1}getState(){return{handlersInstalled:null!==this._boundBeforeUnload,flushAttempted:this._pageCloseFlushAttempted}}destroy(){this.remove(),this.onFlush=null,this.onAddCustomEvent=null,this.onSendBeacon=null,this.getIsRecording=null,this.getCurrentChunkLength=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.logger=null}}class CheckpointManager{constructor(S={}){this.checkpointInterval=S.checkpointInterval||6e4,this.lastCheckpointTime=0,this.checkpointTimer=null,this.checkpointCount=0,this.checkpointAvailable=null,this.getRRWeb=S.getRRWeb||(()=>null),this.getIsRecording=S.getIsRecording||(()=>!1),this.getSessionStartTime=S.getSessionStartTime||(()=>Date.now()),this.getChunkCounter=S.getChunkCounter||(()=>0),this.getEventCount=S.getEventCount||(()=>0),this.onAddCustomEvent=S.onAddCustomEvent||(()=>{}),this.logger=S.logger||console}start(){this.checkpointTimer&&clearInterval(this.checkpointTimer),this.lastCheckpointTime=Date.now(),this.checkpointCount=0,this.checkpointTimer=setInterval(()=>{this.requestCheckpoint()},this.checkpointInterval),this.logger.info?.(`[Checkpoint] Timer started (interval: ${this.checkpointInterval/1e3}s)`)}stop(){this.checkpointTimer&&(clearInterval(this.checkpointTimer),this.checkpointTimer=null)}requestCheckpoint(){if(!this.getIsRecording())return;const S=Date.now();if(!(S-this.lastCheckpointTime<.9*this.checkpointInterval))try{const b=this.getRRWeb();let I=null;if(b&&("function"==typeof b.takeFullSnapshot?I=b.takeFullSnapshot:b.record&&"function"==typeof b.record.takeFullSnapshot&&(I=b.record.takeFullSnapshot)),I)try{I(),this.lastCheckpointTime=S,this.checkpointAvailable=!0,this.checkpointCount++,this.onAddCustomEvent("checkpoint",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),checkpointNumber:this.checkpointCount,snapshotRequested:!0}),this.logger.info?.(`[Checkpoint] #${this.checkpointCount} at ${Math.round((S-this.getSessionStartTime())/1e3)}s`)}catch(b){this.logger.warn?.("[Checkpoint] takeFullSnapshot error:",b.message),this.checkpointAvailable=!1,this._addCheckpointMarker(S,"takeFullSnapshot error: "+b.message)}else!1!==this.checkpointAvailable&&(this.logger.warn?.("[Checkpoint] Manual snapshots not available - relying on rrweb checkoutEveryNms"),this.checkpointAvailable=!1),this._addCheckpointMarker(S,"using rrweb auto-checkout")}catch(S){this.logger.warn?.("[Checkpoint] Request failed:",S.message),this._addCheckpointMarker(Date.now(),"Error: "+S.message)}}_addCheckpointMarker(S,b){this.onAddCustomEvent("checkpoint_marker",{timestamp:S,sessionDuration:S-this.getSessionStartTime(),chunkIndex:this.getChunkCounter(),eventCount:this.getEventCount(),snapshotRequested:!1,reason:b})}takeManualCheckpoint(){this.logger.info?.("[Checkpoint] Manual checkpoint requested"),this.requestCheckpoint()}getState(){return{checkpointCount:this.checkpointCount,lastCheckpointTime:this.lastCheckpointTime,checkpointAvailable:this.checkpointAvailable,checkpointInterval:this.checkpointInterval,timerRunning:null!==this.checkpointTimer}}updateConfig(S){void 0!==S.checkpointInterval&&(this.checkpointInterval=S.checkpointInterval,this.checkpointTimer&&(this.stop(),this.start()))}destroy(){this.stop(),this.getRRWeb=null,this.getIsRecording=null,this.getSessionStartTime=null,this.getChunkCounter=null,this.getEventCount=null,this.onAddCustomEvent=null,this.logger=null}}class RecorderMemoryManager{constructor(S={}){this.maxChunksInMemory=S.maxChunksInMemory||10,this.maxEventsPerSession=S.maxEventsPerSession||5e4,this.maxSessionBytes=S.maxSessionBytes||52428800,this.maxEventsInBuffer=S.maxEventsInBuffer||2e3,this.cleanupInterval=S.cleanupInterval||6e4,this.totalSessionBytes=0,this.cleanupTimer=null,this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=S.onForceFlush||(()=>{}),this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setDataReferences(S){this._allChunks=S.allChunks||null,this._events=S.events||null,this._eventDedupeCache=S.eventDedupeCache||null,this._eventStats=S.eventStats||null}start(){this.cleanupTimer||(this.totalSessionBytes=0,this.cleanupTimer=setInterval(()=>{this.performCleanup()},this.cleanupInterval),this.logger.log?.("[Memory] Started periodic cleanup (60s interval)"))}stop(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.logger.log?.("[Memory] Stopped cleanup timer"))}trackBytes(S){return this.totalSessionBytes+=S,!(this.totalSessionBytes>this.maxSessionBytes)||(this.logger.warn?.(`[Memory] Session size limit reached (${Math.round(this.totalSessionBytes/1024/1024)}MB / ${Math.round(this.maxSessionBytes/1024/1024)}MB)`),!1)}checkEventLimit(S){return!(S>this.maxEventsPerSession)||(this.logger.warn?.(`[Memory] Max events per session (${this.maxEventsPerSession}) exceeded`),!1)}performCleanup(){const S=Date.now();let b={dedupeEntries:0,statsEvents:0,chunks:0,eventsBuffer:0};if(this._eventDedupeCache){const I=S-1e4;for(const[S,x]of this._eventDedupeCache.entries())x<I&&(this._eventDedupeCache.delete(S),b.dedupeEntries++)}if(this._eventStats?.lastMinuteEvents){const I=S-6e4,x=this._eventStats.lastMinuteEvents.length;this._eventStats.lastMinuteEvents=this._eventStats.lastMinuteEvents.filter(S=>S>I),b.statsEvents=x-this._eventStats.lastMinuteEvents.length}if(this._allChunks&&this._allChunks.length>this.maxChunksInMemory)for(;this._allChunks.length>this.maxChunksInMemory;)this._allChunks.shift(),b.chunks++;return this._events&&this._events.length>this.maxEventsInBuffer&&(this.logger.warn?.(`[Memory] Events buffer exceeded ${this.maxEventsInBuffer}, forcing flush`),this.onForceFlush()),(b.dedupeEntries>0||b.statsEvents>0||b.chunks>0)&&this.logger.log?.(`[Memory] Cleanup: ${b.dedupeEntries} dedupe entries, ${b.statsEvents} stat entries, ${b.chunks} chunks`),b}trimEventsArray(S=1e3){if(!this._events||this._events.length<=S)return 0;const b=this._events.length-S;return this._events.splice(0,b),this.logger.log&&this.logger.log?.(`[Memory] Cleared ${b} old events from events array`),b}trimChunksArray(){if(!this._allChunks||this._allChunks.length<=this.maxChunksInMemory)return null;const S=this._allChunks.shift();return this.logger.log?.(`[Memory] Removed old chunk ${S?.sequence} from memory (keeping ${this.maxChunksInMemory} chunks)`),S}getStats(){return{eventsInBuffer:this._events?.length||0,maxEventsInBuffer:this.maxEventsInBuffer,chunksInMemory:this._allChunks?.length||0,maxChunksInMemory:this.maxChunksInMemory,dedupeCacheSize:this._eventDedupeCache?.size||0,totalSessionBytes:this.totalSessionBytes,maxSessionBytes:this.maxSessionBytes,sessionSizePercent:Math.round(this.totalSessionBytes/this.maxSessionBytes*100),statsEventsTracked:this._eventStats?.lastMinuteEvents?.length||0,totalEventsRecorded:this._eventStats?.total||0,estimatedMemoryMB:this.estimateMemoryUsage()}}estimateMemoryUsage(){let S=0;if(S+=500*(this._events?.length||0),this._allChunks)for(const b of this._allChunks)S+=b.sizeBytes||5e4;return S+=100*(this._eventDedupeCache?.size||0),Math.round(S/1048576*100)/100}suggestGC(){if(this._allChunks)for(const S of this._allChunks)S._rawEvents&&(S._rawEvents=null);this.logger.log?.("[Memory] GC hint sent")}updateConfig(S){void 0!==S.maxChunksInMemory&&(this.maxChunksInMemory=S.maxChunksInMemory),void 0!==S.maxEventsPerSession&&(this.maxEventsPerSession=S.maxEventsPerSession),void 0!==S.maxSessionBytes&&(this.maxSessionBytes=S.maxSessionBytes),void 0!==S.maxEventsInBuffer&&(this.maxEventsInBuffer=S.maxEventsInBuffer)}reset(){this.totalSessionBytes=0}destroy(){this.stop(),this._allChunks=null,this._events=null,this._eventDedupeCache=null,this._eventStats=null,this.onForceFlush=null,this.onSessionEnd=null,this.logger=null}}const Ic={0:"DomContentLoaded",1:"Load",2:"FullSnapshot",3:"IncrementalSnapshot",4:"Meta",5:"Custom"};class EventOptimizer{constructor(S={}){this.samplingEnabled=S.enableSampling||!1,this.deduplicationEnabled=S.enableDeduplication||!1,this.mousemoveSampling=S.mousemoveSampling||1,this.scrollSampling=S.scrollSampling||1,this.mutationSampling=S.mutationSampling||1,this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0},this.eventDedupeCache=new Map,this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.logger=S.logger||console}getDedupeCache(){return this.eventDedupeCache}getEventStats(){return this.eventStats}shouldRecordEvent(S){const b=this.getEventTypeName(S.type);return!!["DomContentLoaded","Load","FullSnapshot","Meta","Custom"].includes(b)||!(this.samplingEnabled&&!this._applySampling(S))&&(!this.deduplicationEnabled||!this._isDuplicateEvent(S))}updateStats(S){this.eventStats.total++;const b=this.getEventTypeName(S.type);this.eventStats.byType[b]=(this.eventStats.byType[b]||0)+1;try{const I=JSON.stringify(S).length;this.eventStats.sizeByType[b]||(this.eventStats.sizeByType[b]={total:0,count:0,average:0}),this.eventStats.sizeByType[b].total+=I,this.eventStats.sizeByType[b].count++,this.eventStats.sizeByType[b].average=Math.round(this.eventStats.sizeByType[b].total/this.eventStats.sizeByType[b].count)}catch(S){}const I=Date.now();this.eventStats.lastMinuteEvents.push(I),this.eventStats.lastMinuteEvents=this.eventStats.lastMinuteEvents.filter(S=>I-S<6e4),this.eventStats.currentRate=this.eventStats.lastMinuteEvents.length}adaptToEventRate(){if(!this.samplingEnabled)return;const S=this.eventStats.currentRate;S>3e3?(this.mousemoveSampling=Math.max(.1,this.mousemoveSampling-.1),this.scrollSampling=Math.max(.2,this.scrollSampling-.1),this.logger.warn?.(`[Optimizer] High event rate (${S}/min), increasing sampling`)):S<600&&this.mousemoveSampling<.5&&(this.mousemoveSampling=Math.min(.5,this.mousemoveSampling+.05),this.scrollSampling=Math.min(.7,this.scrollSampling+.05))}_applySampling(S){if(3===S.type&&1===S.data?.source){if(Math.random()>=this.mousemoveSampling)return!1;if(S.data.positions&&S.data.positions.length>0){const b=S.data.positions[S.data.positions.length-1];if(Math.sqrt(Math.pow(b.x-this.lastMousePosition.x,2)+Math.pow(b.y-this.lastMousePosition.y,2))<5)return!1;this.lastMousePosition={x:b.x,y:b.y}}}return 3!==S.type||3!==S.data?.source||Math.random()<this.scrollSampling}_isDuplicateEvent(S){const b=this._getEventKey(S),I=Date.now();if(this.eventDedupeCache.has(b)){if(I-this.eventDedupeCache.get(b)<100)return!0}if(this.eventDedupeCache.set(b,I),this.eventDedupeCache.size>1e3){const S=I-5e3;for(const[b,I]of this.eventDedupeCache.entries())I<S&&this.eventDedupeCache.delete(b)}return!1}_getEventKey(S){if(3===S.type){const b=S.data?.source,I=S.data?.id,x=S.data?.action;return`${S.type}-${b}-${I}-${x}`}try{return`${S.type}-${JSON.stringify(S.data).substring(0,50)}`}catch(b){return`${S.type}-unknown`}}getEventTypeName(S){return Ic[S]||`Unknown(${S})`}getOptimizationStats(){return{eventStats:{...this.eventStats},samplingRates:{mousemove:this.mousemoveSampling,scroll:this.scrollSampling},samplingEnabled:this.samplingEnabled,deduplicationEnabled:this.deduplicationEnabled,deduplicatedEvents:this.eventDedupeCache.size}}logOptimizationReport(){const S=this.getOptimizationStats();this.logger.info?.("📊 Optimization Report:"),this.logger.info?.(" Sampling: "+(S.samplingEnabled?"Enabled":"Disabled")),this.logger.info?.(" Deduplication: "+(S.deduplicationEnabled?"Enabled":"Disabled")),this.logger.info?.(` Event Rate: ${S.eventStats.currentRate}/min`),this.logger.info?.(` Total Events: ${S.eventStats.total}`),this.logger.info?.(` Deduplicated: ${S.deduplicatedEvents}`),S.samplingEnabled&&(this.logger.info?.(" Sampling Rates:"),this.logger.info?.(` Mouse Move: ${(100*S.samplingRates.mousemove).toFixed(0)}%`),this.logger.info?.(` Scroll: ${(100*S.samplingRates.scroll).toFixed(0)}%`)),this.logger.info?.(" Event Distribution:");for(const[b,I]of Object.entries(S.eventStats.byType)){const x=(I/S.eventStats.total*100).toFixed(1),R=S.eventStats.sizeByType[b]?.average||0;this.logger.info?.(` ${b}: ${I} (${x}%) - Avg: ${R}B`)}}updateConfig(S){void 0!==S.enableSampling&&(this.samplingEnabled=S.enableSampling),void 0!==S.enableDeduplication&&(this.deduplicationEnabled=S.enableDeduplication),void 0!==S.mousemoveSampling&&(this.mousemoveSampling=S.mousemoveSampling),void 0!==S.scrollSampling&&(this.scrollSampling=S.scrollSampling),void 0!==S.mutationSampling&&(this.mutationSampling=S.mutationSampling)}reset(){this.eventStats={total:0,byType:{},sizeByType:{},lastMinuteEvents:[],currentRate:0},this.eventDedupeCache.clear(),this.lastMousePosition={x:0,y:0},this.lastScrollPosition={x:0,y:0}}destroy(){this.eventDedupeCache.clear(),this.eventStats=null,this.logger=null}}class ChunkManager{constructor(S={}){this.chunkDuration=S.chunkDuration||3e4,this.maxChunkSize=S.maxChunkSize||5e5,this.maxEventsPerChunk=S.maxEventsPerChunk||500,this.minFlushInterval=S.minFlushInterval||1e4,this.firstChunkFlushed=!1,this.firstChunkFlushTimeout=2e3,this.recordingStartTime=null,this._firstChunkTimer=null,this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.chunkTimer=null,this.sessionId=null,this.sdkContext=null,this.onChunkCreated=S.onChunkCreated||(()=>{}),this.onServerUpload=S.onServerUpload||null,this.onSessionEnd=S.onSessionEnd||(()=>{}),this.logger=S.logger||console}setSessionInfo(S){this.sessionId=S.sessionId,this.sdkContext=S.sdkContext}startRecording(){this.recordingStartTime=Date.now(),this.firstChunkFlushed=!1,this._firstChunkTimer&&clearTimeout(this._firstChunkTimer),this._firstChunkTimer=setTimeout(()=>{!this.firstChunkFlushed&&this.currentChunk.length>0&&(this.logger.info?.("[ChunkManager] Force-flushing first chunk (2s timeout)"),this.flush({force:!0})),this._firstChunkTimer=null},this.firstChunkFlushTimeout)}startTimer(){this.chunkTimer||(this.chunkTimer=setTimeout(()=>{this.flush(),this.startTimer()},this.chunkDuration))}stopTimer(){this.chunkTimer&&(clearTimeout(this.chunkTimer),this.chunkTimer=null)}resetTimer(){this.stopTimer(),this.startTimer()}addEvent(S){return this.currentChunk.push(S),!0}getCurrentChunkLength(){return this.currentChunk.length}checkFlush(){if(0===this.currentChunk.length)return!1;if(!this.firstChunkFlushed&&this.currentChunk.length>0){const S=this.currentChunk.some(S=>2===S.type);if(S)return this.logger.info?.("[ChunkManager] FullSnapshot detected - immediate flush"),this.flush({force:!0}),this.resetTimer(),!0}const S=this.estimateSize(this.currentChunk)>=this.maxChunkSize,b=this.currentChunk.length>=this.maxEventsPerChunk,I=Date.now()-this._lastFlushTime;return(S||!!(b&&I>=this.minFlushInterval))&&(this.flush(),this.resetTimer(),!0)}flush(S={}){if(this._isFlushing)return null;this._isFlushing=!0;try{if(0===this.currentChunk.length)return null;!this.firstChunkFlushed&&(this.firstChunkFlushed=!0,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.logger.info?.("[ChunkManager] First chunk flushed"));const S=this.currentChunk;this.currentChunk=[];const b=this.chunkCounter;this.chunkCounter++,this.sessionId||(this.sessionId=generateSessionId(),this.logger.warn(`[ChunkManager] sessionId was null at flush time for chunk ${b}, generated fallback: ${this.sessionId}`));const I=[],x=[],R=[],A=[];for(const b of S){const S=extractNetworkRef(b,this.sessionId);if(S){I.push(S);const x=extractNetworkFull(b,this.sessionId);x&&R.push(x),A.push(stripNetworkPayload(b));continue}const _=extractConsoleRef(b,this.sessionId);_?(x.push(_),A.push(b)):A.push(b)}const _={projectId:this.sdkContext?.projectId,environment:this.sdkContext?.environment,userId:this.sdkContext?.userId};0===b&&(_.device=collectDeviceMetadata());let D=createChunk({sequence:b,sessionId:this.sessionId,events:A,networkRefs:I,consoleRefs:x,networkFullData:R,metadata:_,isFirstChunk:0===b,isLastChunk:!1});return this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&(D=this.sdkContext.enrichChunk(D)),this.allChunks.push(D),this._lastFlushTime=Date.now(),this.onChunkCreated(D,b),this.onServerUpload&&this.sendToServer(D),D}finally{this._isFlushing=!1}}estimateSize(S){if(!S||0===S.length)return 0;try{if(S.length<=50)return JSON.stringify(S).length;const b=Math.min(50,Math.max(10,Math.floor(.1*S.length))),I=Math.floor(S.length/b);let x=0;for(let b=0;b<S.length;b+=I)x+=JSON.stringify(S[b]).length;const R=x/Math.ceil(S.length/I);return Math.ceil(R*S.length)+2*S.length}catch(S){return 0}}async sendToServer(S){if(this.onServerUpload)try{await this.onServerUpload(S),this.logger.info?.(`Chunk ${S.sequence} sent successfully`)}catch(S){this.logger.warn?.("Failed to send chunk to server:",S)}}getChunks(){return[...this.allChunks]}getChunkCounter(){return this.chunkCounter}setChunkCounter(S){this.chunkCounter=S}getCurrentChunk(){return[...this.currentChunk]}exportChunkedData(S="json"){const b={sessionId:this.sessionId,chunks:this.allChunks,totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length};return"json"===S?JSON.stringify(b,null,2):b}getStats(){const S=this.allChunks.reduce((S,b)=>S+(b.sizeBytes||0),0),b=this.estimateSize(this.currentChunk);return{totalChunks:this.allChunks.length,currentChunkEvents:this.currentChunk.length,currentChunkSize:b,totalSize:S,chunkCounter:this.chunkCounter,avgChunkSize:this.allChunks.length>0?Math.round(S/this.allChunks.length):0}}updateConfig(S){void 0!==S.chunkDuration&&(this.chunkDuration=S.chunkDuration),void 0!==S.maxChunkSize&&(this.maxChunkSize=S.maxChunkSize),void 0!==S.maxEventsPerChunk&&(this.maxEventsPerChunk=S.maxEventsPerChunk),void 0!==S.minFlushInterval&&(this.minFlushInterval=S.minFlushInterval)}reset(){this.currentChunk=[],this.chunkCounter=0,this.allChunks=[],this._isFlushing=!1,this._lastFlushTime=0,this.stopTimer(),this.firstChunkFlushed=!1,this.recordingStartTime=null,this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null)}destroy(){this.stopTimer(),this._firstChunkTimer&&(clearTimeout(this._firstChunkTimer),this._firstChunkTimer=null),this.currentChunk=[],this.allChunks=[],this.onChunkCreated=null,this.onServerUpload=null,this.onSessionEnd=null,this.sdkContext=null,this.logger=null}}class RecorderLogger{constructor(S,b=!1){const I=S.replace(/^\[|\]$/g,"");this.serviceLogger=createLogger(I),this.prefix=`[TraceScout][${S}]`,this.debug=b}log(...S){this.serviceLogger.log(...S)}warn(...S){this.serviceLogger.warn(...S)}error(...S){this.serviceLogger.error(...S)}info(...S){this.serviceLogger.info(...S)}debug(...S){this.debug&&this.serviceLogger.log(...S)}updateDebugMode(S){this.debug=S,this.serviceLogger.updateDebugMode(S)}}class Recorder{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[Recorder] No SDKContext provided - running in v1.x compatibility mode");const b=S.preset?Recorder.getPresetConfig(S.preset):{};if(this.config={emit:()=>{},checkoutEveryNms:6e4,checkoutEveryNth:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,debug:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},chunkDuration:3e4,maxChunkSize:5e5,onChunk:null,enableSampling:!1,enableDeduplication:!1,mousemoveSampling:1,scrollSampling:1,mutationSampling:1,inactivityTimeout:3e5,maxInactivityDuration:18e5,maxSessionDuration:36e5,enableInactivityDetection:!0,maxChunksInMemory:S.maxChunksInMemory||10,maxEventsPerSession:S.maxEventsPerSession||5e4,maxSessionBytes:S.maxSessionBytes||52428800,checkpointInterval:S.checkpointInterval||6e4,...b,...S},this.sdkContext&&"function"==typeof this.sdkContext.setDomPrivacy)try{this.sdkContext.setDomPrivacy(function deriveDomPrivacy(S){if(!S||"object"!=typeof S)return"disabled";if(!0===S.maskAllInputs)return"confirmed";const b="string"==typeof S.maskTextClass&&S.maskTextClass.length>0,I="string"==typeof S.blockClass&&S.blockClass.length>0;return b||I?"partial":"disabled"}(this.config))}catch{}this.events=[],this.isRecording=!1,this.stopFn=null,this.metadata={},this.sessionId=null,this.recordingStartTime=null,this.sessionStartTime=Date.now(),this.sessionEnded=!1,this.sessionEndReason=null,this.statusTimer=null,this.statusInterval=1e4,this.aggregationTimer=null,this.aggregationInterval=3e4,this.lastAggregationThresholdSec=0,this._uploadQueue=null,this.logger=new RecorderLogger("Recorder",this.config.debug),this._initializeModules()}_initializeModules(){this.inactivityManager=new InactivityManager({inactivityTimeout:this.config.inactivityTimeout,maxInactivityDuration:this.config.maxInactivityDuration,maxSessionDuration:this.config.maxSessionDuration,enableInactivityDetection:this.config.enableInactivityDetection,logger:this.logger,onPause:S=>this._onInactivityPause(S),onResume:S=>this._onInactivityResume(S),onSessionEnd:S=>this._onInactivitySessionEnd(S),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.pageLifecycleManager=new PageLifecycleManager({logger:this.logger,getIsRecording:()=>this.isRecording,getCurrentChunkLength:()=>this.chunkManager.getCurrentChunkLength(),getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),onFlush:()=>this.chunkManager.flush(),onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b),onSendBeacon:(S,b)=>this._sendChunkWithBeacon(S,b)}),this.checkpointManager=new CheckpointManager({checkpointInterval:this.config.checkpointInterval,logger:this.logger,getRRWeb:()=>getRRWeb(),getIsRecording:()=>this.isRecording,getSessionStartTime:()=>this.sessionStartTime,getChunkCounter:()=>this.chunkManager.getChunkCounter(),getEventCount:()=>this.events.length,onAddCustomEvent:(S,b)=>this.addCustomEvent(S,b)}),this.memoryManager=new RecorderMemoryManager({maxChunksInMemory:this.config.maxChunksInMemory,maxEventsPerSession:this.config.maxEventsPerSession,maxSessionBytes:this.config.maxSessionBytes,logger:this.logger,onForceFlush:()=>this.chunkManager.flush(),onSessionEnd:S=>this.endSession(S)}),this.eventOptimizer=new EventOptimizer({enableSampling:this.config.enableSampling,enableDeduplication:this.config.enableDeduplication,mousemoveSampling:this.config.mousemoveSampling,scrollSampling:this.config.scrollSampling,mutationSampling:this.config.mutationSampling,logger:this.logger}),this.chunkManager=new ChunkManager({chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize,logger:this.logger,onChunkCreated:(S,b)=>this._onChunkCreated(S,b),onServerUpload:this.config.serverUrl?S=>this.sendChunkToServer(S):null})}async start(S={}){if(this.isRecording)return this.logger.warn("Recording already in progress"),this.stopFn;this.logger.info("Starting session recording...");const b=this._getSessionResumeInfo();b.isResumed&&(this.logger.info(`[V3] Resuming session ${b.sessionId}, continuing from chunk ${b.lastChunkSequence}`),this.chunkManager.setChunkCounter(b.lastChunkSequence+1));try{const b=await loadRRWeb();this.sdkContext&&this.sdkContext.sessionId?this.sessionId=this.sdkContext.sessionId:this.sessionId=this.generateSessionId(),this.chunkManager.setSessionInfo({sessionId:this.sessionId,sdkContext:this.sdkContext});let I=0,x=Date.now();const R={...this.config,...S,emit:b=>{if(I++,this.config.debug&&I%50==0){const S=Date.now()-x;this.logger.log(`${I} events captured (${S}ms since last log)`),x=Date.now()}const R={...b,tracescoutVersion:"1.0.0",sessionId:this.getSessionId()},A=this.chunkManager.estimateSize([R]),_=2===R.type||4===R.type;if(A>1e6&&!_)return void(this.config.debug&&this.logger.warn(`Skipping extremely large event: ${A} bytes, type: ${R.type}`));if(!this.onEvent(R))return;this.chunkManager.addEvent(R),this.events.push(R),this.chunkManager.checkFlush();(S.emit||this.config.emit)(R)}};if(this.stopFn=b.record(R),this.isRecording=!0,this.recordingStartTime=Date.now(),this.sessionStartTime=Date.now(),this._rrweb=b,this.chunkManager&&(this.chunkManager.startRecording(),this.logger.info("[Recorder] First-chunk flush timer started (2s)")),this.memoryManager.setDataReferences({allChunks:this.chunkManager.allChunks,events:this.events,eventDedupeCache:this.eventOptimizer.getDedupeCache(),eventStats:this.eventOptimizer.getEventStats()}),this.config.enableStreamingStorage)try{const{ChunkedCompressedStorage:S}=await Promise.resolve().then(function(){return Mc});this.__streamStore=S,this.__streamStore.initSession(this.sessionId),this.logger.info("Streaming storage initialized")}catch(S){this.logger.warn("Failed to init streaming storage:",S)}return this.chunkManager.startTimer(),this.checkpointManager.start(),this.memoryManager.start(),this.inactivityManager.start(),this.pageLifecycleManager.setup(),this._startStatusTimer(),this.sessionEnded=!1,this.sessionEndReason=null,this._uploadQueue?.didIndexedDBFail?.()&&(this.logger.warn("[Recorder] IndexedDB failed - scheduling backup snapshot"),this._scheduleBackupSnapshot()),this._uploadQueue?.on&&this._uploadQueue.on("firstSnapshotUploadFailed",()=>{this.logger.warn("[Recorder] First snapshot upload failed 3x - taking immediate backup"),this._takeBackupSnapshot()}),this._setupSPANavigationDetection(),this.logger.info("🔴 Recording started",{sessionId:this.sessionId,startTime:this.recordingStartTime,chunkDuration:this.config.chunkDuration,maxChunkSize:this.config.maxChunkSize}),this.stopFn}catch(S){throw this.logger.error("Failed to load or initialize rrweb:",S),S}}stop(){if(!this.isRecording)return this.logger.warn("No recording in progress"),this.events;this.chunkManager.stopTimer(),this.checkpointManager.stop(),this.memoryManager.stop(),this.inactivityManager.stop(),this.pageLifecycleManager.remove(),this._stopStatusTimer(),this._cleanupSPANavigationDetection(),this._backupSnapshotTimer&&(clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=null),this.chunkManager.flush(),this.stopFn&&(this.stopFn(),this.stopFn=null),this._rrweb=null,this.isRecording=!1;const S=Date.now()-this.recordingStartTime;return this.logger.info("Recording stopped",{sessionId:this.sessionId,duration:S,eventCount:this.events.length,totalChunks:this.chunkManager.getChunks().length}),this.events}onEvent(S){return this.eventOptimizer.updateStats(S),this.inactivityManager.trackActivity(S),!!this.inactivityManager.shouldRecordEvent(S)&&(5===S.type||!!this.eventOptimizer.shouldRecordEvent(S)&&(this.eventOptimizer.adaptToEventRate(),!0))}addCustomEvent(S,b){if(!this.isRecording)return!1;if(!S||"string"!=typeof S)return!1;try{let I=b||{};this.sdkContext&&(I={...b,sessionId:this.sdkContext.sessionId,projectId:this.sdkContext.projectId,environment:this.sdkContext.environment,userId:this.sdkContext.userId});const x={type:5,data:{tag:S,payload:I},timestamp:Date.now(),tracescoutVersion:this.sdkContext?"2.0.0":"1.0.0",sessionId:this.getSessionId()};return!!this.onEvent(x)&&(this.chunkManager.addEvent(x),this.events.push(x),this.chunkManager.checkFlush(),!0)}catch(S){return this.logger.error("Failed to add custom event:",S),!1}}_setupSPANavigationDetection(){if("undefined"==typeof window||"undefined"==typeof history)return;this._lastKnownUrl=window.location.href,this._originalPushState=history.pushState,this._originalReplaceState=history.replaceState;const S=this;history.pushState=function(...b){const I=S._originalPushState.apply(this,b);return S._onSPANavigation("pushState"),I},history.replaceState=function(...b){const I=S._originalReplaceState.apply(this,b);return S._onSPANavigation("replaceState"),I},this._popstateHandler=()=>{S._onSPANavigation("popstate")},window.addEventListener("popstate",this._popstateHandler),this._hashchangeHandler=()=>{S._onSPANavigation("hashchange")},window.addEventListener("hashchange",this._hashchangeHandler),this.logger.info("SPA navigation detection enabled")}_onSPANavigation(S){const b=window.location.href;if(b===this._lastKnownUrl)return;const I=this._lastKnownUrl;if(this._lastKnownUrl=b,this.logger.info(`SPA navigation detected (${S}): ${I} → ${b}`),this.addCustomEvent("page_navigation",{url:b,previousUrl:I,title:document.title,navigationType:S,timestamp:Date.now()}),"function"==typeof this.config?.onSpaNavigation)try{this.config.onSpaNavigation(S,I,b)}catch(S){this.logger.warn?.("[Recorder] onSpaNavigation callback threw:",S)}setTimeout(()=>{this._takeFullSnapshotForNavigation(b)},100)}_takeFullSnapshotForNavigation(S){if(this._rrweb&&this.isRecording)try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info(`Taking full snapshot for SPA navigation to: ${S}`),this._rrweb.record.takeFullSnapshot()):this.logger.warn("rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("Failed to take full snapshot for SPA navigation:",S)}}_scheduleBackupSnapshot(){this._backupSnapshotTimer&&clearTimeout(this._backupSnapshotTimer),this._backupSnapshotTimer=setTimeout(()=>{if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] Chunk 0 already acked, skipping backup snapshot");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (2s safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}},2e3)}_takeBackupSnapshot(){if(this.isRecording&&this._rrweb)if(this._uploadQueue?.isFirstSnapshotAcked?.())this.logger.info("[Recorder] First snapshot ACKed - skipping backup");else try{"function"==typeof this._rrweb.record.takeFullSnapshot?(this.logger.info("[Recorder] Taking backup FullSnapshot (safety net)"),this._rrweb.record.takeFullSnapshot()):this.logger.warn("[Recorder] rrweb.record.takeFullSnapshot is not available")}catch(S){this.logger.error("[Recorder] Backup snapshot failed:",S)}}_cleanupSPANavigationDetection(){"undefined"!=typeof window&&"undefined"!=typeof history&&(this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null),this._popstateHandler&&(window.removeEventListener("popstate",this._popstateHandler),this._popstateHandler=null),this._hashchangeHandler&&(window.removeEventListener("hashchange",this._hashchangeHandler),this._hashchangeHandler=null),this._lastKnownUrl=null,this.logger.info("SPA navigation detection disabled"))}_onInactivityPause(S){this.logger.info("[Inactivity] Recording paused")}_onInactivityResume(S){this.logger.info("[Inactivity] Recording resumed")}_onInactivitySessionEnd(S){this.endSession(S.reason)}_onChunkCreated(S,b){const I=this.memoryManager.trackBytes(S.sizeBytes||0);if(this.memoryManager.trimChunksArray(),this.memoryManager.trimEventsArray(1e3),I)if(this.memoryManager.checkEventLimit(this.events.length)){if(this._updateSessionChunkSequence(b),this.__streamStore)try{this.__streamStore.saveChunk(this.sessionId,b,S.events),this.__streamStore.updateSessionInfo(this.sessionId,b+1,this.events.length)}catch(S){}this.config.onChunk&&this.config.onChunk(S)}else this.endSession("max_events");else this.endSession("max_size")}endSession(S="manual"){this.logger.info(`[Session] Ending session: ${this.sessionId} (reason: ${S})`),this.sessionEnded=!0,this.sessionEndReason=S,this.stop(),this.config.onSessionEnd&&this.config.onSessionEnd({sessionId:this.sessionId,reason:S,duration:Date.now()-this.sessionStartTime,totalEvents:this.events.length,totalPausedTime:this.inactivityManager.totalPausedTime})}_getSessionResumeInfo(){return this.sdkContext?.sessionManager?this.sdkContext.sessionManager.getResumeInfo():this.config.sessionManager?this.config.sessionManager.getResumeInfo():{isResumed:!1,sessionId:null,lastChunkSequence:0}}_updateSessionChunkSequence(S){this.sdkContext?.sessionManager?this.sdkContext.sessionManager.updateLastChunkSequence(S):this.config.sessionManager&&this.config.sessionManager.updateLastChunkSequence(S)}setUploadQueue(S){this._uploadQueue=S}_sendChunkWithBeacon(S,b){if(this._uploadQueue?.sendFinalChunkWithBeacon){if(this._uploadQueue.sendFinalChunkWithBeacon(S,b))return void this.logger.info(`[P0] Chunk ${S.sequence} sent via UploadQueue.sendFinalChunkWithBeacon`)}const I=this.sdkContext?.getChunkEndpoint?.()||(this.config.serverUrl?`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`:null);if(!I)return void(this.config.onChunk&&this.config.onChunk(S));const x={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],metadata:{...S.metadata,sentVia:"sendBeacon",closeTrigger:b},sizeBytes:S.sizeBytes},R=JSON.stringify(x);if("undefined"!=typeof navigator&&navigator.sendBeacon)try{const b=new Blob([R],{type:"application/json"});navigator.sendBeacon(I,b)?this.logger.info(`[P0] Chunk ${S.sequence} sent via sendBeacon`):this.config.onChunk&&this.config.onChunk(S)}catch(b){this.config.onChunk&&this.config.onChunk(S)}else this.config.onChunk&&this.config.onChunk(S)}async sendChunkToServer(S){try{const b={version:4,sequence:S.sequence,sessionId:S.sessionId,startTimestamp:S.startTimestamp,endTimestamp:S.endTimestamp,eventCount:S.eventCount,events:S.events,networkRefs:S.networkRefs||[],consoleRefs:S.consoleRefs||[],networkFullData:S._networkFullData||[],metadata:S.metadata,sizeBytes:S.sizeBytes},I=this.sdkContext?.getChunkEndpoint?.()||`${this.config.serverUrl}/api/projects/${this.sdkContext?.projectId}/sessions/${this.sessionId}/chunks`,x=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!x.ok)throw new Error(`Server responded with ${x.status}`);return await x.json()}catch(S){throw this.logger.warn("Failed to send chunk to server:",S),S}}_startStatusTimer(){this.statusTimer&&clearInterval(this.statusTimer),setTimeout(()=>this.logStatus(),1e3),this.statusTimer=setInterval(()=>{this.logStatus()},this.statusInterval),this.config.debug&&(this.aggregationTimer&&clearInterval(this.aggregationTimer),this.aggregationTimer=setInterval(()=>{this._maybeLogAggregationExport()},this.aggregationInterval))}_stopStatusTimer(){this.statusTimer&&(clearInterval(this.statusTimer),this.statusTimer=null),this.aggregationTimer&&(clearInterval(this.aggregationTimer),this.aggregationTimer=null),this.lastAggregationThresholdSec=0}logStatus(){if(!this.isRecording)return;const S=this.chunkManager.getStats(),b=Date.now()-this.recordingStartTime,I=Math.floor(b/1e3),x=Math.floor(I/60),R=I%60,fmtSize=S=>S>=1048576?`${(S/1048576).toFixed(1)}MB`:`${Math.round(S/1024)}KB`;this.logger.info(`📊 Session Status [${x}m ${R}s]:`,{totalEvents:this.events.length,totalSize:fmtSize(S.totalSize),currentChunk:`${S.currentChunkEvents} events (${fmtSize(S.currentChunkSize)})`,completedChunks:S.totalChunks})}_maybeLogAggregationExport(){if(!this.isRecording||!this.recordingStartTime)return;const S=Date.now()-this.recordingStartTime,b=Math.floor(S/this.aggregationInterval)*(this.aggregationInterval/1e3);if(b>0&&b!==this.lastAggregationThresholdSec){this.lastAggregationThresholdSec=b;try{const S=this.buildReplayExport();this.logger.info(`🧩 Session export (${b}s):`,S)}catch(S){this.logger.warn("Failed to export session data:",S)}}}getStatus(){return{isRecording:this.isRecording,eventCount:this.events.length,duration:this.isRecording?Date.now()-this.recordingStartTime:0}}getSessionId(){return this.sessionId||(this.sessionId=generateSessionId()),this.sessionId}getEvents(){return[...this.events]}getChunks(){return this.chunkManager.getChunks()}getMetadata(){return{...this.metadata,sessionId:this.sessionId,startTime:this.recordingStartTime,isRecording:this.isRecording,eventCount:this.events.length}}getConfig(){return{...this.config}}getMemoryStats(){return this.memoryManager.getStats()}getOptimizationStats(){return this.eventOptimizer.getOptimizationStats()}setMetadata(S){this.metadata={...this.metadata,...S}}updateConfig(S){this.config={...this.config,...S},void 0!==S.debug&&this.logger.updateDebugMode(S.debug),this.inactivityManager.updateConfig(S),this.eventOptimizer.updateConfig(S),this.chunkManager.updateConfig(S),this.memoryManager.updateConfig(S),this.checkpointManager.updateConfig(S)}updateDebugMode(S){this.config.debug=S,this.logger.updateDebugMode(S)}clear(){this.events=[],this.logger.info("Events cleared")}pause(){this.isRecording?this.stopFn&&(this.stopFn(),this.stopFn=null,this.isRecording=!1,this.logger.info("Recording paused")):this.logger.warn("No recording to pause")}resume(){this.isRecording?this.logger.warn("Recording already active"):(this.start(),this.logger.info("Recording resumed"))}takeCheckpoint(){this.checkpointManager.takeManualCheckpoint()}flushChunk(){return this.chunkManager.flush()}exportEvents(){return JSON.stringify({sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:this.events,metadata:this.metadata},null,2)}exportChunkedData(S="json"){const b=this.chunkManager.getChunks(),I={sessionId:this.getSessionId(),startTime:this.recordingStartTime,chunks:b,totalChunks:b.length,totalEvents:this.events.length,metadata:this.metadata};return"json"===S?JSON.stringify(I,null,2):I}buildReplayExport(){const S=this.chunkManager.getChunks().map(S=>{if(S?.compressed)try{return this.decompressChunk(S)}catch(b){return S}return S}),b=[];for(const I of S)I?.events&&Array.isArray(I.events)&&b.push(...I.events);return{sessionId:this.getSessionId(),startTime:this.recordingStartTime,events:b,chunks:S,totalChunks:S.length,totalEvents:b.length,metadata:this.metadata}}compressChunkSync(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}async compressChunk(S){return{...S,compressed:!1,compressionType:"none",originalSize:JSON.stringify(S).length}}decompressChunk(S){if(!S.compressed)return S;try{const b=S.compressedData||S.data,I=new Uint8Array(b);if("fflate"===S.compressionType){const S=strFromU8(unzlibSync(I));return JSON.parse(S)}return S}catch(b){return this.logger.error("Failed to decompress chunk:",b),S}}generateSessionId(){return generateSessionId()}getEventTypeName(S){return this.eventOptimizer.getEventTypeName(S)}analyzeLargestEvents(S=5){if(!this.events||0===this.events.length)return void this.logger.info("No events to analyze");const b=this.events.map((S,b)=>({index:b,type:S.type,size:this.chunkManager.estimateSize([S]),timestamp:S.timestamp}));b.sort((S,b)=>b.size-S.size),this.logger.info(`🔍 Top ${S} Largest Events:`),b.slice(0,S).forEach((S,b)=>{this.logger.info(`${b+1}. Event #${S.index}: ${S.type} - ${Math.round(S.size/1024)}KB`)})}logOptimizationReport(){this.eventOptimizer.logOptimizationReport()}static getPresetConfig(S){return{minimal:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:18e4,checkoutEveryNth:300,chunkDuration:9e4,maxChunkSize:2e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.3,scrollSampling:.5,debug:!1},production:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:45e3,maxChunkSize:3e5,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.7,scrollSampling:.8,debug:!1},standard:{maskAllInputs:!0,inlineStylesheet:!1,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0},checkoutEveryNms:12e4,checkoutEveryNth:200,chunkDuration:6e4,maxChunkSize:35e4,enableSampling:!0,enableDeduplication:!0,mousemoveSampling:.5,scrollSampling:.7,debug:!1},detailed:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0},checkoutEveryNms:6e4,checkoutEveryNth:100,chunkDuration:3e4,maxChunkSize:5e5,enableSampling:!1,enableDeduplication:!1,debug:!1},full:{maskAllInputs:!1,inlineStylesheet:!0,recordCanvas:!0,collectFonts:!0,slimDOMOptions:!1,checkoutEveryNms:3e4,checkoutEveryNth:50,chunkDuration:15e3,maxChunkSize:1e6,enableSampling:!1,enableDeduplication:!1,debug:!1}}[S]||{}}}const Ec={MINIMAL:"minimal",STANDARD:"standard",DETAILED:"detailed",FULL:"full"},xc="pending_chunks";class IndexedDBQueue{constructor(S={}){if(this.db=null,this.isSupported="undefined"!=typeof indexedDB,this.initFailed=!1,this.maxItems=S.maxItems||100,this.onError=S.onError||(()=>{}),"undefined"!=typeof window&&!0===window.__TRACESCOUT_FORCE_DISABLE_INDEXEDDB)return console.warn("[IndexedDBQueue] Disabled via FORCE_DISABLE_INDEXEDDB flag"),this.isSupported=!1,void(this.initFailed=!0);this.isSupported&&this._initDB()}async _initDB(){if(this.isSupported)return new Promise((S,b)=>{const I=indexedDB.open("tracescout_queue",1);I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to open database:",b.target.error),this.isSupported=!1,this.initFailed=!0,S(null)},I.onsuccess=b=>{this.db=b.target.result,S(this.db)},I.onupgradeneeded=S=>{const b=S.target.result;if(!b.objectStoreNames.contains(xc)){const S=b.createObjectStore(xc,{keyPath:"id"});S.createIndex("sessionId","sessionId",{unique:!1}),S.createIndex("createdAt","createdAt",{unique:!1}),S.createIndex("priority","priority",{unique:!1})}}})}async _ensureDB(){if(!this.isSupported)return!1;if(!this.db)try{await this._initDB()}catch(S){return!1}return!!this.db}async enqueue(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([xc],"readwrite"),x=I.objectStore(xc),R={id:S.id||`queue_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:S.chunk?.sessionId||S.sessionId,chunk:S.chunk,priority:S.priority||"normal",attempts:S.attempts||0,createdAt:S.createdAt||Date.now(),lastAttempt:S.lastAttempt||null,error:S.error||null},A=x.add(R);A.onsuccess=()=>{b(!0)},A.onerror=S=>{if("ConstraintError"===S.target.error?.name){const S=x.put(R);S.onsuccess=()=>b(!0),S.onerror=()=>b(!1)}else console.warn("[IndexedDBQueue] Failed to enqueue:",S.target.error),b(!1)},I.oncomplete=async()=>{await this._enforceLimit()}}catch(S){console.warn("[IndexedDBQueue] Enqueue error:",S),b(!1)}})}async getAll(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([xc],"readonly"),I=b.objectStore(xc).getAll();I.onsuccess=b=>{const I=b.target.result||[],x={high:3,normal:2,low:1};I.sort((S,b)=>{const I=x[S.priority]||2,R=x[b.priority]||2;return I!==R?R-I:S.createdAt-b.createdAt}),S(I)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to get items:",b.target.error),S([])}}catch(b){console.warn("[IndexedDBQueue] GetAll error:",b),S([])}}):[]}async getBySession(S){return await this._ensureDB()?new Promise(b=>{try{const I=this.db.transaction([xc],"readonly").objectStore(xc),x=I.index("sessionId").getAll(S);x.onsuccess=S=>{b(S.target.result||[])},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to get by session:",S.target.error),b([])}}catch(S){console.warn("[IndexedDBQueue] GetBySession error:",S),b([])}}):[]}async remove(S){return!!await this._ensureDB()&&new Promise(b=>{try{const I=this.db.transaction([xc],"readwrite"),x=I.objectStore(xc).delete(S);x.onsuccess=()=>{b(!0)},x.onerror=S=>{console.warn("[IndexedDBQueue] Failed to remove:",S.target.error),b(!1)}}catch(S){console.warn("[IndexedDBQueue] Remove error:",S),b(!1)}})}async removeMany(S){if(!await this._ensureDB()||!S||0===S.length)return 0;let b=0;for(const I of S)await this.remove(I)&&b++;return b}async update(S,b){return!!await this._ensureDB()&&new Promise(I=>{try{const x=this.db.transaction([xc],"readwrite").objectStore(xc),R=x.get(S);R.onsuccess=S=>{const R=S.target.result;if(!R)return void I(!1);const A={...R,...b},_=x.put(A);_.onsuccess=()=>I(!0),_.onerror=()=>I(!1)},R.onerror=()=>I(!1)}catch(S){console.warn("[IndexedDBQueue] Update error:",S),I(!1)}})}async clear(){return!!await this._ensureDB()&&new Promise(S=>{try{const b=this.db.transaction([xc],"readwrite"),I=b.objectStore(xc).clear();I.onsuccess=()=>{S(!0)},I.onerror=b=>{console.warn("[IndexedDBQueue] Failed to clear:",b.target.error),S(!1)}}catch(b){console.warn("[IndexedDBQueue] Clear error:",b),S(!1)}})}async count(){return await this._ensureDB()?new Promise(S=>{try{const b=this.db.transaction([xc],"readonly"),I=b.objectStore(xc).count();I.onsuccess=b=>{S(b.target.result)},I.onerror=()=>S(0)}catch(b){S(0)}}):0}async _enforceLimit(){const S=await this.count();if(S<=this.maxItems)return;const b=await this.getAll(),I=S-this.maxItems,x=[...b].sort((S,b)=>{const I={high:3,normal:2,low:1},x=I[S.priority]||2,R=I[b.priority]||2;return x!==R?x-R:S.createdAt-b.createdAt}),R=x.slice(0,I).map(S=>S.id);await this.removeMany(R),console.log(`[IndexedDBQueue] Removed ${R.length} old items to enforce limit of ${this.maxItems}`)}isAvailable(){return this.isSupported&&null!==this.db}didInitFail(){return!0===this.initFailed}close(){this.db&&(this.db.close(),this.db=null)}}class CircuitBreaker{constructor(S={}){this.threshold=S.threshold||5,this.resetTimeout=S.resetTimeout||6e4,this.halfOpenMaxAttempts=S.halfOpenMaxAttempts||1,this.failures=0,this.lastFailure=null,this.state="closed",this.halfOpenAttempts=0,this.logger=S.logger||console}canMakeRequest(){if("closed"===this.state)return!0;if("open"===this.state){return Date.now()-this.lastFailure>=this.resetTimeout&&(this.state="half-open",this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Transitioning to half-open state"),!0)}return"half-open"!==this.state||this.halfOpenAttempts<this.halfOpenMaxAttempts}recordSuccess(){"half-open"===this.state?(this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Circuit closed after successful request")):"closed"===this.state&&(this.failures=0)}recordFailure(){this.failures++,this.lastFailure=Date.now(),"half-open"===this.state?(this.state="open",this.halfOpenAttempts=0,this.logger.warn?.("[CircuitBreaker] Circuit reopened after failed test request")):"closed"===this.state&&this.failures>=this.threshold&&(this.state="open",this.logger.error?.(`[CircuitBreaker] Circuit OPENED after ${this.failures} consecutive failures`),this.logger.error?.(`[CircuitBreaker] Will retry after ${this.resetTimeout/1e3}s cooldown`))}recordHalfOpenAttempt(){"half-open"===this.state&&this.halfOpenAttempts++}getStatus(){return{state:this.state,failures:this.failures,lastFailure:this.lastFailure,threshold:this.threshold,resetTimeout:this.resetTimeout,timeUntilReset:"open"===this.state&&this.lastFailure?Math.max(0,this.resetTimeout-(Date.now()-this.lastFailure)):null,halfOpenAttempts:this.halfOpenAttempts,halfOpenMaxAttempts:this.halfOpenMaxAttempts}}reset(){this.state="closed",this.failures=0,this.lastFailure=null,this.halfOpenAttempts=0,this.logger.log?.("[CircuitBreaker] Manually reset to closed state")}forceOpen(){this.state="open",this.lastFailure=Date.now(),this.logger.warn?.("[CircuitBreaker] Manually forced to open state")}updateConfig(S){void 0!==S.threshold&&(this.threshold=S.threshold),void 0!==S.resetTimeout&&(this.resetTimeout=S.resetTimeout),void 0!==S.halfOpenMaxAttempts&&(this.halfOpenMaxAttempts=S.halfOpenMaxAttempts)}destroy(){this.logger=null}}class NetworkMonitor{constructor(S={}){this.checkInterval=S.checkInterval||3e4,this.isOnline="undefined"==typeof navigator||navigator.onLine,this.onStatusChange=S.onStatusChange||(()=>{}),this.logger=S.logger||console,this.checkTimer=null,this._boundOnline=null,this._boundOffline=null}start(){"undefined"!=typeof window&&(this._boundOnline=()=>this._handleStatusChange(!0),this._boundOffline=()=>this._handleStatusChange(!1),window.addEventListener("online",this._boundOnline),window.addEventListener("offline",this._boundOffline),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval),this.logger.log?.("[NetworkMonitor] Started monitoring"))}stop(){"undefined"!=typeof window&&(this._boundOnline&&window.removeEventListener("online",this._boundOnline),this._boundOffline&&window.removeEventListener("offline",this._boundOffline)),this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=null),this._boundOnline=null,this._boundOffline=null,this.logger.log?.("[NetworkMonitor] Stopped monitoring")}_handleStatusChange(S){const b=this.isOnline;this.isOnline=S,b!==S&&(this.logger.log?.("[NetworkMonitor] Status changed: "+(S?"online":"offline")),this.onStatusChange(S,b))}checkStatus(){if("undefined"==typeof navigator)return;const S=navigator.onLine;this.isOnline!==S&&this._handleStatusChange(S)}getStatus(){return this.isOnline}updateConfig(S){void 0!==S.checkInterval&&(this.checkInterval=S.checkInterval,this.checkTimer&&(clearInterval(this.checkTimer),this.checkTimer=setInterval(()=>{this.checkStatus()},this.checkInterval)))}destroy(){this.stop(),this.onStatusChange=null,this.logger=null}}class BeaconSender{constructor(S={}){this.endpoint=S.endpoint||"/api/sessions/upload",this.maxBeaconSize=S.maxBeaconSize||6e4,this.sdkContext=S.sdkContext||null,this.logger=S.logger||console}setEndpoint(S){this.endpoint=S}setSdkContext(S){this.sdkContext=S}send(S,b="unknown"){if(!S||!S.events||0===S.events.length)return this.logger.log?.("[BeaconSender] No events to send"),!1;const I=this._buildPayload(S,b),x=JSON.stringify(I),R=x.length;return R>this.maxBeaconSize?(this.logger.warn?.(`[BeaconSender] Payload too large (${R} bytes), using keepalive fetch`),this._sendWithKeepaliveFetch(x,b)):this._sendWithBeacon(x,b,R)||this._sendWithKeepaliveFetch(x,b)}_buildPayload(S,b){return{chunks:[{id:`final_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunkId:S.chunkId||`chunk_${S.sequence}`,sessionId:S.sessionId,data:S,compressed:!1,originalSize:this._estimateSize(S),projectId:S.metadata?.projectId||this.sdkContext?.projectId,environment:S.metadata?.environment||this.sdkContext?.environment}],batchId:`beacon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:1,sentVia:"sendBeacon",closeTrigger:b}}_sendWithBeacon(S,b,I){if("undefined"==typeof navigator||!navigator.sendBeacon)return!1;try{const x=new Blob([S],{type:"application/json"});return navigator.sendBeacon(this.endpoint,x)?(this.logger.log?.(`[BeaconSender] ✅ Sent via sendBeacon (${b}, ${I} bytes)`),!0):(this.logger.warn?.("[BeaconSender] sendBeacon returned false"),!1)}catch(S){return this.logger.warn?.(`[BeaconSender] sendBeacon failed: ${S.message}`),!1}}_sendWithKeepaliveFetch(S,b){if("undefined"==typeof fetch)return this.logger.warn?.("[BeaconSender] fetch not available"),!1;try{const I={"Content-Type":"application/json","X-SDK-Version":"2.0.0","X-Sent-Via":"keepalive","X-Close-Trigger":b};return this.sdkContext&&(I["X-Project-ID"]=this.sdkContext.projectId||""),fetch(this.endpoint,{method:"POST",headers:I,body:S,keepalive:!0}).catch(S=>{this.logger.warn?.("[BeaconSender] keepalive fetch error:",S)}),this.logger.log?.(`[BeaconSender] ✅ Sent via keepalive fetch (${b})`),!0}catch(S){return this.logger.warn?.(`[BeaconSender] keepalive fetch failed: ${S.message}`),!1}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}updateConfig(S){void 0!==S.endpoint&&(this.endpoint=S.endpoint),void 0!==S.maxBeaconSize&&(this.maxBeaconSize=S.maxBeaconSize)}destroy(){this.sdkContext=null,this.logger=null}}class QueueMemoryManager{constructor(S={}){this.maxQueueSize=S.maxQueueSize||100,this.maxFailedQueueSize=S.maxFailedQueueSize||50,this.maxOfflineItems=S.maxOfflineItems||100,this.logger=S.logger||console}enforceLimit(S,b=this.maxQueueSize){if(S.length<b)return null;const I=S.findIndex(S=>"low"===S.priority);if(I>=0){const x=S.splice(I,1)[0];return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped low-priority chunk:`,x.chunk?.chunkId),x}const x=S.shift();return this.logger.warn?.(`[QueueMemory] Queue at max size (${b}) - dropped oldest chunk:`,x?.chunk?.chunkId),x}enforceFailedLimit(S){if(S.length<this.maxFailedQueueSize)return null;const b=S.shift();return this.logger.warn?.(`[QueueMemory] Failed queue at max (${this.maxFailedQueueSize}) - dropped oldest:`,b?.chunk?.chunkId),b}enforceOfflineLimit(S){if(S.length<=this.maxOfflineItems)return null;const b=S.pop();return this.logger.warn?.("[QueueMemory] Offline queue full - dropped oldest:",b?.chunk?.chunkId),b}calculateQueueBytes(S){return S.reduce((S,b)=>S+(b.originalSize||0),0)}getStats(S,b){const I=this.calculateQueueBytes(S),x=this.calculateQueueBytes(b);return{uploadQueueSize:S.length,uploadQueueBytes:I,failedQueueSize:b.length,failedQueueBytes:x,totalQueuedItems:S.length+b.length,totalQueuedBytes:I+x,maxQueueSize:this.maxQueueSize,maxFailedQueueSize:this.maxFailedQueueSize,maxOfflineItems:this.maxOfflineItems,uploadQueuePercent:Math.round(S.length/this.maxQueueSize*100),failedQueuePercent:Math.round(b.length/this.maxFailedQueueSize*100)}}forceCleanup(S,b,I={}){const{keepUploads:x=10,keepFailed:R=5,clearAll:A=!1}=I,_={uploadQueue:S.length,failedQueue:b.length};let D=0,L=0;A?(D=S.length,L=b.length,S.length=0,b.length=0):(S.length>x&&(D=S.length-x,S.splice(0,D)),b.length>R&&(L=b.length-R,b.splice(0,L)));const B={uploadQueue:S.length,failedQueue:b.length};return this.logger.log?.(`[QueueMemory] Force cleanup: removed ${D} uploads, ${L} failed items`),{before:_,after:B,removed:{uploadQueue:D,failedQueue:L}}}needsCleanup(S,b){const I=S.length/this.maxQueueSize,x=b.length/this.maxFailedQueueSize;return I>=.8||x>=.8}updateConfig(S){void 0!==S.maxQueueSize&&(this.maxQueueSize=S.maxQueueSize),void 0!==S.maxFailedQueueSize&&(this.maxFailedQueueSize=S.maxFailedQueueSize),void 0!==S.maxOfflineItems&&(this.maxOfflineItems=S.maxOfflineItems)}destroy(){this.logger=null}}class UploadQueue{constructor(S={}){this.sdkContext=S.sdkContext||null,this.sdkContext||console.warn("[UploadQueue] No SDKContext provided - running in v1.x compatibility mode");const b=this._generateEndpoint(S);this.config={endpoint:S.endpoint||b,batchSize:S.batchSize||5,maxRetries:S.maxRetries||3,retryDelay:S.retryDelay||1e3,maxRetryDelay:S.maxRetryDelay||3e4,uploadTimeout:S.uploadTimeout||3e4,enableOfflineQueue:!1!==S.enableOfflineQueue,maxOfflineItems:S.maxOfflineItems||100,networkCheckInterval:S.networkCheckInterval||3e4,enableCompression:!1!==S.enableCompression,compressionThreshold:S.compressionThreshold||1024,onUploadSuccess:S.onUploadSuccess||(()=>{}),onUploadError:S.onUploadError||(()=>{}),onNetworkChange:S.onNetworkChange||(()=>{}),onQueueEmpty:S.onQueueEmpty||(()=>{}),headers:S.headers||{},authToken:S.authToken||null,...S},this.uploadQueue=[],this.failedQueue=[],this.isUploading=!1,this._uploadLock=null,this.isQuotaExceeded=!1,this.uploadStats={totalUploaded:0,totalFailed:0,totalBytes:0,averageUploadTime:0,lastUploadTime:null},this.firstSnapshotAcked=!1,this.firstSnapshotChunkId=null,this.firstSnapshotAttempts=0,this._backupSnapshotRequested=!1,this._listeners=new Map,this.retryTimer=null,this._processingTimer=null,this.logger=S.logger||createLogger("UploadQueue"),this._initializeModules(S),this._startProcessing(),this._loadPersistentQueue()}on(S,b){this._listeners.has(S)||this._listeners.set(S,[]),this._listeners.get(S).push(b)}emit(S,...b){const I=this._listeners.get(S);if(I)for(const x of I)try{x(...b)}catch(b){this.logger.warn(`[UploadQueue] Event listener error for '${S}':`,b)}}_generateEndpoint(S){if(this.sdkContext){const b="undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname);return`${S.baseUrl||(b?"http://localhost:3001":"https://api.tracescout.com")}/api/projects/${this.sdkContext.projectId}/sessions/${this.sdkContext.sessionId}/chunks`}return"/api/sessions/upload"}_initializeModules(S){this.circuitBreaker=new CircuitBreaker({threshold:S.circuitBreakerThreshold||5,resetTimeout:S.circuitBreakerResetTimeout||6e4,halfOpenMaxAttempts:S.halfOpenMaxAttempts||1,logger:this.logger}),this.networkMonitor=new NetworkMonitor({checkInterval:this.config.networkCheckInterval,logger:this.logger,onStatusChange:(S,b)=>this._handleNetworkChange(S,b)}),this.networkMonitor.start(),this.beaconSender=new BeaconSender({endpoint:this.config.endpoint,sdkContext:this.sdkContext,logger:this.logger}),this.memoryManager=new QueueMemoryManager({maxQueueSize:S.maxQueueSize||100,maxFailedQueueSize:S.maxFailedQueueSize||50,maxOfflineItems:S.maxOfflineItems||100,logger:this.logger}),this.persistentQueue=new IndexedDBQueue({maxItems:this.config.maxOfflineItems,onError:S=>{this.logger.warn("[UploadQueue] IndexedDB error:",S)}})}async _loadPersistentQueue(){try{const S=await this.persistentQueue.getAll();if(S.length>0){this.logger.log(`[UploadQueue] Recovered ${S.length} items from persistent storage`);for(const b of S)this.uploadQueue.push(b);this._sortQueue(),this.networkMonitor.getStatus()&&!this.isUploading&&this._processQueue()}}catch(S){this.logger.warn("[UploadQueue] Failed to load persistent queue:",S)}}enqueue(S,b="normal"){if(this.isQuotaExceeded)return this.logger.warn("[UploadQueue] Quota exceeded - dropping chunk:",S.chunkId),!1;this.memoryManager.enforceLimit(this.uploadQueue);const I=this._validateChunk(S);if(!I.valid)return this.logger.error(`[UploadQueue] Invalid chunk rejected: ${I.reason}`,S),!1;try{const I=0===S.sequence||!0===S.isFirstChunk;I&&!this.firstSnapshotAcked&&(b="high",this.logger.log("[UploadQueue] Chunk 0 prioritized for immediate upload (contains FullSnapshot)"));const x={id:`upload_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chunk:S,priority:b,attempts:0,createdAt:Date.now(),lastAttempt:null,error:null,compressed:!1,originalSize:this._estimateSize(S),compressedSize:null,isFirstChunk:I};if(I&&!this.firstSnapshotChunkId&&(this.firstSnapshotChunkId=x.id),this.networkMonitor.getStatus())this.uploadQueue.push(x),this._sortQueue();else{if(!this.config.enableOfflineQueue)return this.logger.warn("Network offline and offline queue disabled, dropping chunk:",S.chunkId),!1;this._addToOfflineQueue(x)}return this.logger.log(`Chunk queued for upload: ${S.chunkId} (queue size: ${this.uploadQueue.length})`),I&&this.networkMonitor.getStatus()&&!this.isUploading?(this.logger.log("[UploadQueue] Triggering immediate upload for chunk 0"),this._processQueue()):this.isUploading||this._processQueue(),x.id}catch(S){return this.logger.error("Failed to enqueue chunk:",S),!1}}async _processQueue(){if(!this.circuitBreaker.canMakeRequest())return void this.logger.warn("[UploadQueue] Circuit breaker is open - request blocked");if(this.isUploading||!this.networkMonitor.getStatus()||0===this.uploadQueue.length)return;if(this._uploadLock)return;let S;this._uploadLock=new Promise(b=>{S=b}),this.isUploading=!0,this.logger.log(`Processing upload queue (${this.uploadQueue.length} items)`);try{for(;this.uploadQueue.length>0&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest();){const S=this._createBatch();if(0===S.length)break;if(await this._uploadBatch(S))this.circuitBreaker.recordSuccess();else if(this.circuitBreaker.recordFailure(),"open"===this.circuitBreaker.getStatus().state){this.logger.warn("[UploadQueue] Circuit breaker opened - pausing uploads");break}await this._delay(100)}0===this.uploadQueue.length&&0===this.failedQueue.length&&(this.config.onQueueEmpty(),this.logger.log("Upload queue is empty"))}catch(S){this.logger.error("Error processing upload queue:",S),this.circuitBreaker.recordFailure()}finally{this.isUploading=!1,this._uploadLock=null,S(),this.failedQueue.length>0&&this._scheduleRetry()}}_createBatch(){const S=[],b=Math.min(this.config.batchSize,this.uploadQueue.length);this._sortQueue();for(let I=0;I<b;I++)this.uploadQueue.length>0&&S.push(this.uploadQueue.shift());return S}async _uploadBatch(S){const b=Date.now();try{this.sdkContext&&"function"==typeof this.sdkContext.enrichChunk&&S.forEach(S=>{S.chunk=this.sdkContext.enrichChunk(S.chunk)});const I={chunks:(await this._processBatch(S)).map(S=>({id:S.id,chunkId:S.chunk.chunkId,sessionId:S.chunk.sessionId,data:S.compressed?S.compressedData:S.chunk,compressed:S.compressed,originalSize:S.originalSize,compressedSize:S.compressedSize||S.originalSize,projectId:S.chunk.projectId,environment:S.chunk.environment})),batchId:`batch_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now(),totalItems:S.length},x=await this._makeRequest(I);if(x.ok){const I=await x.json().catch(()=>({}));if(I.results){const S=I.results.find(S=>429===S.code||"QUOTA_EXCEEDED"===S.data?.code);if(S)return this._handleQuotaExceeded(S.data||S),!1}const R=Date.now()-b;this._updateStats(S,R,!0);for(const b of S)try{await this.persistentQueue.remove(b.id)}catch(S){}for(const b of S)(b.id===this.firstSnapshotChunkId||b.isFirstChunk)&&(this.firstSnapshotAcked=!0,this.logger.log("[UploadQueue] ✓ First snapshot (chunk 0) acknowledged by server - session is replayable"));return S.forEach(S=>{this.config.onUploadSuccess(S.chunk,I)}),this.logger.log(`Batch uploaded successfully: ${S.length} chunks in ${R}ms`),!0}if(429===x.status){const S=await x.json().catch(()=>({}));return this._handleQuotaExceeded(S),!1}throw new Error(`Upload failed with status: ${x.status}`)}catch(b){return this.logger.error("Batch upload failed:",b),S.forEach(S=>{S.attempts++,S.lastAttempt=Date.now(),S.error=b.message,(S.id===this.firstSnapshotChunkId||S.isFirstChunk)&&S.attempts>=3&&!this._backupSnapshotRequested&&(this._backupSnapshotRequested=!0,this.logger.warn("[UploadQueue] First snapshot failed 3+ times - requesting backup"),this.emit("firstSnapshotUploadFailed")),S.attempts<this.config.maxRetries?(this.memoryManager.enforceFailedLimit(this.failedQueue),this.failedQueue.push(S)):(this._updateStats([S],0,!1),this.config.onUploadError(S.chunk,b),this.logger.error(`Chunk permanently failed after ${S.attempts} attempts: ${S.chunk.chunkId}`))}),!1}}_handleQuotaExceeded(S){this.isQuotaExceeded=!0,this.uploadQueue=[],this.failedQueue=[],console.error("%c[TraceScout] ⛔ SESSION QUOTA EXCEEDED","color: #ff4444; font-size: 16px; font-weight: bold;"),console.error("%c[TraceScout] Recording has been stopped.","color: #ff4444;"),S.usage&&console.error(`%c[TraceScout] Usage: ${S.usage.sessions}/${S.usage.limit} sessions`,"color: #ff4444;"),this.config.onUploadError(null,{code:"QUOTA_EXCEEDED",message:S.message||"Session quota exceeded",usage:S.usage}),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:quota_exceeded",{detail:S}))}async _processBatch(S){const b=[];for(const I of S)try{if(this.config.enableCompression&&I.originalSize>this.config.compressionThreshold){const S=await this._compressChunk(I.chunk);S.compressed&&S.compressedSize<I.originalSize&&(I.compressed=!0,I.compressedData=S.data,I.compressedSize=S.compressedSize)}b.push(I)}catch(S){this.logger.warn("Failed to process chunk, using original:",S),b.push(I)}return b}async _makeRequest(S){const b=new AbortController,I=setTimeout(()=>b.abort(),this.config.uploadTimeout);try{const x={"Content-Type":"application/json",...this.config.headers};this.sdkContext&&(x["X-Project-ID"]=this.sdkContext.projectId,x["X-Environment"]=this.sdkContext.environment||"production",x["X-SDK-Version"]="2.0.0");const R=await fetch(this.config.endpoint,{method:"POST",headers:x,body:JSON.stringify(S),signal:b.signal});return clearTimeout(I),R}catch(S){throw clearTimeout(I),S}}async _compressChunk(S){if(!this.config.enableCompression)return this.logger.debug("[UploadQueue] Compression disabled via config"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"!=typeof window&&!0===window.__TRACESCOUT_DISABLE_COMPRESSION)return this.logger.debug("[UploadQueue] Compression disabled via __TRACESCOUT_DISABLE_COMPRESSION"),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};if("undefined"==typeof window||"undefined"==typeof CompressionStream)return{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)};try{const b=JSON.stringify(S),I=(new TextEncoder).encode(b).length,x=new Blob([b],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),R=await new Response(x).arrayBuffer(),A=new Uint8Array(R),_=this._uint8ArrayToBase64(A),D=(100*(1-A.length/I)).toFixed(0),L=JSON.stringify(Array.from(A)).length,B=_.length+2;return this.logger.debug(`[UploadQueue] Compressed chunk: original=${I}B, gzip=${A.length}B (${D}% saved), base64=${B}B vs array=${L}B`),{compressed:!0,data:_,originalSize:I,compressedSize:A.length}}catch(b){return this.logger.warn("[UploadQueue] Compression failed, using uncompressed:",b.message),{compressed:!1,data:S,originalSize:this._estimateSize(S),compressedSize:this._estimateSize(S)}}}_uint8ArrayToBase64(S){if(S.length<32768){let b="";for(let I=0;I<S.length;I++)b+=String.fromCharCode(S[I]);return btoa(b)}let b="";for(let I=0;I<S.length;I+=32768){const x=S.subarray(I,Math.min(I+32768,S.length));for(let S=0;S<x.length;S++)b+=String.fromCharCode(x[S])}return btoa(b)}_handleNetworkChange(S,b){this.logger.log("Network status changed: "+(S?"online":"offline")),this.config.onNetworkChange(S,b),S&&!b&&(this._sortQueue(),this.isUploading||this._processQueue())}_sortQueue(){const S={high:3,normal:2,low:1};this.uploadQueue.sort((b,I)=>{const x=S[b.priority]||2,R=S[I.priority]||2;return x!==R?R-x:b.createdAt-I.createdAt})}async _addToOfflineQueue(S){this.uploadQueue.unshift(S);try{await this.persistentQueue.enqueue(S),this.logger.log(`[UploadQueue] Item persisted to IndexedDB: ${S.id}`)}catch(S){this.logger.warn("[UploadQueue] Failed to persist to IndexedDB:",S)}const b=this.memoryManager.enforceOfflineLimit(this.uploadQueue);if(b)try{await this.persistentQueue.remove(b.id)}catch(S){}}_scheduleRetry(){this.retryTimer&&clearTimeout(this.retryTimer);const S=this.circuitBreaker.getStatus();if("open"===S.state){const b=S.timeUntilReset;if(b>0)return this.logger.warn(`[UploadQueue] Delaying retry until circuit resets in ${Math.round(b/1e3)}s`),void(this.retryTimer=setTimeout(()=>{this._scheduleRetry()},b+1e3))}const b=this.config.retryDelay,I=this.config.maxRetryDelay,x=this.failedQueue[0]?.attempts||0,R=b*Math.pow(2,x),A=Math.min(R,I),_=.25*A,D=2*(Math.random()-.5)*_,L=Math.max(b,Math.round(A+D));this.retryTimer=setTimeout(()=>{this.logger.log(`Retrying ${this.failedQueue.length} failed items (attempt ${x+1})`),this.uploadQueue.unshift(...this.failedQueue),this.failedQueue=[],!this.isUploading&&this.networkMonitor.getStatus()&&this.circuitBreaker.canMakeRequest()&&this._processQueue()},L),this.logger.log(`[Retry] Scheduled in ${L}ms`)}_startProcessing(){this._processingTimer=setInterval(()=>{!this.isUploading&&this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()},5e3)}_updateStats(S,b,I){if(I){this.uploadStats.totalUploaded+=S.length,this.uploadStats.lastUploadTime=Date.now();const I=this.uploadStats.averageUploadTime,x=this.uploadStats.totalUploaded;this.uploadStats.averageUploadTime=(I*(x-S.length)+b)/x}else this.uploadStats.totalFailed+=S.length;S.forEach(S=>{this.uploadStats.totalBytes+=S.compressedSize||S.originalSize})}_validateChunk(S){if(!S)return{valid:!1,reason:"Chunk is null or undefined"};if(!S.sessionId)return{valid:!1,reason:"Missing required field: sessionId"};if(void 0===S.sequence&&void 0===S.chunkIndex)return{valid:!1,reason:"Missing required field: sequence"};if(!S.events||!Array.isArray(S.events))return{valid:!1,reason:"Missing or invalid events array"};if(0===S.events.length&&!S.metadata?.isLastChunk)return{valid:!1,reason:"Empty events array (non-final chunk)"};if("number"!=typeof S.startTimestamp||"number"!=typeof S.endTimestamp)return{valid:!1,reason:"Invalid timestamps"};try{JSON.stringify(S)}catch(S){return{valid:!1,reason:`Non-serializable data: ${S.message}`}}return{valid:!0}}_estimateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}_delay(S){return new Promise(b=>setTimeout(b,S))}getStats(){return{...this.uploadStats,queueSize:this.uploadQueue.length,failedQueueSize:this.failedQueue.length,isOnline:this.networkMonitor.getStatus(),isUploading:this.isUploading,isQuotaExceeded:this.isQuotaExceeded,circuitBreaker:this.circuitBreaker.getStatus()}}getCircuitBreakerStatus(){return this.circuitBreaker.getStatus()}resetCircuitBreaker(){this.circuitBreaker.reset()}isQuotaExceededStatus(){return this.isQuotaExceeded}isFirstSnapshotAcked(){return this.firstSnapshotAcked}didIndexedDBFail(){return!!this.persistentQueue&&this.persistentQueue.didInitFail()}getQueue(){return{pending:[...this.uploadQueue],failed:[...this.failedQueue]}}clearQueue(){const S=this.uploadQueue.length+this.failedQueue.length;return this.uploadQueue=[],this.failedQueue=[],this.logger.log(`Cleared ${S} items from queue`),S}pause(){this.isUploading=!0,this.logger.log("Upload queue paused")}resume(){this.isUploading=!1,this.logger.log("Upload queue resumed"),this.networkMonitor.getStatus()&&this.uploadQueue.length>0&&this._processQueue()}updateConfig(S){this.config={...this.config,...S},this.logger.log("Upload queue configuration updated")}getMemoryStats(){return this.memoryManager.getStats(this.uploadQueue,this.failedQueue)}forceMemoryCleanup(S={}){return this.memoryManager.forceCleanup(this.uploadQueue,this.failedQueue,S)}sendFinalChunkWithBeacon(S,b="unknown"){const I=this._validateChunk(S);return I.valid?this.beaconSender.send(S,b):(this.logger.warn(`[Beacon] Invalid final chunk: ${I.reason}`),!1)}async getPersistentQueueStats(){return{persistentQueueSize:await this.persistentQueue.count(),isIndexedDBAvailable:this.persistentQueue.isAvailable()}}destroy(){this.networkMonitor.destroy(),this.retryTimer&&clearTimeout(this.retryTimer),this._processingTimer&&clearInterval(this._processingTimer),this.persistentQueue&&this.persistentQueue.close(),this.circuitBreaker.destroy(),this.beaconSender.destroy(),this.memoryManager.destroy(),this.clearQueue(),this.logger.log("Upload queue destroyed")}}class ChunkedCompressedStorage{static CHUNK_SIZE=50;static CHUNK_PREFIX="rrweb_chunk_";static logger=createLogger("ChunkedCompressedStorage");static initSession(S){sessionStorage.setItem(`${S}_info`,JSON.stringify({startTime:Date.now(),chunkCount:0,totalEvents:0,isActive:!0}))}static updateSessionInfo(S,b,I){try{const x=JSON.parse(sessionStorage.getItem(`${S}_info`)||"{}");x.chunkCount=b,x.totalEvents=I,sessionStorage.setItem(`${S}_info`,JSON.stringify(x))}catch(S){this.logger.warn("Failed to update session info",S)}}static compress(S){const b=zlibSync(strToU8(JSON.stringify(S)),{level:6});return Array.from(b)}static decompress(S){const b=strFromU8(unzlibSync(new Uint8Array(S)));return JSON.parse(b)}static saveChunk(S,b,I){try{const x=this.compress({events:I}),R=`${S}_${this.CHUNK_PREFIX}${b}`;return sessionStorage.setItem(R,JSON.stringify(x)),!0}catch(S){return this.logger.error("saveChunk failed",S),!1}}static loadChunk(S,b){const I=`${S}_${this.CHUNK_PREFIX}${b}`,x=sessionStorage.getItem(I);if(!x)return null;try{const S=JSON.parse(x);return this.decompress(S).events||[]}catch(S){return this.logger.warn("loadChunk failed",S),null}}static getChunkCount(S){const b=sessionStorage.getItem(`${S}_info`);return b&&JSON.parse(b).chunkCount||0}static async streamChunks(S,b={}){const{onChunkLoad:I=()=>{},onProgress:x=()=>{},onComplete:R=()=>{},chunkDelay:A=50,startChunk:_=0}=b,D=this.getChunkCount(S);for(let b=_;b<D;b++){const R=this.loadChunk(S,b);R&&R.length&&I(R,b),x(b+1,D),b<D-1&&A>0&&await new Promise(S=>setTimeout(S,A))}R()}static clearSession(S){Object.keys(sessionStorage).forEach(b=>{b.startsWith(S)&&sessionStorage.removeItem(b)}),sessionStorage.removeItem(`${S}_info`)}}var Mc=Object.freeze({__proto__:null,ChunkedCompressedStorage:ChunkedCompressedStorage});class SessionStorage{constructor(S={}){this.storageKey=S.storageKey||"__tracescout_sessions__",this.maxStorageSize=S.maxStorageSize||52428800,this.maxSessions=S.maxSessions||10,this.logger=S.logger||createLogger("SessionStorage")}storeChunk(S,b){try{const I=this.getSessions();return I[S]||(I[S]={chunks:[],metadata:{startTime:Date.now(),lastActivity:Date.now(),totalEvents:0,totalChunks:0}}),I[S].chunks.push(b),I[S].metadata.lastActivity=Date.now(),I[S].metadata.totalEvents+=b.eventCount,I[S].metadata.totalChunks+=1,this.calculateSize(I)>this.maxStorageSize&&this.cleanup(I),this.saveSessions(I),this.logger.log(`Stored chunk ${b.chunkId} for session ${S}`),!0}catch(S){return this.logger.error("Failed to store chunk:",S),!1}}getSessions(){try{const S=localStorage.getItem(this.storageKey);return S?JSON.parse(S):{}}catch(S){return this.logger.error("Failed to load sessions:",S),{}}}getSession(S){return this.getSessions()[S]||null}saveSessions(S){try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(b){if("QuotaExceededError"===b.name){this.logger.warn("Storage quota exceeded, performing emergency cleanup"),this.emergencyCleanup();try{localStorage.setItem(this.storageKey,JSON.stringify(S))}catch(S){this.logger.error("Storage failed even after cleanup:",S)}}else this.logger.error("Failed to save sessions:",b)}}calculateSize(S){try{return JSON.stringify(S).length}catch(S){return 0}}cleanup(S){const b=Object.entries(S).sort(([,S],[,b])=>S.metadata.lastActivity-b.metadata.lastActivity);for(;this.calculateSize(S)>this.maxStorageSize&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed old session: ${I}`)}for(;Object.keys(S).length>this.maxSessions&&b.length>0;){const[I]=b.shift();delete S[I],this.logger.log(`Removed session due to count limit: ${I}`)}}emergencyCleanup(){try{localStorage.removeItem(this.storageKey),this.logger.warn("Emergency cleanup: cleared all session storage")}catch(S){this.logger.error("Emergency cleanup failed:",S)}}removeSession(S){try{const b=this.getSessions();return!!b[S]&&(delete b[S],this.saveSessions(b),this.logger.log(`Removed session: ${S}`),!0)}catch(S){return this.logger.error("Failed to remove session:",S),!1}}getStorageStats(){try{const S=this.getSessions(),b=this.calculateSize(S),I=Object.keys(S).length;let x=0,R=0;return Object.values(S).forEach(S=>{x+=S.metadata.totalEvents,R+=S.metadata.totalChunks}),{totalSize:b,sessionCount:I,totalEvents:x,totalChunks:R,maxStorageSize:this.maxStorageSize,maxSessions:this.maxSessions,storageUsagePercent:Math.round(b/this.maxStorageSize*100)}}catch(S){return this.logger.error("Failed to get storage stats:",S),null}}exportSession(S,b="json"){try{const I=this.getSession(S);if(!I)return null;const x={sessionId:S,metadata:I.metadata,chunks:I.chunks,totalChunks:I.chunks.length,totalEvents:I.metadata.totalEvents,exportTimestamp:Date.now()};return"json"===b?JSON.stringify(x,null,2):x}catch(S){return this.logger.error("Failed to export session:",S),null}}importSession(S){try{const b="string"==typeof S?JSON.parse(S):S;if(!b.sessionId||!b.chunks)throw new Error("Invalid session data format");const I=this.getSessions();return I[b.sessionId]={chunks:b.chunks,metadata:b.metadata||{startTime:Date.now(),lastActivity:Date.now(),totalEvents:b.totalEvents||0,totalChunks:b.totalChunks||0}},this.saveSessions(I),this.logger.log(`Imported session: ${b.sessionId}`),!0}catch(S){return this.logger.error("Failed to import session:",S),!1}}clearAll(){try{return localStorage.removeItem(this.storageKey),this.logger.log("Cleared all sessions"),!0}catch(S){return this.logger.error("Failed to clear all sessions:",S),!1}}}var Rc=Object.freeze({__proto__:null,BeaconSender:BeaconSender,CHUNK_FORMAT_VERSION:4,CheckpointManager:CheckpointManager,ChunkManager:ChunkManager,ChunkedCompressedStorage:ChunkedCompressedStorage,CircuitBreaker:CircuitBreaker,EventOptimizer:EventOptimizer,InactivityManager:InactivityManager,IndexedDBQueue:IndexedDBQueue,NetworkMonitor:NetworkMonitor,PageLifecycleManager:PageLifecycleManager,QueueMemoryManager:QueueMemoryManager,Recorder:Recorder,RecorderMemoryManager:RecorderMemoryManager,RecorderPresets:Ec,SessionStorage:SessionStorage,UploadQueue:UploadQueue,analyzeSnapshotsInEvents:analyzeSnapshotsInEvents,buildSnapshotIndex:buildSnapshotIndex,chunkHasSnapshot:chunkHasSnapshot,collectDeviceMetadata:collectDeviceMetadata,createChunk:createChunk,detectDeviceType:detectDeviceType,detectTouchCapability:detectTouchCapability,extractConsoleRef:extractConsoleRef,extractNetworkFull:extractNetworkFull,extractNetworkRef:extractNetworkRef,extractResourceRef:extractResourceRef,findNearestSnapshotBefore:findNearestSnapshotBefore,generateConsoleId:generateConsoleId,generateNetworkId:generateNetworkId,generateResourceId:generateResourceId,getConnectionInfo:getConnectionInfo,getEventsAfterSnapshot:getEventsAfterSnapshot,getMemoryInfo:getMemoryInfo,getRRWeb:getRRWeb,getRRWebSource:getRRWebSource,getRecord:getRecord,getSnapshotTimestamps:getSnapshotTimestamps,hashCode:hashCode,isCompatibleVersion:isCompatibleVersion,isRRWebLoaded:isRRWebLoaded,loadRRWeb:loadRRWeb,parseBrowserInfo:parseBrowserInfo,parseOSInfo:parseOSInfo,sanitizeUrl:sanitizeUrl,stripNetworkPayload:stripNetworkPayload});"undefined"!=typeof window&&(window.TraceScout=Qe,Qe.setTransport=TraceScoutMonitoringCore.setTransport.bind(TraceScoutMonitoringCore)),S.BODY_REDACTED_VALUE=Le,S.BaseInterceptor=BaseInterceptor,S.BeaconSender=BeaconSender,S.CHUNK_FORMAT_VERSION=4,S.CORE_WEB_VITALS_DEFAULTS={THRESHOLDS:{lcp:{good:2500,needsImprovement:4e3},fid:{good:100,needsImprovement:300},cls:{good:.1,needsImprovement:.25},inp:{good:200,needsImprovement:500},ttfb:{good:800,needsImprovement:1800},fcp:{good:1800,needsImprovement:3e3}},COLLECT_METRICS:{lcp:!0,fid:!0,cls:!0,inp:!0,ttfb:!0,fcp:!0},USE_WEB_VITALS_LIBRARY:!0,REPORTING_ENABLED:!0,REPORT_THRESHOLD:"needsImprovement"},S.CheckpointManager=CheckpointManager,S.ChunkManager=ChunkManager,S.ChunkedCompressedStorage=ChunkedCompressedStorage,S.CircuitBreaker=CircuitBreaker,S.ConfigManager=ConfigManager,S.ConsoleInterceptor=ConsoleInterceptor,S.CoreWebVitalsMonitor=CoreWebVitalsMonitor,S.DEFAULT_CONFIG=A,S.DEFAULT_FIELD_PATTERNS={EMAIL_REGEX:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,PHONE_REGEX:/^[\+]?[1-9][\d]{0,15}$/,UUID_REGEX:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i},S.DEFAULT_MAX_BODY_BYTES=Pe,S.DEFAULT_MAX_BODY_SIZE=Ne,S.DEFAULT_SENSITIVE_FIELDS=ze,S.EVENT_TYPES={FETCH_HTTP_ERROR:"fetch_http_error",FETCH_NETWORK_ERROR:"fetch_network_error",FETCH_SILENT_LOGIN_FAILURE:"fetch_silent_login_failure",XHR_HTTP_ERROR:"xhr_http_error",XHR_NETWORK_ERROR:"xhr_network_error",XHR_TIMEOUT_ERROR:"xhr_timeout_error",XHR_ABORTED_ERROR:"xhr_aborted_error",XHR_SILENT_LOGIN_FAILURE:"xhr_silent_login_failure",RESOURCE_LOAD_ERROR:"resource_load_error",CUSTOM_API_ERROR:"custom_api_error",UNKNOWN_ERROR:"unknown_error",POSTMESSAGE_COMMUNICATION:"postmessage_communication",POSTMESSAGE_CROSS_ORIGIN:"postmessage_cross_origin",POSTMESSAGE_LARGE_PAYLOAD:"postmessage_large_payload",POSTMESSAGE_SUSPICIOUS_ORIGIN:"postmessage_suspicious_origin",POSTMESSAGE_ERROR:"postmessage_error",FETCH_SLOW_REQUEST:"fetch_slow_request",XHR_SLOW_REQUEST:"xhr_slow_request",PERFORMANCE_DEGRADATION_ALERT:"performance_degradation_alert",P1_INCIDENT_EVENT:"p1_incident_event",CORE_WEB_VITAL:"core_web_vital"},S.ErrorFingerprint=ErrorFingerprint,S.ErrorHandler=ErrorHandler,S.EventManager=EventManager,S.EventOptimizer=EventOptimizer,S.FetchInterceptor=FetchInterceptor,S.InactivityManager=InactivityManager,S.IndexedDBQueue=IndexedDBQueue,S.LOCAL_STORAGE_KEYS={EVENTS:"__api_reporter_events__",USER_PROFILE:"__api_reporter_user_profile__"},S.LogBuffer=LogBuffer,S.LogManager=LogManager,S.Logger=Logger,S.LoggingManager=LoggingManager,S.MAX_BODY_BYTES_CEILING=Be,S.NetworkMonitor=NetworkMonitor,S.PageLifecycleManager=PageLifecycleManager,S.PerformanceMonitor=class PerformanceMonitor{constructor(S={}){this.slowRequestThreshold=S.slowRequestThreshold||2e3,this.averageAlertThreshold=S.averageAlertThreshold||2500,this.maxRequests=S.maxRequestHistory||1e3,this.debug=S.debug||!1,this.logger=createLogger("PerformanceMonitor"),this.requests=[],this.endpointStats=new Map,this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap=new Map,this.logger.log(`Performance monitoring initialized - Slow threshold: ${this.slowRequestThreshold}ms, Alert threshold: ${this.averageAlertThreshold}ms`)}startTracking(S,b,I){this.requestIdMap.set(S,{url:b,method:I,startTime:performance.now(),endpoint:this.getEndpointPattern(b)})}endTracking(S,b){const I=this.requestIdMap.get(S);if(!I)return null;const x=performance.now()-I.startTime;this.requestIdMap.delete(S),this.addRequest(x,I.endpoint);const R=x>this.slowRequestThreshold;R&&this.logSlowRequest(I.url,x);const A=this.checkAverageThreshold();return{duration:x,durationSeconds:Number((x/1e3).toFixed(2)),isSlowRequest:R,endpoint:I.endpoint,performanceAlert:A.alert,metrics:A.metrics}}addRequest(S,b){this.requests.push({duration:S,endpoint:b,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(b)||this.endpointStats.set(b,[]);const I=this.endpointStats.get(b);I.push(S),I.length>100&&I.shift()}checkAverageThreshold(){const S=this.calculateMetrics();return S.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${S.averageSeconds}s`),{alert:!0,metrics:{...S,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${S.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(S.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${S.averageSeconds}s`)),{alert:!1,metrics:S})}calculateMetrics(){if(0===this.requests.length)return{count:0,average:0,averageSeconds:0,min:0,max:0,median:0,p95:0,p99:0};const S=this.requests.map(S=>S.duration).sort((S,b)=>S-b),b=S.length,I=S.reduce((S,b)=>S+b,0)/b,x=S[0],R=S[b-1],A=this.calculatePercentile(S,50),_=this.calculatePercentile(S,95),D=this.calculatePercentile(S,99);return{count:b,average:Math.round(I),averageSeconds:Number((I/1e3).toFixed(2)),min:Math.round(x),max:Math.round(R),median:Math.round(A),p95:Math.round(_),p99:Math.round(D)}}calculatePercentile(S,b){const I=Math.ceil(b/100*S.length)-1;return S[Math.max(0,I)]}getEndpointPattern(S){try{const b=new URL(S);return`${b.hostname}${b.pathname.split("/").slice(0,3).join("/")}`}catch{return S.split("?")[0].split("/").slice(0,4).join("/")}}logSlowRequest(S,b){this.logger.warn(`Slow request detected: ${S} (${b.toFixed(0)}ms)`)}getEndpointStats(S){const b=this.endpointStats.get(S)||[];if(0===b.length)return null;const I=b.sort((S,b)=>S-b),x=I.length,R=I.reduce((S,b)=>S+b,0)/x;return{endpoint:S,count:x,average:Math.round(R),averageSeconds:Number((R/1e3).toFixed(2)),min:Math.round(I[0]),max:Math.round(I[x-1]),median:Math.round(this.calculatePercentile(I,50))}}getAllEndpointStats(){const S=[];for(const[b]of this.endpointStats){const I=this.getEndpointStats(b);I&&S.push(I)}return S.sort((S,b)=>b.count-S.count)}getSessionDuration(){return Date.now()-this.sessionStart}reset(){this.requests=[],this.endpointStats.clear(),this.alertSent=!1,this.sessionStart=Date.now(),this.requestIdMap.clear(),this.logger.log("Performance monitor reset")}getStatus(){const S=this.calculateMetrics();return{active:!0,sessionDuration:this.getSessionDuration(),totalRequests:S.count,currentAverage:S.averageSeconds,slowRequestThreshold:this.slowRequestThreshold,averageAlertThreshold:this.averageAlertThreshold,alertActive:this.alertSent,endpoints:this.getAllEndpointStats()}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}},S.PerformanceResourceObserver=PerformanceResourceObserver,S.PostMessageInterceptor=PostMessageInterceptor,S.QueueMemoryManager=QueueMemoryManager,S.REDACTED_VALUE=_e,S.REPORTER_LOG_PREFIX="[TraceScoutMonitoringCore]",S.RESOURCE_EXTENSIONS=Oe,S.Recorder=Recorder,S.RecorderMemoryManager=RecorderMemoryManager,S.RecorderPresets=Ec,S.RemoteConfigService=class RemoteConfigService{constructor(S,b=null){this.context=S;const I="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname?"https://api.tracescout.com":"http://localhost:3001";this.baseUrl=b||I,this.config=null,this.lastFetched=null,this.refreshInterval=3e5,this.refreshTimer=null,this.logger=createLogger("RemoteConfig"),this.fetchAttempts=0,this.maxFetchAttempts=3,console.log("[RemoteConfigService] Using API base URL:",this.baseUrl)}async fetchConfig(){try{this.fetchAttempts++,this.logger.log("Fetching remote SDK configuration..."),this.logger.log(` Project: ${this.context.projectId}`),this.logger.log(` Workspace: ${this.context.workspaceId}`),this.logger.log(` Attempt: ${this.fetchAttempts}/${this.maxFetchAttempts}`);const S=`${this.baseUrl}/api/projects/${this.context.projectId}/sdk-config`,b=await fetch(S,{method:"GET",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},signal:AbortSignal.timeout(1e4)});if(!b.ok){const S=await b.text();throw new Error(`Config fetch failed: ${b.status} ${b.statusText} - ${S}`)}const I=await b.json();this.#Rt(I),this.config=I,this.lastFetched=Date.now(),this.fetchAttempts=0,this.logger.log("✅ Remote configuration loaded successfully"),this.logger.log(` Config version: ${I.configVersion}`),this.logger.log(` Workspace: ${I.workspace.name}`),this.logger.log(` Project: ${I.project.name}`);const x=Object.keys(I.features).filter(S=>I.features[S].enabled).join(", ");return this.logger.log(` Features enabled: ${x||"none"}`),this.#Tt(),I}catch(S){this.logger.error("Failed to fetch remote config:",S.message),this.fetchAttempts<this.maxFetchAttempts?this.logger.warn(`Will retry... (${this.fetchAttempts}/${this.maxFetchAttempts})`):this.logger.warn("Max fetch attempts reached, using fallback configuration");const b=this.#At();return this.config=b,b}}#Rt(S){if(!S.success)throw new Error("Server returned unsuccessful config response");if(!S.project||S.project.id!==this.context.projectId)throw new Error(`Config projectId mismatch. Expected: ${this.context.projectId}, Got: ${S.project?.id}`);if(!S.workspace||!S.workspace.id)throw new Error("Config missing workspace data");if(!S.features)throw new Error("Config missing features object");if(!S.privacy)throw new Error("Config missing privacy object");if(!S.telemetry)throw new Error("Config missing telemetry object");this.logger.log("✓ Config validation passed")}#At(){return this.logger.warn("⚠️ Using fallback configuration - limited functionality"),this.logger.warn(" Session recording: enabled (100% sample rate)"),this.logger.warn(" Error tracking: enabled"),this.logger.warn(" Other features: disabled"),{success:!0,configVersion:"2.0.0-fallback",lastUpdated:(new Date).toISOString(),workspace:{id:this.context.workspaceId,name:"Unknown Workspace (Fallback)"},project:{id:this.context.projectId,name:"Unknown Project (Fallback)",environment:this.context.environment,allowedOrigins:[]},features:{sessionRecording:{enabled:!0,sampleRate:1,maskAllInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[],chunkDuration:3e4,maxChunkSize:5e5,recordCanvas:!1,collectFonts:!1},errorTracking:{enabled:!0,ignoreErrors:[],sourceMaps:!1,stackTraceLimit:30},performanceMonitoring:{enabled:!1,coreWebVitals:!1,longTaskThreshold:50,resourceTimingBufferSize:250},consoleCapture:{enabled:!0,levels:["error","warn"]},networkMonitoring:{enabled:!1,endpoints:[],captureHeaders:!1,captureBody:!1}},privacy:{maskInputs:!1,maskImages:!1,blockClass:"ts-block",ignoreClass:"ts-ignore",maskTextClass:"ts-mask",blockSelectors:[]},telemetry:{endpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`,sessionEndpoint:`${this.baseUrl}/api/projects/${this.context.projectId}/sessions`,batchSize:10,flushInterval:5e3,enableCompression:!0},service:{send:async S=>{const b=`${this.baseUrl}/api/projects/${this.context.projectId}/telemetry`;console.log("[TraceScout][FallbackService] Sending to:",b),console.log("[TraceScout][FallbackService] Events:",S);try{const I=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json","X-Project-ID":this.context.projectId,"X-SDK-Version":"2.0.0"},body:JSON.stringify({events:S,context:{workspaceId:this.context.workspaceId,projectId:this.context.projectId,environment:this.context.environment,sessionId:this.context.sessionId}})});if(!I.ok)throw new Error(`HTTP ${I.status}: ${I.statusText}`);return await I.json()}catch(S){throw console.error("[TraceScout][FallbackService] Send failed:",S),S}}}}}#Tt(){this.refreshTimer&&clearTimeout(this.refreshTimer),this.refreshTimer=setTimeout(async()=>{this.logger.log("⏰ Refreshing remote configuration...");try{await this.fetchConfig(),this.logger.log("✅ Config refreshed successfully")}catch(S){this.logger.error("Config refresh failed:",S.message)}},this.refreshInterval),this.logger.log(`Next config refresh in ${this.refreshInterval/1e3}s`)}stopRefresh(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null,this.logger.log("Config refresh stopped"))}getConfig(){return this.config}isStale(){return!this.lastFetched||Date.now()-this.lastFetched>this.refreshInterval}async refresh(){return this.logger.log("Forcing config refresh..."),await this.fetchConfig()}getConfigAge(){return this.lastFetched?Math.floor((Date.now()-this.lastFetched)/1e3):-1}},S.ResourceInterceptor=class ResourceInterceptor{constructor(S){this.reporter=S,this.interceptorName="resource",this.logger=createLogger("ResourceInterceptor"),this.boundErrorHandler=this.handleResourceError.bind(this),this.isDestroyed=!1}setup(){this.isDestroyed?this.logger.warn("Attempted to setup destroyed ResourceInterceptor"):(window.addEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor setup complete"))}handleResourceError(S){if(this.isDestroyed)return;const b=S.target;if(b instanceof HTMLScriptElement||b instanceof HTMLLinkElement||b instanceof HTMLImageElement){const S=b.src||b.href||"",I=b.tagName.toLowerCase(),x=parseUrl(S),R={type:"resource_load_error",request:{method:"GET",url:S,domain:x.hostname||this.#_t(S),path:x.pathname||this.#Ot(S),status:0,statusText:"Resource failed to load",response:`${I} element failed to load`,headers:{},interceptor:"resource"},extraData:{tag:I,elementType:b.constructor.name,errorType:"resource_load_failure",resourceType:this.#Dt(I),crossOrigin:this.#Ft(S),isDomElement:!0,integrity:b.integrity||null,crossorigin:b.crossOrigin||null,async:b.async||!1,defer:b.defer||!1,rel:b.rel||null,type:b.type||null},context:{forceLog:!0,isMonitored:this.shouldMonitor(S),scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent,timestamp:Date.now()}};this.logger.log(`Creating resource error event: ${S} [${I}]`),this.reporter&&this.reporter.logEvent?(this.reporter.logEvent(R),this.logger.log(`Resource error event sent for: ${S}`)):this.logger.error("Could not send resource error - reporter.logEvent not available"),this.logger.log(`Resource failed to load: ${S} [${I}]`)}}shouldMonitor(S){return this.reporter.isMonitoredEndpoint?.(S)||!0}updateDebugMode(S){this.logger.updateDebugMode&&this.logger.updateDebugMode(S)}#_t(S){try{return new URL(S,location.origin).hostname}catch{return""}}#Ot(S){try{return new URL(S,location.origin).pathname}catch{return""}}#Dt(S){switch(S.toLowerCase()){case"script":return"javascript";case"link":return"stylesheet";case"img":return"image";case"video":return"video";case"audio":return"audio";case"source":return"media-source";case"track":return"text-track";case"object":return"object";case"embed":return"embed";case"iframe":return"iframe";default:return"unknown"}}#Ft(S){try{return new URL(S,location.origin).origin!==location.origin}catch{return!1}}destroy(){this.isDestroyed?this.logger.warn("ResourceInterceptor already destroyed"):(this.isDestroyed=!0,window.removeEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor destroyed"),this.reporter=null,this.boundErrorHandler=null)}},S.SDKContext=SDKContext,S.SENSITIVE_HEADERS=Ae,S.SENSITIVE_QUERY_PARAMS=$e,S.ServiceLogger=ServiceLogger,S.ServiceManager=ServiceManager,S.SessionManager=SessionManager,S.SessionStorage=SessionStorage,S.TraceScoutMonitoringCore=TraceScoutMonitoringCore,S.UploadQueue=UploadQueue,S.UserProfileManager=UserProfileManager,S.XHRInterceptor=XHRInterceptor,S.analyzeSnapshotsInEvents=analyzeSnapshotsInEvents,S.buildFieldDenylist=buildFieldDenylist,S.buildSnapshotIndex=buildSnapshotIndex,S.captureRequestBody=captureRequestBody,S.captureResponseBody=captureResponseBody,S.chunkHasSnapshot=chunkHasSnapshot,S.classifyMime=classifyMime,S.collectDeviceMetadata=collectDeviceMetadata,S.createChunk=createChunk,S.createLogger=createLogger,S.createSensitiveHeaderSet=function createSensitiveHeaderSet(S=[]){return new Set([...Ae,...S.map(S=>S.toLowerCase())])},S.debounce=debounce,S.deepClone=function deepClone(S){if(null===S||"object"!=typeof S)return S;if(S instanceof Date)return new Date(S.getTime());if(S instanceof Array)return S.map(S=>deepClone(S));if(S instanceof Object){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=deepClone(S[I]));return b}},S.default=Qe,S.detectDeviceType=detectDeviceType,S.detectTouchCapability=detectTouchCapability,S.extractConsoleRef=extractConsoleRef,S.extractNetworkFull=extractNetworkFull,S.extractNetworkRef=extractNetworkRef,S.extractRequestDetails=function extractRequestDetails(S,b,I,x,R="",A="unknown"){try{const _=new URL(S,location.origin);return{method:b.toUpperCase(),url:S,domain:_.hostname,path:_.pathname,status:I,statusText:x,response:R,interceptor:A}}catch{return{method:b.toUpperCase(),url:S,domain:"",path:"",status:I,statusText:x,response:R,interceptor:A}}},S.extractResourceRef=extractResourceRef,S.filterSensitiveHeaders=filterSensitiveHeaders,S.findNearestSnapshotBefore=findNearestSnapshotBefore,S.generateConsoleId=generateConsoleId,S.generateId=generateId,S.generateNetworkId=generateNetworkId,S.generateResourceId=generateResourceId,S.getConnectionInfo=getConnectionInfo,S.getEventsAfterSnapshot=getEventsAfterSnapshot,S.getMemoryInfo=getMemoryInfo,S.getRRWeb=getRRWeb,S.getRRWebSource=getRRWebSource,S.getRecord=getRecord,S.getResourceType=getResourceType,S.getSensitiveHeadersList=function getSensitiveHeadersList(){return[...Ae]},S.getSnapshotTimestamps=getSnapshotTimestamps,S.handleRequestBody=handleRequestBody,S.handleResponseBody=handleResponseBody,S.hashCode=hashCode,S.initializeErrorHandler=function initializeErrorHandler(S,b={}){const I=new ErrorHandler(S,b);return I.install(),I},S.isApiEndpoint=function isApiEndpoint(S){if(!S)return!1;const b=S.toLowerCase();return!![/\/api\//i,/\/v\d+\//i,/\/graphql/i,/\/rest\//i,/\/rpc\//i,/\.json(\?|$)/i].some(S=>S.test(b))||!isStaticResource(S)},S.isCompatibleVersion=isCompatibleVersion,S.isRRWebLoaded=isRRWebLoaded,S.isResourceUrl=(S,b="")=>{const I=S.split("?")[0].toLowerCase();return[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".webp",".ico",".woff",".woff2",".ttf",".eot",".otf",".pdf",".mp4",".mp3",".wav",".zip",".tar",".gz",".xml",".txt",".csv"].some(S=>I.endsWith(S))},S.isSensitiveField=isSensitiveField,S.isSensitiveHeader=function isSensitiveHeader(S){return!!S&&Ae.includes(S.toLowerCase())},S.isStaticResource=isStaticResource,S.isTextualContentType=isTextualContentType,S.loadRRWeb=loadRRWeb,S.loggingManager=_,S.monitoringCore=Qe,S.parseBrowserInfo=parseBrowserInfo,S.parseFormData=parseFormData,S.parseOSInfo=parseOSInfo,S.parseRequestUrl=function parseRequestUrl(S){try{return new URL(S,location.origin)}catch(S){return null}},S.parseUrl=parseUrl,S.redactFormUrlEncoded=redactFormUrlEncoded,S.redactObject=redactObject,S.safeJsonParse=function safeJsonParse(S,b=null){try{return JSON.parse(S)}catch(S){return b}},S.safeJsonStringify=function safeJsonStringify(S,b="{}"){try{return JSON.stringify(S)}catch(S){return b}},S.safeMime=safeMime,S.safeParseConsoleArgs=safeParseConsoleArgs,S.safeSessionStorage=I,S.safeStorage=b,S.safeStringify=safeStringify,S.splitSanitizedUrl=splitSanitizedUrl,S.stripNetworkPayload=stripNetworkPayload,S.throttle=throttle$1,S.truncateToBytes=truncateToBytes,S.typeUtils=x,S.utf8Bytes=utf8Bytes,S.utils=R,S.validateDomains=validateDomains,S.validateEndpoints=validateEndpoints,S.validateService=validateService,Object.defineProperty(S,"__esModule",{value:!0})});
|