@tracescout/browser 2.5.0 → 2.7.0
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/CHANGELOG.md +14 -0
- package/dist/tracescout.esm.min.js +1 -1
- package/dist/tracescout.min.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
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 S={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)}},b={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}}},I={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 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}}function safeJsonParse(S,b=null){try{return JSON.parse(S)}catch(S){return b}}function safeJsonStringify(S,b="{}"){try{return JSON.stringify(S)}catch(S){return 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 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))},x={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=>x.cloneDeep(S));if("object"==typeof S){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=x.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)&&(x.isObject(S[b])&&x.isObject(I[b])?I[b]=x.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),R=Object.keys(b);if(I.length!==R.length)return!1;for(const A of I){if(!R.includes(A))return!1;if(!x.isEqual(S[A],b[A]))return!1}return!0}},R={EVENTS:"__api_reporter_events__",USER_PROFILE:"__api_reporter_user_profile__"},A={RETRY_INTERVAL_MS:3e4,DEDUPLICATION_WINDOW_MS:6e4,MAX_QUEUE_SIZE:1e3,MAX_RETRIES:3,BATCH_SIZE:10,DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS:[]},_="[TraceScoutMonitoringCore]",D={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"},L={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},B={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"};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 U=new LoggingManager;function createLogger(S){return U.createLogger(S)}class Logger{constructor(S="",b=!1){this.serviceName=S.replace(/^\[|\]$/g,""),this.serviceLogger=U.createLogger(this.serviceName),b&&U.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=x.merge({},this.defaultConfig,S,{debug:"boolean"==typeof x.get(S,"debug")?x.get(S,"debug"):Boolean(x.get(S,"debug")),retryIntervalMs:Math.max(1e3,x.get(S,"retryIntervalMs",this.defaultConfig.retryIntervalMs)),deduplicationWindowMs:Math.max(100,x.get(S,"deduplicationWindowMs",this.defaultConfig.deduplicationWindowMs)),maxQueueSize:Math.max(10,x.get(S,"maxQueueSize",this.defaultConfig.maxQueueSize)),maxRetries:Math.max(1,Math.min(10,x.get(S,"maxRetries",this.defaultConfig.maxRetries))),batchSize:Math.max(1,Math.min(100,x.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 x.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 $,j,W,H,V,Q=-1,o=function(S){addEventListener("pageshow",function(b){b.persisted&&(Q=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 Q>=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)}},G=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},g=function(S){"hidden"===document.visibilityState&&G>-1&&(G="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 G<0&&(G=h(),y(),o(function(){setTimeout(function(){G=h(),y()},0)})),{get firstHiddenTime(){return G}}},C=function(S){document.prerendering?addEventListener("prerenderingchange",function(){return S()},!0):S()},J=[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,J,b.reportAllChanges),o(function(x){R=f("FCP"),I=d(S,R,J,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,I(!0)})}))})},X=[.1,.25],Y={passive:!0,capture:!0},ee=new Date,P=function(S,b){$||($=b,j=S,W=new Date,k(removeEventListener),F())},F=function(){if(j>=0&&j<W-ee){var S={entryType:"first-input",name:$.type,target:$.target,cancelable:$.cancelable,startTime:$.timeStamp,processingStart:$.timeStamp+j};H.forEach(function(b){b(S)}),H=[]}},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,Y),removeEventListener("pointercancel",i,Y)};addEventListener("pointerup",t,Y),addEventListener("pointercancel",i,Y)}(b,S):P(b,S)}},k=function(S){["mousedown","keydown","touchstart","pointerdown"].forEach(function(b){return S(b,M,Y)})},te=[100,300],se=0,re=1/0,ne=0,N=function(S){S.forEach(function(S){S.interactionId&&(re=Math.min(re,S.interactionId),ne=Math.max(ne,S.interactionId),se=ne?(ne-re)/7+1:0)})},O=function(){return V?se:performance.interactionCount||0},q=function(){"interactionCount"in performance||V||(V=s("event",N,{type:"event",buffered:!0,durationThreshold:0}))},ie=[200,500],oe=0,z=function(){return O()-oe},ae=[],le={},K=function(S){var b=ae[ae.length-1],I=le[S.interactionId];if(I||ae.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]};le[x.id]=x,ae.push(x)}ae.sort(function(S,b){return b.latency-S.latency}),ae.splice(10).forEach(function(S){delete le[S.id]})}},ce=[2500,4e3],ue={},he=[800,1800],de=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,he,b.reportAllChanges);de(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,he,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,ce,b.reportAllChanges);var _=v(function(){ue[R.id]||(a(A.takeRecords()),A.disconnect(),ue[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,ce,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,ue[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,te,b.reportAllChanges),A&&p(v(function(){m(A.takeRecords()),A.disconnect()})),A&&o(function(){var x;R=f("FID"),I=d(S,R,te,b.reportAllChanges),H=[],j=-1,$=null,k(addEventListener),x=l,H.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,X,b.reportAllChanges),p(function(){c(_.takeRecords()),I(!0)}),o(function(){R=0,x=f("CLS",0),I=d(S,x,X,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&&!ae.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(ae.length-1,Math.floor(z()/50)),ae[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,ie,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(){ae=[],oe=O(),R=f("INP"),x=d(S,R,ie,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}}let ge=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)}`}};const pe="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+=pe[b[S]>>4]+pe[15&b[S]];return I.slice(0,S)}let b="";for(let I=0;I<S;I++)b+=pe[Math.floor(16*Math.random())];return b}(12)}`}const fe=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.topFrameIdentity=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.5.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,domPrivacy:this.domPrivacy||void 0,url:window.location.href,referrer:document.referrer,title:document.title}}}recordError(){this.errorCount++}setDomPrivacy(S){"string"==typeof S&&fe.has(S)&&(this.domPrivacy=S)}setTopFrameIdentity(S){this.topFrameIdentity=S&&"object"==typeof S?S:null}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,R={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},A=this.topFrameIdentity;return A&&"object"==typeof A&&("string"==typeof A.frameId&&A.frameId&&(R.frameId=A.frameId),"string"==typeof A.topFrameId&&A.topFrameId&&(R.topFrameId=A.topFrameId),"string"==typeof A.frameInstanceId&&A.frameInstanceId&&(R.frameInstanceId=A.frameInstanceId),R.frameDepth=0,R.captureRealm="top","string"==typeof A.frameOrigin&&A.frameOrigin&&(R.frameOrigin=A.frameOrigin),"string"==typeof A.frameUrl&&A.frameUrl&&(R.frameUrl=A.frameUrl),"string"==typeof A.frameLifecycle&&A.frameLifecycle&&(R.frameLifecycle=A.frameLifecycle),"string"==typeof A.privacyStatus&&A.privacyStatus&&(R.privacyStatus=A.privacyStatus)),R}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 me={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||me.CHANNEL_NAME,this.heartbeatInterval=S.heartbeatInterval||me.HEARTBEAT_INTERVAL,this.tabTimeout=S.tabTimeout||me.TAB_TIMEOUT,this.awayThreshold=S.awayThreshold||me.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 ye="__ts_aid";let ve=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(ye);return S||ve}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}(ye,b,63072e3)||(ve=b),b}const Se={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||Se.INACTIVITY_TIMEOUT,this.maxSessionDuration=S.maxSessionDuration||Se.MAX_SESSION_DURATION,this.activityThrottle=S.activityThrottle||Se.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 x.sortBy(x.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=x.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 b={events:this.eventQueue,timestamp:Date.now()};S.set(this.storageKeys.EVENTS||"__api_reporter_events__",b)}catch(S){this.logger.error("Failed to save events to local storage:",S)}}loadFromLocal(){try{const b=S.get(this.storageKeys.EVENTS||"__api_reporter_events__");b&&b.events&&(this.eventQueue=b.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{S.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=x.get(S,"maxRetries",3),this.initializeService()}initializeService(){if(!x.get(this.config,"service"))throw new Error("Service configuration is required");this.setService(x.get(this.config,"service"),x.get(this.config,"serviceOptions",{}))}setService(S,b={}){if(!x.isObject(S)||!x.isFunction(x.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||x.isEmpty(S)||!this.service)return this.logger.warn("Cannot send events:",{isSending:this.isSending,isEmpty:x.isEmpty(S),noService:!this.service}),x.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++,x.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 x.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(!x.isObject(S))return this.logger.warn("Invalid profile object provided"),!1;try{const b=this.getProfile(),I=x.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(x.isEmpty(x.get(S,"uniqId"))){const b=x.merge(S,{uniqId:generateId(),createdAt:(new Date).toISOString()});this.setProfile(b),this.logger.log("Generated new user profile:",x.get(b,"uniqId"))}}catch(S){this.logger.error("Failed to ensure user profile:",S)}}extractContextFromData({data:S,source:b="response",url:I=""}){const R={};try{if(!x.isObject(S)||!x.isArray(this.fieldsToExtract))return R;const A=x.toLower(I);return this.fieldsToExtract.forEach(_=>{try{const D=x.toLower(x.get(_,"api","")),L=x.get(_,"source",""),B="*"===D||A.includes(D);if(!B||!("*"===L||L===b))return;const U=x.get(_,"fields",[]);x.isArray(U)?U.forEach(x=>{try{this.recursiveFieldMatch({context:R,matchRule:x,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with pattern "${x}":`,S)}}):x.isObject(U)&&x.entries(U).forEach(([x,A])=>{try{this.recursiveFieldMatchWithMapping({context:R,newKey:x,matchRule:A,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with mapping "${x}": "${A}":`,S)}})}catch(S){this.logger.warn("Failed to process extraction rule:",S)}}),R}catch(S){return this.logger.error("Failed to extract context from data:",S),R}}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:R,url:A}){try{if(!x.isObject(I))return;if(x.isString(b)){const R=x.get(I,b);if(void 0!==R)return S[b]=R,void this.logger.log(`Found field by path: ${b} = ${JSON.stringify(R)}`);const A=x.find(x.entries(I),([S])=>x.toLower(S)===x.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 R=x.find(x.entries(I),([S,I])=>x.isString(I)&&b.test(I));if(R){const[b,I]=R;return S[b]=I,void this.logger.log(`Found field by value pattern: ${b} = ${I}`)}}x.values(I).forEach(I=>{x.isObject(I)&&!x.isNull(I)&&this.recursiveFieldMatch({context:S,matchRule:b,data:I,source:R,url:A})})}catch(S){this.logger.warn("Error in recursive field matching:",S)}}recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:R,source:A,url:_}){try{if(!x.isObject(R))return;if(x.isString(I)){const A=x.get(R,I);if(void 0!==A)return S[b]=A,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(A)}`);const _=x.find(x.entries(R),([S])=>x.toLower(S)===x.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=x.find(x.entries(R),([S,b])=>x.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}`)}}x.values(R).forEach(R=>{x.isObject(R)&&!x.isNull(R)&&this.recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:R,source:A,url:_})})}catch(S){this.logger.warn("Error in recursive field matching with mapping:",S)}}validateFieldValue(S,b){try{if(x.isString(b)){const I=x.get(DEFAULT_FIELD_PATTERNS,b);return I&&I.test(S)}if(x.isFunction(b))return b(S);if(x.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(x.isFunction(b))return b(S);if(x.isString(b))switch(b){case"toLowerCase":return x.toLower(S);case"toUpperCase":return x.toUpper(S);case"trim":return x.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 x.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!x.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 we=["/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 we)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(!x.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 be={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 Ce=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ke=new Set(["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody","maxBodyBytes","excludeEndpoints","requestSanitizer","responseSanitizer","sensitiveFields"]),Ie=["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody"];const Ee=/^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$/,xe=new Set(Object.keys(be));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(!Ce.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&&"iframe"!==S&&(xe.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))ke.has(I)||b.push(`network.${I}`);if(b.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:b};for(const b of Ie)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||!Ee.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 Me="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ulid(S=Date.now()){return function encodeTimestamp(S){let b="",I=S;for(let S=9;S>=0;S--)b=Me[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+=Me[x>>R&31];return S}()}const Re=Object.freeze(["session_start","session_end","replay_chunk","page_view","route_change","network_request","console_event","js_error","performance_metric","custom_event","user_identified"]),Te=new Set(Re);function wrapInEnvelope(S,b,I){if(!Te.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),isNonEmptyString$3(I.frameId)&&(x.frameId=I.frameId),isNonEmptyString$3(I.parentFrameId)&&(x.parentFrameId=I.parentFrameId),isNonEmptyString$3(I.topFrameId)&&(x.topFrameId=I.topFrameId),isNonEmptyString$3(I.frameInstanceId)&&(x.frameInstanceId=I.frameInstanceId),isNonNegativeInt(I.frameDepth)&&(x.frameDepth=I.frameDepth),isNonEmptyString$3(I.frameOrigin)&&(x.frameOrigin=I.frameOrigin),isNonEmptyString$3(I.frameUrl)&&(x.frameUrl=I.frameUrl),isNonEmptyString$3(I.frameLifecycle)&&(x.frameLifecycle=I.frameLifecycle),isNonEmptyString$3(I.captureRealm)&&(x.captureRealm=I.captureRealm),isNonEmptyString$3(I.privacyStatus)&&(x.privacyStatus=I.privacyStatus),isNonNegativeInt(I.bridgeProtocolVersion)&&(x.bridgeProtocolVersion=I.bridgeProtocolVersion),isNonNegativeInt(I.localSequence)&&(x.localSequence=I.localSequence),Number.isFinite(I.tsLocal)&&(x.tsLocal=I.tsLocal),Number.isFinite(I.tsNormalized)&&(x.tsNormalized=I.tsNormalized),Number.isFinite(I.clockOffsetMs)&&(x.clockOffsetMs=I.clockOffsetMs),Number.isFinite(I.clockUncertaintyMs)&&(x.clockUncertaintyMs=I.clockUncertaintyMs),{...x,...b}}function isNonEmptyString$3(S){return"string"==typeof S&&S.length>0}function isNonNegativeInt(S){return Number.isInteger(S)&&S>=0}const Ae=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/i;function normalizeOrigin(S){if("string"!=typeof S)return null;const b=S.trim();if(!b||"*"===b||"null"===b)return null;if(!Ae.test(b))return null;if(/^http:\/\//i.test(b)&&!function isLocalhostOrigin(S){return/^https?:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/i.test(S)}(b))return null;try{const S=new URL(b);return S.pathname&&"/"!==S.pathname||(S.search||S.hash)?null:(S.protocol+"//"+S.host).toLowerCase()}catch(S){return null}}function parseIframeConfig(S){const disabled=S=>({enabled:!1,role:null,parentOrigin:null,childOrigins:[],reason:S});if(null==S)return disabled("absent");if("object"!=typeof S||Array.isArray(S))return disabled("not_an_object");if(!0!==S.merge)return disabled("merge_not_enabled");const b="childOrigins"in S&&void 0!==S.childOrigins,I="parentOrigin"in S&&void 0!==S.parentOrigin;if(!b&&!I)return disabled("no_origins_declared");let x=[];if(b){const b=function normalizeChildOrigins(S){if(!Array.isArray(S))return null;const b=[],I=new Set;for(const x of S){const S=normalizeOrigin(x);if(!S)return null;I.has(S)||(I.add(S),b.push(S))}return b.length>0?b:null}(S.childOrigins);if(!b)return disabled("invalid_child_origins");x=b}let R=null;if(I){const b=normalizeOrigin(S.parentOrigin);if(!b)return disabled("invalid_parent_origin");R=b}let A=null;if(x.length>0&&R)A="both";else if(x.length>0)A="parent";else{if(!R)return disabled("no_origins_declared");A="child"}return{enabled:!0,role:A,parentOrigin:R,childOrigins:x,reason:null}}const _e="undefined"!=typeof TextEncoder?new TextEncoder:null;function getSubtle(){const S="undefined"!=typeof globalThis?globalThis.crypto:void 0;return S&&S.subtle?S.subtle:null}function hex(S){return Array.from(new Uint8Array(S)).map(S=>S.toString(16).padStart(2,"0")).join("")}function fromHex(S){const b=new Uint8Array(S.length/2);for(let I=0;I<b.length;I++)b[I]=parseInt(S.substr(2*I,2),16);return b}async function sha256Hex(S){const b=getSubtle();return hex(await b.digest("SHA-256",_e.encode(S)))}async function hmacHex(S,b){const I=getSubtle();return hex(await I.sign("HMAC",S,_e.encode(b)))}function macInput(S){return[S.v,S.frameId,S.frameInstanceId,S.navigationGeneration,S.counter,S.projectId,S.sessionId,S.payloadType,S.payloadHash].join("|")}function safeEq(S,b){if("string"!=typeof S||"string"!=typeof b||S.length!==b.length)return!1;let I=0;for(let x=0;x<S.length;x++)I|=S.charCodeAt(x)^b.charCodeAt(x);return 0===I}const Oe=new Set(["rrweb-dom","telemetry"]);const De={PROTOCOL_VERSION:1,ALLOWED_PAYLOAD_TYPES:Oe,hex:hex,fromHex:fromHex,sha256Hex:sha256Hex,randHex:function randHex(S){const b=new Uint8Array(S);return globalThis.crypto.getRandomValues(b),hex(b)},importKey:async function importKey(S){return getSubtle().importKey("raw",fromHex(S),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])},hmacHex:hmacHex,macInput:macInput,safeEq:safeEq,sealData:async function sealData(S,b,I){const x=void 0===I.payload?"":JSON.stringify(I.payload),R=await sha256Hex(x),A={v:1,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:I.payloadType,payloadHash:R},_=await hmacHex(S,macInput(A));return{v:1,kind:"data",frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,payloadType:I.payloadType,tag:I.tag,tsLocal:I.tsLocal,tsNormalized:I.tsNormalized,payloadHash:R,hmac:_,payload:I.payload}},validateData:async function validateData(S,b){try{if(!b||b.closed)return{ok:!1,reason:"stale_port"};if(!b.admitted||!b.key)return{ok:!1,reason:"not_admitted"};if(!S||"data"!==S.kind||"number"!=typeof S.counter||"string"!=typeof S.hmac||"string"!=typeof S.payloadHash)return{ok:!1,reason:"bad_shape"};if(S.v!==b.protocolVersion)return{ok:!1,reason:"protocol_mismatch",fatal:!0};if(!Oe.has(S.payloadType))return{ok:!1,reason:"bad_payload_type"};if(S.frameId!==b.frameId)return{ok:!1,reason:"wrong_frame:"+S.frameId};if(S.frameInstanceId!==b.frameInstanceId)return{ok:!1,reason:"stale_frame_instance"};if(S.navigationGeneration!==b.navigationGeneration)return{ok:!1,reason:"stale_generation"};const I=void 0===S.payload?"":JSON.stringify(S.payload);if(I.length>(b.maxBytes||65536))return{ok:!1,reason:"oversize:"+I.length};if(!safeEq(await sha256Hex(I),S.payloadHash))return{ok:!1,reason:"payload_hash_mismatch"};return safeEq(await hmacHex(b.key,macInput({v:S.v,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:S.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:S.payloadType,payloadHash:S.payloadHash})),S.hmac)?S.counter<=b.lastCounter?{ok:!1,reason:"counter_not_monotonic:"+S.counter+"<="+b.lastCounter}:{ok:!0}:{ok:!1,reason:"hmac_mismatch"}}catch(S){return{ok:!1,reason:"validator_error"}}}},Fe=De.PROTOCOL_VERSION,Ne="__TS_IFRAME_BRIDGE",Le="__TS_IFRAME_BRIDGE_PARENT_REGISTER";class BridgeChild{#f;#m;#y;#v;#o;#S;#w=null;#b=null;#C=null;#k=!1;#I=0;#E=null;#x=[];#M=[];#R=!1;#T=0;#A=1/0;#_=new Map;#O={forwarded:0,droppedUnadmitted:0,droppedBackpressure:0,offersRejected:0};constructor({parentOrigin:S,projectId:b,selfWindow:I,parentWindow:x,logger:R,queueCap:A}={}){this.#f=S,this.#m=b,this.#y=I,this.#v=x||I&&I.parent,this.#o=R||null,this.#S=A||1e3}get isAdmitted(){return this.#k}getStats(){return{admitted:this.#k,queued:this.#x.length+this.#M.length,...this.#O}}install(){if(!this.#y)return!1;const S={forwardRrwebDom:S=>this.forwardRrwebDom(S),forwardTelemetry:(S,b)=>this.forwardTelemetry(S,b),isAdmitted:()=>this.#k,__tsRole:"child"};try{Object.defineProperty(this.#y,Ne,{value:S,configurable:!0,enumerable:!1,writable:!0})}catch(b){this.#y[Ne]=S}this.#E=S=>{try{this.#D(S)}catch(S){this.#F("offer handler failed:",S)}};try{this.#y.addEventListener("message",this.#E)}catch(S){this.#F("addEventListener failed:",S)}return!0}#D(S){const b=S&&S.data;if(!b||"offer"!==b.__tsBridge)return;if(S.origin!==this.#f)return this.#O.offersRejected++,this.#F("offer origin mismatch");if(S.source!==this.#v)return this.#O.offersRejected++,this.#F("offer source mismatch");if(b.v!==Fe)return this.#O.offersRejected++,this.#F("offer protocol mismatch");if(this.#m&&b.projectId&&b.projectId!==this.#m)return this.#O.offersRejected++,this.#F("offer project mismatch");const I=S.ports&&S.ports[0];if(!I)return this.#O.offersRejected++,this.#F("offer missing port");this.#N(),this.#b={frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,projectId:b.projectId,sessionId:b.sessionId},this.#w=I,I.onmessage=S=>{try{this.#L(S.data)}catch(S){this.#F("control handler failed:",S)}};try{I.start&&I.start()}catch(S){}try{I.unref&&I.unref()}catch(S){}try{I.postMessage({c:"hello",v:Fe})}catch(S){this.#F("hello failed:",S)}}async#L(S){if(S&&this.#w)if("secret"!==S.c){if("pong"===S.c){const b=this.#_.get(S.id);if(!b)return;this.#_.delete(S.id);const I=Date.now()-b.sent,x=I/2,R=S.tParent-(b.sent+x);I<this.#A&&(this.#A=I,this.#T=R)}}else{if("string"!=typeof S.secret||!S.secret)return;try{this.#C=await De.importKey(S.secret),this.#k=!0,this.#P(),this.#B()}catch(S){this.#F("secret import failed:",S)}}}#P(){for(let S=0;S<5;S++){const S=De.randHex(8),b=Date.now();this.#_.set(S,{sent:b});try{this.#w.postMessage({c:"ping",id:S,t0:b})}catch(S){}}}forwardRrwebDom(S){return this.#z("rrweb-dom",void 0,S)}forwardTelemetry(S,b){return this.#z("telemetry",S,b)}#z(S,b,I){if(!this.#k)return this.#O.droppedUnadmitted++,!1;const x=function priorityForTag(S,b){return"rrweb-dom"===S?"high":"performance_metric"===b||"network_resource"===b?"low":"high"}(S,b),R=Date.now(),A={payloadType:S,tag:b,payload:I,priority:x,tsLocal:R,tsNormalized:this.#A===1/0?R:R+this.#T};if(this.#x.length+this.#M.length>=this.#S){if("low"===x)return this.#O.droppedBackpressure++,!1;this.#M.length>0?(this.#M.shift(),this.#O.droppedBackpressure++):(this.#x.shift(),this.#O.droppedBackpressure++)}return("low"===x?this.#M:this.#x).push(A),this.#B(),!0}async#B(){if(!this.#R&&this.#k&&this.#w&&this.#C){this.#R=!0;try{for(;this.#x.length||this.#M.length;){const S=this.#x.length?this.#x.shift():this.#M.shift(),b=++this.#I;try{const I=await De.sealData(this.#C,this.#b,{counter:b,payloadType:S.payloadType,tag:S.tag,tsLocal:S.tsLocal,tsNormalized:S.tsNormalized,payload:S.payload});this.#w.postMessage(I),this.#O.forwarded++}catch(S){this.#F("seal/post failed:",S)}}}finally{this.#R=!1}}}#N(){if(this.#w)try{this.#w.close&&this.#w.close()}catch(S){}this.#w=null,this.#C=null,this.#k=!1,this.#I=0,this.#x.length=0,this.#M.length=0,this.#_.clear(),this.#T=0,this.#A=1/0}shutdown(){try{this.#E&&this.#y.removeEventListener("message",this.#E)}catch(S){}this.#N();try{this.#y[Ne]&&"child"===this.#y[Ne].__tsRole&&delete this.#y[Ne]}catch(S){}this.#E=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:child]",...S)}catch(S){}}}class BridgeParent{#U;#m;#$;#j;#o;#S;#q;#W;#H;#V;#Q;#G=new Map;#K=new WeakMap;#J=0;#X=0;#Y=new WeakSet;#Z=null;#ee=null;#te=!1;#O={admitted:0,closed:0,accepted:0,rejected:0,fatal:0};#se=[];constructor({childOrigins:S,projectId:b,sessionId:I,topWindow:x,logger:R,queueCap:A,maxBytes:_,parentFrameId:D,topFrameId:L,feedRrwebDom:B,feedTelemetry:U}={}){this.#U=S instanceof Set?S:new Set(S||[]),this.#m=b,this.#$=I,this.#j=x||("undefined"!=typeof window?window:void 0),this.#o=R||null,this.#S=A||1e3,this.#q=_||65536,this.#W=D||"ts-top",this.#H=L||"ts-top",this.#V="function"==typeof B?B:()=>{},this.#Q="function"==typeof U?U:()=>{}}get isStarted(){return this.#te}getStats(){return{active:this.#G.size,...this.#O}}getRejectLog(){return this.#se.slice()}start(){if(this.#te)return!0;if(!this.#j)return!1;this.#te=!0;try{this.#j[Le]=S=>this.registerRrwebManager(S)}catch(S){}try{this.#re(this.#j.document),this.#ne(this.#j.document)}catch(S){this.#F("start scan failed:",S)}return!0}registerRrwebManager(S){this.#ee=S||null}#re(S){if(!S||"function"!=typeof S.querySelectorAll)return;let b;try{b=S.querySelectorAll("iframe")}catch(S){return}b.forEach(S=>{this.#ie(S),this.#oe(S)})}#ne(S){try{const b=this.#j.MutationObserver;if(!b)return;this.#Z=new b(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation failed:",S)}}),this.#Z.observe(S.documentElement||S,{childList:!0,subtree:!0})}catch(S){this.#F("observe failed:",S)}}#ae(S){if(S&&1===S.nodeType&&("IFRAME"===S.tagName&&(this.#ie(S),this.#oe(S)),S.querySelectorAll))try{S.querySelectorAll("iframe").forEach(S=>{this.#ie(S),this.#oe(S)})}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#K.get(S);if(!b)return;if(S.isConnected)return;const I=this.#G.get(b);I&&this.#ce(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#ie(S){if(!this.#Y.has(S)){this.#Y.add(S);try{S.addEventListener("load",()=>{try{this.#oe(S)}catch(S){this.#F("load re-admit failed:",S)}})}catch(S){}}}#ue(S){let b=null;try{b=S.src||S.getAttribute&&S.getAttribute("src")}catch(S){b=null}if(!b)return null;try{const S=this.#j.location&&this.#j.location.href||void 0,I=new URL(b,S);return(I.protocol+"//"+I.host).toLowerCase()}catch(S){return null}}#he(S){let b=this.#K.get(S);return b||(b="ts-xframe-"+ ++this.#J,this.#K.set(S,b)),b}#oe(S){const b=this.#ue(S);if(!b||!this.#U.has(b))return;let I=null;try{I=S.contentWindow}catch(S){I=null}if(!I)return;const x=this.#he(S),R=++this.#X,A=this.#G.get(x);let _;A&&this.#ce(A,"superseded");try{_=new this.#j.MessageChannel}catch(S){try{_=new MessageChannel}catch(S){return void this.#F("MessageChannel unavailable:",S)}}const D={frameId:x,frameInstanceId:`${x}-g${R}`,navigationGeneration:R,projectId:this.#m,sessionId:this.#$,expectedOrigin:b,sourceWindow:I,protocolVersion:Fe,lastCounter:-1,closed:!1,admitted:!1,key:null,maxBytes:this.#q,port:_.port1,secret:De.randHex(32),nonce:De.randHex(16),el:S};D.port.onmessage=S=>{this.#de(D,S&&S.data)};try{D.port.start&&D.port.start()}catch(S){}try{D.port.unref&&D.port.unref()}catch(S){}this.#G.set(x,D);const L={__tsBridge:"offer",v:Fe,projectId:this.#m,sessionId:this.#$,frameId:x,parentFrameId:this.#W,topFrameId:this.#H,frameInstanceId:D.frameInstanceId,navigationGeneration:R};try{I.postMessage(L,b,[_.port2]),this.#O.admitted++}catch(S){this.#F("offer post failed:",S),this.#ce(D,"offer_failed")}}async#de(S,b){if(b&&!S.closed)if("hello"!==b.c)if("ping"!==b.c){if("data"===b.kind){const I=await De.validateData(b,S);return I.ok?(S.lastCounter=b.counter,this.#O.accepted++,void("rrweb-dom"===b.payloadType?this.#ge(S,b.payload):"telemetry"===b.payloadType&&this.#pe(S,b))):(this.#O.rejected++,this.#fe(S.frameId,I.reason),void(I.fatal&&(this.#O.fatal++,this.#ce(S,"protocol_mismatch"))))}this.#O.rejected++,this.#fe(S.frameId,"unknown_message")}else try{S.port.postMessage({c:"pong",id:b.id,t0:b.t0,tParent:Date.now()})}catch(S){}else try{S.key=await De.importKey(S.secret),S.admitted=!0,S.port.postMessage({c:"secret",secret:S.secret,nonce:S.nonce}),S.secret=null}catch(S){this.#F("secret delivery failed:",S)}}#ge(S,b){try{const I={data:b,origin:S.expectedOrigin,source:S.sourceWindow};this.#ee&&"function"==typeof this.#ee.handleMessage&&this.#ee.handleMessage(I),this.#V(S,b,I)}catch(S){this.#F("deliverDom failed:",S)}}#pe(S,b){try{this.#Q(S,b)}catch(S){this.#F("deliverTelemetry failed:",S)}}#ce(S,b){S.closed=!0;try{S.port&&S.port.close&&S.port.close()}catch(S){}S.port=null,S.key=null,S.sourceWindow=null,S.el=null,this.#G.get(S.frameId)===S&&this.#G.delete(S.frameId),this.#O.closed++}shutdown(){for(const S of Array.from(this.#G.values()))this.#ce(S,"shutdown");this.#G.clear();try{this.#Z&&this.#Z.disconnect()}catch(S){}this.#Z=null;try{this.#j[Le]&&delete this.#j[Le]}catch(S){}this.#ee=null,this.#te=!1}#fe(S,b){this.#se.push({frameId:S,reason:b,t:Date.now()}),this.#se.length>200&&this.#se.shift()}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:parent]",...S)}catch(S){}}}class CrossOriginIframeBridge{#me;#ye;#m;#$;#o;#j;#ve=null;#Se=null;constructor({config:S,core:b,projectId:I,sessionId:x,logger:R,topWindow:A}={}){this.#me=S,this.#ye=b,this.#m=I,this.#$=x,this.#o=R||null,this.#j=A||("undefined"!=typeof window?window:void 0)}get parent(){return this.#ve}get child(){return this.#Se}get isChildMode(){return!!this.#Se}start(){if(!this.#me||!this.#me.enabled)return!1;const S=this.#me.role;try{return"child"!==S&&"both"!==S||(this.#Se=new BridgeChild({parentOrigin:this.#me.parentOrigin,projectId:this.#m,selfWindow:this.#j,parentWindow:this.#j&&this.#j.parent,logger:this.#o}),this.#Se.install()),"parent"!==S&&"both"!==S||(this.#ve=new BridgeParent({childOrigins:new Set(this.#me.childOrigins),projectId:this.#m,sessionId:this.#$,topWindow:this.#j,logger:this.#o,feedTelemetry:(S,b)=>this.#Q(S,b)}),this.#ve.start()),!0}catch(S){return this.#F("bridge start failed (fail-closed):",S),!1}}#Q(S,b){const I=b.payload&&"object"==typeof b.payload?b.payload:{},x=Object.assign({},I,{frameId:S.frameId,parentFrameId:"ts-top",topFrameId:"ts-top",frameInstanceId:S.frameInstanceId,frameOrigin:S.expectedOrigin,captureRealm:"iframe",privacyStatus:"unknown",bridgeProtocolVersion:Fe,localSequence:b.counter,tsLocal:b.tsLocal,tsNormalized:b.tsNormalized});try{this.#ye&&this.#ye.addSessionCustomEvent(b.tag,x)}catch(S){this.#F("writer feed failed:",S)}}shutdown(){try{this.#Se&&this.#Se.shutdown()}catch(S){}try{this.#ve&&this.#ve.shutdown()}catch(S){}this.#Se=null,this.#ve=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge]",...S)}catch(S){}}}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{#we=!1;#be=!1;#Ce;#ke;#Ie;#Ee;#xe;#Me;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.#ke=S.addCustomEvent,this.#Me=S.getContext,this.#Ie=S.readGuard,this.#Ee=S.writeGuard,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitStart(S={}){if(this.#we)return!1;let b=null;try{b=this.#Ie()}catch(S){b=null}if(b&&!0===b.sessionStartEmitted)return this.#we=!0,!1;b||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const I=this.#Me(),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.#xe("[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.#Ce("session_start",_,I)}catch(S){return this.#xe("[SDK lifecycle] session_start envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_start",B)}catch(S){return this.#xe("[SDK lifecycle] session_start addCustomEvent failed:",S),!1}this.#we=!0;try{this.#Ee({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.#be)return!1;const b=mapInternalEndReason(S.reason);if(!b)return this.#xe("[SDK lifecycle] session_end refused for non-logical reason:",S.reason),!1;let I=null;try{I=this.#Ie()}catch(S){I=null}if(I&&!0===I.sessionEndEmitted)return this.#be=!0,!1;I||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const x=this.#Me(),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.#Ce("session_end",_,x)}catch(S){return this.#xe("[SDK lifecycle] session_end envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_end",D)}catch(S){return this.#xe("[SDK lifecycle] session_end addCustomEvent failed:",S),!1}this.#be=!0;try{this.#Ee({sessionEndEmitted:!0,endedAt:R,endReason:b})}catch(S){}return!0}get startEmitted(){return this.#we}get endEmitted(){return this.#be}}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{#Re;#Te=!1;#Ae=null;#ke;#_e;#Ce;#xe;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.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{},this.#Re=uuidv4()}getCurrentPageviewId(){return this.#Re}emitInitialPageView(S={}){if(this.#Te)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.#xe("[SDK pageview] initial page_view skipped — url unavailable"),!1;const R=urlParts(x);if(!isNonEmptyString$1(R.path))return this.#xe("[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.#Oe(this.#Re);let D;try{D=this.#Ce("page_view",A,_)}catch(S){return this.#xe("[SDK pageview] initial page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",D)}catch(S){return this.#xe("[SDK pageview] initial page_view addCustomEvent failed:",S),!1}return this.#Te=!0,this.#Ae=x,!0}recordNavigation(S,b,I){if(!isNonEmptyString$1(I))return this.#xe("[SDK pageview] navigation skipped — toUrl unavailable"),!1;if(null!==this.#Ae&&this.#Ae===I)return!1;if(!["pushState","replaceState","popstate","hashchange"].includes(S))return this.#xe("[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.#xe("[SDK pageview] navigation skipped — could not derive toPath"),!1;const _=this.#Re,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.#Ce("route_change",L,this.#Oe(_))}catch(S){return this.#xe("[SDK pageview] route_change envelope wrap failed:",S),!1}try{this.#ke("tracescout.route_change",B)}catch(S){return this.#xe("[SDK pageview] route_change addCustomEvent failed:",S),!1}this.#Re=D,this.#Ae=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.#Ce("page_view",$,this.#Oe(D))}catch(S){return this.#xe("[SDK pageview] post-nav page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",j)}catch(S){return this.#xe("[SDK pageview] post-nav page_view addCustomEvent failed:",S),!1}return!0}#Oe(S){const b=this.#_e()||{};return Object.assign({},b,{pageviewId:S})}get initialEmitted(){return this.#Te}get lastUrl(){return this.#Ae}}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 Pe=new Set(["navigate","reload","back-forward","prerender","back-forward-cache","restore"]);function isNonEmptyString(S){return"string"==typeof S&&S.length>0}class WebVitalsEmitter{#De;#Fe;#Ne=new Set;#ke;#_e;#Ce;#xe;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.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#De=S.initialPageviewId,this.#Fe=S.initialUrl,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="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.#xe("[SDK web-vitals] emit refused — unknown metric type:",S),!1;if(this.#Ne.has(I))return!1;if(!function isPositiveFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)&&S>=0}(b.value))return this.#xe("[SDK web-vitals] emit refused — invalid value for",I,b.value),!1;const x=normalizeRating(b.libRating)??normalizeRating(b.rating);if(!x)return this.#xe("[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&&Pe.has(b.navigationType)&&(R.navigationType=b.navigationType);const _=this.#_e()||{},D=Object.assign({},_,{pageviewId:this.#De,url:this.#Fe});let L;try{L=this.#Ce("performance_metric",R,D)}catch(S){return this.#xe("[SDK web-vitals] envelope wrap failed:",S),!1}try{this.#ke("tracescout.performance_metric",L)}catch(S){return this.#xe("[SDK web-vitals] addCustomEvent failed:",S),!1}return this.#Ne.add(I),!0}get emittedMetrics(){return new Set(this.#Ne)}get initialPageviewId(){return this.#De}get initialUrl(){return this.#Fe}}const Be=/^[a-zA-Z][a-zA-Z0-9_.-]*$/,ze=["_ts_","internal","system"],Ue=["password","token","authorization","cookie","ssn","creditcard","secret","apikey"],$e=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($e.has(b)){x("pollution-key",b);continue}if(ze.some(S=>b.startsWith(S))){x("reserved-key",b);continue}const A=b.toLowerCase();if(Ue.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{#ke;#_e;#Ce;#xe;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.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitCustomEvent(S,b){if(!function isValidEventName(S){return"string"==typeof S&&S.length>=1&&S.length<=128&&Be.test(S)}(S))return this.#xe("[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.#xe("[SDK track] properties keys dropped:",I);const R={name:S};Object.keys(x).length>0&&(R.properties=x);const A=this.#_e()||{};let _;try{_=this.#Ce("custom_event",R,A)}catch(S){return this.#xe("[SDK track] envelope wrap failed:",S),!1}try{this.#ke("tracescout.custom_event",_)}catch(S){return this.#xe("[SDK track] addCustomEvent failed:",S),!1}return!0}emitUserIdentified(S){if(!S||"object"!=typeof S)return!1;if(!isValidUserId(S.userId))return this.#xe("[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.#xe("[SDK identify] traits keys dropped:",I);const R={mode:b};Object.keys(x).length>0&&(R.traits=x);const A=this.#_e()||{},_=Object.assign({},A,{userId:S.userId});let D;isValidEmail(S.userEmail)&&(_.userEmail=S.userEmail),isValidUserName(S.userName)&&(_.userName=S.userName);try{D=this.#Ce("user_identified",R,_)}catch(S){return this.#xe("[SDK identify] envelope wrap failed:",S),!1}try{this.#ke("tracescout.user_identified",D)}catch(S){return this.#xe("[SDK identify] addCustomEvent failed:",S),!1}return!0}}class SessionRecordingFeature{#o=null;#Le=null;#Pe=null;#a=null;#Be=null;#ze=null;#Ue=null;#$e=null;#je=!1;#qe=!1;#We=null;#He=0;#Ve=null;#Qe=null;#Ge=null;#Ke=null;constructor({logger:S,sdkContext:b,config:I,options:x}){this.#o=S,this.#Le=b,this.#Pe=I,this.#a=x}async initialize(S,b){try{console.log("[TraceScout] Loading recording module..."),this.#Be=await Promise.resolve().then(function(){return jc});const{SessionStorage:I,UploadQueue:x,Recorder:R}=this.#Be;return this.#Ue=new I({storageKey:"__tracescout_sessions_v2__",maxStorageSize:2097152,maxSessions:5,logger:this.#o}),console.log("[TraceScout] ✓ Session storage initialized"),!0===this.#a.childMode?(this.#$e=null,console.log("[TraceScout] ⏭️ Upload queue SUPPRESSED (cross-origin child — parent owns the session)")):(this.#$e=this.#Je(x,S,b),console.log("[TraceScout] ✓ Upload queue initialized"),console.log(` Endpoint: /api/projects/${this.#Le.projectId}/sessions/${this.#Le.sessionId}/chunks`)),this.#ze=this.#Xe(R,S),console.log("[TraceScout] ✓ Session recorder initialized"),await this.#ze.start(),console.log("[TraceScout] ✓ Session recording started"),this.#a.onSessionStart&&this.#a.onSessionStart(this.#Le.sessionId),this.#je=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize session recording:",S),!1}}#Je(S,b,I){return new S({sdkContext:this.#Le,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.#Ge?.(b);this.#o?.error(`❌ Chunk ${S?.chunkIndex} upload failed:`,b?.message)},onNetworkChange:S=>{this.#o?.log("Network status: "+(S?"online":"offline"))}})}#Xe(S,b){const I=b.features.sessionRecording;return new S({sdkContext:this.#Le,serverSettings:I,emit:S=>this.#Ye(S),onChunk:S=>{this.#Ze(S),this.#$e&&this.#$e.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.#qe=!0,this.#We=S.reason,this.#a.onSessionEnd&&this.#a.onSessionEnd(S),this.#Qe?.(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.#Pe.debug||!1,recordCrossOriginIframes:!0===this.#Pe.recordCrossOriginIframes,onSpaNavigation:(S,b,I)=>{"function"==typeof this.#Ke&&this.#Ke(S,b,I)}})}#Ye(S){}#Ze(S){const b=Date.now();if(b-this.#He>=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.#He=b}this.#Ue&&this.#Ue.storeChunk(S.sessionId,S),this.#Ve?.(S)}setCallbacks({onChunkCreated:S,onSessionEnd:b,onQuotaExceeded:I,onSpaNavigation:x}){this.#Ve=S,this.#Qe=b,this.#Ge=I,this.#Ke=x||null}get isAvailable(){return this.#je&&null!=this.#ze}get isRecording(){return this.#ze?.isRecording||!1}get sessionEnded(){return this.#qe}get sessionEndReason(){return this.#We}get recorder(){return this.#ze}get uploadQueue(){return this.#$e}get sessionStorage(){return this.#Ue}async start(S={}){if(!this.#ze)return this.#o?.warn("Session recording not enabled"),null;try{const b=this.#ze.start(S),I=this.#ze.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.#ze)return this.#o?.warn("Session recording not enabled"),null;try{this.#ze.stop();const S=this.#ze.getEvents(),b=this.#ze.getSessionId();return this.#o?.info("Session recording stopped:",b),{sessionId:b,startTime:this.#ze.recordingStartTime,duration:Date.now()-this.#ze.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.#ze)return!1;try{return this.#ze.addCustomEvent(S,b)}catch(S){return!1}}getStatus(){return this.#ze?{available:!0,isRecording:this.#ze.isRecording,sessionId:this.#ze.getSessionId(),eventCount:this.#ze.getEvents().length,startTime:this.#ze.recordingStartTime}:{available:!1,error:"Session recording not enabled"}}getEvents(){return this.#ze?.getEvents()||[]}getChunks(){return this.#ze?.getChunks?.()||[]}getMetadata(){return this.#ze?.getMetadata?.()||{}}getSessionId(){return this.#ze?.getSessionId()}updateSessionId(S){this.#ze&&(this.#ze.sessionId=S),this.#qe=!1,this.#We=null}updateUploadEndpoint(S){this.#$e&&(this.#$e.config.endpoint=S)}destroy(){if(this.#ze){try{this.#ze.stop()}catch(S){}this.#ze=null}this.#Ue=null,this.#$e=null,this.#Be=null,this.#je=!1}}class LogManager{#o=null;#Pe=null;#Le=null;#et=[];#tt={};#st="debug";#rt=1e3;#nt=new Map;#it=5e3;#ot=null;#at=!0;static LOG_LEVELS={debug:0,info:1,warn:2,error:3,fatal:4};constructor(S={},b=null,I=null){this.#Pe=S,this.#Le=b,this.#ot=I,this.#o=new Logger("[LogManager]",S.debug),this.#at=!1!==S.logs?.enabled,this.#st=S.logs?.minLevel||"debug",this.#rt=S.logs?.maxBufferSize||1e3,this.#o.log("LogManager initialized",{enabled:this.#at,minLevel:this.#st,maxBufferSize:this.#rt})}log(S,b,I={}){if(!this.#at)return!1;if(!this.#lt(S))return!1;try{const x=this.#ct(S,b,I);return!this.#ut(x)&&(this.#et.push(x),this.#et.length>=this.#rt&&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.#tt[S]=b:"object"==typeof S&&Object.assign(this.#tt,S),this.#o.log("Context attached:",S)}clearContext(){this.#tt={},this.#o.log("Context cleared")}setLogLevel(S){LogManager.LOG_LEVELS.hasOwnProperty(S)?(this.#st=S,this.#o.log("Log level set to:",S)):this.#o.warn("Invalid log level:",S)}getLogLevel(){return this.#st}setEnabled(S){this.#at=S,this.#o.log("Logging",S?"enabled":"disabled")}isEnabled(){return this.#at}flush(){if(0===this.#et.length)return[];const S=[...this.#et];if(this.#et=[],this.#o.log(`Flushing ${S.length} logs`),this.#ot)try{this.#ot(S)}catch(S){this.#o.error("Error in flush callback:",S)}return S}getQueueSize(){return this.#et.length}getQueue(){return[...this.#et]}clearQueue(){const S=this.#et.length;this.#et=[],this.#o.log(`Cleared ${S} logs from queue`)}getStats(){const S={queueSize:this.#et.length,byLevel:{},enabled:this.#at,minLevel:this.#st};return this.#et.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}#ct(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.#ht(),...this.#tt};this.#Le&&(A.sessionId=this.#Le.sessionId,A.projectId=this.#Le.projectId,A.environment=this.#Le.environment,this.#Le.userId&&(A.userId=this.#Le.userId));const _=this.#dt(I);return"error"!==S&&"fatal"!==S||!1===this.#Pe.logs?.attachStackTrace||_.stack||(_.stack=this.#gt()),{logId:R,timestamp:x,level:S,message:String(b),metadata:_,context:A}}#ht(){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}#dt(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}#gt(){try{const S=(new Error).stack||"";return S.split("\n").slice(3).join("\n")}catch(S){return"Stack trace unavailable"}}#lt(S){const b=LogManager.LOG_LEVELS[S],I=LogManager.LOG_LEVELS[this.#st];return void 0===b||void 0===I||b>=I}#ut(S){const b=`${S.level}:${S.message}`,I=Date.now(),x=this.#nt.get(b);return!!(x&&I-x<this.#it)||(this.#nt.set(b,I),this.#nt.size>1e3&&this.#pt(),!1)}#pt(){const S=Date.now();for(const[b,I]of this.#nt.entries())S-I>this.#it&&this.#nt.delete(b)}destroy(){this.flush(),this.#et=[],this.#tt={},this.#nt.clear(),this.#ot=null,this.#o.log("LogManager destroyed")}}class LogBuffer{#o=null;#Pe=null;#Le=null;#ft=[];#mt=null;#yt=5e3;#vt=100;#St=!1;#wt=null;#bt=!0;#Ct=0;static MAX_CONSECUTIVE_FAILURES=5;constructor(S={},b=null,I=null){this.#Pe=S,this.#Le=b,this.#wt=I,this.#o=new Logger("[LogBuffer]",S.debug),this.#yt=S.logs?.flushInterval||5e3,this.#vt=S.logs?.maxBatchSize||100,this.#bt=!1!==S.telemetry?.enableCompression,this.#kt(),this.#o.log("LogBuffer initialized",{flushInterval:this.#yt,maxBatchSize:this.#vt,compressionEnabled:this.#bt})}add(S){Array.isArray(S)||(S=[S]),this.#ft.push(...S),this.#o.log(`Added ${S.length} logs to buffer. Buffer size: ${this.#ft.length}`),this.#ft.length>=this.#vt&&(this.#o.log("Buffer size threshold reached, flushing..."),this.flush())}async flush(){if(0===this.#ft.length)return{success:!0,sent:0};if(this.#St)return this.#o.log("Already sending, skipping flush"),{success:!1,reason:"Already sending"};const S=this.#ft.splice(0,this.#vt);if(0===S.length)return{success:!0,sent:0};this.#o.log(`Flushing ${S.length} logs`);try{this.#St=!0;const b=this.#It(S);let I=b,x=!1;if(this.#bt&&"function"==typeof this.#Et)try{I=await this.#Et(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.#wt&&await this.#wt(I,x),this.#o.log(`Successfully sent batch with ${S.length} logs`),this.#Ct=0,{success:!0,sent:S.length}}catch(b){return this.#Ct++,this.#o.error(`Failed to flush logs (consecutive failures: ${this.#Ct}):`,b),this.#Ct>LogBuffer.MAX_CONSECUTIVE_FAILURES?(this.#o.warn(`Dropping batch of ${S.length} logs after ${this.#Ct} consecutive failures`),{success:!1,dropped:S.length,error:b.message}):(this.#ft.unshift(...S),{success:!1,error:b.message})}finally{this.#St=!1}}getConsecutiveFailures(){return this.#Ct}async forceFlush(){this.#xt();try{await this.flush()}finally{this.#kt()}}getBufferSize(){return this.#ft.length}getStats(){const S={bufferSize:this.#ft.length,isSending:this.#St,flushInterval:this.#yt,maxBatchSize:this.#vt,byLevel:{}};return this.#ft.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}clear(){const S=this.#ft.length;this.#ft=[],this.#o.log(`Cleared ${S} logs from buffer`)}destroy(){this.#xt(),this.flush().catch(S=>{this.#o.error("Error during final flush:",S)}),this.clear(),this.#o.log("LogBuffer destroyed")}#It(S){return{batchId:`batch_${Date.now()}_${generateId()}`,timestamp:Date.now(),projectId:this.#Le?.projectId,count:S.length,logs:S}}async#Et(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")}#kt(){this.#mt||(this.#mt=setInterval(()=>{this.#ft.length>0&&this.flush().catch(S=>{this.#o.error("Auto-flush failed:",S)})},this.#yt),this.#o.log("Auto-flush started"))}#xt(){this.#mt&&(clearInterval(this.#mt),this.#mt=null,this.#o.log("Auto-flush stopped"))}}class LoggingFeature{#o=null;#Le=null;#Pe=null;#Mt=null;#Rt=null;#je=!1;constructor({logger:S,sdkContext:b,config:I}){this.#o=S,this.#Le=b,this.#Pe=I}initialize(S){console.log("[TraceScout] Initializing logging system...");try{return this.#Mt=new LogManager(this.#Pe,this.#Le,S=>{this.#Rt&&this.#Rt.add(S)}),this.#Rt=new LogBuffer(this.#Pe,this.#Le,async(S,b)=>this.#Tt(S,b)),console.log("[TraceScout] ✓ Logging system initialized"),this.#je=!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),U.configure(b),S.enabledLogServices&&Array.isArray(S.enabledLogServices)?U.enableServices(S.enabledLogServices,S.logLevel||"info"):S.debug&&U.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#Tt(S,b){if(!this.#Le)throw new Error("SDK not initialized");const I=this.#Le.projectId,x=`${resolveApiBaseUrl(this.#Pe)}/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.#je&&null!=this.#Mt}get logManager(){return this.#Mt}get logBuffer(){return this.#Rt}log(S,b,I={}){return!!this.#Mt&&this.#Mt.log(S,b,I)}debug(S,b={}){return this.#Mt?.debug(S,b)||!1}info(S,b={}){return this.#Mt?.info(S,b)||!1}warn(S,b={}){return this.#Mt?.warn(S,b)||!1}error(S,b={}){return this.#Mt?.error(S,b)||!1}fatal(S,b={}){return this.#Mt?.fatal(S,b)||!1}setContext(S,b){return!!this.#Mt&&(this.#Mt.attachContext(S,b),!0)}clearContext(){return!!this.#Mt&&(this.#Mt.clearContext(),!0)}setLogLevel(S){return!!this.#Mt&&(this.#Mt.setLogLevel(S),!0)}getStats(){return this.#Mt?{manager:this.#Mt.getStats(),buffer:this.#Rt?this.#Rt.getStats():null}:null}async flush(){if(!this.#Rt)return!1;try{return await this.#Rt.forceFlush(),!0}catch(S){return this.#o?.error("Failed to flush logs:",S),!1}}enableServices(S,b="info"){try{return U.enableServices(S,b),!0}catch(S){return this.#o?.error("Failed to enable logging:",S),!1}}disableServices(S){try{return U.disableServices(S),!0}catch(S){return this.#o?.error("Failed to disable logging:",S),!1}}enableAll(S="info"){try{return U.enableAll(S),!0}catch(S){return this.#o?.error("Failed to enable all logging:",S),!1}}disableAll(){try{return U.disableAll(),!0}catch(S){return this.#o?.error("Failed to disable all logging:",S),!1}}getConfig(){try{return U.getConfig()}catch(S){return this.#o?.error("Failed to get logging config:",S),null}}getEnabledServices(){try{return U.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.#Rt&&(this.#Rt.destroy(),this.#Rt=null),this.#Mt&&(this.#Mt.destroy(),this.#Mt=null),this.#je=!1}}class ConsoleInterceptor{constructor(S,b={},I=null,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),this.realmConsole=x&&x.console?x.console:"undefined"!=typeof console?console:void 0,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");const b=this.realmConsole;S.forEach(S=>{this.originalMethods[S]=b[S],b[S]=this.createInterceptor(S)}),this.installed=!0,this.logger.debug("Console interceptor installed")}uninstall(){if(!this.installed)return;const S=this.realmConsole;Object.keys(this.originalMethods).forEach(b=>{S[b]=this.originalMethods[b]}),this.originalMethods={},this.installed=!1,this.logger.debug("Console interceptor uninstalled")}createInterceptor(S){const b=this;return function(...I){b.originalMethods[S].apply(b.realmConsole,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 je=["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"],qe="[REDACTED]";function filterSensitiveHeaders(S,b=[]){if(!S)return{};const I={},x=new Set([...je,...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)?qe:S});else if("object"==typeof S)for(const[b,R]of Object.entries(S)){const S=b.toLowerCase();I[b]=x.has(S)?qe:R}return I}function isSensitiveHeader(S){return!!S&&je.includes(S.toLowerCase())}function getSensitiveHeadersList(){return[...je]}function createSensitiveHeaderSet(S=[]){return new Set([...je,...S.map(S=>S.toLowerCase())])}const We=[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".woff",".woff2",".ttf",".eot",".ico",".webp",".avif"],He=["text/css","text/javascript","application/javascript","image/","font/","application/font","application/x-font"],Ve=[/\.(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(We.some(b=>S.toLowerCase().includes(b)))return!0;const I=He.some(S=>b.toLowerCase().startsWith(S));return!!I||Ve.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"}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)}const Qe=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=Qe,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=Qe,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 Ge="[REDACTED]",Ke=10240,Je=65536,Xe=["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(Xe);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]=Ge,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,Ge);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:Ke;return b>Je&&(b=Je),{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=Ge,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 Ye="[REDACTED]",Ze=["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=[...Ze];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(_,Ye)}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${Ye}`);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,I){this.reporter=S,this.interceptorName=b,this.realm=I||("undefined"!=typeof window?window:void 0),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:Ke;b>=0||(b=Ke),b>Je&&(b=Je);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:Qe,onWarn:(...S)=>this.logger.warn(...S)})}handleResponseData(S,b){return handleResponseBody(b,{maxSize:Qe,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:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logEvent(R)}extractDomain(S){try{return new URL(S,this.realm?.location?.origin).hostname}catch{return"unknown"}}extractPath(S){try{return new URL(S,this.realm?.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 et=/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/,tt=/^0+$/;function readTraceContextFromHeaders(S){return function parseTraceparent(S){if("string"!=typeof S)return null;const b=S.match(et);if(!b)return null;const I=b[1],x=b[2];return tt.test(I)||tt.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 st="undefined"!=typeof window&&window.fetch?window.fetch.bind(window):void 0;class FetchInterceptor extends BaseInterceptor{constructor(S,b){super(S,"fetch",b),this.originalFetch=this.realm&&this.realm.fetch?this.realm.fetch.bind(this.realm):st}setup(){this.logger.log("Initializing Fetch interceptor...");const S=this,b=this.realm;b._apiReporter_originalFetch||(b._apiReporter_originalFetch=this.originalFetch),b.fetch=async function(...I){I=S.injectCorrelationHeaders(I);const x=b.Request,R=b.Headers,A=x&&I[0]instanceof x?I[0].url:String(I[0]),_=I[1]||{},D=_.method||(x&&I[0]instanceof x?I[0].method:"GET"),L=_.body;let B={};x&&I[0]instanceof x?I[0].headers.forEach((S,b)=>{B[b]=S}):_.headers&&(R&&_.headers instanceof R?_.headers.forEach((S,b)=>{B[b]=S}):Object.assign(B,_.headers));const U=filterSensitiveHeaders(B),$=S.shouldMonitor(A),j=S.isStaticResource(A);let W=null;$&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&(W=S.reporter.performanceMonitor.generateRequestId(),S.reporter.performanceMonitor.startTracking(W,A,D));const H=Date.now();if(!j){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(A,b),x=S.sanitizeRequestUrlFields(A,b),R=getHeader(B,"content-type"),_=S.buildRequestBodyFields(L,R,b,I),$={interceptor:"fetch",method:D,url:x.url,requestHeaders:b.captureRequestHeaders?U:{},timestamp:H,..._};x.path&&($.requestPath=x.path),x.query&&($.requestQuery=x.query);const j=readTraceContextFromHeaders(B);j&&($.traceId=j.traceId,$.spanId=j.spanId),S.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing API request:",{url:x.url,hasHeaders:!!U&&Object.keys(U).length>0,bodyState:_.requestBodyState}),S.addToSessionReplay("network_request",$)}try{const x=await S.originalFetch.apply(b,I);let R=null;return W&&(R=S.reporter.performanceMonitor.endTracking(W,x.status)),await S.handleResponse(x,A,D,R),x}catch(b){throw W&&S.reporter.performanceMonitor.endTracking(W,0),S.handleNetworkError(A,D,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:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.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(){const S=this.realm;S&&S._apiReporter_originalFetch&&(S.fetch=S._apiReporter_originalFetch,delete S._apiReporter_originalFetch),super.destroy()}injectCorrelationHeaders(S){const b=SDKContext.getInstance();if(!b||!b.sessionId)return S;const I=this.realm,x=I.Request,R=I.Headers,A=tracePropagationDecision(x&&S[0]instanceof x?S[0].url:String(S[0]));if(!A.traceparent&&!A.baggage)return S;const _=[];if(A.baggage&&(b.sessionId&&_.push(`sessionId=${encodeURIComponent(b.sessionId)}`),b.userId&&_.push(`userId=${encodeURIComponent(b.userId)}`),b.projectId&&_.push(`projectId=${encodeURIComponent(b.projectId)}`)),x&&S[0]instanceof x){const b=S[0],I=S[1]||{},D=new R(b.headers);if(I.headers)if(R&&I.headers instanceof R)I.headers.forEach((S,b)=>D.set(b,S));else for(const S in I.headers)D.set(S,I.headers[S]);const L=hasHeader(D,"traceparent");A.baggage&&_.length>0&&!getHeader(D,"baggage")&&setHeader(D,"baggage",_.join(",")),A.traceparent&&!L&&setHeader(D,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`);const B={...I};delete B.headers;return[new x(b,{...B,headers:D})]}const D=S[0],L=S[1]||{};if(L.headers=L.headers||{},R&&L.headers instanceof R){const S={};L.headers.forEach((b,I)=>{S[I]=b}),L.headers=S}const B=hasHeader(L.headers,"traceparent");return A.baggage&&_.length>0&&!getHeader(L.headers,"baggage")&&setHeader(L.headers,"baggage",_.join(",")),A.traceparent&&!B&&setHeader(L.headers,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`),[D,L]}generateW3CTraceId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}class XHRInterceptor extends BaseInterceptor{constructor(S,b){super(S,"xhr",b),this.XHR=this.realm&&this.realm.XMLHttpRequest?this.realm.XMLHttpRequest:XMLHttpRequest,this.originalOpen=this.XHR.prototype.open,this.originalSend=this.XHR.prototype.send}setup(){this.logger.log("Initializing XHR interceptor...");const S=this,b=this.XHR.prototype;b.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 I=b.setRequestHeader;this._originalSetRequestHeader=I,b.setRequestHeader=function(S,b){return this._apiReporterRequestHeaders||(this._apiReporterRequestHeaders={}),this._apiReporterUserSetHeaders||(this._apiReporterUserSetHeaders=new Set),this._apiReporterUserSetHeaders.add(S.toLowerCase()),setHeader(this._apiReporterRequestHeaders,S,b),I.call(this,S,b)},b.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:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.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(){this.XHR.prototype.open=this.originalOpen,this.XHR.prototype.send=this.originalSend,this._originalSetRequestHeader&&(this.XHR.prototype.setRequestHeader=this._originalSetRequestHeader),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=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}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.#At(S),path:x.pathname||this.#_t(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.#Ot(I),crossOrigin:this.#Dt(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)}#At(S){try{return new URL(S,location.origin).hostname}catch{return""}}#_t(S){try{return new URL(S,location.origin).pathname}catch{return""}}#Ot(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"}}#Dt(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)}}const rt=["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={},I=null){this.reporter=S,this.realm=I||("undefined"!=typeof window?window:void 0),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"):this.realm&&void 0!==this.realm.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 this.realm.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 this.realm.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((this.realm?.performance?.timeOrigin||0)+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((this.realm?.performance?.timeOrigin||0)+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 rt){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,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),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(){if(this.installed)return;const S=this.realm;this.config.captureErrors&&(this.originalHandlers.onerror=S.onerror,S.onerror=this.handleError.bind(this)),this.config.captureUnhandledRejections&&(this.originalHandlers.onunhandledrejection=S.onunhandledrejection,this._boundRejectionHandler=this.handleUnhandledRejection.bind(this),S.addEventListener("unhandledrejection",this._boundRejectionHandler)),this.installed=!0,this.logger.debug("Error handler installed")}uninstall(){if(!this.installed)return;const S=this.realm;this.config.captureErrors&&(S.onerror=this.originalHandlers.onerror||null),this.config.captureUnhandledRejections&&(this._boundRejectionHandler&&(S.removeEventListener("unhandledrejection",this._boundRejectionHandler),this._boundRejectionHandler=null),this.originalHandlers.onunhandledrejection&&(S.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:this.realm?.navigator?.userAgent,url:this.realm?.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:this.realm?.navigator?.userAgent,url:this.realm?.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()}}function initializeErrorHandler(S,b={}){const I=new ErrorHandler(S,b);return I.install(),I}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"))}}const nt="ts-top";class IframeInstrumentationManager{#ye=null;#Pe=null;#o=null;#j=null;#Ft=Symbol("__tsIframeInstalled__");#te=!1;#Nt=new Map;#Lt=[];#Pt=[];#Y=new WeakSet;#K=new WeakMap;#Bt=new Map;#J=0;#zt=0;#O={installs:0,teardowns:0,reentrySkips:0,inaccessible:0,installErrors:0};#Ut=[];constructor({core:S,config:b,logger:I,topWindow:x}={}){this.#ye=S,this.#Pe=b||S?.config||{},this.#o=I||null,this.#j=x||("undefined"!=typeof window?window:void 0)}get isStarted(){return this.#te}start(){if(this.#te)return!0;if(!this.#j)return!1;try{this.#te=!0,this.#$t();const S=this.#j.document;return this.#jt(S,this.#j,nt,1),this.#qt(S,this.#j,nt,1,null),!0}catch(S){return this.#F("start failed (fail-closed):",S),!0}}shutdown(){try{for(const S of Array.from(this.#Nt.values()))this.#Wt(S,"disconnected");this.#Nt.clear();for(const S of this.#Pt)try{S.mo.disconnect()}catch(S){}this.#Pt.length=0,this.#Lt.length=0}catch(S){this.#F("shutdown error (fail-closed):",S)}finally{this.#te=!1;try{this.#ye?.setIframeTopFrameContext?.(null)}catch(S){}}}#jt(S,b,I,x){if(!S)return;let R=null;try{R=S.querySelectorAll("iframe")}catch(S){R=null}R&&R.forEach(S=>{this.#ie(S,I,x),this.#Ht(S,I,x)});try{const S=b&&b.frames,R=S?S.length:0;for(let b=0;b<R;b++){let R=null;try{R=S[b]&&S[b].frameElement}catch(S){R=null}R&&"IFRAME"===R.tagName&&!this.#K.has(R)&&(this.#ie(R,I,x),this.#Ht(R,I,x))}}catch(S){}}#ie(S,b,I){if(!this.#Y.has(S)){this.#Y.add(S);try{S.addEventListener("load",()=>{try{this.#Ht(S,b,I)}catch(S){this.#F("load-reinstall failed (fail-closed):",S)}})}catch(S){this.#F("hookLoad failed (fail-closed):",S)}}}#Ht(S,b,I){let x=null;try{x=S.contentWindow}catch(S){x=null}x&&this.#Vt(S,x,b,I)}#he(S){let b=this.#K.get(S);return b||(b="ts-frame-"+ ++this.#J,this.#K.set(S,b)),b}#Vt(S,b,I,x){try{const b=S.getAttribute&&S.getAttribute("src");if(b){const I=new URL(b,"undefined"!=typeof location&&location.href||void 0);if(("http:"===I.protocol||"https:"===I.protocol)&&"undefined"!=typeof location&&I.origin!==location.origin)return this.#O.inaccessible++,this.#Qt("inaccessible",{frameId:this.#he(S),depth:x,reason:"cross-origin-src"}),null}}catch(S){}let R;try{if(R=b.document,!R)throw new Error("no document")}catch(b){return this.#O.inaccessible++,this.#Qt("inaccessible",{frameId:this.#he(S),depth:x}),null}const A=this.#he(S),_=b[this.#Ft];if(_&&null!=_.realmEpoch)return this.#O.reentrySkips++,this.#Qt("reentry-skip",{frameId:A,realmEpoch:_.realmEpoch}),_;const D=this.#Nt.get(A);if(D&&D.win!==b){const S="reloaded"===this.#Gt(A,this.#Kt(b))?"reloaded":"navigated";this.#Wt(D,S)}const L=++this.#zt,B=this.#Jt(b),U=this.#Kt(b),$=this.#Gt(A,U),j=this.#Xt(),W={frameId:A,frameInstanceId:`${A}-r${L}`,parentFrameId:I,topFrameId:nt,frameDepth:x,frameOrigin:B,frameUrl:U,frameLifecycle:$,privacyStatus:j,realmEpoch:L,win:b,el:S,seq:0,interceptors:[],observerRef:null};try{Object.defineProperty(b,this.#Ft,{value:W,configurable:!0,enumerable:!1,writable:!0})}catch(S){return null}const H=this.#Yt(W),V=this.#Pe||{};let Q=!1;try{this.#Zt(W,()=>{const S=new FetchInterceptor(H,b);return S.setup(),S}),this.#Zt(W,()=>{const S=new XHRInterceptor(H,b);return S.setup(),S}),this.#Zt(W,()=>{const S=new ConsoleInterceptor(null,V,H,b);return S.install(),S}),this.#Zt(W,()=>{const S=new ErrorHandler(null,V,H,b);return S.install(),S}),this.#Zt(W,()=>{const S=new PerformanceResourceObserver(H,{captureResources:!1!==V.captureResources,captureNavigation:!1!==V.captureNavigation,debug:!!V.debug,maxResourceEntriesPerSession:V.maxResourceEntriesPerSession||2e3},b);return S.setup(),S}),Q=W.interceptors.length>0}catch(S){return this.#O.installErrors++,this.#F("install block failed (fail-closed):",S),this.#Wt(W,"blocked"),null}if(!Q){try{delete b[this.#Ft]}catch(S){}return null}this.#O.installs++,this.#es(A,U),this.#Nt.set(A,W),this.#ts(A,b),this.#Qt("install",{frameId:A,parentFrameId:I,depth:x,realmEpoch:L,frameLifecycle:$});try{this.#jt(R,b,A,x+1)}catch(S){this.#F("nested scan failed:",S)}return this.#qt(R,b,A,x+1,W),W}#Zt(S,b){try{const I=b();I&&S.interceptors.push(I)}catch(S){this.#O.installErrors++,this.#F("interceptor install failed (fail-closed):",S)}}#Yt(S){const b=this.#ye,stamp=(b,I)=>this.#ss(S,b,I);return new Proxy(b,{get(S,b){if("addSessionCustomEvent"===b)return stamp;const I=Reflect.get(S,b,S);return"function"==typeof I?I.bind(S):I}})}#ss(S,b,I){try{const x=I&&"object"==typeof I?I:{},R="number"==typeof x.timestamp?x.timestamp:Date.now(),A=Object.assign({},x,{frameId:S.frameId,topFrameId:S.topFrameId,frameInstanceId:S.frameInstanceId,frameDepth:S.frameDepth,frameOrigin:S.frameOrigin,frameUrl:S.frameUrl,frameLifecycle:S.frameLifecycle,captureRealm:"iframe",privacyStatus:S.privacyStatus,localSequence:S.seq++,tsLocal:R,tsNormalized:R});return null!=S.parentFrameId&&(A.parentFrameId=S.parentFrameId),this.#ye.addSessionCustomEvent(b,A)}catch(S){return this.#F("stamp/emit failed (fail-closed):",S),!1}}#qt(S,b,I,x,R){try{const A=b.MutationObserver;if(!A)return;const _=new A(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S,I,x)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation handler failed (fail-closed):",S)}});_.observe(S.documentElement||S,{childList:!0,subtree:!0});const D={mo:_,win:b};this.#Pt.push(D),R&&(R.observerRef=()=>{try{_.disconnect()}catch(S){}const S=this.#Pt.indexOf(D);S>=0&&this.#Pt.splice(S,1)})}catch(S){this.#F("observeDocument failed (fail-closed):",S)}}#ae(S,b,I){if(!S||1!==S.nodeType)return;const attach=S=>{this.#ie(S,b,I),this.#Ht(S,b,I)};if("IFRAME"===S.tagName&&attach(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(attach)}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#K.get(S);if(!b)return;if(S.isConnected)return;const I=this.#Nt.get(b);I&&this.#Wt(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#Wt(S,b){for(const b of S.interceptors)try{"function"==typeof b.destroy?b.destroy():"function"==typeof b.uninstall&&b.uninstall()}catch(S){this.#F("interceptor teardown failed (fail-closed):",S)}if(S.interceptors=[],"function"==typeof S.observerRef){try{S.observerRef()}catch(S){}S.observerRef=null}this.#Nt.delete(S.frameId);try{delete S.win[this.#Ft]}catch(S){}if(this.#rs(S.frameId),"detached"===b){const b=this.#Bt.get(S.frameId);b&&(b.detached=!0)}S.win=null,S.el=null,this.#O.teardowns++,this.#Qt("teardown",{frameId:S.frameId,reason:b})}#$t(){const S=this.#j;try{this.#ye?.setIframeTopFrameContext?.({frameId:nt,frameInstanceId:`${nt}-r0`,topFrameId:nt,frameOrigin:this.#Jt(S),frameUrl:this.#Kt(S),frameLifecycle:"attached",privacyStatus:this.#Xt()})}catch(S){this.#F("registerTopFrameContext failed (fail-closed):",S)}}#Jt(S){try{const b=S.location&&S.location.origin;if("string"==typeof b&&b)return b.slice(0,256)}catch(S){}}#Kt(S){try{const b=S.location&&S.location.href;if("string"!=typeof b||!b)return;const{url:I}=splitSanitizedUrl(b,{});return(I||b).slice(0,2048)}catch(S){return}}#Xt(){try{const S=SDKContext.getInstance()?.domPrivacy;if("confirmed"===S||"partial"===S||"disabled"===S)return S}catch(S){}return"unknown"}#Gt(S,b){const I=this.#Bt.get(S);return I&&I.everInstalled?I.detached?"reattached":null!=I.lastUrl&&null!=b&&I.lastUrl===b?"reloaded":"navigated":"attached"}#es(S,b){const I=this.#Bt.get(S)||{};I.everInstalled=!0,I.detached=!1,I.lastUrl=b,this.#Bt.set(S,I)}#ts(S,b){const I=this.#Lt.find(b=>b.frameId===S);I?I.win=b:this.#Lt.push({frameId:S,win:b})}#rs(S){for(let b=this.#Lt.length-1;b>=0;b--)this.#Lt[b].frameId===S&&(this.#Lt[b].win=null,this.#Lt.splice(b,1))}getStats(){return{active:this.#Nt.size,allRealms:this.#Lt.length,observers:this.#Pt.length,...this.#O}}getInstallLog(){return this.#Ut.slice()}verifyRestored(){return this.#ns().map(S=>{const b={frameId:S.frameId,alive:!1},I=S.win;if(!I)return b;try{b.alive=!0,b.fetchRestored=!(I.fetch&&I.fetch.__tsPoCWrapped),b.consoleRestored="function"==typeof I.console.log}catch(S){b.error=S&&S.name}return b})}#ns(){const S=[];for(const b of this.#Nt.values())S.push({frameId:b.frameId,win:b.win});for(const b of this.#Lt)S.some(S=>S.frameId===b.frameId)||S.push(b);return S}#Qt(S,b){this.#Ut.push(Object.assign({ev:S,t:Date.now()},b))}#F(...S){try{this.#Pe?.debug&&this.#o?.warn&&this.#o.warn("[IframeInstrumentation]",...S)}catch(S){}}}class InterceptorFeature{#o=null;#Pe=null;#is=null;#os=null;#as=null;#ls=null;#je=!1;constructor({logger:S,config:b,monitoringCore:I,eventManager:x}){this.#o=S,this.#Pe=b,this.#is=I,this.#os=x}initialize(S,b=null){try{this.#as={};return S&&S.isRecording?(console.log("[TraceScout] 🔌 Setting up session recording interceptors bundle..."),this.#cs(),this.#us(),this.#hs(),this.#ds(b),this.#gs(),this.#ps(),this.#fs(),console.log("[TraceScout] ✅ Session recording bundle complete (DOM + Network + Console + Errors)"),this.#o?.log("Interceptors setup complete"),this.#je=!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}}#cs(){console.log("[TraceScout] 📡 Setting up FetchInterceptor..."),this.#as.fetch=new FetchInterceptor(this.#is),this.#as.fetch.setup?.()||this.#as.fetch.install?.(),console.log("[TraceScout] ✅ FetchInterceptor active")}#us(){console.log("[TraceScout] 📡 Setting up XHRInterceptor..."),this.#as.xhr=new XHRInterceptor(this.#is),this.#as.xhr.setup?.()||this.#as.xhr.install?.(),console.log("[TraceScout] ✅ XHRInterceptor active")}#hs(){const S=!1!==this.#Pe?.captureResources,b=!1!==this.#Pe?.captureNavigation;if(S||b)try{console.log("[TraceScout] 📊 Setting up PerformanceResourceObserver...",{captureResources:S,captureNavigation:b,maxResourceEntriesPerSession:this.#Pe?.maxResourceEntriesPerSession||2e3}),this.#as.performanceResource=new PerformanceResourceObserver(this.#is,{captureResources:S,captureNavigation:b,debug:this.#Pe?.debug||!1,maxDedupeEntries:this.#Pe?.maxDedupeEntries||5e3,filterOtherInitiator:!1!==this.#Pe?.filterOtherInitiator,maxResourceEntriesPerSession:this.#Pe?.maxResourceEntriesPerSession||2e3,resourceAllowlist:this.#Pe?.resourceAllowlist||null,resourceBlocklist:this.#Pe?.resourceBlocklist||null}),this.#as.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")}#ds(S){console.log("[TraceScout] 💬 Setting up ConsoleInterceptor..."),this.#as.console=new ConsoleInterceptor(this.#os,this.#Pe,this.#is),S&&this.#as.console.setLogManager(S),this.#as.console.install?.(),console.log("[TraceScout] ✅ ConsoleInterceptor active")}#gs(){try{console.log("[TraceScout] 🚨 Setting up ErrorHandler..."),this.#as.errors=new ErrorHandler(this.#os,this.#Pe,this.#is),console.log("[TraceScout] ErrorHandler created, installing...",{hasInstall:"function"==typeof this.#as.errors?.install,hasReporter:!!this.#is}),this.#as.errors.install?.(),console.log("[TraceScout] ✅ ErrorHandler active")}catch(S){console.error("[TraceScout] ❌ ErrorHandler setup failed:",S)}}#fs(){try{this.#ls=new IframeInstrumentationManager({core:this.#is,config:this.#Pe,logger:this.#o}),this.#ls.start(),console.log("[TraceScout] 🪟 Same-origin iframe instrumentation active")}catch(S){console.warn("[TraceScout] ⚠️ Iframe instrumentation skipped:",S?.message),this.#ls=null}}get iframeManager(){return this.#ls}#ps(){this.#Pe?.monitorPostMessages&&"object"==typeof this.#Pe.monitorPostMessages&&(this.#as.postMessage=new PostMessageInterceptor(this.#is),this.#as.postMessage.setup?.()||this.#as.postMessage.install?.())}get isInitialized(){return this.#je}get interceptors(){return this.#as}getInterceptor(S){return this.#as?.[S]||null}updateDebugMode(S){this.#as&&Object.values(this.#as).forEach(b=>{b&&b.updateDebugMode&&b.updateDebugMode(S)})}destroy(){if(this.#ls){try{this.#ls.shutdown()}catch(S){}this.#ls=null}this.#as&&(Object.values(this.#as).forEach(S=>{S?.destroy?.()||S?.uninstall?.()}),this.#as=null),this.#je=!1}}class EventLifecycleFeature{#o=null;#Pe=null;#ms=null;#ys=null;#vs=null;#Ss=null;#ws=null;#bs=null;#Cs=null;#ks=null;#je=!1;#Is=!1;constructor({logger:S,config:b}){this.#o=S,this.#Pe=b}setCallbacks({onCustomApiError:S,onBeforeUnload:b,onUserActivity:I,onVisibilityChange:x}){this.#ws=S,this.#bs=b,this.#Cs=I,this.#ks=x}initialize(){try{return this.#ms=this.#Es.bind(this),this.#ys=this.#xs.bind(this),this.#vs=this.#Ms.bind(this),this.#Ss=this.#Rs.bind(this),document.addEventListener("custom-api-error",this.#ms),window.addEventListener("beforeunload",this.#ys),document.addEventListener("click",this.#vs,{passive:!0,capture:!0}),document.addEventListener("keydown",this.#vs,{passive:!0,capture:!0}),document.addEventListener("scroll",this.#vs,{passive:!0,capture:!0}),document.addEventListener("visibilitychange",this.#Ss),this.#o?.log("Event listeners setup complete"),this.#je=!0,!0}catch(S){return this.#o?.error("Failed to setup event listeners:",S),!1}}#Es(S){this.#ws?.(S)}#xs(S){this.#bs?.(S)}#Ms(){this.#Is||this.#Cs?.()}#Rs(){this.#Is||("visible"===document.visibilityState?this.#ks?.("visible"):this.#ks?.("hidden"))}get isInitialized(){return this.#je}setQuotaExceeded(S){this.#Is=S,S&&this.#Ts()}#Ts(){this.#vs&&(document.removeEventListener("click",this.#vs,{capture:!0}),document.removeEventListener("keydown",this.#vs,{capture:!0}),document.removeEventListener("scroll",this.#vs,{capture:!0}),this.#vs=null),this.#Ss&&(document.removeEventListener("visibilitychange",this.#Ss),this.#Ss=null)}destroy(){try{document.removeEventListener("custom-api-error",this.#ms),window.removeEventListener("beforeunload",this.#ys),this.#Ts(),this.#ms=null,this.#ys=null,this.#je=!1}catch(S){this.#o?.error("Failed to cleanup event listeners:",S)}}}class TraceScoutMonitoringCore{#je=!1;#o=null;#As=null;#os=null;#_s=null;#Os=null;#Ds=null;#Fs=null;#Le=null;#Ns=null;#Ls=null;#Ps=null;#Bs=null;#as=null;#zs=null;#Us=null;#$s=null;#js=null;#qs=null;#Ws=null;#Hs=null;#Vs=null;#Qs=null;_consecutiveFailures=0;#Is=!1;#Gs=null;#Ks=!1;#Js=null;#Xs=0;#Ys=null;#Zs=null;#er=!1;static#tr=null;static#sr=!1;constructor(){this.config=x.defaults({retryIntervalMs:x.get(A,"RETRY_INTERVAL_MS",5e3),deduplicationWindowMs:x.get(A,"DEDUPLICATION_WINDOW_MS",3e4),maxQueueSize:x.get(A,"MAX_QUEUE_SIZE",1e3),maxRetries:x.get(A,"MAX_RETRIES",3),batchSize:x.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.#As=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.#Hs=throttle$1(this.sendEvents.bind(this),1e3))}static setTransport(S){TraceScoutMonitoringCore.#sr?console.error("[TraceScout] setTransport() must be called before init()"):"object"==typeof S&&null!==S?"string"==typeof S.apiBaseUrl&&S.apiBaseUrl?TraceScoutMonitoringCore.#tr=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.#Ks)return this.#o.warn("TraceScoutMonitoringCore already initialized"),{sampled:this.#Gs??!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.#Ks=!0,TraceScoutMonitoringCore.#sr=!0,this.#Ys=parseIframeConfig(I.options.iframe),!this.#Ys.enabled&&this.#Ys.reason&&"absent"!==this.#Ys.reason&&I.options.debug&&console.warn("[TraceScout] iframe bridge disabled (fail-closed):",this.#Ys.reason),this.#er=this.#Ys.enabled&&("child"===this.#Ys.role||"both"===this.#Ys.role);const x=TraceScoutMonitoringCore.#tr,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.#Gs=shouldSampleSession(1,{anonymousId:A}),!this.#Gs)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.#Fs=I.sessionManager.sessionManager,this.#Le=I.sdkContext,this.#Ns=I.remoteConfigService,this.config=I.config,this.#Ls=R,this.#os=I.managers.eventManager,this.#_s=I.managers.serviceManager,this.#Os=I.managers.userProfileManager,this.#Ds=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.#Bs=new LoggingFeature({logger:this.#o,sdkContext:this.#Le,config:this.config}),this.#Bs.initialize(I.serverConfig),this.#Bs.configure(this.config);const x=I.serverConfig?.features?.performanceMonitoring?.enabled;if(x&&(this.#Ws=new CoreWebVitalsMonitor(this.config),console.log("[TraceScout] ✓ Performance monitoring initialized")),this.#Ys?.enabled)try{this.config.recordCrossOriginIframes=!0,this.#Zs=new CrossOriginIframeBridge({config:this.#Ys,core:this,projectId:this.#Le.projectId,sessionId:this.#Le.sessionId,logger:this.#o}),this.#Zs.start()}catch(S){this.config?.debug&&this.#o.warn?.("iframe bridge start failed (fail-closed):",S),this.#Zs=null}this.#Ps=new SessionRecordingFeature({logger:this.#o,sdkContext:this.#Le,config:this.config,options:{...b,childMode:this.#er}}),this.#Ps.setCallbacks({onChunkCreated:S=>this.#Ze(S),onSessionEnd:S=>this.#rr(S),onQuotaExceeded:S=>this.#nr(S),onSpaNavigation:(S,b,I)=>{this.#$s?.recordNavigation(S,b,I)}});const A=await this.#Ps.initialize(I.serverConfig,this.#Ns);if(this.#$s=new PageviewManager({addCustomEvent:(S,b)=>this.#Ps?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.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.#Le.setPageviewManager(this.#$s),this.#Us=new SessionLifecycleEmitter({addCustomEvent:(S,b)=>this.#Ps?.addCustomEvent(S,b),getContext:()=>this.#Le.getEventContext({release:this.config?.release,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),readGuard:()=>this.#Fs?.getLifecycleGuard?.()??null,writeGuard:S=>this.#Fs?.setLifecycleGuard?.(S),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Fs&&!this.#er&&(this.#Fs.onLifecycleEnd=({reason:S})=>{this.#Us?.emitEnd({reason:S})}),A&&this.#Ws){const S=this.#$s.getCurrentPageviewId(),b="undefined"!=typeof window&&"string"==typeof window.location?.href?window.location.href:"";b&&(this.#js=new WebVitalsEmitter({addCustomEvent:(S,b)=>this.#Ps?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.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.#Ws.addCallback?.((S,b)=>{this.#js?.emit(S,b)}),this.#Ws.metrics&&"function"==typeof this.#Ws.metrics.forEach&&this.#Ws.metrics.forEach(S=>{this.#js?.emit(S.type,S)}))}if(A&&(this.#qs=new TrackIdentifyEmitter({addCustomEvent:(S,b)=>this.#Ps?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.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&&!this.#er){const S=!0===this.#Fs?.isResumedSession?.();this.#$s.emitInitialPageView({isResumed:S})}return!A||this.#er||!this.#Fs||this.#Fs.isResumedSession?.()||this.#Fs.getLifecycleGuard?.()?.sessionStartEmitted||this.#Us.emitStart({}),A?(this.#as=new InterceptorFeature({logger:this.#o,config:this.config,monitoringCore:this,eventManager:this.#os}),this.#as.initialize(this.#Ps.recorder,this.#Bs.logManager),console.log("[TraceScout] ✓ Session recording bundle initialized (DOM + Network + Console + Errors)")):console.log("[TraceScout] ⏭️ Skipping interceptors (bundled with session recording)"),this.#zs=new EventLifecycleFeature({logger:this.#o,config:this.config}),this.#zs.setCallbacks({onCustomApiError:S=>this.#Es(S),onBeforeUnload:S=>this.#xs(S),onUserActivity:()=>this.#Ms(),onVisibilityChange:S=>this.#Rs(S)}),this.#zs.initialize(),this.#ir(),this.#os&&this.#os.loadFromLocal(),this.#Os&&this.#Os.ensureProfile(),this.#je=!0,this.#or(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}}#or(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.#Le.sessionId}`),console.log(` Environment: ${this.#Le.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.#Le.sessionId})}#ar(S,b){try{const I=Object.keys(b.features||{}).filter(S=>b.features[S].enabled);S({sessionId:this.#Le.sessionId,workspace:b.workspace.name,project:b.project.name,environment:this.#Le.environment,featuresEnabled:I,configVersion:b.configVersion})}catch(S){this.#o.error("Error in onReady callback:",S)}}#Ze(S){this.#Fs&&(this.#Fs.incrementChunkCount(),this.#Fs.incrementEventCount(S.eventCount||0))}#rr(S){if(!S||"object"!=typeof S)return;const b=mapInternalEndReason(S.reason);b&&this.#Us?.emitEnd({reason:b,totalChunks:"number"==typeof S.totalChunks?S.totalChunks:void 0,totalEvents:"number"==typeof S.totalEvents?S.totalEvents:void 0})}#Es(S){}#xs(S){}#Ms(){this.#Is||this.#Ps?.sessionEnded&&!this.#Ps?.isRecording&&(console.log("[TraceScout] 🔄 User activity detected after session end - starting new session"),this.forceNewSession("activity_after_"+this.#Ps.sessionEndReason))}#Rs(S){this.#Is||"visible"===S&&this.#Ps?.sessionEnded&&!this.#Ps?.isRecording&&(console.log("[TraceScout] 🔄 Tab visible after session end - starting new session"),this.forceNewSession("tab_focus_after_"+this.#Ps.sessionEndReason))}#nr(S){this.#Is||(this.#Is=!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.#zs?.setQuotaExceeded(!0),this.#Ps?.stop(),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:recording_stopped",{detail:{reason:"quota_exceeded",usage:S?.usage,message:S?.message||"Session quota exceeded"}})))}#ir(){"development"===this.config.environment||this.config.debug?this.#o.log("⚠️ Auto-retry DISABLED (development mode) - reduces API spam"):(this.#Vs=setInterval(()=>{this.#lr()},this.config.retryIntervalMs),this.#o.log("Auto-retry enabled (production mode)")),this.#Qs=setInterval(()=>{this.#cr()},6e4),this.#o.log("Background processes started")}#ur(){this.#Vs&&(clearInterval(this.#Vs),this.#Vs=null),this.#Qs&&(clearInterval(this.#Qs),this.#Qs=null)}async#lr(){try{if(this.#_s?.isSending)return;const S=this.#os?.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.#os.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++}}#cr(){try{if(this.#os){const S=this.config.eventMaxAge||864e5;this.#os.cleanupOldEvents(S)}}catch(S){this.#o.error("Error during cleanup:",S)}}#hr(){return"evt_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}destroy(){if(this.#je)try{try{this.#Zs?.shutdown()}catch(S){}this.#Zs=null,this.#Bs?.destroy(),this.#as?.destroy(),this.#Ps?.destroy(),this.#zs?.destroy(),this.#ur(),this.#Fs&&this.#Fs.destroy(),this.#je=!1,this.#o.info("TraceScoutMonitoringCore destroyed successfully")}catch(S){this.#o.error("Error during destruction:",S)}}logEvent(S,b={},I={}){if(this.#je)try{let x;"object"==typeof S&&S.type?(x={id:S.id||this.#hr(),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.#hr(),type:S,data:b,context:{isMonitored:!0,forceLog:I.forceLog||!1,status:I.status||"success",...I.context},timestamp:Date.now()};if(this.#os.addEvent(x)){this.#o.log("Event logged:",x.type);this.#os.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.#_s||!this.#os)return this.#o.warn("ServiceManager or EventManager not available"),!1;try{const b=S||this.#os.getEvents();if(!b||0===b.length)return!0;this.#o.info(`📤 Attempting to send ${b.length} events`);const I=await this.#_s.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.#os.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.#os?(this.#os.clearEvents(),this.#o.log("Event queue cleared")):this.#o.warn("EventManager not available")}isMonitoredEndpoint(S){if("string"!=typeof S||x.isEmpty(S))return!1;try{const b=this.config.endpoints||[],I=this.config.domainsToTrack||[];if(b.includes("*")||"*"===b)return!0;const R=S.toLowerCase();let A;try{A=new URL(R)}catch{return!1}if(!x.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&&!x.isEmpty(S)&&(!!x.isArray(this.config.fieldsToExtract)&&this.config.fieldsToExtract.some(I=>{const R=x.toLower(x.get(I,"api","")),A=x.get(I,"source","");return("*"===R||S.toLowerCase().includes(R))&&("*"===A||A===b)}))}extractUserContextFromBody({data:S,source:b="response",url:I=""}){if(!this.#Os)return{};try{return this.#Os.extractContextFromData({data:S,source:b,url:I})}catch(S){return this.#o.error("Failed to extract user context:",S),{}}}async startSessionRecording(S={}){return this.#Ps?.start(S)||null}stopSessionRecording(){return this.#Ps?.stop()||null}addSessionCustomEvent(S,b){if(this.#er&&this.#Zs?.child)try{return!0===this.#Zs.child.forwardTelemetry(S,b)}catch(S){return!1}if(this.#Le&&"object"==typeof b&&null!==b){const I=this.#dr(S);if(I){let x;try{const S=this.#Le.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),this.#gr(b,S);x=wrapInEnvelope(I,this.#pr(I,b),S)}catch(S){if(this.config?.debug&&this.#o.warn?.("addSessionCustomEvent: envelope build failed; skipping v1 emit:",S),"function"==typeof this.#Ls?.onError)try{this.#Ls.onError(S)}catch(S){}return!1}return this.#Ps?.addCustomEvent(S,x)||!1}}return this.#Ps?.addCustomEvent(S,b)||!1}setIframeTopFrameContext(S){this.#Js=S&&"object"==typeof S?S:null,this.#Js||(this.#Xs=0);try{this.#Le?.setTopFrameIdentity?.(this.#Js)}catch(S){}}static#fr=["frameId","parentFrameId","topFrameId","frameInstanceId","frameDepth","frameOrigin","frameUrl","frameLifecycle","captureRealm","privacyStatus","bridgeProtocolVersion","localSequence","tsLocal","tsNormalized","clockOffsetMs","clockUncertaintyMs"];#gr(S,b){const I=TraceScoutMonitoringCore.#fr;if("string"==typeof S.frameId&&S.frameId.length>0){for(const x of I){const I=S[x];null!=I&&""!==I&&(b[x]=I)}return}const x=this.#Js;if(!x)return;b.frameId=x.frameId,b.frameInstanceId=x.frameInstanceId,b.topFrameId=x.topFrameId,b.frameDepth=0,b.captureRealm="top","string"==typeof x.frameOrigin&&(b.frameOrigin=x.frameOrigin),"string"==typeof x.frameUrl&&(b.frameUrl=x.frameUrl),"string"==typeof x.frameLifecycle&&(b.frameLifecycle=x.frameLifecycle),"string"==typeof x.privacyStatus&&(b.privacyStatus=x.privacyStatus);const R="number"==typeof S.timestamp?S.timestamp:Date.now();b.localSequence=this.#Xs++,b.tsLocal=R,b.tsNormalized=R}#dr(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}}#pr(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.#Ps?.getStatus()||{available:!1,error:"Session recording not enabled"}}async getSessionEvents(S){return this.#Ps?.getEvents()||[]}exportSessionData(S="json"){if(!this.#Ps?.isAvailable)return this.#o.warn("Session recording not enabled"),null;try{const b=this.#Ps.getEvents(),I=this.#Ps.getChunks(),x=this.#Ps.getMetadata(),R=this.#Ps.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.#Ps.recorder?.recordingStartTime,endTime:this.#Ps.isRecording?null:Date.now(),duration:this.#Ps.recorder?.recordingStartTime?Date.now()-this.#Ps.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.#Ps?.getChunks()||[]}listChunks(){return(this.#Ps?.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.#Ps?.uploadQueue?.getStats()||null}getUploadQueue(){return this.#Ps?.uploadQueue?.getQueue()||null}pauseUploads(){return this.#Ps?.uploadQueue?.pause(),!0}resumeUploads(){return this.#Ps?.uploadQueue?.resume(),!0}getSessionStorageStats(){return this.#Ps?.sessionStorage?.getStorageStats()||null}getStoredSessions(){return this.#Ps?.sessionStorage?.getSessions()||{}}clearSessionStorage(){return this.#Ps?.sessionStorage?.clearAll()||!1}log(S,b,I={}){return this.#Bs?.log(S,b,I)||!1}debug(S,b={}){return this.#Bs?.debug(S,b)||!1}info(S,b={}){return this.#Bs?.info(S,b)||!1}warn(S,b={}){return this.#Bs?.warn(S,b)||!1}error(S,b={}){return this.#Bs?.error(S,b)||!1}fatal(S,b={}){return this.#Bs?.fatal(S,b)||!1}setLogContext(S,b){return this.#Bs?.setContext(S,b)||!1}clearLogContext(){return this.#Bs?.clearContext()||!1}setLogLevel(S){return this.#Bs?.setLogLevel(S)||!1}getLogStats(){return this.#Bs?.getStats()||null}async flushLogs(){return this.#Bs?.flush()||!1}enableLogging(S,b="info"){return this.#Bs?.enableServices(S,b)||!1}disableLogging(S){return this.#Bs?.disableServices(S)||!1}enableAllLogging(S="info"){return this.#Bs?.enableAll(S)||!1}disableAllLogging(){return this.#Bs?.disableAll()||!1}getLoggingConfig(){return this.#Bs?.getConfig()||null}getEnabledLogServices(){return this.#Bs?.getEnabledServices()||[]}getAvailableLogServices(){return this.#Bs?.getAvailableServices()||[]}setUserProfile(S){if(!this.#Os)return this.#o.warn("UserProfileManager not available"),!1;let b=!1;try{b=!0===this.#Os.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.#mr(b,I,{mode:"merge"},{skipUserProfileWrite:!0})}catch(S){this.#o.warn?.("Failed to route setUserProfile through identify:",S)}}return b}getUserProfile(){if(!this.#Os)return{};try{return this.#Os.getProfile()}catch(S){return this.#o.error("Failed to get user profile:",S),{}}}getSdkContext(){return!1===this.#Gs?{sampled:!1}:this.#Le}setUserMetadata(S,b={}){return this.identify(S,b,{mode:"merge"})}clearUserMetadata(){return!!this.#Le&&(this.#Le.clearUser(),this.#Fs&&this.#Fs.clearUserMetadata(),!0)}identify(S,b={},I={}){return this.#mr(S,b,I,{skipUserProfileWrite:!1})}#mr(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.#Le)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.#Le.userAttributes||{},$="set"===R?{}:{...U};null!==_&&($.email=_),null!==D&&($.name=D);const j=Object.assign({},$,B);if(this.#Le.setUser(S,j),this.#Fs)try{this.#Fs.updateUserMetadata(S,j)}catch(S){this.#o.warn?.("SessionManager.updateUserMetadata threw:",S)}if(!x.skipUserProfileWrite&&this.#Os)try{this.#Os.setProfile({userId:S,...j})}catch(S){this.#o.warn?.("UserProfileManager.setProfile threw:",S)}return this.#qs?this.#qs.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.#je)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.#qs?this.#qs.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.#je?(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.#Fs?.getSessionInfo?.()||{};return{initialized:this.#je,recording:this.#Ps?.isRecording||!1,sessionId:this.#Le?.sessionId||null,eventQueueSize:this.#os?.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.#je)return this.#o.warn("SDK not initialized"),null;if(this.#Is)return console.warn("[TraceScout] Cannot start new session - quota exceeded."),null;console.log("[TraceScout] 🔄 Forcing new session, reason:",S),this.#Ps?.stop(),this.#Fs&&this.#Fs.forceNewSession(S);const b=this.#Fs?.getOrCreateSession({projectId:this.#Le.projectId,environment:this.#Le.environment,userId:this.#Le.userId});if(this.#Le&&b&&(this.#Le.sessionId=b,this.#Le.sessionStartTime=Date.now()),this.#Ps&&b){this.#Ps.updateSessionId(b);const S=this.config.apiBaseUrl||"http://localhost:3001";this.#Ps.updateUploadEndpoint(`${S}/api/projects/${this.#Le.projectId}/sessions/${b}/chunks`),this.#Ps.recorder?.start()}return b}debugMode(S){this.config.debug=S,this.#o.updateDebugMode(S),this.#_s&&this.#_s.updateDebugMode(S),this.#as?.updateDebugMode(S),this.#o.log("Debug mode "+(S?"enabled":"disabled"))}getQueueStatus(){return{queueSize:this.#os?this.#os.getQueueSize():0,isSending:!!this.#_s&&this.#_s.isSending,isInitialized:this.#je,service:this.#_s?this.#_s.getServiceName():"none",configSource:this.config?.configSource||"local",configVersion:this.config?.configVersion||"local"}}getPerformanceMetrics(){return this.#Ds?.getMetrics()||null}getCoreWebVitalsMonitor(){return this.#Ws}getCoreWebVitalsMetrics(){return this.#Ws?.getAllMetrics()||null}getCoreWebVitalsInsights(){return this.#Ws?.getPerformanceInsights()||null}generateCoreWebVitalsReport(){return this.#Ws?.generateReport()||null}updateCoreWebVitalsThresholds(S){this.#Ws?this.#Ws.updateThresholds(S):this.#o.warn("Core Web Vitals monitor not available")}}let it;try{it=new TraceScoutMonitoringCore}catch(S){it={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=it}catch(S){}var ot=it;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}}}function parseRequestUrl(S){try{return new URL(S,location.origin)}catch(S){return null}}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.#yr(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.#vr(),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.#Sr();return this.config=b,b}}#yr(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")}#Sr(){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}}}}}#vr(){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}}function __tsSafeContentDoc(S){try{if(S&&"IFRAME"===S.tagName&&S.src)try{var b=new URL(S.src);if(("http:"===b.protocol||"https:"===b.protocol)&&"undefined"!=typeof location&&b.origin!==location.origin)return null}catch(S){}return S.contentDocument}catch(S){return null}}var at,lt=Object.defineProperty,__publicField=(S,b,I)=>((S,b,I)=>b in S?lt(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),ct=Object.defineProperty,__publicField$1=(S,b,I)=>((S,b,I)=>b in S?ct(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),ut=(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))(ut||{});const ht={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},dt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},gt={};function getUntaintedPrototype$1(S){if(gt[S])return gt[S];const b=globalThis[S],I=b.prototype,x=S in ht?ht[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 dt?dt[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 gt[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?gt[S]=A:I}catch{return I}}const pt={};function getUntaintedAccessor$1(S,b,I){var x;const R=`${S}.${String(I)}`;if(pt[R])return pt[R].call(b);const A=getUntaintedPrototype$1(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(pt[R]=_,_.call(b)):b[I]}const ft={};function getUntaintedMethod$1(S,b,I){const x=`${S}.${String(I)}`;if(ft[x])return ft[x].bind(b);const R=getUntaintedPrototype$1(S)[I];return"function"!=typeof R?b[I]:(ft[x]=R,R.bind(b))}const mt={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&&mt.host(S)||null;return Boolean(b&&"shadowRoot"in b&&mt.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 yt="__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 vt=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,St=/^(?:[a-z+]+:)?\/\//i,wt=/^www\..*/i,bt=/^(data:)([^,]*),(.*)/i;function absolutifyURLs(S,b){return(S||"").replace(vt,(S,I,x,R,A,_)=>{const D=x||A||_,L=I||R||"";if(!D)return S;if(St.test(D)||wt.test(D))return`url(${L}${D}${L})`;if(bt.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 kt=new RegExp("[^a-z0-9-_:]");function genId(){return Ct++}let It,Et;const xt=/^[^ \t\n\r\u000c]+/,Mt=/^[, \t\n\r\u000c]+/;const Rt=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=Rt.get(S);if(I||(I=S.createElement("a"),Rt.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(Mt),!(I>=b.length);){let R=collectCharacters(xt);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(mt.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(mt.parentNode(S),b,I)}function needMaskingText(S,b,I,x){let R;if(isElement(S)){if(R=S,!mt.childNodes(R).length)return!1}else{if(null===mt.parentElement(S))return!1;R=mt.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:ut.Document,childNodes:[],compatMode:S.compatMode}:{type:ut.Document,childNodes:[]};case S.DOCUMENT_TYPE_NODE:return{type:ut.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 kt.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=yt in R?R[yt]: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){It||(It=I.createElement("canvas"),Et=It.getContext("2d"));const b=S,x=b.currentSrc||b.getAttribute("src")||"<unknown-src>",R=b.crossOrigin,recordInlineImage=()=>{b.removeEventListener("load",recordInlineImage);try{It.width=b.naturalWidth,It.height=b.naturalHeight,Et.drawImage(b,0,0),Q.rr_dataURL=It.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)||(__tsSafeContentDoc(S)||(Q.rr_src=Q.src),delete Q.src);let J;try{customElements.get(V)&&(J=!0)}catch(S){}return{type:ut.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,_=mt.parentNode(S),D=_&&_.tagName;let L="";const B="STYLE"===D||void 0,U="SCRIPT"===D||void 0;U?L="SCRIPT_PLACEHOLDER":A||(L=mt.textContent(S),B&&L&&(L=absolutifyURLs(L,getHref(b.doc))));!B&&!U&&L&&I&&(L=x?x(L,mt.parentElement(S)):L.replace(/[\S]/g,"*"));return{type:ut.Text,textContent:L||"",rootId:R}}(S,{doc:I,needsMask:_,maskTextFn:B,rootId:G,cssCaptured:Q});case S.CDATA_SECTION_NODE:return{type:ut.CDATA,textContent:"",rootId:G};case S.COMMENT_NODE:return{type:ut.Comment,textContent:mt.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===ut.Comment)return!0;if(S.type===ut.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===ut.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===ut.Element){ce=ce&&!le.needBlock,delete le.needBlock;const b=mt.shadowRoot(S);b&&isNativeShadowDom(b)&&(le.isShadowHost=!0)}if((le.type===ut.Document||le.type===ut.Element)&&ce){W.headWhitespace&&le.type===ut.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===ut.Element&&"textarea"===le.tagName&&void 0!==le.attributes.value);else{le.type===ut.Element&&void 0!==le.attributes._cssText&&"string"==typeof le.attributes._cssText&&(b.cssCaptured=!0);for(const I of Array.from(mt.childNodes(S))){const S=serializeNodeWithId(I,b);S&&le.childNodes.push(S)}}let se=null;if(isElement(S)&&(se=mt.shadowRoot(S)))for(const S of Array.from(mt.childNodes(se))){const I=serializeNodeWithId(S,b);I&&(isNativeShadowDom(se)&&(I.isShadow=!0),le.childNodes.push(I))}}const ue=mt.parentNode(S);return ue&&isShadowRoot(ue)&&isNativeShadowDom(ue)&&(le.isShadow=!0),le.type===ut.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=__tsSafeContentDoc(S);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===ut.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 Tt={exports:{}},At=String,create$1=function(){return{isColorSupported:!1,reset:At,bold:At,dim:At,italic:At,underline:At,inverse:At,hidden:At,strikethrough:At,black:At,red:At,green:At,yellow:At,blue:At,magenta:At,cyan:At,white:At,gray:At,bgBlack:At,bgRed:At,bgGreen:At,bgYellow:At,bgBlue:At,bgMagenta:At,bgCyan:At,bgWhite:At}};Tt.exports=create$1(),Tt.exports.createColors=create$1;var _t=Tt.exports;const Ot=getAugmentedNamespace$1(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Dt=_t,Ft=Ot,Nt=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=Dt.isColorSupported),Ft&&S&&(b=Ft(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}=Dt.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 Lt=Nt;Nt.default=Nt;var Pt={};Pt.isClean=Symbol("isClean"),Pt.my=Symbol("my");const Bt={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let zt=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 Bt[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=Bt[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 Ut=zt;zt.default=zt;let $t=Ut;function stringify$4$1(S,b){new $t(b).stringify(S)}var jt=stringify$4$1;stringify$4$1.default=stringify$4$1;let{isClean:qt,my:Wt}=Pt,Ht=Lt,Vt=Ut,Qt=jt;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 Gt=class Node2{constructor(S={}){this.raws={},this[qt]=!1,this[Wt]=!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 Ht(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[qt]){this[qt]=!1;let S=this;for(;S=S.parent;)S[qt]=!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 Vt).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=Qt){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 Kt=Gt;Gt.default=Gt;let Jt=Kt,Xt=class Declaration extends Jt{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 Yt=Xt;Xt.default=Xt;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:es,SourceMapGenerator:ts}=Ot,{existsSync:ss,readFileSync:rs}=Ot,{dirname:ns,join:is}=Ot;let os=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=ns(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new es(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=ns(S),ss(S))return this.mapFile=S,rs(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 es)return ts.fromSourceMap(b).toString();if(b instanceof ts)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=is(ns(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 as=os;os.default=os;let{SourceMapConsumer:ls,SourceMapGenerator:cs}=Ot,{fileURLToPath:us,pathToFileURL:hs}=Ot,{isAbsolute:ds,resolve:gs}=Ot,{nanoid:ps}=Zt,fs=Ot,ms=Lt,ys=as,vs=Symbol("fromOffsetCache"),Ss=Boolean(ls&&cs),ws=Boolean(gs&&ds),bs=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&&(!ws||/^\w+:\/\//.test(b.from)||ds(b.from)?this.file=b.from:this.file=gs(b.from)),ws&&Ss){let S=new ys(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 "+ps(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 ms(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 ms(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&&(hs&&(R.input.url=hs(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[vs])I=this[vs];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[vs]=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:gs(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=ds(D.source)?hs(D.source):new URL(D.source,this.map.consumer().sourceRoot||hs(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(!us)throw new Error("file: protocol is not available in this PostCSS build");L.file=us(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=bs;bs.default=bs,fs&&fs.registerInput&&fs.registerInput(bs);let{SourceMapConsumer:ks,SourceMapGenerator:Is}=Ot,{dirname:Es,relative:xs,resolve:Ms,sep:Rs}=Ot,{pathToFileURL:Ts}=Ot,As=Cs,_s=Boolean(ks&&Is),Os=Boolean(Es&&Ms&&xs&&Rs);var Ds=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||Es(S.file);!1===this.mapOpts.sourcesContent?(b=new ks(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(),Os&&_s&&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=Is.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Is({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 Is({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?Es(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=Es(Ms(I,this.mapOpts.annotation)));let x=xs(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 As(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(Ts){let b=Ts(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;"\\"===Rs&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let Fs=Kt,Ns=class Comment extends Fs{constructor(S){super(S),this.type="comment"}};var Ls=Ns;Ns.default=Ns;let Ps,Bs,zs,Us,{isClean:$s,my:js}=Pt,qs=Yt,Ws=Ls,Hs=Kt;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[$s]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp$1(b)}let Vs=class Container extends Hs{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(Ps(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 qs(S)]}else if(S.selector)S=[new Bs(S)];else if(S.name)S=[new zs(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new Ws(S)]}return S.map(S=>(S[js]||Container.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[$s]&&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]}};Vs.registerParse=S=>{Ps=S},Vs.registerRule=S=>{Bs=S},Vs.registerAtRule=S=>{zs=S},Vs.registerRoot=S=>{Us=S};var Qs=Vs;Vs.default=Vs,Vs.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,zs.prototype):"rule"===S.type?Object.setPrototypeOf(S,Bs.prototype):"decl"===S.type?Object.setPrototypeOf(S,qs.prototype):"comment"===S.type?Object.setPrototypeOf(S,Ws.prototype):"root"===S.type&&Object.setPrototypeOf(S,Us.prototype),S[js]=!0,S.nodes&&S.nodes.forEach(S=>{Vs.rebuild(S)})};let Gs,Ks,Js=Qs,Xs=class Document2 extends Js{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Gs(new Ks,this,S).stringify()}};Xs.registerLazyResult=S=>{Gs=S},Xs.registerProcessor=S=>{Ks=S};var Ys=Xs;Xs.default=Xs;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 er=Zs;Zs.default=Zs;let tr=er,sr=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 tr(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var rr=sr;sr.default=sr;const nr="'".charCodeAt(0),ir='"'.charCodeAt(0),or="\\".charCodeAt(0),ar="/".charCodeAt(0),lr="\n".charCodeAt(0),cr=" ".charCodeAt(0),ur="\f".charCodeAt(0),hr="\t".charCodeAt(0),dr="\r".charCodeAt(0),gr="[".charCodeAt(0),pr="]".charCodeAt(0),fr="(".charCodeAt(0),mr=")".charCodeAt(0),yr="{".charCodeAt(0),vr="}".charCodeAt(0),Sr=";".charCodeAt(0),wr="*".charCodeAt(0),br=":".charCodeAt(0),Cr="@".charCodeAt(0),kr=/[\t\n\f\r "#'()/;[\\\]{}]/g,Ir=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Er=/.[\r\n"'(/\\]/,xr=/[\da-f]/i;let Mr=Qs,Rr=class AtRule extends Mr{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 Tr=Rr;Rr.default=Rr,Mr.registerAtRule(Rr);let Ar,_r,Or=Qs,Dr=class Root extends Or{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 Ar(new _r,this,S).stringify()}};Dr.registerLazyResult=S=>{Ar=S},Dr.registerProcessor=S=>{_r=S};var Fr=Dr;Dr.default=Dr,Or.registerRoot(Dr);let Nr={comma:S=>Nr.split(S,[","],!0),space:S=>Nr.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 Lr=Nr;Nr.default=Nr;let Pr=Qs,Br=Lr,zr=class Rule extends Pr{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Br.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 Ur=zr;zr.default=zr,Pr.registerRule(zr);let $r=Yt,jr=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 lr:case cr:case hr:case dr:case ur:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===cr||I===lr||I===hr||I===dr||I===ur);$=["space",j.slice(V,x)],V=x-1;break;case gr:case pr:case yr:case vr:case br:case Sr:case mr:{let S=String.fromCharCode(I);$=[S,S,V];break}case fr:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==nr&&U!==ir&&U!==cr&&U!==lr&&U!==hr&&U!==ur&&U!==dr){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)===or;)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||Er.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case nr:case ir:R=I===nr?"'":'"',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)===or;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Cr:kr.lastIndex=V+1,kr.test(j),x=0===kr.lastIndex?j.length-1:kr.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case or:for(x=V,_=!0;j.charCodeAt(x+1)===or;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==ar&&I!==cr&&I!==lr&&I!==hr&&I!==dr&&I!==ur&&(x+=1,xr.test(j.charAt(x)))){for(;xr.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===cr&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===ar&&j.charCodeAt(V+1)===wr?(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):(Ir.lastIndex=V+1,Ir.test(j),x=0===Ir.lastIndex?j.length-1:Ir.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},qr=Ls,Wr=Tr,Hr=Fr,Vr=Ur;const Qr={empty:!0,space:!0};var Gr=class Parser{constructor(S){this.input=S,this.root=new Hr,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 Wr;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 qr;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=jr(this.input)}decl(S,b){let I=new $r;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 Vr;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",Qr[D]||Qr[_]||","===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 Vr;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 Kr=Qs,Jr=Gr,Xr=Cs;function parse$3$1(S,b){let I=new Xr(S,b),x=new Jr(I);try{x.parse()}catch(S){throw S}return x.root}var Yr=parse$3$1;parse$3$1.default=parse$3$1,Kr.registerParse(parse$3$1);let{isClean:Zr,my:en}=Pt,tn=Ds,sn=jt,rn=Qs,nn=Ys,an=rr,cn=Yr,un=Fr;const hn={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},dn={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},gn={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=hn[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 pn={},fn=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 an)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=cn;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[en]&&rn.rebuild(x)}else x=cleanMarks$1(b);this.result=new an(S,x,I),this.helpers={...pn,postcss:pn,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(!dn[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!gn[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=sn;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new tn(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"}};fn.registerPostcss=S=>{pn=S};var mn=fn;fn.default=fn,un.registerLazyResult(fn),nn.registerLazyResult(fn);let yn=Ds,vn=jt,Sn=Yr;const wn=rr;let bn=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=vn;this.result=new wn(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new yn(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 Cn=bn;bn.default=bn;let kn=Cn,In=mn,En=Ys,xn=Fr,Mn=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 In(this,S,b):new kn(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var Rn=Mn;Mn.default=Mn,xn.registerProcessor(Mn),En.registerProcessor(Mn);let Tn=Yt,An=as,_n=Ls,On=Tr,Dn=Cs,Fn=Fr,Nn=Ur;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__:Dn.prototype};I.map&&(I.map={...I.map,__proto__:An.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 Fn(x);if("decl"===x.type)return new Tn(x);if("rule"===x.type)return new Nn(x);if("comment"===x.type)return new _n(x);if("atrule"===x.type)return new On(x);throw new Error("Unknown node type: "+S.type)}var Ln=fromJSON$1$1;fromJSON$1$1.default=fromJSON$1$1;let Pn=Lt,Bn=Yt,zn=mn,Un=Qs,$n=Rn,jn=jt,qn=Ln,Wn=Ys,Hn=er,Vn=Ls,Qn=Tr,Gn=rr,Kn=Cs,Jn=Yr,Xn=Lr,Yn=Ur,Zn=Fr,ei=Kt;function postcss$3(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new $n(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 $n).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=jn,postcss$3.parse=Jn,postcss$3.fromJSON=qn,postcss$3.list=Xn,postcss$3.comment=S=>new Vn(S),postcss$3.atRule=S=>new Qn(S),postcss$3.decl=S=>new Bn(S),postcss$3.rule=S=>new Yn(S),postcss$3.root=S=>new Zn(S),postcss$3.document=S=>new Wn(S),postcss$3.CssSyntaxError=Pn,postcss$3.Declaration=Bn,postcss$3.Container=Un,postcss$3.Processor=$n,postcss$3.Document=Wn,postcss$3.Comment=Vn,postcss$3.Warning=Hn,postcss$3.AtRule=Qn,postcss$3.Result=Gn,postcss$3.Input=Kn,postcss$3.Rule=Yn,postcss$3.Root=Zn,postcss$3.Node=ei,zn.registerPostcss(postcss$3),postcss$3.default=postcss$3;var ti=Object.defineProperty,__publicField2=(S,b,I)=>((S,b,I)=>b in S?ti(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 si={exports:{}},ri=String,create=function(){return{isColorSupported:!1,reset:ri,bold:ri,dim:ri,italic:ri,underline:ri,inverse:ri,hidden:ri,strikethrough:ri,black:ri,red:ri,green:ri,yellow:ri,blue:ri,magenta:ri,cyan:ri,white:ri,gray:ri,bgBlack:ri,bgRed:ri,bgGreen:ri,bgYellow:ri,bgBlue:ri,bgMagenta:ri,bgCyan:ri,bgWhite:ri}};si.exports=create(),si.exports.createColors=create;var ni=si.exports;const ii=getAugmentedNamespace(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let oi=ni,ai=ii,li=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=oi.isColorSupported),ai&&S&&(b=ai(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}=oi.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 ci=li;li.default=li;var ui={};ui.isClean=Symbol("isClean"),ui.my=Symbol("my");const hi={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let di=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 hi[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=hi[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 gi=di;di.default=di;let pi=gi;function stringify$4(S,b){new pi(b).stringify(S)}var fi=stringify$4;stringify$4.default=stringify$4;let{isClean:mi,my:yi}=ui,vi=ci,Si=gi,wi=fi;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 bi=class Node3{constructor(S={}){this.raws={},this[mi]=!1,this[yi]=!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 vi(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[mi]){this[mi]=!1;let S=this;for(;S=S.parent;)S[mi]=!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 Si).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=wi){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=bi;bi.default=bi;let ki=Ci,Ii=class Declaration2 extends ki{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 Ei=Ii;Ii.default=Ii;var xi={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:Mi,SourceMapGenerator:Ri}=ii,{existsSync:Ti,readFileSync:Ai}=ii,{dirname:_i,join:Oi}=ii;let Di=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=_i(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new Mi(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=_i(S),Ti(S))return this.mapFile=S,Ai(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 Mi)return Ri.fromSourceMap(b).toString();if(b instanceof Ri)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=Oi(_i(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 Fi=Di;Di.default=Di;let{SourceMapConsumer:Ni,SourceMapGenerator:Li}=ii,{fileURLToPath:Pi,pathToFileURL:Bi}=ii,{isAbsolute:zi,resolve:Ui}=ii,{nanoid:$i}=xi,ji=ii,qi=ci,Wi=Fi,Hi=Symbol("fromOffsetCache"),Vi=Boolean(Ni&&Li),Qi=Boolean(Ui&&zi),Gi=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&&(!Qi||/^\w+:\/\//.test(b.from)||zi(b.from)?this.file=b.from:this.file=Ui(b.from)),Qi&&Vi){let S=new Wi(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 "+$i(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 qi(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 qi(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&&(Bi&&(R.input.url=Bi(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[Hi])I=this[Hi];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[Hi]=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:Ui(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=zi(D.source)?Bi(D.source):new URL(D.source,this.map.consumer().sourceRoot||Bi(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(!Pi)throw new Error("file: protocol is not available in this PostCSS build");L.file=Pi(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 Ki=Gi;Gi.default=Gi,ji&&ji.registerInput&&ji.registerInput(Gi);let{SourceMapConsumer:Ji,SourceMapGenerator:Xi}=ii,{dirname:Yi,relative:Zi,resolve:eo,sep:to}=ii,{pathToFileURL:so}=ii,ro=Ki,no=Boolean(Ji&&Xi),io=Boolean(Yi&&eo&&Zi&&to);var oo=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||Yi(S.file);!1===this.mapOpts.sourcesContent?(b=new Ji(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(),io&&no&&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=Xi.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Xi({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 Xi({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?Yi(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=Yi(eo(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 ro(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(so){let b=so(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;"\\"===to&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let ao=Ci,lo=class Comment2 extends ao{constructor(S){super(S),this.type="comment"}};var co=lo;lo.default=lo;let uo,ho,go,po,{isClean:fo,my:mo}=ui,yo=Ei,vo=co,So=Ci;function cleanSource(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource(S.nodes)),delete S.source,S))}function markDirtyUp(S){if(S[fo]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp(b)}let wo=class Container2 extends So{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(uo(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 yo(S)]}else if(S.selector)S=[new ho(S)];else if(S.name)S=[new go(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new vo(S)]}return S.map(S=>(S[mo]||Container2.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[fo]&&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]}};wo.registerParse=S=>{uo=S},wo.registerRule=S=>{ho=S},wo.registerAtRule=S=>{go=S},wo.registerRoot=S=>{po=S};var bo=wo;wo.default=wo,wo.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,go.prototype):"rule"===S.type?Object.setPrototypeOf(S,ho.prototype):"decl"===S.type?Object.setPrototypeOf(S,yo.prototype):"comment"===S.type?Object.setPrototypeOf(S,vo.prototype):"root"===S.type&&Object.setPrototypeOf(S,po.prototype),S[mo]=!0,S.nodes&&S.nodes.forEach(S=>{wo.rebuild(S)})};let Co,ko,Io=bo,Eo=class Document23 extends Io{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Co(new ko,this,S).stringify()}};Eo.registerLazyResult=S=>{Co=S},Eo.registerProcessor=S=>{ko=S};var xo=Eo;Eo.default=Eo;let Mo=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 Ro=Mo;Mo.default=Mo;let To=Ro,Ao=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 To(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var _o=Ao;Ao.default=Ao;const Oo="'".charCodeAt(0),Do='"'.charCodeAt(0),Fo="\\".charCodeAt(0),No="/".charCodeAt(0),Lo="\n".charCodeAt(0),Po=" ".charCodeAt(0),Bo="\f".charCodeAt(0),zo="\t".charCodeAt(0),Uo="\r".charCodeAt(0),$o="[".charCodeAt(0),jo="]".charCodeAt(0),qo="(".charCodeAt(0),Wo=")".charCodeAt(0),Ho="{".charCodeAt(0),Vo="}".charCodeAt(0),Qo=";".charCodeAt(0),Go="*".charCodeAt(0),Ko=":".charCodeAt(0),Jo="@".charCodeAt(0),Xo=/[\t\n\f\r "#'()/;[\\\]{}]/g,Yo=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Zo=/.[\r\n"'(/\\]/,ea=/[\da-f]/i;let ta=bo,sa=class AtRule2 extends ta{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 ra=sa;sa.default=sa,ta.registerAtRule(sa);let na,ia,oa=bo,aa=class Root2 extends oa{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 na(new ia,this,S).stringify()}};aa.registerLazyResult=S=>{na=S},aa.registerProcessor=S=>{ia=S};var la=aa;aa.default=aa,oa.registerRoot(aa);let ca={comma:S=>ca.split(S,[","],!0),space:S=>ca.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 ua=ca;ca.default=ca;let ha=bo,da=ua,ga=class Rule2 extends ha{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return da.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 pa=ga;ga.default=ga,ha.registerRule(ga);let fa=Ei,ma=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 Lo:case Po:case zo:case Uo:case Bo:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===Po||I===Lo||I===zo||I===Uo||I===Bo);$=["space",j.slice(V,x)],V=x-1;break;case $o:case jo:case Ho:case Vo:case Ko:case Qo:case Wo:{let S=String.fromCharCode(I);$=[S,S,V];break}case qo:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==Oo&&U!==Do&&U!==Po&&U!==Lo&&U!==zo&&U!==Bo&&U!==Uo){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)===Fo;)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 Oo:case Do:R=I===Oo?"'":'"',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)===Fo;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Jo:Xo.lastIndex=V+1,Xo.test(j),x=0===Xo.lastIndex?j.length-1:Xo.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case Fo:for(x=V,_=!0;j.charCodeAt(x+1)===Fo;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==No&&I!==Po&&I!==Lo&&I!==zo&&I!==Uo&&I!==Bo&&(x+=1,ea.test(j.charAt(x)))){for(;ea.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===Po&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===No&&j.charCodeAt(V+1)===Go?(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):(Yo.lastIndex=V+1,Yo.test(j),x=0===Yo.lastIndex?j.length-1:Yo.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},ya=co,va=ra,Sa=la,wa=pa;const ba={empty:!0,space:!0};var Ca=class Parser2{constructor(S){this.input=S,this.root=new Sa,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 va;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 ya;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=ma(this.input)}decl(S,b){let I=new fa;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 wa;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",ba[D]||ba[_]||","===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 wa;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 ka=bo,Ia=Ca,Ea=Ki;function parse$3(S,b){let I=new Ea(S,b),x=new Ia(I);try{x.parse()}catch(S){throw S}return x.root}var xa=parse$3;parse$3.default=parse$3,ka.registerParse(parse$3);let{isClean:Ma,my:Ra}=ui,Ta=oo,Aa=fi,_a=bo,Oa=xo,Da=_o,Fa=xa,Na=la;const La={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},Pa={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},Ba={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents(S){let b=!1,I=La[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[Ma]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks(S)),S}let za={},Ua=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 Da)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=Fa;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[Ra]&&_a.rebuild(x)}else x=cleanMarks(b);this.result=new Da(S,x,I),this.helpers={...za,postcss:za,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(!Pa[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Ba[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[Ma];){S[Ma]=!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=Aa;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new Ta(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[Ma];)S[Ma]=!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[Ma])return x[Ma]=!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[Ma]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[Ma]=!0;let b=getEvents(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[Ma]||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"}};Ua.registerPostcss=S=>{za=S};var $a=Ua;Ua.default=Ua,Na.registerLazyResult(Ua),Oa.registerLazyResult(Ua);let ja=oo,qa=fi,Wa=xa;const Ha=_o;let Va=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=qa;this.result=new Ha(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new ja(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=Wa;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 Qa=Va;Va.default=Va;let Ga=Qa,Ka=$a,Ja=xo,Xa=la,Ya=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 Ka(this,S,b):new Ga(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var Za=Ya;Ya.default=Ya,Xa.registerProcessor(Ya),Ja.registerProcessor(Ya);let el=Ei,tl=Fi,sl=co,rl=ra,nl=Ki,il=la,ol=pa;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__:nl.prototype};I.map&&(I.map={...I.map,__proto__:tl.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 il(x);if("decl"===x.type)return new el(x);if("rule"===x.type)return new ol(x);if("comment"===x.type)return new sl(x);if("atrule"===x.type)return new rl(x);throw new Error("Unknown node type: "+S.type)}var al=fromJSON$1;fromJSON$1.default=fromJSON$1;let ll=ci,cl=Ei,ul=$a,hl=bo,dl=Za,gl=fi,pl=al,fl=xo,ml=Ro,yl=co,vl=ra,Sl=_o,wl=Ki,bl=xa,Cl=ua,kl=pa,Il=la,El=Ci;function postcss(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new dl(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 dl).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=gl,postcss.parse=bl,postcss.fromJSON=pl,postcss.list=Cl,postcss.comment=S=>new yl(S),postcss.atRule=S=>new vl(S),postcss.decl=S=>new cl(S),postcss.rule=S=>new kl(S),postcss.root=S=>new Il(S),postcss.document=S=>new fl(S),postcss.CssSyntaxError=ll,postcss.Declaration=cl,postcss.Container=hl,postcss.Processor=dl,postcss.Document=fl,postcss.Comment=yl,postcss.Warning=ml,postcss.AtRule=vl,postcss.Result=Sl,postcss.Input=wl,postcss.Rule=kl,postcss.Root=Il,postcss.Node=El,ul.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 xl={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Ml={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Rl={};function getUntaintedPrototype(S){if(Rl[S])return Rl[S];const b=globalThis[S],I=b.prototype,x=S in xl?xl[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 Ml?Ml[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 Rl[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?Rl[S]=A:I}catch{return I}}const Tl={};function getUntaintedAccessor(S,b,I){var x;const R=`${S}.${String(I)}`;if(Tl[R])return Tl[R].call(b);const A=getUntaintedPrototype(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(Tl[R]=_,_.call(b)):b[I]}const Al={};function getUntaintedMethod(S,b,I){const x=`${S}.${String(I)}`;if(Al[x])return Al[x].bind(b);const R=getUntaintedPrototype(S)[I];return"function"!=typeof R?b[I]:(Al[x]=R,R.bind(b))}function mutationObserverCtor(){return getUntaintedPrototype("MutationObserver").constructor}const _l={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 Ol="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 Dl={map:{},getId:()=>(console.error(Ol),-1),getNode:()=>(console.error(Ol),null),removeNodeFromMap(){console.error(Ol)},has:()=>(console.error(Ol),!1),reset(){console.error(Ol)}};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&&(Dl=new Proxy(Dl,{get:(S,b,I)=>("map"===b&&console.error(Ol),Reflect.get(S,b,I))}));let Fl=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=_l.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=_l.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:_l.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=_l.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(_l.shadowRoot(S)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(Fl=()=>(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=_l.getRootNode(S))?void 0:b.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&_l.host(_l.getRootNode(S))&&(I=_l.host(_l.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 _l.contains(b,I)}function inDom(S){const b=S.ownerDocument;return!!b&&(_l.contains(b,S)||shadowHostInDom(S))}var Nl=(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))(Nl||{}),Ll=(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))(Ll||{}),Pl=(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))(Pl||{}),Bl=(S=>(S[S.Mouse=0]="Mouse",S[S.Pen=1]="Pen",S[S.Touch=2]="Touch",S))(Bl||{}),zl=(S=>(S[S["2D"]=0]="2D",S[S.WebGL=1]="WebGL",S[S.WebGL2=2]="WebGL2",S))(zl||{}),Ul=(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))(Ul||{}),$l=(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))($l||{});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=_l.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(_l.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(_l.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(_l.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(_l.parentNode(I.value));if(-1===getNextId(I.value))continue;if(-1!==b){S=I;break}{const b=I.value,x=_l.parentNode(b);if(x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const b=_l.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=_l.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(_l.childNodes(S),S=>_l.textContent(S)||"").join("")}),__publicField(this,"processMutation",S=>{if(!isIgnored(S.target,this.mirror,this.slimDOMOptions))switch(S.type){case"characterData":{const b=_l.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(__tsSafeContentDoc(b))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(_l.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),_l.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)||(_l.childNodes(S).forEach(S=>this.genAdds(S)),hasShadowRoot(S)&&_l.childNodes(_l.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),_l.childNodes(b).forEach(b=>deepDelete(S,b))}function isParentRemoved(S,b,I){return 0!==S.size&&function _isParentRemoved(S,b,I){const x=_l.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=_l.parentNode(b);return!!I&&(!!S.has(I)||_isAncestorInSet(S,I))}let jl;const callbackWrapper=S=>{if(!jl)return S;return(...b)=>{try{return S(...b)}catch(S){if(jl&&!0===jl(S))return;throw S}}},ql=[];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;ql.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(Pl).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=Bl.Mouse;break;case"touch":D=Bl.Touch;break;case"pen":D=Bl.Pen}D===Bl.Touch&&(Pl[b]===Pl.MouseDown?B="TouchStart":Pl[b]===Pl.MouseUp&&(B="TouchEnd"))}else legacy_isTouchEvent(A)&&(D=Bl.Touch);null!==D?(L=D,(B.startsWith("Touch")&&D===Bl.Touch||B.startsWith("Mouse")&&D===Bl.Mouse)&&(D=null)):Pl[b]===Pl.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:Pl[B],id:$,x:j,y:W,...null!==D&&{pointerType:D}})})(A);if(window.PointerEvent)switch(Pl[A]){case Pl.MouseDown:case Pl.MouseUp:_=_.replace("mouse","pointer");break;case Pl.TouchStart:case Pl.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 Wl=["INPUT","TEXTAREA","SELECT"],Hl=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(_l.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;_||(_=Fl()),D.push({x:I,y:R,id:x.getId(b),timeOffset:Fl()-_}),L("undefined"!=typeof DragEvent&&S instanceof DragEvent?Ll.Drag:S instanceof MouseEvent?Ll.MouseMove:Ll.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=_l.parentElement(I)),!I||!$||Wl.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=Hl.get(b);if(!R||R.text!==x.text||R.isChecked!==x.isChecked){Hl.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",_(Ul.Play),A),on("pause",_(Ul.Pause),A),on("seeked",_(Ul.Seeked),A),on("volumechange",_(Ul.VolumeChange),A),on("ratechange",_(Ul.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(()=>{ql.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.__TS_IFRAME_BRIDGE_PARENT_REGISTER&&window.__TS_IFRAME_BRIDGE_PARENT_REGISTER(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;this.mutationCb({adds:[{parentId:this.mirror.getId(S),nextId:null,node:b}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),null==(I=this.loadListener)||I.call(this,S),__tsSafeContentDoc(S)&&__tsSafeContentDoc(S).adoptedStyleSheets&&__tsSafeContentDoc(S).adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(__tsSafeContentDoc(S).adoptedStyleSheets,this.mirror.getId(__tsSafeContentDoc(S)))}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 Nl.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:Nl.IncrementalSnapshot,data:{source:Ll.Mutation,adds:[{parentId:this.mirror.getId(S),nextId:null,node:b.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Nl.Meta:case Nl.Load:case Nl.DomContentLoaded:return!1;case Nl.Plugin:return b;case Nl.Custom:return this.replaceIds(b.data.payload,S,["id","parentId","previousId","nextId"]),b;case Nl.IncrementalSnapshot:switch(b.data.source){case Ll.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 Ll.Drag:case Ll.TouchMove:case Ll.MouseMove:return b.data.positions.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case Ll.ViewportResize:return!1;case Ll.MediaInteraction:case Ll.MouseInteraction:case Ll.Scroll:case Ll.CanvasMutation:case Ll.Input:return this.replaceIds(b.data,S,["id"]),b;case Ll.StyleSheetRule:case Ll.StyleDeclaration:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleId"]),b;case Ll.Font:return b;case Ll.Selection:return b.data.ranges.forEach(b=>{this.replaceIds(b,S,["start","end"])}),b;case Ll.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===$l.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(_l.host(S))),this.restoreHandlers.push(initAdoptedStyleSheetObserver({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},S))},0)}observeAttachShadow(S){S.contentWindow&&__tsSafeContentDoc(S)&&this.patchAttachShadow(S.contentWindow.Element,__tsSafeContentDoc(S))}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=_l.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 Vl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ql="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Gl=0;Gl<64;Gl++)Ql[Vl.charCodeAt(Gl)]=Gl;const Kl=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=Kl.get(S);return I||(I=new Map,Kl.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+=Vl[I[b]>>2],R+=Vl[(3&I[b])<<4|I[b+1]>>4],R+=Vl[(15&I[b+1])<<2|I[b+2]>>6],R+=Vl[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 Jl="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Xl="undefined"!=typeof window&&window.Blob&&new Blob([(Yl=Jl,Uint8Array.from(atob(Yl),S=>S.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});var Yl;function WorkerWrapper(S){let b;try{if(b=Xl&&(window.URL||window.webkitURL).createObjectURL(Xl),!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,"+Jl,{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:zl["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:zl["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:zl["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,zl.WebGL,S,I,x,b)),void 0!==b.WebGL2RenderingContext&&R.push(...patchGLPrototype(b.WebGL2RenderingContext.prototype,zl.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,ec,tc,sc=!1;try{if(2!==Array.from([1],S=>2*S)[0]){const S=document.createElement("iframe");document.body.appendChild(S),Array.from=(null==(at=S.contentWindow)?void 0:at.Array.from)||Array.from,document.body.removeChild(S)}}catch(err){console.debug("Unable to override Array.from",err)}const rc=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){jl=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),rc.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=Fl(),!(null==(A=ql[0])?void 0:A.isFrozen())||_.type===Nl.FullSnapshot||_.type===Nl.IncrementalSnapshot&&_.data.source===Ll.Mutation||ql.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.__TS_IFRAME_BRIDGE&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom(S)}if(_.type===Nl.FullSnapshot)fe=_,me=0;else if(_.type===Nl.IncrementalSnapshot){if(_.data.source===Ll.Mutation&&_.data.isAttachIframe)return;me++;const S=x&&me>=x,b=I&&_.timestamp-fe.timestamp>I;(S||b)&&ec(!0)}};const wrappedMutationEmit=S=>{Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Mutation,...S}})},wrappedScrollEmit=S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Scroll,...S}}),wrappedCanvasMutationEmit=S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.CanvasMutation,...S}}),ye=new StylesheetManager({mutationCb:wrappedMutationEmit,adoptedStyleSheetCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.AdoptedStyleSheet,...S}})}),ve=new IframeManager({mirror:rc,mutationCb:wrappedMutationEmit,stylesheetManager:ye,recordCrossOriginIframes:se,wrappedEmit:Zl});for(const S of ae||[])S.getMirror&&S.getMirror({nodeMirror:rc,crossOriginIframeMirror:ve.crossOriginIframeMirror,crossOriginIframeStyleMirror:ve.crossOriginIframeStyleMirror});const Se=new ProcessedNodeManager;tc=new CanvasManager({recordCanvas:te,mutationCb:wrappedCanvasMutationEmit,win:window,blockClass:R,blockSelector:A,mirror:rc,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:tc,keepIframeSrcFn:le,processedNodeManager:Se},mirror:rc});ec=(S=!1)=>{if(!ee)return;Zl({type:Nl.Meta,data:{href:window.location.href,width:getWindowWidth(),height:getWindowHeight()}},S),ye.reset(),we.init(),ql.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:rc,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,rc)&&ve.addIframe(S),isSerializedStylesheet(S,rc)&&ye.trackLinkElement(S),hasShadowRoot(S)&&we.addShadowRoot(_l.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:Nl.FullSnapshot,data:{node:b,initialOffset:getWindowScroll(window)}},S),ql.forEach(S=>S.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ye.adoptStyleSheets(document.adoptedStyleSheets,rc.getId(document))};try{const S=[],observe=S=>{var b;return callbackWrapper(initObservers)({mutationCb:wrappedMutationEmit,mousemoveCb:(S,b)=>Zl({type:Nl.IncrementalSnapshot,data:{source:b,positions:S}}),mouseInteractionCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.MouseInteraction,...S}}),scrollCb:wrappedScrollEmit,viewportResizeCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.ViewportResize,...S}}),inputCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Input,...S}}),mediaInteractionCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.MediaInteraction,...S}}),styleSheetRuleCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.StyleSheetRule,...S}}),styleDeclarationCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.StyleDeclaration,...S}}),canvasMutationCb:wrappedCanvasMutationEmit,fontCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Font,...S}}),selectionCb:S=>{Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Selection,...S}})},customElementCb:S=>{Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.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:rc,iframeManager:ve,stylesheetManager:ye,shadowDomManager:we,processedNodeManager:Se,canvasManager:tc,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:Nl.Plugin,data:{plugin:S.name,payload:b}})})))||[]},Q)};ve.addLoadListener(b=>{try{S.push(observe(__tsSafeContentDoc(b)))}catch(S){console.warn(S)}});const init=()=>{ec(),S.push(observe(document)),sc=!0};return"interactive"===document.readyState||"complete"===document.readyState?init():(S.push(on("DOMContentLoaded",()=>{Zl({type:Nl.DomContentLoaded,data:{}}),"DOMContentLoaded"===re&&init()})),S.push(on("load",()=>{Zl({type:Nl.Load,data:{}}),"load"===re&&init()},window))),()=>{S.forEach(S=>S()),Se.destroy(),sc=!1,function unregisterErrorHandler(){jl=void 0}()}}catch(S){console.warn(S)}}var nc,ic;record.addCustomEvent=(S,b)=>{if(!sc)throw new Error("please add custom event after start recording");Zl({type:Nl.Custom,data:{tag:S,payload:b}})},record.freezePage=()=>{ql.forEach(S=>S.freeze())},record.takeFullSnapshot=S=>{if(!sc)throw new Error("please take full snapshot after start recording");ec(S)},record.mirror=rc,(ic=nc||(nc={}))[ic.NotStarted=0]="NotStarted",ic[ic.Running=1]="Running",ic[ic.Stopped=2]="Stopped";const oc=createLogger("RRWeb-Loader");let ac=null,cc=null;try{record?(ac=record,cc={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;"),oc.log("rrweb record() statically imported and ready")):console.error("[TraceScout] ❌ rrweb record import found but not a function")}catch($){console.error("[TraceScout] ❌ Static rrweb record import failed:",$.message),oc.warn("Static rrweb record import failed:",$.message)}async function loadRRWeb(){if(!cc||!cc.record)throw new Error("rrweb record not available - bundling failed");return cc}function getRRWeb(){return cc}function getRecord(){return ac}function isRRWebLoaded(){return!!cc}function getRRWebSource(){return{isBundled:!0,source:"bundled",details:"@rrweb/record bundled with SDK",isRecordOnly:!0}}var uc=Uint8Array,hc=Uint16Array,dc=Int32Array,gc=new uc([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]),pc=new uc([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]),fc=new uc([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 hc(31),x=0;x<31;++x)I[x]=b+=1<<S[x-1];var R=new dc(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}},mc=freb(gc,2),yc=mc.b,vc=mc.r;yc[28]=258,vc[258]=28;for(var Sc=freb(pc,0),wc=Sc.b,bc=Sc.r,Cc=new hc(32768),kc=0;kc<32768;++kc){var Ic=(43690&kc)>>1|(21845&kc)<<1;Ic=(61680&(Ic=(52428&Ic)>>2|(13107&Ic)<<2))>>4|(3855&Ic)<<4,Cc[kc]=((65280&Ic)>>8|(255&Ic)<<8)>>1}var hMap=function(S,b,I){for(var x=S.length,R=0,A=new hc(b);R<x;++R)S[R]&&++A[S[R]-1];var _,D=new hc(b);for(R=1;R<b;++R)D[R]=D[R-1]+A[R-1]<<1;if(I){_=new hc(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 hc(x),R=0;R<x;++R)S[R]&&(_[R]=Cc[D[S[R]-1]++]>>15-S[R]);return _},Ec=new uc(288);for(kc=0;kc<144;++kc)Ec[kc]=8;for(kc=144;kc<256;++kc)Ec[kc]=9;for(kc=256;kc<280;++kc)Ec[kc]=7;for(kc=280;kc<288;++kc)Ec[kc]=8;var xc=new uc(32);for(kc=0;kc<32;++kc)xc[kc]=5;var Mc=hMap(Ec,9,0),Rc=hMap(Ec,9,1),Tc=hMap(xc,5,0),Ac=hMap(xc,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 uc(S.subarray(b,I))},_c=["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||_c[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:Dc,l:0};if(1==R){var _=new uc(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 hc(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 uc(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 hc(++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 hc(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[fc[ae-1]];--ae);var le,ce,ue,he,de=B+5<<3,ge=clen(R,Ec)+clen(A,xc)+_,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[fc[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=Mc,ce=Ec,ue=Tc,he=xc;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+=gc[Se]);var be=31&we;wbits16(b,U,ue[be]),U+=he[be],be>3&&(wbits16(b,U,we>>5&8191),U+=pc[be])}else wbits16(b,U,le[we]),U+=ce[we]}return wbits16(b,U,le[256]),U+ce[256]},Oc=new dc([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Dc=new uc(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 uc(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 uc(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 $=Oc[b-1],j=$>>13,W=8191&$,H=(1<<I)-1,V=A.p||new hc(32768),Q=A.h||new hc(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 dc(25e3),Y=new hc(288),ee=new hc(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|vc[de]<<18|bc[ge];var Ie=31&vc[de],Ee=31&bc[ge];se+=gc[Ie]+pc[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 uc(0);var _=!I,D=_||2!=b.i,L=b.i;_&&(I=new uc(3*R));var cbuf=function(S){var b=I.length;if(S>b){var x=new uc(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=Rc,W=Ac,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 uc(te),re=new uc(19),ne=0;ne<ee;++ne)re[fc[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=gc[ne=ye-257];ve=bits(S,U,(1<<Se)-1)+yc[ne],U+=Se}var we=W[bits16(S,U)&fe],be=we>>4;if(we||err(3),U+=15&we,ge=wc[be],be>3&&(Se=pc[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 Fc="undefined"!=typeof TextEncoder&&new TextEncoder,Nc="undefined"!=typeof TextDecoder&&new TextDecoder;try{Nc.decode(Dc,{stream:!0})}catch($){}function strToU8(S,b){if(b){for(var I=new uc(S.length),x=0;x<S.length;++x)I[x]=S.charCodeAt(x);return I}if(Fc)return Fc.encode(S);var R=S.length,A=new uc(S.length+(S.length>>1)),_=0,w=function(S){A[_++]=S};for(x=0;x<R;++x){if(_+5>A.length){var D=new uc(_+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(Nc)return Nc.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 Lc=["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 Lc)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||[]}const Pc=4;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 Bc={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 Bc[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 $c});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 zc={MINIMAL:"minimal",STANDARD:"standard",DETAILED:"detailed",FULL:"full"},Uc="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(Uc)){const S=b.createObjectStore(Uc,{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([Uc],"readwrite"),x=I.objectStore(Uc),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([Uc],"readonly"),I=b.objectStore(Uc).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([Uc],"readonly").objectStore(Uc),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([Uc],"readwrite"),x=I.objectStore(Uc).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([Uc],"readwrite").objectStore(Uc),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([Uc],"readwrite"),I=b.objectStore(Uc).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([Uc],"readonly"),I=b.objectStore(Uc).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 $c=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 jc=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:zc,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=ot,ot.setTransport=TraceScoutMonitoringCore.setTransport.bind(TraceScoutMonitoringCore));export{Ge as BODY_REDACTED_VALUE,BaseInterceptor,BeaconSender,Pc as CHUNK_FORMAT_VERSION,B as CORE_WEB_VITALS_DEFAULTS,CheckpointManager,ChunkManager,ChunkedCompressedStorage,CircuitBreaker,ConfigManager,ConsoleInterceptor,CoreWebVitalsMonitor,A as DEFAULT_CONFIG,L as DEFAULT_FIELD_PATTERNS,Ke as DEFAULT_MAX_BODY_BYTES,Qe as DEFAULT_MAX_BODY_SIZE,Xe as DEFAULT_SENSITIVE_FIELDS,D as EVENT_TYPES,ErrorFingerprint,ErrorHandler,EventManager,EventOptimizer,FetchInterceptor,InactivityManager,IndexedDBQueue,R as LOCAL_STORAGE_KEYS,LogBuffer,LogManager,Logger,LoggingManager,Je as MAX_BODY_BYTES_CEILING,NetworkMonitor,PageLifecycleManager,ge as PerformanceMonitor,PerformanceResourceObserver,PostMessageInterceptor,QueueMemoryManager,qe as REDACTED_VALUE,_ as REPORTER_LOG_PREFIX,We as RESOURCE_EXTENSIONS,Recorder,RecorderMemoryManager,zc as RecorderPresets,RemoteConfigService,ResourceInterceptor,SDKContext,je as SENSITIVE_HEADERS,Ze as SENSITIVE_QUERY_PARAMS,ServiceLogger,ServiceManager,SessionManager,SessionStorage,TraceScoutMonitoringCore,UploadQueue,UserProfileManager,XHRInterceptor,analyzeSnapshotsInEvents,buildFieldDenylist,buildSnapshotIndex,captureRequestBody,captureResponseBody,chunkHasSnapshot,classifyMime,collectDeviceMetadata,createChunk,createLogger,createSensitiveHeaderSet,debounce,deepClone,ot as default,detectDeviceType,detectTouchCapability,extractConsoleRef,extractNetworkFull,extractNetworkRef,extractRequestDetails,extractResourceRef,filterSensitiveHeaders,findNearestSnapshotBefore,generateConsoleId,generateId,generateNetworkId,generateResourceId,getConnectionInfo,getEventsAfterSnapshot,getMemoryInfo,getRRWeb,getRRWebSource,getRecord,getResourceType,getSensitiveHeadersList,getSnapshotTimestamps,handleRequestBody,handleResponseBody,hashCode,initializeErrorHandler,isApiEndpoint,isCompatibleVersion,isRRWebLoaded,isResourceUrl,isSensitiveField,isSensitiveHeader,isStaticResource,isTextualContentType,loadRRWeb,U as loggingManager,ot as monitoringCore,parseBrowserInfo,parseFormData,parseOSInfo,parseRequestUrl,parseUrl,redactFormUrlEncoded,redactObject,safeJsonParse,safeJsonStringify,safeMime,safeParseConsoleArgs,b as safeSessionStorage,S as safeStorage,safeStringify,splitSanitizedUrl,stripNetworkPayload,throttle$1 as throttle,truncateToBytes,I as typeUtils,utf8Bytes,x as utils,validateDomains,validateEndpoints,validateService};
|
|
1
|
+
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 S={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)}},b={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}}},I={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 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}}function safeJsonParse(S,b=null){try{return JSON.parse(S)}catch(S){return b}}function safeJsonStringify(S,b="{}"){try{return JSON.stringify(S)}catch(S){return 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 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))},x={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=>x.cloneDeep(S));if("object"==typeof S){const b={};for(const I in S)S.hasOwnProperty(I)&&(b[I]=x.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)&&(x.isObject(S[b])&&x.isObject(I[b])?I[b]=x.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),R=Object.keys(b);if(I.length!==R.length)return!1;for(const A of I){if(!R.includes(A))return!1;if(!x.isEqual(S[A],b[A]))return!1}return!0}},R={EVENTS:"__api_reporter_events__",USER_PROFILE:"__api_reporter_user_profile__"},A={RETRY_INTERVAL_MS:3e4,DEDUPLICATION_WINDOW_MS:6e4,MAX_QUEUE_SIZE:1e3,MAX_RETRIES:3,BATCH_SIZE:10,DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS:[]},_="[TraceScoutMonitoringCore]",D={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"},L={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},B={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"};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 U=new LoggingManager;function createLogger(S){return U.createLogger(S)}class Logger{constructor(S="",b=!1){this.serviceName=S.replace(/^\[|\]$/g,""),this.serviceLogger=U.createLogger(this.serviceName),b&&U.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=x.merge({},this.defaultConfig,S,{debug:"boolean"==typeof x.get(S,"debug")?x.get(S,"debug"):Boolean(x.get(S,"debug")),retryIntervalMs:Math.max(1e3,x.get(S,"retryIntervalMs",this.defaultConfig.retryIntervalMs)),deduplicationWindowMs:Math.max(100,x.get(S,"deduplicationWindowMs",this.defaultConfig.deduplicationWindowMs)),maxQueueSize:Math.max(10,x.get(S,"maxQueueSize",this.defaultConfig.maxQueueSize)),maxRetries:Math.max(1,Math.min(10,x.get(S,"maxRetries",this.defaultConfig.maxRetries))),batchSize:Math.max(1,Math.min(100,x.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 x.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 $,j,W,H,V,Q=-1,o=function(S){addEventListener("pageshow",function(b){b.persisted&&(Q=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 Q>=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)}},G=-1,h=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},g=function(S){"hidden"===document.visibilityState&&G>-1&&(G="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 G<0&&(G=h(),y(),o(function(){setTimeout(function(){G=h(),y()},0)})),{get firstHiddenTime(){return G}}},C=function(S){document.prerendering?addEventListener("prerenderingchange",function(){return S()},!0):S()},J=[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,J,b.reportAllChanges),o(function(x){R=f("FCP"),I=d(S,R,J,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,I(!0)})}))})},X=[.1,.25],Y={passive:!0,capture:!0},ee=new Date,P=function(S,b){$||($=b,j=S,W=new Date,k(removeEventListener),F())},F=function(){if(j>=0&&j<W-ee){var S={entryType:"first-input",name:$.type,target:$.target,cancelable:$.cancelable,startTime:$.timeStamp,processingStart:$.timeStamp+j};H.forEach(function(b){b(S)}),H=[]}},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,Y),removeEventListener("pointercancel",i,Y)};addEventListener("pointerup",t,Y),addEventListener("pointercancel",i,Y)}(b,S):P(b,S)}},k=function(S){["mousedown","keydown","touchstart","pointerdown"].forEach(function(b){return S(b,M,Y)})},te=[100,300],se=0,re=1/0,ne=0,N=function(S){S.forEach(function(S){S.interactionId&&(re=Math.min(re,S.interactionId),ne=Math.max(ne,S.interactionId),se=ne?(ne-re)/7+1:0)})},O=function(){return V?se:performance.interactionCount||0},q=function(){"interactionCount"in performance||V||(V=s("event",N,{type:"event",buffered:!0,durationThreshold:0}))},ie=[200,500],oe=0,z=function(){return O()-oe},ae=[],le={},K=function(S){var b=ae[ae.length-1],I=le[S.interactionId];if(I||ae.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]};le[x.id]=x,ae.push(x)}ae.sort(function(S,b){return b.latency-S.latency}),ae.splice(10).forEach(function(S){delete le[S.id]})}},ce=[2500,4e3],ue={},he=[800,1800],de=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,he,b.reportAllChanges);de(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,he,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,ce,b.reportAllChanges);var _=v(function(){ue[R.id]||(a(A.takeRecords()),A.disconnect(),ue[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,ce,b.reportAllChanges),l(function(){R.value=performance.now()-x.timeStamp,ue[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,te,b.reportAllChanges),A&&p(v(function(){m(A.takeRecords()),A.disconnect()})),A&&o(function(){var x;R=f("FID"),I=d(S,R,te,b.reportAllChanges),H=[],j=-1,$=null,k(addEventListener),x=l,H.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,X,b.reportAllChanges),p(function(){c(_.takeRecords()),I(!0)}),o(function(){R=0,x=f("CLS",0),I=d(S,x,X,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&&!ae.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(ae.length-1,Math.floor(z()/50)),ae[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,ie,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(){ae=[],oe=O(),R=f("INP"),x=d(S,R,ie,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}}let ge=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)}`}};const pe="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+=pe[b[S]>>4]+pe[15&b[S]];return I.slice(0,S)}let b="";for(let I=0;I<S;I++)b+=pe[Math.floor(16*Math.random())];return b}(12)}`}const fe=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.topFrameIdentity=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.7.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,domPrivacy:this.domPrivacy||void 0,url:window.location.href,referrer:document.referrer,title:document.title}}}recordError(){this.errorCount++}setDomPrivacy(S){"string"==typeof S&&fe.has(S)&&(this.domPrivacy=S)}setTopFrameIdentity(S){this.topFrameIdentity=S&&"object"==typeof S?S:null}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,R={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,dist:S.dist??null,debugId:S.debugId??null,sourceName:S.sourceName??null,url:"undefined"!=typeof window?window.location.href:null,pageviewId:x},A=this.topFrameIdentity;return A&&"object"==typeof A&&("string"==typeof A.frameId&&A.frameId&&(R.frameId=A.frameId),"string"==typeof A.topFrameId&&A.topFrameId&&(R.topFrameId=A.topFrameId),"string"==typeof A.frameInstanceId&&A.frameInstanceId&&(R.frameInstanceId=A.frameInstanceId),R.frameDepth=0,R.captureRealm="top","string"==typeof A.frameOrigin&&A.frameOrigin&&(R.frameOrigin=A.frameOrigin),"string"==typeof A.frameUrl&&A.frameUrl&&(R.frameUrl=A.frameUrl),"string"==typeof A.frameLifecycle&&A.frameLifecycle&&(R.frameLifecycle=A.frameLifecycle),"string"==typeof A.privacyStatus&&A.privacyStatus&&(R.privacyStatus=A.privacyStatus)),R}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 me={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||me.CHANNEL_NAME,this.heartbeatInterval=S.heartbeatInterval||me.HEARTBEAT_INTERVAL,this.tabTimeout=S.tabTimeout||me.TAB_TIMEOUT,this.awayThreshold=S.awayThreshold||me.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 ye="__ts_aid";let ve=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(ye);return S||ve}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}(ye,b,63072e3)||(ve=b),b}const Se={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||Se.INACTIVITY_TIMEOUT,this.maxSessionDuration=S.maxSessionDuration||Se.MAX_SESSION_DURATION,this.activityThrottle=S.activityThrottle||Se.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 x.sortBy(x.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=x.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 b={events:this.eventQueue,timestamp:Date.now()};S.set(this.storageKeys.EVENTS||"__api_reporter_events__",b)}catch(S){this.logger.error("Failed to save events to local storage:",S)}}loadFromLocal(){try{const b=S.get(this.storageKeys.EVENTS||"__api_reporter_events__");b&&b.events&&(this.eventQueue=b.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{S.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=x.get(S,"maxRetries",3),this.initializeService()}initializeService(){if(!x.get(this.config,"service"))throw new Error("Service configuration is required");this.setService(x.get(this.config,"service"),x.get(this.config,"serviceOptions",{}))}setService(S,b={}){if(!x.isObject(S)||!x.isFunction(x.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||x.isEmpty(S)||!this.service)return this.logger.warn("Cannot send events:",{isSending:this.isSending,isEmpty:x.isEmpty(S),noService:!this.service}),x.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++,x.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 x.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(!x.isObject(S))return this.logger.warn("Invalid profile object provided"),!1;try{const b=this.getProfile(),I=x.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(x.isEmpty(x.get(S,"uniqId"))){const b=x.merge(S,{uniqId:generateId(),createdAt:(new Date).toISOString()});this.setProfile(b),this.logger.log("Generated new user profile:",x.get(b,"uniqId"))}}catch(S){this.logger.error("Failed to ensure user profile:",S)}}extractContextFromData({data:S,source:b="response",url:I=""}){const R={};try{if(!x.isObject(S)||!x.isArray(this.fieldsToExtract))return R;const A=x.toLower(I);return this.fieldsToExtract.forEach(_=>{try{const D=x.toLower(x.get(_,"api","")),L=x.get(_,"source",""),B="*"===D||A.includes(D);if(!B||!("*"===L||L===b))return;const U=x.get(_,"fields",[]);x.isArray(U)?U.forEach(x=>{try{this.recursiveFieldMatch({context:R,matchRule:x,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with pattern "${x}":`,S)}}):x.isObject(U)&&x.entries(U).forEach(([x,A])=>{try{this.recursiveFieldMatchWithMapping({context:R,newKey:x,matchRule:A,data:S,source:b,url:I})}catch(S){this.logger.warn(`Failed to extract field with mapping "${x}": "${A}":`,S)}})}catch(S){this.logger.warn("Failed to process extraction rule:",S)}}),R}catch(S){return this.logger.error("Failed to extract context from data:",S),R}}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:R,url:A}){try{if(!x.isObject(I))return;if(x.isString(b)){const R=x.get(I,b);if(void 0!==R)return S[b]=R,void this.logger.log(`Found field by path: ${b} = ${JSON.stringify(R)}`);const A=x.find(x.entries(I),([S])=>x.toLower(S)===x.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 R=x.find(x.entries(I),([S,I])=>x.isString(I)&&b.test(I));if(R){const[b,I]=R;return S[b]=I,void this.logger.log(`Found field by value pattern: ${b} = ${I}`)}}x.values(I).forEach(I=>{x.isObject(I)&&!x.isNull(I)&&this.recursiveFieldMatch({context:S,matchRule:b,data:I,source:R,url:A})})}catch(S){this.logger.warn("Error in recursive field matching:",S)}}recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:R,source:A,url:_}){try{if(!x.isObject(R))return;if(x.isString(I)){const A=x.get(R,I);if(void 0!==A)return S[b]=A,void this.logger.log(`Found field with mapping: ${I} -> ${b} = ${JSON.stringify(A)}`);const _=x.find(x.entries(R),([S])=>x.toLower(S)===x.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=x.find(x.entries(R),([S,b])=>x.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}`)}}x.values(R).forEach(R=>{x.isObject(R)&&!x.isNull(R)&&this.recursiveFieldMatchWithMapping({context:S,newKey:b,matchRule:I,data:R,source:A,url:_})})}catch(S){this.logger.warn("Error in recursive field matching with mapping:",S)}}validateFieldValue(S,b){try{if(x.isString(b)){const I=x.get(DEFAULT_FIELD_PATTERNS,b);return I&&I.test(S)}if(x.isFunction(b))return b(S);if(x.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(x.isFunction(b))return b(S);if(x.isString(b))switch(b){case"toLowerCase":return x.toLower(S);case"toUpperCase":return x.toUpper(S);case"trim":return x.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 x.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!x.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 we=["/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 we)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(!x.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,dist:b.dist,debugId:b.debugId,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 be={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)."},dist:{type:"string",minLength:1,maxLength:64,description:"B2 source maps: optional build variant (e.g. 'web', 'ios-webview'). Emitted on every v1 envelope as `dist`; used with `release` to match uploaded source-map artifacts."},debugId:{type:"string",minLength:8,maxLength:64,pattern:"^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$",description:"B2 source maps: optional build-pinned debug ID (hex/UUID form). Strongest source-map match identity. May also be supplied by an injected build-time global (globalThis.__TRACESCOUT_DEBUG_ID__) read synchronously at init — never fetched over the network."}};const Ce=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ke=new Set(["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody","maxBodyBytes","excludeEndpoints","requestSanitizer","responseSanitizer","sensitiveFields"]),Ie=["isEnabled","captureRequestHeaders","captureResponseHeaders","captureRequestBody","captureResponseBody"];const Ee=/^([a-z0-9]|[a-z0-9][a-z0-9._-]{0,98}[a-z0-9])$/,xe=new Set(Object.keys(be));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(!Ce.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&&"iframe"!==S&&(xe.has(S)||x.push(S));if(x.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:x};if(void 0!==I.debugId){const S=/^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$/;if("string"!=typeof I.debugId||!S.test(I.debugId))return{ok:!1,code:"CONFIG_INVALID_DEBUG_ID",keys:["debugId"]}}if(void 0!==I.dist&&("string"!=typeof I.dist||I.dist.length<1||I.dist.length>64))return{ok:!1,code:"CONFIG_INVALID_DIST",keys:["dist"]};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))ke.has(I)||b.push(`network.${I}`);if(b.length>0)return{ok:!1,code:"CONFIG_UNKNOWN_KEYS",keys:b};for(const b of Ie)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||!Ee.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 Me="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ulid(S=Date.now()){return function encodeTimestamp(S){let b="",I=S;for(let S=9;S>=0;S--)b=Me[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+=Me[x>>R&31];return S}()}const Re=Object.freeze(["session_start","session_end","replay_chunk","page_view","route_change","network_request","console_event","js_error","performance_metric","custom_event","user_identified"]),Te=new Set(Re);function wrapInEnvelope(S,b,I){if(!Te.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.dist)&&(x.dist=I.dist),isNonEmptyString$3(I.debugId)&&(x.debugId=I.debugId),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),isNonEmptyString$3(I.frameId)&&(x.frameId=I.frameId),isNonEmptyString$3(I.parentFrameId)&&(x.parentFrameId=I.parentFrameId),isNonEmptyString$3(I.topFrameId)&&(x.topFrameId=I.topFrameId),isNonEmptyString$3(I.frameInstanceId)&&(x.frameInstanceId=I.frameInstanceId),isNonNegativeInt(I.frameDepth)&&(x.frameDepth=I.frameDepth),isNonEmptyString$3(I.frameOrigin)&&(x.frameOrigin=I.frameOrigin),isNonEmptyString$3(I.frameUrl)&&(x.frameUrl=I.frameUrl),isNonEmptyString$3(I.frameLifecycle)&&(x.frameLifecycle=I.frameLifecycle),isNonEmptyString$3(I.captureRealm)&&(x.captureRealm=I.captureRealm),isNonEmptyString$3(I.privacyStatus)&&(x.privacyStatus=I.privacyStatus),isNonNegativeInt(I.bridgeProtocolVersion)&&(x.bridgeProtocolVersion=I.bridgeProtocolVersion),isNonNegativeInt(I.localSequence)&&(x.localSequence=I.localSequence),Number.isFinite(I.tsLocal)&&(x.tsLocal=I.tsLocal),Number.isFinite(I.tsNormalized)&&(x.tsNormalized=I.tsNormalized),Number.isFinite(I.clockOffsetMs)&&(x.clockOffsetMs=I.clockOffsetMs),Number.isFinite(I.clockUncertaintyMs)&&(x.clockUncertaintyMs=I.clockUncertaintyMs),{...x,...b}}function isNonEmptyString$3(S){return"string"==typeof S&&S.length>0}function isNonNegativeInt(S){return Number.isInteger(S)&&S>=0}const Ae=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/i;function normalizeOrigin(S){if("string"!=typeof S)return null;const b=S.trim();if(!b||"*"===b||"null"===b)return null;if(!Ae.test(b))return null;if(/^http:\/\//i.test(b)&&!function isLocalhostOrigin(S){return/^https?:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/i.test(S)}(b))return null;try{const S=new URL(b);return S.pathname&&"/"!==S.pathname||(S.search||S.hash)?null:(S.protocol+"//"+S.host).toLowerCase()}catch(S){return null}}function parseIframeConfig(S){const disabled=S=>({enabled:!1,role:null,parentOrigin:null,childOrigins:[],reason:S});if(null==S)return disabled("absent");if("object"!=typeof S||Array.isArray(S))return disabled("not_an_object");if(!0!==S.merge)return disabled("merge_not_enabled");const b="childOrigins"in S&&void 0!==S.childOrigins,I="parentOrigin"in S&&void 0!==S.parentOrigin;if(!b&&!I)return disabled("no_origins_declared");let x=[];if(b){const b=function normalizeChildOrigins(S){if(!Array.isArray(S))return null;const b=[],I=new Set;for(const x of S){const S=normalizeOrigin(x);if(!S)return null;I.has(S)||(I.add(S),b.push(S))}return b.length>0?b:null}(S.childOrigins);if(!b)return disabled("invalid_child_origins");x=b}let R=null;if(I){const b=normalizeOrigin(S.parentOrigin);if(!b)return disabled("invalid_parent_origin");R=b}let A=null;if(x.length>0&&R)A="both";else if(x.length>0)A="parent";else{if(!R)return disabled("no_origins_declared");A="child"}return{enabled:!0,role:A,parentOrigin:R,childOrigins:x,reason:null}}const _e="undefined"!=typeof TextEncoder?new TextEncoder:null;function getSubtle(){const S="undefined"!=typeof globalThis?globalThis.crypto:void 0;return S&&S.subtle?S.subtle:null}function hex(S){return Array.from(new Uint8Array(S)).map(S=>S.toString(16).padStart(2,"0")).join("")}function fromHex(S){const b=new Uint8Array(S.length/2);for(let I=0;I<b.length;I++)b[I]=parseInt(S.substr(2*I,2),16);return b}async function sha256Hex(S){const b=getSubtle();return hex(await b.digest("SHA-256",_e.encode(S)))}async function hmacHex(S,b){const I=getSubtle();return hex(await I.sign("HMAC",S,_e.encode(b)))}function macInput(S){return[S.v,S.frameId,S.frameInstanceId,S.navigationGeneration,S.counter,S.projectId,S.sessionId,S.payloadType,S.payloadHash].join("|")}function safeEq(S,b){if("string"!=typeof S||"string"!=typeof b||S.length!==b.length)return!1;let I=0;for(let x=0;x<S.length;x++)I|=S.charCodeAt(x)^b.charCodeAt(x);return 0===I}const Oe=new Set(["rrweb-dom","telemetry"]);const De={PROTOCOL_VERSION:1,ALLOWED_PAYLOAD_TYPES:Oe,hex:hex,fromHex:fromHex,sha256Hex:sha256Hex,randHex:function randHex(S){const b=new Uint8Array(S);return globalThis.crypto.getRandomValues(b),hex(b)},importKey:async function importKey(S){return getSubtle().importKey("raw",fromHex(S),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])},hmacHex:hmacHex,macInput:macInput,safeEq:safeEq,sealData:async function sealData(S,b,I){const x=void 0===I.payload?"":JSON.stringify(I.payload),R=await sha256Hex(x),A={v:1,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:I.payloadType,payloadHash:R},_=await hmacHex(S,macInput(A));return{v:1,kind:"data",frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:I.counter,payloadType:I.payloadType,tag:I.tag,tsLocal:I.tsLocal,tsNormalized:I.tsNormalized,payloadHash:R,hmac:_,payload:I.payload}},validateData:async function validateData(S,b){try{if(!b||b.closed)return{ok:!1,reason:"stale_port"};if(!b.admitted||!b.key)return{ok:!1,reason:"not_admitted"};if(!S||"data"!==S.kind||"number"!=typeof S.counter||"string"!=typeof S.hmac||"string"!=typeof S.payloadHash)return{ok:!1,reason:"bad_shape"};if(S.v!==b.protocolVersion)return{ok:!1,reason:"protocol_mismatch",fatal:!0};if(!Oe.has(S.payloadType))return{ok:!1,reason:"bad_payload_type"};if(S.frameId!==b.frameId)return{ok:!1,reason:"wrong_frame:"+S.frameId};if(S.frameInstanceId!==b.frameInstanceId)return{ok:!1,reason:"stale_frame_instance"};if(S.navigationGeneration!==b.navigationGeneration)return{ok:!1,reason:"stale_generation"};const I=void 0===S.payload?"":JSON.stringify(S.payload);if(I.length>(b.maxBytes||65536))return{ok:!1,reason:"oversize:"+I.length};if(!safeEq(await sha256Hex(I),S.payloadHash))return{ok:!1,reason:"payload_hash_mismatch"};return safeEq(await hmacHex(b.key,macInput({v:S.v,frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,counter:S.counter,projectId:b.projectId,sessionId:b.sessionId,payloadType:S.payloadType,payloadHash:S.payloadHash})),S.hmac)?S.counter<=b.lastCounter?{ok:!1,reason:"counter_not_monotonic:"+S.counter+"<="+b.lastCounter}:{ok:!0}:{ok:!1,reason:"hmac_mismatch"}}catch(S){return{ok:!1,reason:"validator_error"}}}},Fe=De.PROTOCOL_VERSION,Ne="__TS_IFRAME_BRIDGE",Le="__TS_IFRAME_BRIDGE_PARENT_REGISTER";class BridgeChild{#f;#m;#y;#v;#o;#S;#w=null;#b=null;#C=null;#k=!1;#I=0;#E=null;#x=[];#M=[];#R=!1;#T=0;#A=1/0;#_=new Map;#O={forwarded:0,droppedUnadmitted:0,droppedBackpressure:0,offersRejected:0};constructor({parentOrigin:S,projectId:b,selfWindow:I,parentWindow:x,logger:R,queueCap:A}={}){this.#f=S,this.#m=b,this.#y=I,this.#v=x||I&&I.parent,this.#o=R||null,this.#S=A||1e3}get isAdmitted(){return this.#k}getStats(){return{admitted:this.#k,queued:this.#x.length+this.#M.length,...this.#O}}install(){if(!this.#y)return!1;const S={forwardRrwebDom:S=>this.forwardRrwebDom(S),forwardTelemetry:(S,b)=>this.forwardTelemetry(S,b),isAdmitted:()=>this.#k,__tsRole:"child"};try{Object.defineProperty(this.#y,Ne,{value:S,configurable:!0,enumerable:!1,writable:!0})}catch(b){this.#y[Ne]=S}this.#E=S=>{try{this.#D(S)}catch(S){this.#F("offer handler failed:",S)}};try{this.#y.addEventListener("message",this.#E)}catch(S){this.#F("addEventListener failed:",S)}return!0}#D(S){const b=S&&S.data;if(!b||"offer"!==b.__tsBridge)return;if(S.origin!==this.#f)return this.#O.offersRejected++,this.#F("offer origin mismatch");if(S.source!==this.#v)return this.#O.offersRejected++,this.#F("offer source mismatch");if(b.v!==Fe)return this.#O.offersRejected++,this.#F("offer protocol mismatch");if(this.#m&&b.projectId&&b.projectId!==this.#m)return this.#O.offersRejected++,this.#F("offer project mismatch");const I=S.ports&&S.ports[0];if(!I)return this.#O.offersRejected++,this.#F("offer missing port");this.#N(),this.#b={frameId:b.frameId,frameInstanceId:b.frameInstanceId,navigationGeneration:b.navigationGeneration,projectId:b.projectId,sessionId:b.sessionId},this.#w=I,I.onmessage=S=>{try{this.#L(S.data)}catch(S){this.#F("control handler failed:",S)}};try{I.start&&I.start()}catch(S){}try{I.unref&&I.unref()}catch(S){}try{I.postMessage({c:"hello",v:Fe})}catch(S){this.#F("hello failed:",S)}}async#L(S){if(S&&this.#w)if("secret"!==S.c){if("pong"===S.c){const b=this.#_.get(S.id);if(!b)return;this.#_.delete(S.id);const I=Date.now()-b.sent,x=I/2,R=S.tParent-(b.sent+x);I<this.#A&&(this.#A=I,this.#T=R)}}else{if("string"!=typeof S.secret||!S.secret)return;try{this.#C=await De.importKey(S.secret),this.#k=!0,this.#P(),this.#B()}catch(S){this.#F("secret import failed:",S)}}}#P(){for(let S=0;S<5;S++){const S=De.randHex(8),b=Date.now();this.#_.set(S,{sent:b});try{this.#w.postMessage({c:"ping",id:S,t0:b})}catch(S){}}}forwardRrwebDom(S){return this.#z("rrweb-dom",void 0,S)}forwardTelemetry(S,b){return this.#z("telemetry",S,b)}#z(S,b,I){if(!this.#k)return this.#O.droppedUnadmitted++,!1;const x=function priorityForTag(S,b){return"rrweb-dom"===S?"high":"performance_metric"===b||"network_resource"===b?"low":"high"}(S,b),R=Date.now(),A={payloadType:S,tag:b,payload:I,priority:x,tsLocal:R,tsNormalized:this.#A===1/0?R:R+this.#T};if(this.#x.length+this.#M.length>=this.#S){if("low"===x)return this.#O.droppedBackpressure++,!1;this.#M.length>0?(this.#M.shift(),this.#O.droppedBackpressure++):(this.#x.shift(),this.#O.droppedBackpressure++)}return("low"===x?this.#M:this.#x).push(A),this.#B(),!0}async#B(){if(!this.#R&&this.#k&&this.#w&&this.#C){this.#R=!0;try{for(;this.#x.length||this.#M.length;){const S=this.#x.length?this.#x.shift():this.#M.shift(),b=++this.#I;try{const I=await De.sealData(this.#C,this.#b,{counter:b,payloadType:S.payloadType,tag:S.tag,tsLocal:S.tsLocal,tsNormalized:S.tsNormalized,payload:S.payload});this.#w.postMessage(I),this.#O.forwarded++}catch(S){this.#F("seal/post failed:",S)}}}finally{this.#R=!1}}}#N(){if(this.#w)try{this.#w.close&&this.#w.close()}catch(S){}this.#w=null,this.#C=null,this.#k=!1,this.#I=0,this.#x.length=0,this.#M.length=0,this.#_.clear(),this.#T=0,this.#A=1/0}shutdown(){try{this.#E&&this.#y.removeEventListener("message",this.#E)}catch(S){}this.#N();try{this.#y[Ne]&&"child"===this.#y[Ne].__tsRole&&delete this.#y[Ne]}catch(S){}this.#E=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:child]",...S)}catch(S){}}}class BridgeParent{#U;#m;#$;#j;#o;#S;#q;#W;#H;#V;#Q;#G=new Map;#K=new WeakMap;#J=0;#X=0;#Y=new WeakSet;#Z=null;#ee=null;#te=!1;#O={admitted:0,closed:0,accepted:0,rejected:0,fatal:0};#se=[];constructor({childOrigins:S,projectId:b,sessionId:I,topWindow:x,logger:R,queueCap:A,maxBytes:_,parentFrameId:D,topFrameId:L,feedRrwebDom:B,feedTelemetry:U}={}){this.#U=S instanceof Set?S:new Set(S||[]),this.#m=b,this.#$=I,this.#j=x||("undefined"!=typeof window?window:void 0),this.#o=R||null,this.#S=A||1e3,this.#q=_||65536,this.#W=D||"ts-top",this.#H=L||"ts-top",this.#V="function"==typeof B?B:()=>{},this.#Q="function"==typeof U?U:()=>{}}get isStarted(){return this.#te}getStats(){return{active:this.#G.size,...this.#O}}getRejectLog(){return this.#se.slice()}start(){if(this.#te)return!0;if(!this.#j)return!1;this.#te=!0;try{this.#j[Le]=S=>this.registerRrwebManager(S)}catch(S){}try{this.#re(this.#j.document),this.#ne(this.#j.document)}catch(S){this.#F("start scan failed:",S)}return!0}registerRrwebManager(S){this.#ee=S||null}#re(S){if(!S||"function"!=typeof S.querySelectorAll)return;let b;try{b=S.querySelectorAll("iframe")}catch(S){return}b.forEach(S=>{this.#ie(S),this.#oe(S)})}#ne(S){try{const b=this.#j.MutationObserver;if(!b)return;this.#Z=new b(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation failed:",S)}}),this.#Z.observe(S.documentElement||S,{childList:!0,subtree:!0})}catch(S){this.#F("observe failed:",S)}}#ae(S){if(S&&1===S.nodeType&&("IFRAME"===S.tagName&&(this.#ie(S),this.#oe(S)),S.querySelectorAll))try{S.querySelectorAll("iframe").forEach(S=>{this.#ie(S),this.#oe(S)})}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#K.get(S);if(!b)return;if(S.isConnected)return;const I=this.#G.get(b);I&&this.#ce(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#ie(S){if(!this.#Y.has(S)){this.#Y.add(S);try{S.addEventListener("load",()=>{try{this.#oe(S)}catch(S){this.#F("load re-admit failed:",S)}})}catch(S){}}}#ue(S){let b=null;try{b=S.src||S.getAttribute&&S.getAttribute("src")}catch(S){b=null}if(!b)return null;try{const S=this.#j.location&&this.#j.location.href||void 0,I=new URL(b,S);return(I.protocol+"//"+I.host).toLowerCase()}catch(S){return null}}#he(S){let b=this.#K.get(S);return b||(b="ts-xframe-"+ ++this.#J,this.#K.set(S,b)),b}#oe(S){const b=this.#ue(S);if(!b||!this.#U.has(b))return;let I=null;try{I=S.contentWindow}catch(S){I=null}if(!I)return;const x=this.#he(S),R=++this.#X,A=this.#G.get(x);let _;A&&this.#ce(A,"superseded");try{_=new this.#j.MessageChannel}catch(S){try{_=new MessageChannel}catch(S){return void this.#F("MessageChannel unavailable:",S)}}const D={frameId:x,frameInstanceId:`${x}-g${R}`,navigationGeneration:R,projectId:this.#m,sessionId:this.#$,expectedOrigin:b,sourceWindow:I,protocolVersion:Fe,lastCounter:-1,closed:!1,admitted:!1,key:null,maxBytes:this.#q,port:_.port1,secret:De.randHex(32),nonce:De.randHex(16),el:S};D.port.onmessage=S=>{this.#de(D,S&&S.data)};try{D.port.start&&D.port.start()}catch(S){}try{D.port.unref&&D.port.unref()}catch(S){}this.#G.set(x,D);const L={__tsBridge:"offer",v:Fe,projectId:this.#m,sessionId:this.#$,frameId:x,parentFrameId:this.#W,topFrameId:this.#H,frameInstanceId:D.frameInstanceId,navigationGeneration:R};try{I.postMessage(L,b,[_.port2]),this.#O.admitted++}catch(S){this.#F("offer post failed:",S),this.#ce(D,"offer_failed")}}async#de(S,b){if(b&&!S.closed)if("hello"!==b.c)if("ping"!==b.c){if("data"===b.kind){const I=await De.validateData(b,S);return I.ok?(S.lastCounter=b.counter,this.#O.accepted++,void("rrweb-dom"===b.payloadType?this.#ge(S,b.payload):"telemetry"===b.payloadType&&this.#pe(S,b))):(this.#O.rejected++,this.#fe(S.frameId,I.reason),void(I.fatal&&(this.#O.fatal++,this.#ce(S,"protocol_mismatch"))))}this.#O.rejected++,this.#fe(S.frameId,"unknown_message")}else try{S.port.postMessage({c:"pong",id:b.id,t0:b.t0,tParent:Date.now()})}catch(S){}else try{S.key=await De.importKey(S.secret),S.admitted=!0,S.port.postMessage({c:"secret",secret:S.secret,nonce:S.nonce}),S.secret=null}catch(S){this.#F("secret delivery failed:",S)}}#ge(S,b){try{const I={data:b,origin:S.expectedOrigin,source:S.sourceWindow};this.#ee&&"function"==typeof this.#ee.handleMessage&&this.#ee.handleMessage(I),this.#V(S,b,I)}catch(S){this.#F("deliverDom failed:",S)}}#pe(S,b){try{this.#Q(S,b)}catch(S){this.#F("deliverTelemetry failed:",S)}}#ce(S,b){S.closed=!0;try{S.port&&S.port.close&&S.port.close()}catch(S){}S.port=null,S.key=null,S.sourceWindow=null,S.el=null,this.#G.get(S.frameId)===S&&this.#G.delete(S.frameId),this.#O.closed++}shutdown(){for(const S of Array.from(this.#G.values()))this.#ce(S,"shutdown");this.#G.clear();try{this.#Z&&this.#Z.disconnect()}catch(S){}this.#Z=null;try{this.#j[Le]&&delete this.#j[Le]}catch(S){}this.#ee=null,this.#te=!1}#fe(S,b){this.#se.push({frameId:S,reason:b,t:Date.now()}),this.#se.length>200&&this.#se.shift()}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge:parent]",...S)}catch(S){}}}class CrossOriginIframeBridge{#me;#ye;#m;#$;#o;#j;#ve=null;#Se=null;constructor({config:S,core:b,projectId:I,sessionId:x,logger:R,topWindow:A}={}){this.#me=S,this.#ye=b,this.#m=I,this.#$=x,this.#o=R||null,this.#j=A||("undefined"!=typeof window?window:void 0)}get parent(){return this.#ve}get child(){return this.#Se}get isChildMode(){return!!this.#Se}start(){if(!this.#me||!this.#me.enabled)return!1;const S=this.#me.role;try{return"child"!==S&&"both"!==S||(this.#Se=new BridgeChild({parentOrigin:this.#me.parentOrigin,projectId:this.#m,selfWindow:this.#j,parentWindow:this.#j&&this.#j.parent,logger:this.#o}),this.#Se.install()),"parent"!==S&&"both"!==S||(this.#ve=new BridgeParent({childOrigins:new Set(this.#me.childOrigins),projectId:this.#m,sessionId:this.#$,topWindow:this.#j,logger:this.#o,feedTelemetry:(S,b)=>this.#Q(S,b)}),this.#ve.start()),!0}catch(S){return this.#F("bridge start failed (fail-closed):",S),!1}}#Q(S,b){const I=b.payload&&"object"==typeof b.payload?b.payload:{},x=Object.assign({},I,{frameId:S.frameId,parentFrameId:"ts-top",topFrameId:"ts-top",frameInstanceId:S.frameInstanceId,frameOrigin:S.expectedOrigin,captureRealm:"iframe",privacyStatus:"unknown",bridgeProtocolVersion:Fe,localSequence:b.counter,tsLocal:b.tsLocal,tsNormalized:b.tsNormalized});try{this.#ye&&this.#ye.addSessionCustomEvent(b.tag,x)}catch(S){this.#F("writer feed failed:",S)}}shutdown(){try{this.#Se&&this.#Se.shutdown()}catch(S){}try{this.#ve&&this.#ve.shutdown()}catch(S){}this.#Se=null,this.#ve=null}#F(...S){try{this.#o?.warn&&this.#o.warn("[IframeBridge]",...S)}catch(S){}}}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{#we=!1;#be=!1;#Ce;#ke;#Ie;#Ee;#xe;#Me;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.#ke=S.addCustomEvent,this.#Me=S.getContext,this.#Ie=S.readGuard,this.#Ee=S.writeGuard,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitStart(S={}){if(this.#we)return!1;let b=null;try{b=this.#Ie()}catch(S){b=null}if(b&&!0===b.sessionStartEmitted)return this.#we=!0,!1;b||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const I=this.#Me(),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.#xe("[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.#Ce("session_start",_,I)}catch(S){return this.#xe("[SDK lifecycle] session_start envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_start",B)}catch(S){return this.#xe("[SDK lifecycle] session_start addCustomEvent failed:",S),!1}this.#we=!0;try{this.#Ee({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.#be)return!1;const b=mapInternalEndReason(S.reason);if(!b)return this.#xe("[SDK lifecycle] session_end refused for non-logical reason:",S.reason),!1;let I=null;try{I=this.#Ie()}catch(S){I=null}if(I&&!0===I.sessionEndEmitted)return this.#be=!0,!1;I||this.#xe("[SDK lifecycle] persisted guard unavailable — falling back to in-memory dedup only");const x=this.#Me(),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.#Ce("session_end",_,x)}catch(S){return this.#xe("[SDK lifecycle] session_end envelope wrap failed:",S),!1}try{this.#ke("tracescout.session_end",D)}catch(S){return this.#xe("[SDK lifecycle] session_end addCustomEvent failed:",S),!1}this.#be=!0;try{this.#Ee({sessionEndEmitted:!0,endedAt:R,endReason:b})}catch(S){}return!0}get startEmitted(){return this.#we}get endEmitted(){return this.#be}}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{#Re;#Te=!1;#Ae=null;#ke;#_e;#Ce;#xe;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.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{},this.#Re=uuidv4()}getCurrentPageviewId(){return this.#Re}emitInitialPageView(S={}){if(this.#Te)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.#xe("[SDK pageview] initial page_view skipped — url unavailable"),!1;const R=urlParts(x);if(!isNonEmptyString$1(R.path))return this.#xe("[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.#Oe(this.#Re);let D;try{D=this.#Ce("page_view",A,_)}catch(S){return this.#xe("[SDK pageview] initial page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",D)}catch(S){return this.#xe("[SDK pageview] initial page_view addCustomEvent failed:",S),!1}return this.#Te=!0,this.#Ae=x,!0}recordNavigation(S,b,I){if(!isNonEmptyString$1(I))return this.#xe("[SDK pageview] navigation skipped — toUrl unavailable"),!1;if(null!==this.#Ae&&this.#Ae===I)return!1;if(!["pushState","replaceState","popstate","hashchange"].includes(S))return this.#xe("[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.#xe("[SDK pageview] navigation skipped — could not derive toPath"),!1;const _=this.#Re,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.#Ce("route_change",L,this.#Oe(_))}catch(S){return this.#xe("[SDK pageview] route_change envelope wrap failed:",S),!1}try{this.#ke("tracescout.route_change",B)}catch(S){return this.#xe("[SDK pageview] route_change addCustomEvent failed:",S),!1}this.#Re=D,this.#Ae=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.#Ce("page_view",$,this.#Oe(D))}catch(S){return this.#xe("[SDK pageview] post-nav page_view envelope wrap failed:",S),!1}try{this.#ke("tracescout.page_view",j)}catch(S){return this.#xe("[SDK pageview] post-nav page_view addCustomEvent failed:",S),!1}return!0}#Oe(S){const b=this.#_e()||{};return Object.assign({},b,{pageviewId:S})}get initialEmitted(){return this.#Te}get lastUrl(){return this.#Ae}}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 Pe=new Set(["navigate","reload","back-forward","prerender","back-forward-cache","restore"]);function isNonEmptyString(S){return"string"==typeof S&&S.length>0}class WebVitalsEmitter{#De;#Fe;#Ne=new Set;#ke;#_e;#Ce;#xe;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.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#De=S.initialPageviewId,this.#Fe=S.initialUrl,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="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.#xe("[SDK web-vitals] emit refused — unknown metric type:",S),!1;if(this.#Ne.has(I))return!1;if(!function isPositiveFiniteNumber(S){return"number"==typeof S&&Number.isFinite(S)&&S>=0}(b.value))return this.#xe("[SDK web-vitals] emit refused — invalid value for",I,b.value),!1;const x=normalizeRating(b.libRating)??normalizeRating(b.rating);if(!x)return this.#xe("[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&&Pe.has(b.navigationType)&&(R.navigationType=b.navigationType);const _=this.#_e()||{},D=Object.assign({},_,{pageviewId:this.#De,url:this.#Fe});let L;try{L=this.#Ce("performance_metric",R,D)}catch(S){return this.#xe("[SDK web-vitals] envelope wrap failed:",S),!1}try{this.#ke("tracescout.performance_metric",L)}catch(S){return this.#xe("[SDK web-vitals] addCustomEvent failed:",S),!1}return this.#Ne.add(I),!0}get emittedMetrics(){return new Set(this.#Ne)}get initialPageviewId(){return this.#De}get initialUrl(){return this.#Fe}}const Be=/^[a-zA-Z][a-zA-Z0-9_.-]*$/,ze=["_ts_","internal","system"],Ue=["password","token","authorization","cookie","ssn","creditcard","secret","apikey"],$e=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($e.has(b)){x("pollution-key",b);continue}if(ze.some(S=>b.startsWith(S))){x("reserved-key",b);continue}const A=b.toLowerCase();if(Ue.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{#ke;#_e;#Ce;#xe;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.#ke=S.addCustomEvent,this.#_e=S.getBaseContext,this.#Ce=S.wrap||wrapInEnvelope,this.#xe="function"==typeof S.debug?S.debug:()=>{}}emitCustomEvent(S,b){if(!function isValidEventName(S){return"string"==typeof S&&S.length>=1&&S.length<=128&&Be.test(S)}(S))return this.#xe("[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.#xe("[SDK track] properties keys dropped:",I);const R={name:S};Object.keys(x).length>0&&(R.properties=x);const A=this.#_e()||{};let _;try{_=this.#Ce("custom_event",R,A)}catch(S){return this.#xe("[SDK track] envelope wrap failed:",S),!1}try{this.#ke("tracescout.custom_event",_)}catch(S){return this.#xe("[SDK track] addCustomEvent failed:",S),!1}return!0}emitUserIdentified(S){if(!S||"object"!=typeof S)return!1;if(!isValidUserId(S.userId))return this.#xe("[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.#xe("[SDK identify] traits keys dropped:",I);const R={mode:b};Object.keys(x).length>0&&(R.traits=x);const A=this.#_e()||{},_=Object.assign({},A,{userId:S.userId});let D;isValidEmail(S.userEmail)&&(_.userEmail=S.userEmail),isValidUserName(S.userName)&&(_.userName=S.userName);try{D=this.#Ce("user_identified",R,_)}catch(S){return this.#xe("[SDK identify] envelope wrap failed:",S),!1}try{this.#ke("tracescout.user_identified",D)}catch(S){return this.#xe("[SDK identify] addCustomEvent failed:",S),!1}return!0}}class SessionRecordingFeature{#o=null;#Le=null;#Pe=null;#a=null;#Be=null;#ze=null;#Ue=null;#$e=null;#je=!1;#qe=!1;#We=null;#He=0;#Ve=null;#Qe=null;#Ge=null;#Ke=null;constructor({logger:S,sdkContext:b,config:I,options:x}){this.#o=S,this.#Le=b,this.#Pe=I,this.#a=x}async initialize(S,b){try{console.log("[TraceScout] Loading recording module..."),this.#Be=await Promise.resolve().then(function(){return jc});const{SessionStorage:I,UploadQueue:x,Recorder:R}=this.#Be;return this.#Ue=new I({storageKey:"__tracescout_sessions_v2__",maxStorageSize:2097152,maxSessions:5,logger:this.#o}),console.log("[TraceScout] ✓ Session storage initialized"),!0===this.#a.childMode?(this.#$e=null,console.log("[TraceScout] ⏭️ Upload queue SUPPRESSED (cross-origin child — parent owns the session)")):(this.#$e=this.#Je(x,S,b),console.log("[TraceScout] ✓ Upload queue initialized"),console.log(` Endpoint: /api/projects/${this.#Le.projectId}/sessions/${this.#Le.sessionId}/chunks`)),this.#ze=this.#Xe(R,S),console.log("[TraceScout] ✓ Session recorder initialized"),await this.#ze.start(),console.log("[TraceScout] ✓ Session recording started"),this.#a.onSessionStart&&this.#a.onSessionStart(this.#Le.sessionId),this.#je=!0,!0}catch(S){return console.error("[TraceScout] Failed to initialize session recording:",S),!1}}#Je(S,b,I){return new S({sdkContext:this.#Le,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.#Ge?.(b);this.#o?.error(`❌ Chunk ${S?.chunkIndex} upload failed:`,b?.message)},onNetworkChange:S=>{this.#o?.log("Network status: "+(S?"online":"offline"))}})}#Xe(S,b){const I=b.features.sessionRecording;return new S({sdkContext:this.#Le,serverSettings:I,emit:S=>this.#Ye(S),onChunk:S=>{this.#Ze(S),this.#$e&&this.#$e.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.#qe=!0,this.#We=S.reason,this.#a.onSessionEnd&&this.#a.onSessionEnd(S),this.#Qe?.(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.#Pe.debug||!1,recordCrossOriginIframes:!0===this.#Pe.recordCrossOriginIframes,onSpaNavigation:(S,b,I)=>{"function"==typeof this.#Ke&&this.#Ke(S,b,I)}})}#Ye(S){}#Ze(S){const b=Date.now();if(b-this.#He>=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.#He=b}this.#Ue&&this.#Ue.storeChunk(S.sessionId,S),this.#Ve?.(S)}setCallbacks({onChunkCreated:S,onSessionEnd:b,onQuotaExceeded:I,onSpaNavigation:x}){this.#Ve=S,this.#Qe=b,this.#Ge=I,this.#Ke=x||null}get isAvailable(){return this.#je&&null!=this.#ze}get isRecording(){return this.#ze?.isRecording||!1}get sessionEnded(){return this.#qe}get sessionEndReason(){return this.#We}get recorder(){return this.#ze}get uploadQueue(){return this.#$e}get sessionStorage(){return this.#Ue}async start(S={}){if(!this.#ze)return this.#o?.warn("Session recording not enabled"),null;try{const b=this.#ze.start(S),I=this.#ze.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.#ze)return this.#o?.warn("Session recording not enabled"),null;try{this.#ze.stop();const S=this.#ze.getEvents(),b=this.#ze.getSessionId();return this.#o?.info("Session recording stopped:",b),{sessionId:b,startTime:this.#ze.recordingStartTime,duration:Date.now()-this.#ze.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.#ze)return!1;try{return this.#ze.addCustomEvent(S,b)}catch(S){return!1}}getStatus(){return this.#ze?{available:!0,isRecording:this.#ze.isRecording,sessionId:this.#ze.getSessionId(),eventCount:this.#ze.getEvents().length,startTime:this.#ze.recordingStartTime}:{available:!1,error:"Session recording not enabled"}}getEvents(){return this.#ze?.getEvents()||[]}getChunks(){return this.#ze?.getChunks?.()||[]}getMetadata(){return this.#ze?.getMetadata?.()||{}}getSessionId(){return this.#ze?.getSessionId()}updateSessionId(S){this.#ze&&(this.#ze.sessionId=S),this.#qe=!1,this.#We=null}updateUploadEndpoint(S){this.#$e&&(this.#$e.config.endpoint=S)}destroy(){if(this.#ze){try{this.#ze.stop()}catch(S){}this.#ze=null}this.#Ue=null,this.#$e=null,this.#Be=null,this.#je=!1}}class LogManager{#o=null;#Pe=null;#Le=null;#et=[];#tt={};#st="debug";#rt=1e3;#nt=new Map;#it=5e3;#ot=null;#at=!0;static LOG_LEVELS={debug:0,info:1,warn:2,error:3,fatal:4};constructor(S={},b=null,I=null){this.#Pe=S,this.#Le=b,this.#ot=I,this.#o=new Logger("[LogManager]",S.debug),this.#at=!1!==S.logs?.enabled,this.#st=S.logs?.minLevel||"debug",this.#rt=S.logs?.maxBufferSize||1e3,this.#o.log("LogManager initialized",{enabled:this.#at,minLevel:this.#st,maxBufferSize:this.#rt})}log(S,b,I={}){if(!this.#at)return!1;if(!this.#lt(S))return!1;try{const x=this.#ct(S,b,I);return!this.#ut(x)&&(this.#et.push(x),this.#et.length>=this.#rt&&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.#tt[S]=b:"object"==typeof S&&Object.assign(this.#tt,S),this.#o.log("Context attached:",S)}clearContext(){this.#tt={},this.#o.log("Context cleared")}setLogLevel(S){LogManager.LOG_LEVELS.hasOwnProperty(S)?(this.#st=S,this.#o.log("Log level set to:",S)):this.#o.warn("Invalid log level:",S)}getLogLevel(){return this.#st}setEnabled(S){this.#at=S,this.#o.log("Logging",S?"enabled":"disabled")}isEnabled(){return this.#at}flush(){if(0===this.#et.length)return[];const S=[...this.#et];if(this.#et=[],this.#o.log(`Flushing ${S.length} logs`),this.#ot)try{this.#ot(S)}catch(S){this.#o.error("Error in flush callback:",S)}return S}getQueueSize(){return this.#et.length}getQueue(){return[...this.#et]}clearQueue(){const S=this.#et.length;this.#et=[],this.#o.log(`Cleared ${S} logs from queue`)}getStats(){const S={queueSize:this.#et.length,byLevel:{},enabled:this.#at,minLevel:this.#st};return this.#et.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}#ct(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.#ht(),...this.#tt};this.#Le&&(A.sessionId=this.#Le.sessionId,A.projectId=this.#Le.projectId,A.environment=this.#Le.environment,this.#Le.userId&&(A.userId=this.#Le.userId));const _=this.#dt(I);return"error"!==S&&"fatal"!==S||!1===this.#Pe.logs?.attachStackTrace||_.stack||(_.stack=this.#gt()),{logId:R,timestamp:x,level:S,message:String(b),metadata:_,context:A}}#ht(){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}#dt(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}#gt(){try{const S=(new Error).stack||"";return S.split("\n").slice(3).join("\n")}catch(S){return"Stack trace unavailable"}}#lt(S){const b=LogManager.LOG_LEVELS[S],I=LogManager.LOG_LEVELS[this.#st];return void 0===b||void 0===I||b>=I}#ut(S){const b=`${S.level}:${S.message}`,I=Date.now(),x=this.#nt.get(b);return!!(x&&I-x<this.#it)||(this.#nt.set(b,I),this.#nt.size>1e3&&this.#pt(),!1)}#pt(){const S=Date.now();for(const[b,I]of this.#nt.entries())S-I>this.#it&&this.#nt.delete(b)}destroy(){this.flush(),this.#et=[],this.#tt={},this.#nt.clear(),this.#ot=null,this.#o.log("LogManager destroyed")}}function newOperationId(){return`ts-${uuidv4()}`}class LogBuffer{#o=null;#Pe=null;#Le=null;#ft=[];#mt=null;#yt=5e3;#vt=100;#St=!1;#wt=null;#bt=!0;#Ct=0;static MAX_CONSECUTIVE_FAILURES=5;#kt=null;constructor(S={},b=null,I=null){this.#Pe=S,this.#Le=b,this.#wt=I,this.#o=new Logger("[LogBuffer]",S.debug),this.#yt=S.logs?.flushInterval||5e3,this.#vt=S.logs?.maxBatchSize||100,this.#bt=!1!==S.telemetry?.enableCompression,this.#It(),this.#o.log("LogBuffer initialized",{flushInterval:this.#yt,maxBatchSize:this.#vt,compressionEnabled:this.#bt})}add(S){Array.isArray(S)||(S=[S]),this.#ft.push(...S),this.#o.log(`Added ${S.length} logs to buffer. Buffer size: ${this.#ft.length}`),this.#ft.length>=this.#vt&&(this.#o.log("Buffer size threshold reached, flushing..."),this.flush())}async flush(){if(this.#St)return this.#o.log("Already sending, skipping flush"),{success:!1,reason:"Already sending"};if(null===this.#kt&&0===this.#ft.length)return{success:!0,sent:0};if(null===this.#kt){const S=this.#ft.splice(0,this.#vt);if(0===S.length)return{success:!0,sent:0};this.#kt={operationId:newOperationId(),logs:S}}const S=this.#kt.logs;this.#o.log(`Flushing ${S.length} logs (operation ${this.#kt.operationId})`);try{this.#St=!0;const b=this.#Et(S,this.#kt.operationId);let I=b,x=!1;if(this.#bt&&"function"==typeof this.#xt)try{I=await this.#xt(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.#wt&&await this.#wt(I,x),this.#o.log(`Successfully sent batch with ${S.length} logs`),this.#Ct=0,this.#kt=null,{success:!0,sent:S.length}}catch(b){return this.#Ct++,this.#o.error(`Failed to flush logs (consecutive failures: ${this.#Ct}):`,b),this.#Ct>LogBuffer.MAX_CONSECUTIVE_FAILURES?(this.#o.warn(`Dropping batch of ${S.length} logs after ${this.#Ct} consecutive failures`),this.#kt=null,{success:!1,dropped:S.length,error:b.message}):{success:!1,error:b.message}}finally{this.#St=!1}}getConsecutiveFailures(){return this.#Ct}async forceFlush(){this.#Mt();try{await this.flush()}finally{this.#It()}}getBufferSize(){return this.#ft.length}getStats(){const S={bufferSize:this.#ft.length,isSending:this.#St,flushInterval:this.#yt,maxBatchSize:this.#vt,byLevel:{}};return this.#ft.forEach(b=>{S.byLevel[b.level]=(S.byLevel[b.level]||0)+1}),S}clear(){const S=this.#ft.length;this.#ft=[],this.#o.log(`Cleared ${S} logs from buffer`)}destroy(){this.#Mt(),this.flush().catch(S=>{this.#o.error("Error during final flush:",S)}),this.clear(),this.#o.log("LogBuffer destroyed")}#Et(S,b){return{batchId:b||newOperationId(),timestamp:Date.now(),projectId:this.#Le?.projectId,count:S.length,logs:S}}async#xt(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")}#It(){this.#mt||(this.#mt=setInterval(()=>{this.#ft.length>0&&this.flush().catch(S=>{this.#o.error("Auto-flush failed:",S)})},this.#yt),this.#o.log("Auto-flush started"))}#Mt(){this.#mt&&(clearInterval(this.#mt),this.#mt=null,this.#o.log("Auto-flush stopped"))}}class LoggingFeature{#o=null;#Le=null;#Pe=null;#Rt=null;#Tt=null;#je=!1;constructor({logger:S,sdkContext:b,config:I}){this.#o=S,this.#Le=b,this.#Pe=I}initialize(S){console.log("[TraceScout] Initializing logging system...");try{return this.#Rt=new LogManager(this.#Pe,this.#Le,S=>{this.#Tt&&this.#Tt.add(S)}),this.#Tt=new LogBuffer(this.#Pe,this.#Le,async(S,b)=>this.#At(S,b)),console.log("[TraceScout] ✓ Logging system initialized"),this.#je=!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),U.configure(b),S.enabledLogServices&&Array.isArray(S.enabledLogServices)?U.enableServices(S.enabledLogServices,S.logLevel||"info"):S.debug&&U.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#At(S,b){if(!this.#Le)throw new Error("SDK not initialized");const I=this.#Le.projectId,x=`${resolveApiBaseUrl(this.#Pe)}/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.#je&&null!=this.#Rt}get logManager(){return this.#Rt}get logBuffer(){return this.#Tt}log(S,b,I={}){return!!this.#Rt&&this.#Rt.log(S,b,I)}debug(S,b={}){return this.#Rt?.debug(S,b)||!1}info(S,b={}){return this.#Rt?.info(S,b)||!1}warn(S,b={}){return this.#Rt?.warn(S,b)||!1}error(S,b={}){return this.#Rt?.error(S,b)||!1}fatal(S,b={}){return this.#Rt?.fatal(S,b)||!1}setContext(S,b){return!!this.#Rt&&(this.#Rt.attachContext(S,b),!0)}clearContext(){return!!this.#Rt&&(this.#Rt.clearContext(),!0)}setLogLevel(S){return!!this.#Rt&&(this.#Rt.setLogLevel(S),!0)}getStats(){return this.#Rt?{manager:this.#Rt.getStats(),buffer:this.#Tt?this.#Tt.getStats():null}:null}async flush(){if(!this.#Tt)return!1;try{return await this.#Tt.forceFlush(),!0}catch(S){return this.#o?.error("Failed to flush logs:",S),!1}}enableServices(S,b="info"){try{return U.enableServices(S,b),!0}catch(S){return this.#o?.error("Failed to enable logging:",S),!1}}disableServices(S){try{return U.disableServices(S),!0}catch(S){return this.#o?.error("Failed to disable logging:",S),!1}}enableAll(S="info"){try{return U.enableAll(S),!0}catch(S){return this.#o?.error("Failed to enable all logging:",S),!1}}disableAll(){try{return U.disableAll(),!0}catch(S){return this.#o?.error("Failed to disable all logging:",S),!1}}getConfig(){try{return U.getConfig()}catch(S){return this.#o?.error("Failed to get logging config:",S),null}}getEnabledServices(){try{return U.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.#Tt&&(this.#Tt.destroy(),this.#Tt=null),this.#Rt&&(this.#Rt.destroy(),this.#Rt=null),this.#je=!1}}class ConsoleInterceptor{constructor(S,b={},I=null,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),this.realmConsole=x&&x.console?x.console:"undefined"!=typeof console?console:void 0,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");const b=this.realmConsole;S.forEach(S=>{this.originalMethods[S]=b[S],b[S]=this.createInterceptor(S)}),this.installed=!0,this.logger.debug("Console interceptor installed")}uninstall(){if(!this.installed)return;const S=this.realmConsole;Object.keys(this.originalMethods).forEach(b=>{S[b]=this.originalMethods[b]}),this.originalMethods={},this.installed=!1,this.logger.debug("Console interceptor uninstalled")}createInterceptor(S){const b=this;return function(...I){b.originalMethods[S].apply(b.realmConsole,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 je=["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"],qe="[REDACTED]";function filterSensitiveHeaders(S,b=[]){if(!S)return{};const I={},x=new Set([...je,...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)?qe:S});else if("object"==typeof S)for(const[b,R]of Object.entries(S)){const S=b.toLowerCase();I[b]=x.has(S)?qe:R}return I}function isSensitiveHeader(S){return!!S&&je.includes(S.toLowerCase())}function getSensitiveHeadersList(){return[...je]}function createSensitiveHeaderSet(S=[]){return new Set([...je,...S.map(S=>S.toLowerCase())])}const We=[".js",".css",".png",".jpg",".jpeg",".gif",".svg",".woff",".woff2",".ttf",".eot",".ico",".webp",".avif"],He=["text/css","text/javascript","application/javascript","image/","font/","application/font","application/x-font"],Ve=[/\.(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(We.some(b=>S.toLowerCase().includes(b)))return!0;const I=He.some(S=>b.toLowerCase().startsWith(S));return!!I||Ve.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"}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)}const Qe=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=Qe,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=Qe,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 Ge="[REDACTED]",Ke=10240,Je=65536,Xe=["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(Xe);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]=Ge,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,Ge);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:Ke;return b>Je&&(b=Je),{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=Ge,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 Ye="[REDACTED]",Ze=["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=[...Ze];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(_,Ye)}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${Ye}`);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,I){this.reporter=S,this.interceptorName=b,this.realm=I||("undefined"!=typeof window?window:void 0),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:Ke;b>=0||(b=Ke),b>Je&&(b=Je);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:Qe,onWarn:(...S)=>this.logger.warn(...S)})}handleResponseData(S,b){return handleResponseBody(b,{maxSize:Qe,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:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.navigator?.userAgent}};this.logEvent(R)}extractDomain(S){try{return new URL(S,this.realm?.location?.origin).hostname}catch{return"unknown"}}extractPath(S){try{return new URL(S,this.realm?.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 et=/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/,tt=/^0+$/;function readTraceContextFromHeaders(S){return function parseTraceparent(S){if("string"!=typeof S)return null;const b=S.match(et);if(!b)return null;const I=b[1],x=b[2];return tt.test(I)||tt.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 st="undefined"!=typeof window&&window.fetch?window.fetch.bind(window):void 0;class FetchInterceptor extends BaseInterceptor{constructor(S,b){super(S,"fetch",b),this.originalFetch=this.realm&&this.realm.fetch?this.realm.fetch.bind(this.realm):st}setup(){this.logger.log("Initializing Fetch interceptor...");const S=this,b=this.realm;b._apiReporter_originalFetch||(b._apiReporter_originalFetch=this.originalFetch),b.fetch=async function(...I){I=S.injectCorrelationHeaders(I);const x=b.Request,R=b.Headers,A=x&&I[0]instanceof x?I[0].url:String(I[0]),_=I[1]||{},D=_.method||(x&&I[0]instanceof x?I[0].method:"GET"),L=_.body;let B={};x&&I[0]instanceof x?I[0].headers.forEach((S,b)=>{B[b]=S}):_.headers&&(R&&_.headers instanceof R?_.headers.forEach((S,b)=>{B[b]=S}):Object.assign(B,_.headers));const U=filterSensitiveHeaders(B),$=S.shouldMonitor(A),j=S.isStaticResource(A);let W=null;$&&S.reporter.performanceMonitor&&S.reporter.config?.monitorPerformance&&(W=S.reporter.performanceMonitor.generateRequestId(),S.reporter.performanceMonitor.startTracking(W,A,D));const H=Date.now();if(!j){const b=S.getNetworkConfig(),I=S.isEndpointExcluded(A,b),x=S.sanitizeRequestUrlFields(A,b),R=getHeader(B,"content-type"),_=S.buildRequestBodyFields(L,R,b,I),$={interceptor:"fetch",method:D,url:x.url,requestHeaders:b.captureRequestHeaders?U:{},timestamp:H,..._};x.path&&($.requestPath=x.path),x.query&&($.requestQuery=x.query);const j=readTraceContextFromHeaders(B);j&&($.traceId=j.traceId,$.spanId=j.spanId),S.reporter?.config?.debug&&console.log("[FetchInterceptor] Capturing API request:",{url:x.url,hasHeaders:!!U&&Object.keys(U).length>0,bodyState:_.requestBodyState}),S.addToSessionReplay("network_request",$)}try{const x=await S.originalFetch.apply(b,I);let R=null;return W&&(R=S.reporter.performanceMonitor.endTracking(W,x.status)),await S.handleResponse(x,A,D,R),x}catch(b){throw W&&S.reporter.performanceMonitor.endTracking(W,0),S.handleNetworkError(A,D,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:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.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(){const S=this.realm;S&&S._apiReporter_originalFetch&&(S.fetch=S._apiReporter_originalFetch,delete S._apiReporter_originalFetch),super.destroy()}injectCorrelationHeaders(S){const b=SDKContext.getInstance();if(!b||!b.sessionId)return S;const I=this.realm,x=I.Request,R=I.Headers,A=tracePropagationDecision(x&&S[0]instanceof x?S[0].url:String(S[0]));if(!A.traceparent&&!A.baggage)return S;const _=[];if(A.baggage&&(b.sessionId&&_.push(`sessionId=${encodeURIComponent(b.sessionId)}`),b.userId&&_.push(`userId=${encodeURIComponent(b.userId)}`),b.projectId&&_.push(`projectId=${encodeURIComponent(b.projectId)}`)),x&&S[0]instanceof x){const b=S[0],I=S[1]||{},D=new R(b.headers);if(I.headers)if(R&&I.headers instanceof R)I.headers.forEach((S,b)=>D.set(b,S));else for(const S in I.headers)D.set(S,I.headers[S]);const L=hasHeader(D,"traceparent");A.baggage&&_.length>0&&!getHeader(D,"baggage")&&setHeader(D,"baggage",_.join(",")),A.traceparent&&!L&&setHeader(D,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`);const B={...I};delete B.headers;return[new x(b,{...B,headers:D})]}const D=S[0],L=S[1]||{};if(L.headers=L.headers||{},R&&L.headers instanceof R){const S={};L.headers.forEach((b,I)=>{S[I]=b}),L.headers=S}const B=hasHeader(L.headers,"traceparent");return A.baggage&&_.length>0&&!getHeader(L.headers,"baggage")&&setHeader(L.headers,"baggage",_.join(",")),A.traceparent&&!B&&setHeader(L.headers,"traceparent",`00-${this.generateW3CTraceId()}-${this.generateW3CSpanId()}-01`),[D,L]}generateW3CTraceId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}class XHRInterceptor extends BaseInterceptor{constructor(S,b){super(S,"xhr",b),this.XHR=this.realm&&this.realm.XMLHttpRequest?this.realm.XMLHttpRequest:XMLHttpRequest,this.originalOpen=this.XHR.prototype.open,this.originalSend=this.XHR.prototype.send}setup(){this.logger.log("Initializing XHR interceptor...");const S=this,b=this.XHR.prototype;b.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 I=b.setRequestHeader;this._originalSetRequestHeader=I,b.setRequestHeader=function(S,b){return this._apiReporterRequestHeaders||(this._apiReporterRequestHeaders={}),this._apiReporterUserSetHeaders||(this._apiReporterUserSetHeaders=new Set),this._apiReporterUserSetHeaders.add(S.toLowerCase()),setHeader(this._apiReporterRequestHeaders,S,b),I.call(this,S,b)},b.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:this.realm?.origin,pageUrl:this.realm?.location?.href,userAgent:this.realm?.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(){this.XHR.prototype.open=this.originalOpen,this.XHR.prototype.send=this.originalSend,this._originalSetRequestHeader&&(this.XHR.prototype.setRequestHeader=this._originalSetRequestHeader),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=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(16);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}generateW3CSpanId(){const S=this.realm&&this.realm.crypto||("undefined"!=typeof crypto?crypto:void 0),b=new Uint8Array(8);return S.getRandomValues(b),Array.from(b,S=>S.toString(16).padStart(2,"0")).join("")}}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)}}const rt=["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={},I=null){this.reporter=S,this.realm=I||("undefined"!=typeof window?window:void 0),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"):this.realm&&void 0!==this.realm.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 this.realm.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 this.realm.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((this.realm?.performance?.timeOrigin||0)+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((this.realm?.performance?.timeOrigin||0)+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 rt){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,x=null){this.eventManager=S,this.reporter=I,this.realm=x||("undefined"!=typeof window?window:void 0),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(){if(this.installed)return;const S=this.realm;this.config.captureErrors&&(this.originalHandlers.onerror=S.onerror,S.onerror=this.handleError.bind(this)),this.config.captureUnhandledRejections&&(this.originalHandlers.onunhandledrejection=S.onunhandledrejection,this._boundRejectionHandler=this.handleUnhandledRejection.bind(this),S.addEventListener("unhandledrejection",this._boundRejectionHandler)),this.installed=!0,this.logger.debug("Error handler installed")}uninstall(){if(!this.installed)return;const S=this.realm;this.config.captureErrors&&(S.onerror=this.originalHandlers.onerror||null),this.config.captureUnhandledRejections&&(this._boundRejectionHandler&&(S.removeEventListener("unhandledrejection",this._boundRejectionHandler),this._boundRejectionHandler=null),this.originalHandlers.onunhandledrejection&&(S.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:this.realm?.navigator?.userAgent,url:this.realm?.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:this.realm?.navigator?.userAgent,url:this.realm?.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()}}function initializeErrorHandler(S,b={}){const I=new ErrorHandler(S,b);return I.install(),I}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"))}}const nt="ts-top";class IframeInstrumentationManager{#ye=null;#Pe=null;#o=null;#j=null;#Nt=Symbol("__tsIframeInstalled__");#te=!1;#Lt=new Map;#Pt=[];#Bt=[];#Y=new WeakSet;#K=new WeakMap;#zt=new Map;#J=0;#Ut=0;#O={installs:0,teardowns:0,reentrySkips:0,inaccessible:0,installErrors:0};#$t=[];constructor({core:S,config:b,logger:I,topWindow:x}={}){this.#ye=S,this.#Pe=b||S?.config||{},this.#o=I||null,this.#j=x||("undefined"!=typeof window?window:void 0)}get isStarted(){return this.#te}start(){if(this.#te)return!0;if(!this.#j)return!1;try{this.#te=!0,this.#jt();const S=this.#j.document;return this.#qt(S,this.#j,nt,1),this.#Wt(S,this.#j,nt,1,null),!0}catch(S){return this.#F("start failed (fail-closed):",S),!0}}shutdown(){try{for(const S of Array.from(this.#Lt.values()))this.#Ht(S,"disconnected");this.#Lt.clear();for(const S of this.#Bt)try{S.mo.disconnect()}catch(S){}this.#Bt.length=0,this.#Pt.length=0}catch(S){this.#F("shutdown error (fail-closed):",S)}finally{this.#te=!1;try{this.#ye?.setIframeTopFrameContext?.(null)}catch(S){}}}#qt(S,b,I,x){if(!S)return;let R=null;try{R=S.querySelectorAll("iframe")}catch(S){R=null}R&&R.forEach(S=>{this.#ie(S,I,x),this.#Vt(S,I,x)});try{const S=b&&b.frames,R=S?S.length:0;for(let b=0;b<R;b++){let R=null;try{R=S[b]&&S[b].frameElement}catch(S){R=null}R&&"IFRAME"===R.tagName&&!this.#K.has(R)&&(this.#ie(R,I,x),this.#Vt(R,I,x))}}catch(S){}}#ie(S,b,I){if(!this.#Y.has(S)){this.#Y.add(S);try{S.addEventListener("load",()=>{try{this.#Vt(S,b,I)}catch(S){this.#F("load-reinstall failed (fail-closed):",S)}})}catch(S){this.#F("hookLoad failed (fail-closed):",S)}}}#Vt(S,b,I){let x=null;try{x=S.contentWindow}catch(S){x=null}x&&this.#Qt(S,x,b,I)}#he(S){let b=this.#K.get(S);return b||(b="ts-frame-"+ ++this.#J,this.#K.set(S,b)),b}#Qt(S,b,I,x){try{const b=S.getAttribute&&S.getAttribute("src");if(b){const I=new URL(b,"undefined"!=typeof location&&location.href||void 0);if(("http:"===I.protocol||"https:"===I.protocol)&&"undefined"!=typeof location&&I.origin!==location.origin)return this.#O.inaccessible++,this.#Gt("inaccessible",{frameId:this.#he(S),depth:x,reason:"cross-origin-src"}),null}}catch(S){}let R;try{if(R=b.document,!R)throw new Error("no document")}catch(b){return this.#O.inaccessible++,this.#Gt("inaccessible",{frameId:this.#he(S),depth:x}),null}const A=this.#he(S),_=b[this.#Nt];if(_&&null!=_.realmEpoch)return this.#O.reentrySkips++,this.#Gt("reentry-skip",{frameId:A,realmEpoch:_.realmEpoch}),_;const D=this.#Lt.get(A);if(D&&D.win!==b){const S="reloaded"===this.#Kt(A,this.#Jt(b))?"reloaded":"navigated";this.#Ht(D,S)}const L=++this.#Ut,B=this.#Xt(b),U=this.#Jt(b),$=this.#Kt(A,U),j=this.#Yt(),W={frameId:A,frameInstanceId:`${A}-r${L}`,parentFrameId:I,topFrameId:nt,frameDepth:x,frameOrigin:B,frameUrl:U,frameLifecycle:$,privacyStatus:j,realmEpoch:L,win:b,el:S,seq:0,interceptors:[],observerRef:null};try{Object.defineProperty(b,this.#Nt,{value:W,configurable:!0,enumerable:!1,writable:!0})}catch(S){return null}const H=this.#Zt(W),V=this.#Pe||{};let Q=!1;try{this.#es(W,()=>{const S=new FetchInterceptor(H,b);return S.setup(),S}),this.#es(W,()=>{const S=new XHRInterceptor(H,b);return S.setup(),S}),this.#es(W,()=>{const S=new ConsoleInterceptor(null,V,H,b);return S.install(),S}),this.#es(W,()=>{const S=new ErrorHandler(null,V,H,b);return S.install(),S}),this.#es(W,()=>{const S=new PerformanceResourceObserver(H,{captureResources:!1!==V.captureResources,captureNavigation:!1!==V.captureNavigation,debug:!!V.debug,maxResourceEntriesPerSession:V.maxResourceEntriesPerSession||2e3},b);return S.setup(),S}),Q=W.interceptors.length>0}catch(S){return this.#O.installErrors++,this.#F("install block failed (fail-closed):",S),this.#Ht(W,"blocked"),null}if(!Q){try{delete b[this.#Nt]}catch(S){}return null}this.#O.installs++,this.#ts(A,U),this.#Lt.set(A,W),this.#ss(A,b),this.#Gt("install",{frameId:A,parentFrameId:I,depth:x,realmEpoch:L,frameLifecycle:$});try{this.#qt(R,b,A,x+1)}catch(S){this.#F("nested scan failed:",S)}return this.#Wt(R,b,A,x+1,W),W}#es(S,b){try{const I=b();I&&S.interceptors.push(I)}catch(S){this.#O.installErrors++,this.#F("interceptor install failed (fail-closed):",S)}}#Zt(S){const b=this.#ye,stamp=(b,I)=>this.#rs(S,b,I);return new Proxy(b,{get(S,b){if("addSessionCustomEvent"===b)return stamp;const I=Reflect.get(S,b,S);return"function"==typeof I?I.bind(S):I}})}#rs(S,b,I){try{const x=I&&"object"==typeof I?I:{},R="number"==typeof x.timestamp?x.timestamp:Date.now(),A=Object.assign({},x,{frameId:S.frameId,topFrameId:S.topFrameId,frameInstanceId:S.frameInstanceId,frameDepth:S.frameDepth,frameOrigin:S.frameOrigin,frameUrl:S.frameUrl,frameLifecycle:S.frameLifecycle,captureRealm:"iframe",privacyStatus:S.privacyStatus,localSequence:S.seq++,tsLocal:R,tsNormalized:R});return null!=S.parentFrameId&&(A.parentFrameId=S.parentFrameId),this.#ye.addSessionCustomEvent(b,A)}catch(S){return this.#F("stamp/emit failed (fail-closed):",S),!1}}#Wt(S,b,I,x,R){try{const A=b.MutationObserver;if(!A)return;const _=new A(S=>{try{for(const b of S)b.addedNodes&&b.addedNodes.forEach(S=>this.#ae(S,I,x)),b.removedNodes&&b.removedNodes.forEach(S=>this.#le(S))}catch(S){this.#F("mutation handler failed (fail-closed):",S)}});_.observe(S.documentElement||S,{childList:!0,subtree:!0});const D={mo:_,win:b};this.#Bt.push(D),R&&(R.observerRef=()=>{try{_.disconnect()}catch(S){}const S=this.#Bt.indexOf(D);S>=0&&this.#Bt.splice(S,1)})}catch(S){this.#F("observeDocument failed (fail-closed):",S)}}#ae(S,b,I){if(!S||1!==S.nodeType)return;const attach=S=>{this.#ie(S,b,I),this.#Vt(S,b,I)};if("IFRAME"===S.tagName&&attach(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(attach)}catch(S){}}#le(S){if(!S||1!==S.nodeType)return;const one=S=>{const b=this.#K.get(S);if(!b)return;if(S.isConnected)return;const I=this.#Lt.get(b);I&&this.#Ht(I,"detached")};if("IFRAME"===S.tagName&&one(S),S.querySelectorAll)try{S.querySelectorAll("iframe").forEach(one)}catch(S){}}#Ht(S,b){for(const b of S.interceptors)try{"function"==typeof b.destroy?b.destroy():"function"==typeof b.uninstall&&b.uninstall()}catch(S){this.#F("interceptor teardown failed (fail-closed):",S)}if(S.interceptors=[],"function"==typeof S.observerRef){try{S.observerRef()}catch(S){}S.observerRef=null}this.#Lt.delete(S.frameId);try{delete S.win[this.#Nt]}catch(S){}if(this.#ns(S.frameId),"detached"===b){const b=this.#zt.get(S.frameId);b&&(b.detached=!0)}S.win=null,S.el=null,this.#O.teardowns++,this.#Gt("teardown",{frameId:S.frameId,reason:b})}#jt(){const S=this.#j;try{this.#ye?.setIframeTopFrameContext?.({frameId:nt,frameInstanceId:`${nt}-r0`,topFrameId:nt,frameOrigin:this.#Xt(S),frameUrl:this.#Jt(S),frameLifecycle:"attached",privacyStatus:this.#Yt()})}catch(S){this.#F("registerTopFrameContext failed (fail-closed):",S)}}#Xt(S){try{const b=S.location&&S.location.origin;if("string"==typeof b&&b)return b.slice(0,256)}catch(S){}}#Jt(S){try{const b=S.location&&S.location.href;if("string"!=typeof b||!b)return;const{url:I}=splitSanitizedUrl(b,{});return(I||b).slice(0,2048)}catch(S){return}}#Yt(){try{const S=SDKContext.getInstance()?.domPrivacy;if("confirmed"===S||"partial"===S||"disabled"===S)return S}catch(S){}return"unknown"}#Kt(S,b){const I=this.#zt.get(S);return I&&I.everInstalled?I.detached?"reattached":null!=I.lastUrl&&null!=b&&I.lastUrl===b?"reloaded":"navigated":"attached"}#ts(S,b){const I=this.#zt.get(S)||{};I.everInstalled=!0,I.detached=!1,I.lastUrl=b,this.#zt.set(S,I)}#ss(S,b){const I=this.#Pt.find(b=>b.frameId===S);I?I.win=b:this.#Pt.push({frameId:S,win:b})}#ns(S){for(let b=this.#Pt.length-1;b>=0;b--)this.#Pt[b].frameId===S&&(this.#Pt[b].win=null,this.#Pt.splice(b,1))}getStats(){return{active:this.#Lt.size,allRealms:this.#Pt.length,observers:this.#Bt.length,...this.#O}}getInstallLog(){return this.#$t.slice()}verifyRestored(){return this.#is().map(S=>{const b={frameId:S.frameId,alive:!1},I=S.win;if(!I)return b;try{b.alive=!0,b.fetchRestored=!(I.fetch&&I.fetch.__tsPoCWrapped),b.consoleRestored="function"==typeof I.console.log}catch(S){b.error=S&&S.name}return b})}#is(){const S=[];for(const b of this.#Lt.values())S.push({frameId:b.frameId,win:b.win});for(const b of this.#Pt)S.some(S=>S.frameId===b.frameId)||S.push(b);return S}#Gt(S,b){this.#$t.push(Object.assign({ev:S,t:Date.now()},b))}#F(...S){try{this.#Pe?.debug&&this.#o?.warn&&this.#o.warn("[IframeInstrumentation]",...S)}catch(S){}}}class InterceptorFeature{#o=null;#Pe=null;#os=null;#as=null;#ls=null;#cs=null;#je=!1;constructor({logger:S,config:b,monitoringCore:I,eventManager:x}){this.#o=S,this.#Pe=b,this.#os=I,this.#as=x}initialize(S,b=null){try{this.#ls={};return S&&S.isRecording?(console.log("[TraceScout] 🔌 Setting up session recording interceptors bundle..."),this.#us(),this.#hs(),this.#ds(),this.#gs(b),this.#ps(),this.#fs(),this.#ms(),console.log("[TraceScout] ✅ Session recording bundle complete (DOM + Network + Console + Errors)"),this.#o?.log("Interceptors setup complete"),this.#je=!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}}#us(){console.log("[TraceScout] 📡 Setting up FetchInterceptor..."),this.#ls.fetch=new FetchInterceptor(this.#os),this.#ls.fetch.setup?.()||this.#ls.fetch.install?.(),console.log("[TraceScout] ✅ FetchInterceptor active")}#hs(){console.log("[TraceScout] 📡 Setting up XHRInterceptor..."),this.#ls.xhr=new XHRInterceptor(this.#os),this.#ls.xhr.setup?.()||this.#ls.xhr.install?.(),console.log("[TraceScout] ✅ XHRInterceptor active")}#ds(){const S=!1!==this.#Pe?.captureResources,b=!1!==this.#Pe?.captureNavigation;if(S||b)try{console.log("[TraceScout] 📊 Setting up PerformanceResourceObserver...",{captureResources:S,captureNavigation:b,maxResourceEntriesPerSession:this.#Pe?.maxResourceEntriesPerSession||2e3}),this.#ls.performanceResource=new PerformanceResourceObserver(this.#os,{captureResources:S,captureNavigation:b,debug:this.#Pe?.debug||!1,maxDedupeEntries:this.#Pe?.maxDedupeEntries||5e3,filterOtherInitiator:!1!==this.#Pe?.filterOtherInitiator,maxResourceEntriesPerSession:this.#Pe?.maxResourceEntriesPerSession||2e3,resourceAllowlist:this.#Pe?.resourceAllowlist||null,resourceBlocklist:this.#Pe?.resourceBlocklist||null}),this.#ls.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")}#gs(S){console.log("[TraceScout] 💬 Setting up ConsoleInterceptor..."),this.#ls.console=new ConsoleInterceptor(this.#as,this.#Pe,this.#os),S&&this.#ls.console.setLogManager(S),this.#ls.console.install?.(),console.log("[TraceScout] ✅ ConsoleInterceptor active")}#ps(){try{console.log("[TraceScout] 🚨 Setting up ErrorHandler..."),this.#ls.errors=new ErrorHandler(this.#as,this.#Pe,this.#os),console.log("[TraceScout] ErrorHandler created, installing...",{hasInstall:"function"==typeof this.#ls.errors?.install,hasReporter:!!this.#os}),this.#ls.errors.install?.(),console.log("[TraceScout] ✅ ErrorHandler active")}catch(S){console.error("[TraceScout] ❌ ErrorHandler setup failed:",S)}}#ms(){try{this.#cs=new IframeInstrumentationManager({core:this.#os,config:this.#Pe,logger:this.#o}),this.#cs.start(),console.log("[TraceScout] 🪟 Same-origin iframe instrumentation active")}catch(S){console.warn("[TraceScout] ⚠️ Iframe instrumentation skipped:",S?.message),this.#cs=null}}get iframeManager(){return this.#cs}#fs(){this.#Pe?.monitorPostMessages&&"object"==typeof this.#Pe.monitorPostMessages&&(this.#ls.postMessage=new PostMessageInterceptor(this.#os),this.#ls.postMessage.setup?.()||this.#ls.postMessage.install?.())}get isInitialized(){return this.#je}get interceptors(){return this.#ls}getInterceptor(S){return this.#ls?.[S]||null}updateDebugMode(S){this.#ls&&Object.values(this.#ls).forEach(b=>{b&&b.updateDebugMode&&b.updateDebugMode(S)})}destroy(){if(this.#cs){try{this.#cs.shutdown()}catch(S){}this.#cs=null}this.#ls&&(Object.values(this.#ls).forEach(S=>{S?.destroy?.()||S?.uninstall?.()}),this.#ls=null),this.#je=!1}}class EventLifecycleFeature{#o=null;#Pe=null;#ys=null;#vs=null;#Ss=null;#ws=null;#bs=null;#Cs=null;#ks=null;#Is=null;#je=!1;#Es=!1;constructor({logger:S,config:b}){this.#o=S,this.#Pe=b}setCallbacks({onCustomApiError:S,onBeforeUnload:b,onUserActivity:I,onVisibilityChange:x}){this.#bs=S,this.#Cs=b,this.#ks=I,this.#Is=x}initialize(){try{return this.#ys=this.#xs.bind(this),this.#vs=this.#Ms.bind(this),this.#Ss=this.#Rs.bind(this),this.#ws=this.#Ts.bind(this),document.addEventListener("custom-api-error",this.#ys),window.addEventListener("beforeunload",this.#vs),document.addEventListener("click",this.#Ss,{passive:!0,capture:!0}),document.addEventListener("keydown",this.#Ss,{passive:!0,capture:!0}),document.addEventListener("scroll",this.#Ss,{passive:!0,capture:!0}),document.addEventListener("visibilitychange",this.#ws),this.#o?.log("Event listeners setup complete"),this.#je=!0,!0}catch(S){return this.#o?.error("Failed to setup event listeners:",S),!1}}#xs(S){this.#bs?.(S)}#Ms(S){this.#Cs?.(S)}#Rs(){this.#Es||this.#ks?.()}#Ts(){this.#Es||("visible"===document.visibilityState?this.#Is?.("visible"):this.#Is?.("hidden"))}get isInitialized(){return this.#je}setQuotaExceeded(S){this.#Es=S,S&&this.#As()}#As(){this.#Ss&&(document.removeEventListener("click",this.#Ss,{capture:!0}),document.removeEventListener("keydown",this.#Ss,{capture:!0}),document.removeEventListener("scroll",this.#Ss,{capture:!0}),this.#Ss=null),this.#ws&&(document.removeEventListener("visibilitychange",this.#ws),this.#ws=null)}destroy(){try{document.removeEventListener("custom-api-error",this.#ys),window.removeEventListener("beforeunload",this.#vs),this.#As(),this.#ys=null,this.#vs=null,this.#je=!1}catch(S){this.#o?.error("Failed to cleanup event listeners:",S)}}}function readInjectedDebugId(){try{const S="undefined"!=typeof globalThis?globalThis.__TRACESCOUT_DEBUG_ID__:void 0;if("string"==typeof S&&/^[0-9a-fA-F][0-9a-fA-F-]{6,62}[0-9a-fA-F]$/.test(S))return S}catch(S){}return null}class TraceScoutMonitoringCore{#je=!1;#o=null;#_s=null;#as=null;#Os=null;#Ds=null;#Fs=null;#Ns=null;#Le=null;#Ls=null;#Ps=null;#Bs=null;#zs=null;#ls=null;#Us=null;#$s=null;#js=null;#qs=null;#Ws=null;#Hs=null;#Vs=null;#Qs=null;#Gs=null;_consecutiveFailures=0;#Es=!1;#Ks=null;#Js=!1;#Xs=null;#Ys=0;#Zs=null;#er=null;#tr=!1;static#sr=null;static#rr=!1;constructor(){this.config=x.defaults({retryIntervalMs:x.get(A,"RETRY_INTERVAL_MS",5e3),deduplicationWindowMs:x.get(A,"DEDUPLICATION_WINDOW_MS",3e4),maxQueueSize:x.get(A,"MAX_QUEUE_SIZE",1e3),maxRetries:x.get(A,"MAX_RETRIES",3),batchSize:x.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.#_s=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.#Vs=throttle$1(this.sendEvents.bind(this),1e3))}static setTransport(S){TraceScoutMonitoringCore.#rr?console.error("[TraceScout] setTransport() must be called before init()"):"object"==typeof S&&null!==S?"string"==typeof S.apiBaseUrl&&S.apiBaseUrl?TraceScoutMonitoringCore.#sr=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.#Js)return this.#o.warn("TraceScoutMonitoringCore already initialized"),{sampled:this.#Ks??!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.#Js=!0,TraceScoutMonitoringCore.#rr=!0,this.#Zs=parseIframeConfig(I.options.iframe),!this.#Zs.enabled&&this.#Zs.reason&&"absent"!==this.#Zs.reason&&I.options.debug&&console.warn("[TraceScout] iframe bridge disabled (fail-closed):",this.#Zs.reason),this.#tr=this.#Zs.enabled&&("child"===this.#Zs.role||"both"===this.#Zs.role);const x=TraceScoutMonitoringCore.#sr,R={projectId:I.projectId,environment:I.options.environment||"production",release:I.options.release,dist:I.options.dist,debugId:I.options.debugId??readInjectedDebugId(),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.#Ks=shouldSampleSession(1,{anonymousId:A}),!this.#Ks)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.#Ns=I.sessionManager.sessionManager,this.#Le=I.sdkContext,this.#Ls=I.remoteConfigService,this.config=I.config,this.#Ps=R,this.#as=I.managers.eventManager,this.#Os=I.managers.serviceManager,this.#Ds=I.managers.userProfileManager,this.#Fs=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.#zs=new LoggingFeature({logger:this.#o,sdkContext:this.#Le,config:this.config}),this.#zs.initialize(I.serverConfig),this.#zs.configure(this.config);const x=I.serverConfig?.features?.performanceMonitoring?.enabled;if(x&&(this.#Hs=new CoreWebVitalsMonitor(this.config),console.log("[TraceScout] ✓ Performance monitoring initialized")),this.#Zs?.enabled)try{this.config.recordCrossOriginIframes=!0,this.#er=new CrossOriginIframeBridge({config:this.#Zs,core:this,projectId:this.#Le.projectId,sessionId:this.#Le.sessionId,logger:this.#o}),this.#er.start()}catch(S){this.config?.debug&&this.#o.warn?.("iframe bridge start failed (fail-closed):",S),this.#er=null}this.#Bs=new SessionRecordingFeature({logger:this.#o,sdkContext:this.#Le,config:this.config,options:{...b,childMode:this.#tr}}),this.#Bs.setCallbacks({onChunkCreated:S=>this.#Ze(S),onSessionEnd:S=>this.#nr(S),onQuotaExceeded:S=>this.#ir(S),onSpaNavigation:(S,b,I)=>{this.#js?.recordNavigation(S,b,I)}});const A=await this.#Bs.initialize(I.serverConfig,this.#Ls);if(this.#js=new PageviewManager({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Le.setPageviewManager(this.#js),this.#$s=new SessionLifecycleEmitter({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),readGuard:()=>this.#Ns?.getLifecycleGuard?.()??null,writeGuard:S=>this.#Ns?.setLifecycleGuard?.(S),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}}),this.#Ns&&!this.#tr&&(this.#Ns.onLifecycleEnd=({reason:S})=>{this.#$s?.emitEnd({reason:S})}),A&&this.#Hs){const S=this.#js.getCurrentPageviewId(),b="undefined"!=typeof window&&"string"==typeof window.location?.href?window.location.href:"";b&&(this.#qs=new WebVitalsEmitter({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,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.#Hs.addCallback?.((S,b)=>{this.#qs?.emit(S,b)}),this.#Hs.metrics&&"function"==typeof this.#Hs.metrics.forEach&&this.#Hs.metrics.forEach(S=>{this.#qs?.emit(S.type,S)}))}if(A&&(this.#Ws=new TrackIdentifyEmitter({addCustomEvent:(S,b)=>this.#Bs?.addCustomEvent(S,b),getBaseContext:()=>this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,sourceName:this.config?.sourceName,sdkVersion:this.config?.sdkVersion||"1.0.0"}),debug:(...S)=>{this.config?.debug&&this.#o.warn?.(...S)}})),A&&!this.#tr){const S=!0===this.#Ns?.isResumedSession?.();this.#js.emitInitialPageView({isResumed:S})}return!A||this.#tr||!this.#Ns||this.#Ns.isResumedSession?.()||this.#Ns.getLifecycleGuard?.()?.sessionStartEmitted||this.#$s.emitStart({}),A?(this.#ls=new InterceptorFeature({logger:this.#o,config:this.config,monitoringCore:this,eventManager:this.#as}),this.#ls.initialize(this.#Bs.recorder,this.#zs.logManager),console.log("[TraceScout] ✓ Session recording bundle initialized (DOM + Network + Console + Errors)")):console.log("[TraceScout] ⏭️ Skipping interceptors (bundled with session recording)"),this.#Us=new EventLifecycleFeature({logger:this.#o,config:this.config}),this.#Us.setCallbacks({onCustomApiError:S=>this.#xs(S),onBeforeUnload:S=>this.#Ms(S),onUserActivity:()=>this.#Rs(),onVisibilityChange:S=>this.#Ts(S)}),this.#Us.initialize(),this.#or(),this.#as&&this.#as.loadFromLocal(),this.#Ds&&this.#Ds.ensureProfile(),this.#je=!0,this.#ar(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}}#ar(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.#Le.sessionId}`),console.log(` Environment: ${this.#Le.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.#Le.sessionId})}#lr(S,b){try{const I=Object.keys(b.features||{}).filter(S=>b.features[S].enabled);S({sessionId:this.#Le.sessionId,workspace:b.workspace.name,project:b.project.name,environment:this.#Le.environment,featuresEnabled:I,configVersion:b.configVersion})}catch(S){this.#o.error("Error in onReady callback:",S)}}#Ze(S){this.#Ns&&(this.#Ns.incrementChunkCount(),this.#Ns.incrementEventCount(S.eventCount||0))}#nr(S){if(!S||"object"!=typeof S)return;const b=mapInternalEndReason(S.reason);b&&this.#$s?.emitEnd({reason:b,totalChunks:"number"==typeof S.totalChunks?S.totalChunks:void 0,totalEvents:"number"==typeof S.totalEvents?S.totalEvents:void 0})}#xs(S){}#Ms(S){}#Rs(){this.#Es||this.#Bs?.sessionEnded&&!this.#Bs?.isRecording&&(console.log("[TraceScout] 🔄 User activity detected after session end - starting new session"),this.forceNewSession("activity_after_"+this.#Bs.sessionEndReason))}#Ts(S){this.#Es||"visible"===S&&this.#Bs?.sessionEnded&&!this.#Bs?.isRecording&&(console.log("[TraceScout] 🔄 Tab visible after session end - starting new session"),this.forceNewSession("tab_focus_after_"+this.#Bs.sessionEndReason))}#ir(S){this.#Es||(this.#Es=!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.#Us?.setQuotaExceeded(!0),this.#Bs?.stop(),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("tracescout:recording_stopped",{detail:{reason:"quota_exceeded",usage:S?.usage,message:S?.message||"Session quota exceeded"}})))}#or(){"development"===this.config.environment||this.config.debug?this.#o.log("⚠️ Auto-retry DISABLED (development mode) - reduces API spam"):(this.#Qs=setInterval(()=>{this.#cr()},this.config.retryIntervalMs),this.#o.log("Auto-retry enabled (production mode)")),this.#Gs=setInterval(()=>{this.#ur()},6e4),this.#o.log("Background processes started")}#hr(){this.#Qs&&(clearInterval(this.#Qs),this.#Qs=null),this.#Gs&&(clearInterval(this.#Gs),this.#Gs=null)}async#cr(){try{if(this.#Os?.isSending)return;const S=this.#as?.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.#as.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++}}#ur(){try{if(this.#as){const S=this.config.eventMaxAge||864e5;this.#as.cleanupOldEvents(S)}}catch(S){this.#o.error("Error during cleanup:",S)}}#dr(){return"evt_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}destroy(){if(this.#je)try{try{this.#er?.shutdown()}catch(S){}this.#er=null,this.#zs?.destroy(),this.#ls?.destroy(),this.#Bs?.destroy(),this.#Us?.destroy(),this.#hr(),this.#Ns&&this.#Ns.destroy(),this.#je=!1,this.#o.info("TraceScoutMonitoringCore destroyed successfully")}catch(S){this.#o.error("Error during destruction:",S)}}logEvent(S,b={},I={}){if(this.#je)try{let x;"object"==typeof S&&S.type?(x={id:S.id||this.#dr(),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.#dr(),type:S,data:b,context:{isMonitored:!0,forceLog:I.forceLog||!1,status:I.status||"success",...I.context},timestamp:Date.now()};if(this.#as.addEvent(x)){this.#o.log("Event logged:",x.type);this.#as.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.#Os||!this.#as)return this.#o.warn("ServiceManager or EventManager not available"),!1;try{const b=S||this.#as.getEvents();if(!b||0===b.length)return!0;this.#o.info(`📤 Attempting to send ${b.length} events`);const I=await this.#Os.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.#as.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.#as?(this.#as.clearEvents(),this.#o.log("Event queue cleared")):this.#o.warn("EventManager not available")}isMonitoredEndpoint(S){if("string"!=typeof S||x.isEmpty(S))return!1;try{const b=this.config.endpoints||[],I=this.config.domainsToTrack||[];if(b.includes("*")||"*"===b)return!0;const R=S.toLowerCase();let A;try{A=new URL(R)}catch{return!1}if(!x.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&&!x.isEmpty(S)&&(!!x.isArray(this.config.fieldsToExtract)&&this.config.fieldsToExtract.some(I=>{const R=x.toLower(x.get(I,"api","")),A=x.get(I,"source","");return("*"===R||S.toLowerCase().includes(R))&&("*"===A||A===b)}))}extractUserContextFromBody({data:S,source:b="response",url:I=""}){if(!this.#Ds)return{};try{return this.#Ds.extractContextFromData({data:S,source:b,url:I})}catch(S){return this.#o.error("Failed to extract user context:",S),{}}}async startSessionRecording(S={}){return this.#Bs?.start(S)||null}stopSessionRecording(){return this.#Bs?.stop()||null}addSessionCustomEvent(S,b){if(this.#tr&&this.#er?.child)try{return!0===this.#er.child.forwardTelemetry(S,b)}catch(S){return!1}if(this.#Le&&"object"==typeof b&&null!==b){const I=this.#gr(S);if(I){let x;try{const S=this.#Le.getEventContext({release:this.config?.release,dist:this.config?.dist,debugId:this.config?.debugId,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),this.#pr(b,S);x=wrapInEnvelope(I,this.#fr(I,b),S)}catch(S){if(this.config?.debug&&this.#o.warn?.("addSessionCustomEvent: envelope build failed; skipping v1 emit:",S),"function"==typeof this.#Ps?.onError)try{this.#Ps.onError(S)}catch(S){}return!1}return this.#Bs?.addCustomEvent(S,x)||!1}}return this.#Bs?.addCustomEvent(S,b)||!1}setIframeTopFrameContext(S){this.#Xs=S&&"object"==typeof S?S:null,this.#Xs||(this.#Ys=0);try{this.#Le?.setTopFrameIdentity?.(this.#Xs)}catch(S){}}static#mr=["frameId","parentFrameId","topFrameId","frameInstanceId","frameDepth","frameOrigin","frameUrl","frameLifecycle","captureRealm","privacyStatus","bridgeProtocolVersion","localSequence","tsLocal","tsNormalized","clockOffsetMs","clockUncertaintyMs"];#pr(S,b){const I=TraceScoutMonitoringCore.#mr;if("string"==typeof S.frameId&&S.frameId.length>0){for(const x of I){const I=S[x];null!=I&&""!==I&&(b[x]=I)}return}const x=this.#Xs;if(!x)return;b.frameId=x.frameId,b.frameInstanceId=x.frameInstanceId,b.topFrameId=x.topFrameId,b.frameDepth=0,b.captureRealm="top","string"==typeof x.frameOrigin&&(b.frameOrigin=x.frameOrigin),"string"==typeof x.frameUrl&&(b.frameUrl=x.frameUrl),"string"==typeof x.frameLifecycle&&(b.frameLifecycle=x.frameLifecycle),"string"==typeof x.privacyStatus&&(b.privacyStatus=x.privacyStatus);const R="number"==typeof S.timestamp?S.timestamp:Date.now();b.localSequence=this.#Ys++,b.tsLocal=R,b.tsNormalized=R}#gr(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}}#fr(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.#Bs?.getStatus()||{available:!1,error:"Session recording not enabled"}}async getSessionEvents(S){return this.#Bs?.getEvents()||[]}exportSessionData(S="json"){if(!this.#Bs?.isAvailable)return this.#o.warn("Session recording not enabled"),null;try{const b=this.#Bs.getEvents(),I=this.#Bs.getChunks(),x=this.#Bs.getMetadata(),R=this.#Bs.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.#Bs.recorder?.recordingStartTime,endTime:this.#Bs.isRecording?null:Date.now(),duration:this.#Bs.recorder?.recordingStartTime?Date.now()-this.#Bs.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.#Bs?.getChunks()||[]}listChunks(){return(this.#Bs?.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.#Bs?.uploadQueue?.getStats()||null}getUploadQueue(){return this.#Bs?.uploadQueue?.getQueue()||null}pauseUploads(){return this.#Bs?.uploadQueue?.pause(),!0}resumeUploads(){return this.#Bs?.uploadQueue?.resume(),!0}getSessionStorageStats(){return this.#Bs?.sessionStorage?.getStorageStats()||null}getStoredSessions(){return this.#Bs?.sessionStorage?.getSessions()||{}}clearSessionStorage(){return this.#Bs?.sessionStorage?.clearAll()||!1}log(S,b,I={}){return this.#zs?.log(S,b,I)||!1}debug(S,b={}){return this.#zs?.debug(S,b)||!1}info(S,b={}){return this.#zs?.info(S,b)||!1}warn(S,b={}){return this.#zs?.warn(S,b)||!1}error(S,b={}){return this.#zs?.error(S,b)||!1}fatal(S,b={}){return this.#zs?.fatal(S,b)||!1}setLogContext(S,b){return this.#zs?.setContext(S,b)||!1}clearLogContext(){return this.#zs?.clearContext()||!1}setLogLevel(S){return this.#zs?.setLogLevel(S)||!1}getLogStats(){return this.#zs?.getStats()||null}async flushLogs(){return this.#zs?.flush()||!1}enableLogging(S,b="info"){return this.#zs?.enableServices(S,b)||!1}disableLogging(S){return this.#zs?.disableServices(S)||!1}enableAllLogging(S="info"){return this.#zs?.enableAll(S)||!1}disableAllLogging(){return this.#zs?.disableAll()||!1}getLoggingConfig(){return this.#zs?.getConfig()||null}getEnabledLogServices(){return this.#zs?.getEnabledServices()||[]}getAvailableLogServices(){return this.#zs?.getAvailableServices()||[]}setUserProfile(S){if(!this.#Ds)return this.#o.warn("UserProfileManager not available"),!1;let b=!1;try{b=!0===this.#Ds.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.#yr(b,I,{mode:"merge"},{skipUserProfileWrite:!0})}catch(S){this.#o.warn?.("Failed to route setUserProfile through identify:",S)}}return b}getUserProfile(){if(!this.#Ds)return{};try{return this.#Ds.getProfile()}catch(S){return this.#o.error("Failed to get user profile:",S),{}}}getSdkContext(){return!1===this.#Ks?{sampled:!1}:this.#Le}setUserMetadata(S,b={}){return this.identify(S,b,{mode:"merge"})}clearUserMetadata(){return!!this.#Le&&(this.#Le.clearUser(),this.#Ns&&this.#Ns.clearUserMetadata(),!0)}identify(S,b={},I={}){return this.#yr(S,b,I,{skipUserProfileWrite:!1})}#yr(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.#Le)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.#Le.userAttributes||{},$="set"===R?{}:{...U};null!==_&&($.email=_),null!==D&&($.name=D);const j=Object.assign({},$,B);if(this.#Le.setUser(S,j),this.#Ns)try{this.#Ns.updateUserMetadata(S,j)}catch(S){this.#o.warn?.("SessionManager.updateUserMetadata threw:",S)}if(!x.skipUserProfileWrite&&this.#Ds)try{this.#Ds.setProfile({userId:S,...j})}catch(S){this.#o.warn?.("UserProfileManager.setProfile threw:",S)}return this.#Ws?this.#Ws.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.#je)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.#Ws?this.#Ws.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.#je?(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.#Ns?.getSessionInfo?.()||{};return{initialized:this.#je,recording:this.#Bs?.isRecording||!1,sessionId:this.#Le?.sessionId||null,eventQueueSize:this.#as?.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.#je)return this.#o.warn("SDK not initialized"),null;if(this.#Es)return console.warn("[TraceScout] Cannot start new session - quota exceeded."),null;console.log("[TraceScout] 🔄 Forcing new session, reason:",S),this.#Bs?.stop(),this.#Ns&&this.#Ns.forceNewSession(S);const b=this.#Ns?.getOrCreateSession({projectId:this.#Le.projectId,environment:this.#Le.environment,userId:this.#Le.userId});if(this.#Le&&b&&(this.#Le.sessionId=b,this.#Le.sessionStartTime=Date.now()),this.#Bs&&b){this.#Bs.updateSessionId(b);const S=this.config.apiBaseUrl||"http://localhost:3001";this.#Bs.updateUploadEndpoint(`${S}/api/projects/${this.#Le.projectId}/sessions/${b}/chunks`),this.#Bs.recorder?.start()}return b}debugMode(S){this.config.debug=S,this.#o.updateDebugMode(S),this.#Os&&this.#Os.updateDebugMode(S),this.#ls?.updateDebugMode(S),this.#o.log("Debug mode "+(S?"enabled":"disabled"))}getQueueStatus(){return{queueSize:this.#as?this.#as.getQueueSize():0,isSending:!!this.#Os&&this.#Os.isSending,isInitialized:this.#je,service:this.#Os?this.#Os.getServiceName():"none",configSource:this.config?.configSource||"local",configVersion:this.config?.configVersion||"local"}}getPerformanceMetrics(){return this.#Fs?.getMetrics()||null}getCoreWebVitalsMonitor(){return this.#Hs}getCoreWebVitalsMetrics(){return this.#Hs?.getAllMetrics()||null}getCoreWebVitalsInsights(){return this.#Hs?.getPerformanceInsights()||null}generateCoreWebVitalsReport(){return this.#Hs?.generateReport()||null}updateCoreWebVitalsThresholds(S){this.#Hs?this.#Hs.updateThresholds(S):this.#o.warn("Core Web Vitals monitor not available")}}let it;try{it=new TraceScoutMonitoringCore}catch(S){it={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=it}catch(S){}var ot=it;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}}}function parseRequestUrl(S){try{return new URL(S,location.origin)}catch(S){return null}}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.#vr(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.#Sr(),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.#wr();return this.config=b,b}}#vr(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")}#wr(){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}}}}}#Sr(){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}}function __tsSafeContentDoc(S){try{if(S&&"IFRAME"===S.tagName&&S.src)try{var b=new URL(S.src);if(("http:"===b.protocol||"https:"===b.protocol)&&"undefined"!=typeof location&&b.origin!==location.origin)return null}catch(S){}return S.contentDocument}catch(S){return null}}var at,lt=Object.defineProperty,__publicField=(S,b,I)=>((S,b,I)=>b in S?lt(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),ct=Object.defineProperty,__publicField$1=(S,b,I)=>((S,b,I)=>b in S?ct(S,b,{enumerable:!0,configurable:!0,writable:!0,value:I}):S[b]=I)(S,"symbol"!=typeof b?b+"":b,I),ut=(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))(ut||{});const ht={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},dt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},gt={};function getUntaintedPrototype$1(S){if(gt[S])return gt[S];const b=globalThis[S],I=b.prototype,x=S in ht?ht[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 dt?dt[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 gt[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?gt[S]=A:I}catch{return I}}const pt={};function getUntaintedAccessor$1(S,b,I){var x;const R=`${S}.${String(I)}`;if(pt[R])return pt[R].call(b);const A=getUntaintedPrototype$1(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(pt[R]=_,_.call(b)):b[I]}const ft={};function getUntaintedMethod$1(S,b,I){const x=`${S}.${String(I)}`;if(ft[x])return ft[x].bind(b);const R=getUntaintedPrototype$1(S)[I];return"function"!=typeof R?b[I]:(ft[x]=R,R.bind(b))}const mt={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&&mt.host(S)||null;return Boolean(b&&"shadowRoot"in b&&mt.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 yt="__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 vt=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,St=/^(?:[a-z+]+:)?\/\//i,wt=/^www\..*/i,bt=/^(data:)([^,]*),(.*)/i;function absolutifyURLs(S,b){return(S||"").replace(vt,(S,I,x,R,A,_)=>{const D=x||A||_,L=I||R||"";if(!D)return S;if(St.test(D)||wt.test(D))return`url(${L}${D}${L})`;if(bt.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 kt=new RegExp("[^a-z0-9-_:]");function genId(){return Ct++}let It,Et;const xt=/^[^ \t\n\r\u000c]+/,Mt=/^[, \t\n\r\u000c]+/;const Rt=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=Rt.get(S);if(I||(I=S.createElement("a"),Rt.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(Mt),!(I>=b.length);){let R=collectCharacters(xt);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(mt.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(mt.parentNode(S),b,I)}function needMaskingText(S,b,I,x){let R;if(isElement(S)){if(R=S,!mt.childNodes(R).length)return!1}else{if(null===mt.parentElement(S))return!1;R=mt.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:ut.Document,childNodes:[],compatMode:S.compatMode}:{type:ut.Document,childNodes:[]};case S.DOCUMENT_TYPE_NODE:return{type:ut.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 kt.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=yt in R?R[yt]: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){It||(It=I.createElement("canvas"),Et=It.getContext("2d"));const b=S,x=b.currentSrc||b.getAttribute("src")||"<unknown-src>",R=b.crossOrigin,recordInlineImage=()=>{b.removeEventListener("load",recordInlineImage);try{It.width=b.naturalWidth,It.height=b.naturalHeight,Et.drawImage(b,0,0),Q.rr_dataURL=It.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)||(__tsSafeContentDoc(S)||(Q.rr_src=Q.src),delete Q.src);let J;try{customElements.get(V)&&(J=!0)}catch(S){}return{type:ut.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,_=mt.parentNode(S),D=_&&_.tagName;let L="";const B="STYLE"===D||void 0,U="SCRIPT"===D||void 0;U?L="SCRIPT_PLACEHOLDER":A||(L=mt.textContent(S),B&&L&&(L=absolutifyURLs(L,getHref(b.doc))));!B&&!U&&L&&I&&(L=x?x(L,mt.parentElement(S)):L.replace(/[\S]/g,"*"));return{type:ut.Text,textContent:L||"",rootId:R}}(S,{doc:I,needsMask:_,maskTextFn:B,rootId:G,cssCaptured:Q});case S.CDATA_SECTION_NODE:return{type:ut.CDATA,textContent:"",rootId:G};case S.COMMENT_NODE:return{type:ut.Comment,textContent:mt.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===ut.Comment)return!0;if(S.type===ut.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===ut.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===ut.Element){ce=ce&&!le.needBlock,delete le.needBlock;const b=mt.shadowRoot(S);b&&isNativeShadowDom(b)&&(le.isShadowHost=!0)}if((le.type===ut.Document||le.type===ut.Element)&&ce){W.headWhitespace&&le.type===ut.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===ut.Element&&"textarea"===le.tagName&&void 0!==le.attributes.value);else{le.type===ut.Element&&void 0!==le.attributes._cssText&&"string"==typeof le.attributes._cssText&&(b.cssCaptured=!0);for(const I of Array.from(mt.childNodes(S))){const S=serializeNodeWithId(I,b);S&&le.childNodes.push(S)}}let se=null;if(isElement(S)&&(se=mt.shadowRoot(S)))for(const S of Array.from(mt.childNodes(se))){const I=serializeNodeWithId(S,b);I&&(isNativeShadowDom(se)&&(I.isShadow=!0),le.childNodes.push(I))}}const ue=mt.parentNode(S);return ue&&isShadowRoot(ue)&&isNativeShadowDom(ue)&&(le.isShadow=!0),le.type===ut.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=__tsSafeContentDoc(S);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===ut.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 Tt={exports:{}},At=String,create$1=function(){return{isColorSupported:!1,reset:At,bold:At,dim:At,italic:At,underline:At,inverse:At,hidden:At,strikethrough:At,black:At,red:At,green:At,yellow:At,blue:At,magenta:At,cyan:At,white:At,gray:At,bgBlack:At,bgRed:At,bgGreen:At,bgYellow:At,bgBlue:At,bgMagenta:At,bgCyan:At,bgWhite:At}};Tt.exports=create$1(),Tt.exports.createColors=create$1;var _t=Tt.exports;const Ot=getAugmentedNamespace$1(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Dt=_t,Ft=Ot,Nt=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=Dt.isColorSupported),Ft&&S&&(b=Ft(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}=Dt.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 Lt=Nt;Nt.default=Nt;var Pt={};Pt.isClean=Symbol("isClean"),Pt.my=Symbol("my");const Bt={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let zt=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 Bt[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=Bt[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 Ut=zt;zt.default=zt;let $t=Ut;function stringify$4$1(S,b){new $t(b).stringify(S)}var jt=stringify$4$1;stringify$4$1.default=stringify$4$1;let{isClean:qt,my:Wt}=Pt,Ht=Lt,Vt=Ut,Qt=jt;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 Gt=class Node2{constructor(S={}){this.raws={},this[qt]=!1,this[Wt]=!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 Ht(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[qt]){this[qt]=!1;let S=this;for(;S=S.parent;)S[qt]=!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 Vt).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=Qt){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 Kt=Gt;Gt.default=Gt;let Jt=Kt,Xt=class Declaration extends Jt{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 Yt=Xt;Xt.default=Xt;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:es,SourceMapGenerator:ts}=Ot,{existsSync:ss,readFileSync:rs}=Ot,{dirname:ns,join:is}=Ot;let os=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=ns(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new es(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=ns(S),ss(S))return this.mapFile=S,rs(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 es)return ts.fromSourceMap(b).toString();if(b instanceof ts)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=is(ns(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 as=os;os.default=os;let{SourceMapConsumer:ls,SourceMapGenerator:cs}=Ot,{fileURLToPath:us,pathToFileURL:hs}=Ot,{isAbsolute:ds,resolve:gs}=Ot,{nanoid:ps}=Zt,fs=Ot,ms=Lt,ys=as,vs=Symbol("fromOffsetCache"),Ss=Boolean(ls&&cs),ws=Boolean(gs&&ds),bs=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&&(!ws||/^\w+:\/\//.test(b.from)||ds(b.from)?this.file=b.from:this.file=gs(b.from)),ws&&Ss){let S=new ys(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 "+ps(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 ms(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 ms(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&&(hs&&(R.input.url=hs(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[vs])I=this[vs];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[vs]=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:gs(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=ds(D.source)?hs(D.source):new URL(D.source,this.map.consumer().sourceRoot||hs(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(!us)throw new Error("file: protocol is not available in this PostCSS build");L.file=us(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=bs;bs.default=bs,fs&&fs.registerInput&&fs.registerInput(bs);let{SourceMapConsumer:ks,SourceMapGenerator:Is}=Ot,{dirname:Es,relative:xs,resolve:Ms,sep:Rs}=Ot,{pathToFileURL:Ts}=Ot,As=Cs,_s=Boolean(ks&&Is),Os=Boolean(Es&&Ms&&xs&&Rs);var Ds=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||Es(S.file);!1===this.mapOpts.sourcesContent?(b=new ks(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(),Os&&_s&&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=Is.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Is({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 Is({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?Es(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=Es(Ms(I,this.mapOpts.annotation)));let x=xs(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 As(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(Ts){let b=Ts(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;"\\"===Rs&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let Fs=Kt,Ns=class Comment extends Fs{constructor(S){super(S),this.type="comment"}};var Ls=Ns;Ns.default=Ns;let Ps,Bs,zs,Us,{isClean:$s,my:js}=Pt,qs=Yt,Ws=Ls,Hs=Kt;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[$s]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp$1(b)}let Vs=class Container extends Hs{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(Ps(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 qs(S)]}else if(S.selector)S=[new Bs(S)];else if(S.name)S=[new zs(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new Ws(S)]}return S.map(S=>(S[js]||Container.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[$s]&&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]}};Vs.registerParse=S=>{Ps=S},Vs.registerRule=S=>{Bs=S},Vs.registerAtRule=S=>{zs=S},Vs.registerRoot=S=>{Us=S};var Qs=Vs;Vs.default=Vs,Vs.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,zs.prototype):"rule"===S.type?Object.setPrototypeOf(S,Bs.prototype):"decl"===S.type?Object.setPrototypeOf(S,qs.prototype):"comment"===S.type?Object.setPrototypeOf(S,Ws.prototype):"root"===S.type&&Object.setPrototypeOf(S,Us.prototype),S[js]=!0,S.nodes&&S.nodes.forEach(S=>{Vs.rebuild(S)})};let Gs,Ks,Js=Qs,Xs=class Document2 extends Js{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Gs(new Ks,this,S).stringify()}};Xs.registerLazyResult=S=>{Gs=S},Xs.registerProcessor=S=>{Ks=S};var Ys=Xs;Xs.default=Xs;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 er=Zs;Zs.default=Zs;let tr=er,sr=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 tr(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var rr=sr;sr.default=sr;const nr="'".charCodeAt(0),ir='"'.charCodeAt(0),or="\\".charCodeAt(0),ar="/".charCodeAt(0),lr="\n".charCodeAt(0),cr=" ".charCodeAt(0),ur="\f".charCodeAt(0),hr="\t".charCodeAt(0),dr="\r".charCodeAt(0),gr="[".charCodeAt(0),pr="]".charCodeAt(0),fr="(".charCodeAt(0),mr=")".charCodeAt(0),yr="{".charCodeAt(0),vr="}".charCodeAt(0),Sr=";".charCodeAt(0),wr="*".charCodeAt(0),br=":".charCodeAt(0),Cr="@".charCodeAt(0),kr=/[\t\n\f\r "#'()/;[\\\]{}]/g,Ir=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Er=/.[\r\n"'(/\\]/,xr=/[\da-f]/i;let Mr=Qs,Rr=class AtRule extends Mr{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 Tr=Rr;Rr.default=Rr,Mr.registerAtRule(Rr);let Ar,_r,Or=Qs,Dr=class Root extends Or{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 Ar(new _r,this,S).stringify()}};Dr.registerLazyResult=S=>{Ar=S},Dr.registerProcessor=S=>{_r=S};var Fr=Dr;Dr.default=Dr,Or.registerRoot(Dr);let Nr={comma:S=>Nr.split(S,[","],!0),space:S=>Nr.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 Lr=Nr;Nr.default=Nr;let Pr=Qs,Br=Lr,zr=class Rule extends Pr{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Br.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 Ur=zr;zr.default=zr,Pr.registerRule(zr);let $r=Yt,jr=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 lr:case cr:case hr:case dr:case ur:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===cr||I===lr||I===hr||I===dr||I===ur);$=["space",j.slice(V,x)],V=x-1;break;case gr:case pr:case yr:case vr:case br:case Sr:case mr:{let S=String.fromCharCode(I);$=[S,S,V];break}case fr:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==nr&&U!==ir&&U!==cr&&U!==lr&&U!==hr&&U!==ur&&U!==dr){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)===or;)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||Er.test(A)?$=["(","(",V]:($=["brackets",A,V,x],V=x);break;case nr:case ir:R=I===nr?"'":'"',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)===or;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Cr:kr.lastIndex=V+1,kr.test(j),x=0===kr.lastIndex?j.length-1:kr.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case or:for(x=V,_=!0;j.charCodeAt(x+1)===or;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==ar&&I!==cr&&I!==lr&&I!==hr&&I!==dr&&I!==ur&&(x+=1,xr.test(j.charAt(x)))){for(;xr.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===cr&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===ar&&j.charCodeAt(V+1)===wr?(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):(Ir.lastIndex=V+1,Ir.test(j),x=0===Ir.lastIndex?j.length-1:Ir.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},qr=Ls,Wr=Tr,Hr=Fr,Vr=Ur;const Qr={empty:!0,space:!0};var Gr=class Parser{constructor(S){this.input=S,this.root=new Hr,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 Wr;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 qr;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=jr(this.input)}decl(S,b){let I=new $r;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 Vr;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",Qr[D]||Qr[_]||","===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 Vr;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 Kr=Qs,Jr=Gr,Xr=Cs;function parse$3$1(S,b){let I=new Xr(S,b),x=new Jr(I);try{x.parse()}catch(S){throw S}return x.root}var Yr=parse$3$1;parse$3$1.default=parse$3$1,Kr.registerParse(parse$3$1);let{isClean:Zr,my:en}=Pt,tn=Ds,sn=jt,rn=Qs,nn=Ys,an=rr,cn=Yr,un=Fr;const hn={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},dn={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},gn={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=hn[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 pn={},fn=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 an)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=cn;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[en]&&rn.rebuild(x)}else x=cleanMarks$1(b);this.result=new an(S,x,I),this.helpers={...pn,postcss:pn,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(!dn[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!gn[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=sn;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new tn(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"}};fn.registerPostcss=S=>{pn=S};var mn=fn;fn.default=fn,un.registerLazyResult(fn),nn.registerLazyResult(fn);let yn=Ds,vn=jt,Sn=Yr;const wn=rr;let bn=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=vn;this.result=new wn(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new yn(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 Cn=bn;bn.default=bn;let kn=Cn,In=mn,En=Ys,xn=Fr,Mn=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 In(this,S,b):new kn(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var Rn=Mn;Mn.default=Mn,xn.registerProcessor(Mn),En.registerProcessor(Mn);let Tn=Yt,An=as,_n=Ls,On=Tr,Dn=Cs,Fn=Fr,Nn=Ur;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__:Dn.prototype};I.map&&(I.map={...I.map,__proto__:An.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 Fn(x);if("decl"===x.type)return new Tn(x);if("rule"===x.type)return new Nn(x);if("comment"===x.type)return new _n(x);if("atrule"===x.type)return new On(x);throw new Error("Unknown node type: "+S.type)}var Ln=fromJSON$1$1;fromJSON$1$1.default=fromJSON$1$1;let Pn=Lt,Bn=Yt,zn=mn,Un=Qs,$n=Rn,jn=jt,qn=Ln,Wn=Ys,Hn=er,Vn=Ls,Qn=Tr,Gn=rr,Kn=Cs,Jn=Yr,Xn=Lr,Yn=Ur,Zn=Fr,ei=Kt;function postcss$3(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new $n(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 $n).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=jn,postcss$3.parse=Jn,postcss$3.fromJSON=qn,postcss$3.list=Xn,postcss$3.comment=S=>new Vn(S),postcss$3.atRule=S=>new Qn(S),postcss$3.decl=S=>new Bn(S),postcss$3.rule=S=>new Yn(S),postcss$3.root=S=>new Zn(S),postcss$3.document=S=>new Wn(S),postcss$3.CssSyntaxError=Pn,postcss$3.Declaration=Bn,postcss$3.Container=Un,postcss$3.Processor=$n,postcss$3.Document=Wn,postcss$3.Comment=Vn,postcss$3.Warning=Hn,postcss$3.AtRule=Qn,postcss$3.Result=Gn,postcss$3.Input=Kn,postcss$3.Rule=Yn,postcss$3.Root=Zn,postcss$3.Node=ei,zn.registerPostcss(postcss$3),postcss$3.default=postcss$3;var ti=Object.defineProperty,__publicField2=(S,b,I)=>((S,b,I)=>b in S?ti(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 si={exports:{}},ri=String,create=function(){return{isColorSupported:!1,reset:ri,bold:ri,dim:ri,italic:ri,underline:ri,inverse:ri,hidden:ri,strikethrough:ri,black:ri,red:ri,green:ri,yellow:ri,blue:ri,magenta:ri,cyan:ri,white:ri,gray:ri,bgBlack:ri,bgRed:ri,bgGreen:ri,bgYellow:ri,bgBlue:ri,bgMagenta:ri,bgCyan:ri,bgWhite:ri}};si.exports=create(),si.exports.createColors=create;var ni=si.exports;const ii=getAugmentedNamespace(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let oi=ni,ai=ii,li=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=oi.isColorSupported),ai&&S&&(b=ai(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}=oi.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 ci=li;li.default=li;var ui={};ui.isClean=Symbol("isClean"),ui.my=Symbol("my");const hi={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let di=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 hi[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=hi[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 gi=di;di.default=di;let pi=gi;function stringify$4(S,b){new pi(b).stringify(S)}var fi=stringify$4;stringify$4.default=stringify$4;let{isClean:mi,my:yi}=ui,vi=ci,Si=gi,wi=fi;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 bi=class Node3{constructor(S={}){this.raws={},this[mi]=!1,this[yi]=!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 vi(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[mi]){this[mi]=!1;let S=this;for(;S=S.parent;)S[mi]=!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 Si).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=wi){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=bi;bi.default=bi;let ki=Ci,Ii=class Declaration2 extends ki{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 Ei=Ii;Ii.default=Ii;var xi={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:Mi,SourceMapGenerator:Ri}=ii,{existsSync:Ti,readFileSync:Ai}=ii,{dirname:_i,join:Oi}=ii;let Di=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=_i(this.mapFile)),x&&(this.text=x)}consumer(){return this.consumerCache||(this.consumerCache=new Mi(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=_i(S),Ti(S))return this.mapFile=S,Ai(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 Mi)return Ri.fromSourceMap(b).toString();if(b instanceof Ri)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=Oi(_i(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 Fi=Di;Di.default=Di;let{SourceMapConsumer:Ni,SourceMapGenerator:Li}=ii,{fileURLToPath:Pi,pathToFileURL:Bi}=ii,{isAbsolute:zi,resolve:Ui}=ii,{nanoid:$i}=xi,ji=ii,qi=ci,Wi=Fi,Hi=Symbol("fromOffsetCache"),Vi=Boolean(Ni&&Li),Qi=Boolean(Ui&&zi),Gi=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&&(!Qi||/^\w+:\/\//.test(b.from)||zi(b.from)?this.file=b.from:this.file=Ui(b.from)),Qi&&Vi){let S=new Wi(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 "+$i(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 qi(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 qi(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&&(Bi&&(R.input.url=Bi(this.file).toString()),R.input.file=this.file),R}fromOffset(S){let b,I;if(this[Hi])I=this[Hi];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[Hi]=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:Ui(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=zi(D.source)?Bi(D.source):new URL(D.source,this.map.consumer().sourceRoot||Bi(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(!Pi)throw new Error("file: protocol is not available in this PostCSS build");L.file=Pi(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 Ki=Gi;Gi.default=Gi,ji&&ji.registerInput&&ji.registerInput(Gi);let{SourceMapConsumer:Ji,SourceMapGenerator:Xi}=ii,{dirname:Yi,relative:Zi,resolve:eo,sep:to}=ii,{pathToFileURL:so}=ii,ro=Ki,no=Boolean(Ji&&Xi),io=Boolean(Yi&&eo&&Zi&&to);var oo=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||Yi(S.file);!1===this.mapOpts.sourcesContent?(b=new Ji(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(),io&&no&&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=Xi.fromSourceMap(S,{ignoreInvalidMapping:!0})}else this.map=new Xi({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 Xi({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?Yi(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(I=Yi(eo(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 ro(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(so){let b=so(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;"\\"===to&&(S=S.replace(/\\/g,"/"));let I=encodeURI(S).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(S,I),I}};let ao=Ci,lo=class Comment2 extends ao{constructor(S){super(S),this.type="comment"}};var co=lo;lo.default=lo;let uo,ho,go,po,{isClean:fo,my:mo}=ui,yo=Ei,vo=co,So=Ci;function cleanSource(S){return S.map(S=>(S.nodes&&(S.nodes=cleanSource(S.nodes)),delete S.source,S))}function markDirtyUp(S){if(S[fo]=!1,S.proxyOf.nodes)for(let b of S.proxyOf.nodes)markDirtyUp(b)}let wo=class Container2 extends So{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(uo(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 yo(S)]}else if(S.selector)S=[new ho(S)];else if(S.name)S=[new go(S)];else{if(!S.text)throw new Error("Unknown node type in node creation");S=[new vo(S)]}return S.map(S=>(S[mo]||Container2.rebuild(S),(S=S.proxyOf).parent&&S.parent.removeChild(S),S[fo]&&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]}};wo.registerParse=S=>{uo=S},wo.registerRule=S=>{ho=S},wo.registerAtRule=S=>{go=S},wo.registerRoot=S=>{po=S};var bo=wo;wo.default=wo,wo.rebuild=S=>{"atrule"===S.type?Object.setPrototypeOf(S,go.prototype):"rule"===S.type?Object.setPrototypeOf(S,ho.prototype):"decl"===S.type?Object.setPrototypeOf(S,yo.prototype):"comment"===S.type?Object.setPrototypeOf(S,vo.prototype):"root"===S.type&&Object.setPrototypeOf(S,po.prototype),S[mo]=!0,S.nodes&&S.nodes.forEach(S=>{wo.rebuild(S)})};let Co,ko,Io=bo,Eo=class Document23 extends Io{constructor(S){super({type:"document",...S}),this.nodes||(this.nodes=[])}toResult(S={}){return new Co(new ko,this,S).stringify()}};Eo.registerLazyResult=S=>{Co=S},Eo.registerProcessor=S=>{ko=S};var xo=Eo;Eo.default=Eo;let Mo=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 Ro=Mo;Mo.default=Mo;let To=Ro,Ao=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 To(S,b);return this.messages.push(I),I}warnings(){return this.messages.filter(S=>"warning"===S.type)}get content(){return this.css}};var _o=Ao;Ao.default=Ao;const Oo="'".charCodeAt(0),Do='"'.charCodeAt(0),Fo="\\".charCodeAt(0),No="/".charCodeAt(0),Lo="\n".charCodeAt(0),Po=" ".charCodeAt(0),Bo="\f".charCodeAt(0),zo="\t".charCodeAt(0),Uo="\r".charCodeAt(0),$o="[".charCodeAt(0),jo="]".charCodeAt(0),qo="(".charCodeAt(0),Wo=")".charCodeAt(0),Ho="{".charCodeAt(0),Vo="}".charCodeAt(0),Qo=";".charCodeAt(0),Go="*".charCodeAt(0),Ko=":".charCodeAt(0),Jo="@".charCodeAt(0),Xo=/[\t\n\f\r "#'()/;[\\\]{}]/g,Yo=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Zo=/.[\r\n"'(/\\]/,ea=/[\da-f]/i;let ta=bo,sa=class AtRule2 extends ta{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 ra=sa;sa.default=sa,ta.registerAtRule(sa);let na,ia,oa=bo,aa=class Root2 extends oa{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 na(new ia,this,S).stringify()}};aa.registerLazyResult=S=>{na=S},aa.registerProcessor=S=>{ia=S};var la=aa;aa.default=aa,oa.registerRoot(aa);let ca={comma:S=>ca.split(S,[","],!0),space:S=>ca.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 ua=ca;ca.default=ca;let ha=bo,da=ua,ga=class Rule2 extends ha{constructor(S){super(S),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return da.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 pa=ga;ga.default=ga,ha.registerRule(ga);let fa=Ei,ma=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 Lo:case Po:case zo:case Uo:case Bo:x=V;do{x+=1,I=j.charCodeAt(x)}while(I===Po||I===Lo||I===zo||I===Uo||I===Bo);$=["space",j.slice(V,x)],V=x-1;break;case $o:case jo:case Ho:case Vo:case Ko:case Qo:case Wo:{let S=String.fromCharCode(I);$=[S,S,V];break}case qo:if(B=Q.length?Q.pop()[1]:"",U=j.charCodeAt(V+1),"url"===B&&U!==Oo&&U!==Do&&U!==Po&&U!==Lo&&U!==zo&&U!==Bo&&U!==Uo){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)===Fo;)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 Oo:case Do:R=I===Oo?"'":'"',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)===Fo;)L-=1,D=!D}while(D);$=["string",j.slice(V,x+1),V,x],V=x;break;case Jo:Xo.lastIndex=V+1,Xo.test(j),x=0===Xo.lastIndex?j.length-1:Xo.lastIndex-2,$=["at-word",j.slice(V,x+1),V,x],V=x;break;case Fo:for(x=V,_=!0;j.charCodeAt(x+1)===Fo;)x+=1,_=!_;if(I=j.charCodeAt(x+1),_&&I!==No&&I!==Po&&I!==Lo&&I!==zo&&I!==Uo&&I!==Bo&&(x+=1,ea.test(j.charAt(x)))){for(;ea.test(j.charAt(x+1));)x+=1;j.charCodeAt(x+1)===Po&&(x+=1)}$=["word",j.slice(V,x+1),V,x],V=x;break;default:I===No&&j.charCodeAt(V+1)===Go?(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):(Yo.lastIndex=V+1,Yo.test(j),x=0===Yo.lastIndex?j.length-1:Yo.lastIndex-2,$=["word",j.slice(V,x+1),V,x],Q.push($),V=x)}return V++,$},position:function position(){return V}}},ya=co,va=ra,Sa=la,wa=pa;const ba={empty:!0,space:!0};var Ca=class Parser2{constructor(S){this.input=S,this.root=new Sa,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 va;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 ya;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=ma(this.input)}decl(S,b){let I=new fa;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 wa;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",ba[D]||ba[_]||","===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 wa;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 ka=bo,Ia=Ca,Ea=Ki;function parse$3(S,b){let I=new Ea(S,b),x=new Ia(I);try{x.parse()}catch(S){throw S}return x.root}var xa=parse$3;parse$3.default=parse$3,ka.registerParse(parse$3);let{isClean:Ma,my:Ra}=ui,Ta=oo,Aa=fi,_a=bo,Oa=xo,Da=_o,Fa=xa,Na=la;const La={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},Pa={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},Ba={Once:!0,postcssPlugin:!0,prepare:!0};function isPromise(S){return"object"==typeof S&&"function"==typeof S.then}function getEvents(S){let b=!1,I=La[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[Ma]=!1,S.nodes&&S.nodes.forEach(S=>cleanMarks(S)),S}let za={},Ua=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 Da)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=Fa;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[Ra]&&_a.rebuild(x)}else x=cleanMarks(b);this.result=new Da(S,x,I),this.helpers={...za,postcss:za,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(!Pa[b]&&/^[A-Z]/.test(b))throw new Error(`Unknown event ${b} in ${S.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Ba[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[Ma];){S[Ma]=!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=Aa;S.syntax&&(b=S.syntax.stringify),S.stringifier&&(b=S.stringifier),b.stringify&&(b=b.stringify);let I=new Ta(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[Ma];)S[Ma]=!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[Ma])return x[Ma]=!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[Ma]=!0,b.iterator=I.getIterator()));if(this.listeners[S])return void(b.visitors=this.listeners[S])}S.pop()}walkSync(S){S[Ma]=!0;let b=getEvents(S);for(let I of b)if(0===I)S.nodes&&S.each(S=>{S[Ma]||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"}};Ua.registerPostcss=S=>{za=S};var $a=Ua;Ua.default=Ua,Na.registerLazyResult(Ua),Oa.registerLazyResult(Ua);let ja=oo,qa=fi,Wa=xa;const Ha=_o;let Va=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=qa;this.result=new Ha(this._processor,x,this._opts),this.result.css=b;let A=this;Object.defineProperty(this.result,"root",{get:()=>A.root});let _=new ja(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=Wa;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 Qa=Va;Va.default=Va;let Ga=Qa,Ka=$a,Ja=xo,Xa=la,Ya=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 Ka(this,S,b):new Ga(this,S,b)}use(S){return this.plugins=this.plugins.concat(this.normalize([S])),this}};var Za=Ya;Ya.default=Ya,Xa.registerProcessor(Ya),Ja.registerProcessor(Ya);let el=Ei,tl=Fi,sl=co,rl=ra,nl=Ki,il=la,ol=pa;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__:nl.prototype};I.map&&(I.map={...I.map,__proto__:tl.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 il(x);if("decl"===x.type)return new el(x);if("rule"===x.type)return new ol(x);if("comment"===x.type)return new sl(x);if("atrule"===x.type)return new rl(x);throw new Error("Unknown node type: "+S.type)}var al=fromJSON$1;fromJSON$1.default=fromJSON$1;let ll=ci,cl=Ei,ul=$a,hl=bo,dl=Za,gl=fi,pl=al,fl=xo,ml=Ro,yl=co,vl=ra,Sl=_o,wl=Ki,bl=xa,Cl=ua,kl=pa,Il=la,El=Ci;function postcss(...S){return 1===S.length&&Array.isArray(S[0])&&(S=S[0]),new dl(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 dl).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=gl,postcss.parse=bl,postcss.fromJSON=pl,postcss.list=Cl,postcss.comment=S=>new yl(S),postcss.atRule=S=>new vl(S),postcss.decl=S=>new cl(S),postcss.rule=S=>new kl(S),postcss.root=S=>new Il(S),postcss.document=S=>new fl(S),postcss.CssSyntaxError=ll,postcss.Declaration=cl,postcss.Container=hl,postcss.Processor=dl,postcss.Document=fl,postcss.Comment=yl,postcss.Warning=ml,postcss.AtRule=vl,postcss.Result=Sl,postcss.Input=wl,postcss.Rule=kl,postcss.Root=Il,postcss.Node=El,ul.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 xl={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Ml={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Rl={};function getUntaintedPrototype(S){if(Rl[S])return Rl[S];const b=globalThis[S],I=b.prototype,x=S in xl?xl[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 Ml?Ml[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 Rl[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?Rl[S]=A:I}catch{return I}}const Tl={};function getUntaintedAccessor(S,b,I){var x;const R=`${S}.${String(I)}`;if(Tl[R])return Tl[R].call(b);const A=getUntaintedPrototype(S),_=null==(x=Object.getOwnPropertyDescriptor(A,I))?void 0:x.get;return _?(Tl[R]=_,_.call(b)):b[I]}const Al={};function getUntaintedMethod(S,b,I){const x=`${S}.${String(I)}`;if(Al[x])return Al[x].bind(b);const R=getUntaintedPrototype(S)[I];return"function"!=typeof R?b[I]:(Al[x]=R,R.bind(b))}function mutationObserverCtor(){return getUntaintedPrototype("MutationObserver").constructor}const _l={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 Ol="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 Dl={map:{},getId:()=>(console.error(Ol),-1),getNode:()=>(console.error(Ol),null),removeNodeFromMap(){console.error(Ol)},has:()=>(console.error(Ol),!1),reset(){console.error(Ol)}};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&&(Dl=new Proxy(Dl,{get:(S,b,I)=>("map"===b&&console.error(Ol),Reflect.get(S,b,I))}));let Fl=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=_l.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=_l.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:_l.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=_l.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(_l.shadowRoot(S)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(Fl=()=>(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=_l.getRootNode(S))?void 0:b.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&_l.host(_l.getRootNode(S))&&(I=_l.host(_l.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 _l.contains(b,I)}function inDom(S){const b=S.ownerDocument;return!!b&&(_l.contains(b,S)||shadowHostInDom(S))}var Nl=(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))(Nl||{}),Ll=(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))(Ll||{}),Pl=(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))(Pl||{}),Bl=(S=>(S[S.Mouse=0]="Mouse",S[S.Pen=1]="Pen",S[S.Touch=2]="Touch",S))(Bl||{}),zl=(S=>(S[S["2D"]=0]="2D",S[S.WebGL=1]="WebGL",S[S.WebGL2=2]="WebGL2",S))(zl||{}),Ul=(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))(Ul||{}),$l=(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))($l||{});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=_l.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(_l.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(_l.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(_l.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(_l.parentNode(I.value));if(-1===getNextId(I.value))continue;if(-1!==b){S=I;break}{const b=I.value,x=_l.parentNode(b);if(x&&x.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const b=_l.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=_l.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(_l.childNodes(S),S=>_l.textContent(S)||"").join("")}),__publicField(this,"processMutation",S=>{if(!isIgnored(S.target,this.mirror,this.slimDOMOptions))switch(S.type){case"characterData":{const b=_l.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(__tsSafeContentDoc(b))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(_l.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),_l.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)||(_l.childNodes(S).forEach(S=>this.genAdds(S)),hasShadowRoot(S)&&_l.childNodes(_l.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),_l.childNodes(b).forEach(b=>deepDelete(S,b))}function isParentRemoved(S,b,I){return 0!==S.size&&function _isParentRemoved(S,b,I){const x=_l.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=_l.parentNode(b);return!!I&&(!!S.has(I)||_isAncestorInSet(S,I))}let jl;const callbackWrapper=S=>{if(!jl)return S;return(...b)=>{try{return S(...b)}catch(S){if(jl&&!0===jl(S))return;throw S}}},ql=[];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;ql.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(Pl).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=Bl.Mouse;break;case"touch":D=Bl.Touch;break;case"pen":D=Bl.Pen}D===Bl.Touch&&(Pl[b]===Pl.MouseDown?B="TouchStart":Pl[b]===Pl.MouseUp&&(B="TouchEnd"))}else legacy_isTouchEvent(A)&&(D=Bl.Touch);null!==D?(L=D,(B.startsWith("Touch")&&D===Bl.Touch||B.startsWith("Mouse")&&D===Bl.Mouse)&&(D=null)):Pl[b]===Pl.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:Pl[B],id:$,x:j,y:W,...null!==D&&{pointerType:D}})})(A);if(window.PointerEvent)switch(Pl[A]){case Pl.MouseDown:case Pl.MouseUp:_=_.replace("mouse","pointer");break;case Pl.TouchStart:case Pl.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 Wl=["INPUT","TEXTAREA","SELECT"],Hl=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(_l.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;_||(_=Fl()),D.push({x:I,y:R,id:x.getId(b),timeOffset:Fl()-_}),L("undefined"!=typeof DragEvent&&S instanceof DragEvent?Ll.Drag:S instanceof MouseEvent?Ll.MouseMove:Ll.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=_l.parentElement(I)),!I||!$||Wl.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=Hl.get(b);if(!R||R.text!==x.text||R.isChecked!==x.isChecked){Hl.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",_(Ul.Play),A),on("pause",_(Ul.Pause),A),on("seeked",_(Ul.Seeked),A),on("volumechange",_(Ul.VolumeChange),A),on("ratechange",_(Ul.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(()=>{ql.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.__TS_IFRAME_BRIDGE_PARENT_REGISTER&&window.__TS_IFRAME_BRIDGE_PARENT_REGISTER(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;this.mutationCb({adds:[{parentId:this.mirror.getId(S),nextId:null,node:b}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),null==(I=this.loadListener)||I.call(this,S),__tsSafeContentDoc(S)&&__tsSafeContentDoc(S).adoptedStyleSheets&&__tsSafeContentDoc(S).adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(__tsSafeContentDoc(S).adoptedStyleSheets,this.mirror.getId(__tsSafeContentDoc(S)))}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 Nl.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:Nl.IncrementalSnapshot,data:{source:Ll.Mutation,adds:[{parentId:this.mirror.getId(S),nextId:null,node:b.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Nl.Meta:case Nl.Load:case Nl.DomContentLoaded:return!1;case Nl.Plugin:return b;case Nl.Custom:return this.replaceIds(b.data.payload,S,["id","parentId","previousId","nextId"]),b;case Nl.IncrementalSnapshot:switch(b.data.source){case Ll.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 Ll.Drag:case Ll.TouchMove:case Ll.MouseMove:return b.data.positions.forEach(b=>{this.replaceIds(b,S,["id"])}),b;case Ll.ViewportResize:return!1;case Ll.MediaInteraction:case Ll.MouseInteraction:case Ll.Scroll:case Ll.CanvasMutation:case Ll.Input:return this.replaceIds(b.data,S,["id"]),b;case Ll.StyleSheetRule:case Ll.StyleDeclaration:return this.replaceIds(b.data,S,["id"]),this.replaceStyleIds(b.data,S,["styleId"]),b;case Ll.Font:return b;case Ll.Selection:return b.data.ranges.forEach(b=>{this.replaceIds(b,S,["start","end"])}),b;case Ll.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===$l.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(_l.host(S))),this.restoreHandlers.push(initAdoptedStyleSheetObserver({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},S))},0)}observeAttachShadow(S){S.contentWindow&&__tsSafeContentDoc(S)&&this.patchAttachShadow(S.contentWindow.Element,__tsSafeContentDoc(S))}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=_l.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 Vl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ql="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Gl=0;Gl<64;Gl++)Ql[Vl.charCodeAt(Gl)]=Gl;const Kl=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=Kl.get(S);return I||(I=new Map,Kl.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+=Vl[I[b]>>2],R+=Vl[(3&I[b])<<4|I[b+1]>>4],R+=Vl[(15&I[b+1])<<2|I[b+2]>>6],R+=Vl[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 Jl="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Xl="undefined"!=typeof window&&window.Blob&&new Blob([(Yl=Jl,Uint8Array.from(atob(Yl),S=>S.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});var Yl;function WorkerWrapper(S){let b;try{if(b=Xl&&(window.URL||window.webkitURL).createObjectURL(Xl),!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,"+Jl,{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:zl["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:zl["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:zl["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,zl.WebGL,S,I,x,b)),void 0!==b.WebGL2RenderingContext&&R.push(...patchGLPrototype(b.WebGL2RenderingContext.prototype,zl.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,ec,tc,sc=!1;try{if(2!==Array.from([1],S=>2*S)[0]){const S=document.createElement("iframe");document.body.appendChild(S),Array.from=(null==(at=S.contentWindow)?void 0:at.Array.from)||Array.from,document.body.removeChild(S)}}catch(err){console.debug("Unable to override Array.from",err)}const rc=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){jl=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),rc.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=Fl(),!(null==(A=ql[0])?void 0:A.isFrozen())||_.type===Nl.FullSnapshot||_.type===Nl.IncrementalSnapshot&&_.data.source===Ll.Mutation||ql.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.__TS_IFRAME_BRIDGE&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom&&window.__TS_IFRAME_BRIDGE.forwardRrwebDom(S)}if(_.type===Nl.FullSnapshot)fe=_,me=0;else if(_.type===Nl.IncrementalSnapshot){if(_.data.source===Ll.Mutation&&_.data.isAttachIframe)return;me++;const S=x&&me>=x,b=I&&_.timestamp-fe.timestamp>I;(S||b)&&ec(!0)}};const wrappedMutationEmit=S=>{Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Mutation,...S}})},wrappedScrollEmit=S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Scroll,...S}}),wrappedCanvasMutationEmit=S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.CanvasMutation,...S}}),ye=new StylesheetManager({mutationCb:wrappedMutationEmit,adoptedStyleSheetCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.AdoptedStyleSheet,...S}})}),ve=new IframeManager({mirror:rc,mutationCb:wrappedMutationEmit,stylesheetManager:ye,recordCrossOriginIframes:se,wrappedEmit:Zl});for(const S of ae||[])S.getMirror&&S.getMirror({nodeMirror:rc,crossOriginIframeMirror:ve.crossOriginIframeMirror,crossOriginIframeStyleMirror:ve.crossOriginIframeStyleMirror});const Se=new ProcessedNodeManager;tc=new CanvasManager({recordCanvas:te,mutationCb:wrappedCanvasMutationEmit,win:window,blockClass:R,blockSelector:A,mirror:rc,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:tc,keepIframeSrcFn:le,processedNodeManager:Se},mirror:rc});ec=(S=!1)=>{if(!ee)return;Zl({type:Nl.Meta,data:{href:window.location.href,width:getWindowWidth(),height:getWindowHeight()}},S),ye.reset(),we.init(),ql.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:rc,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,rc)&&ve.addIframe(S),isSerializedStylesheet(S,rc)&&ye.trackLinkElement(S),hasShadowRoot(S)&&we.addShadowRoot(_l.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:Nl.FullSnapshot,data:{node:b,initialOffset:getWindowScroll(window)}},S),ql.forEach(S=>S.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ye.adoptStyleSheets(document.adoptedStyleSheets,rc.getId(document))};try{const S=[],observe=S=>{var b;return callbackWrapper(initObservers)({mutationCb:wrappedMutationEmit,mousemoveCb:(S,b)=>Zl({type:Nl.IncrementalSnapshot,data:{source:b,positions:S}}),mouseInteractionCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.MouseInteraction,...S}}),scrollCb:wrappedScrollEmit,viewportResizeCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.ViewportResize,...S}}),inputCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Input,...S}}),mediaInteractionCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.MediaInteraction,...S}}),styleSheetRuleCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.StyleSheetRule,...S}}),styleDeclarationCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.StyleDeclaration,...S}}),canvasMutationCb:wrappedCanvasMutationEmit,fontCb:S=>Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Font,...S}}),selectionCb:S=>{Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.Selection,...S}})},customElementCb:S=>{Zl({type:Nl.IncrementalSnapshot,data:{source:Ll.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:rc,iframeManager:ve,stylesheetManager:ye,shadowDomManager:we,processedNodeManager:Se,canvasManager:tc,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:Nl.Plugin,data:{plugin:S.name,payload:b}})})))||[]},Q)};ve.addLoadListener(b=>{try{S.push(observe(__tsSafeContentDoc(b)))}catch(S){console.warn(S)}});const init=()=>{ec(),S.push(observe(document)),sc=!0};return"interactive"===document.readyState||"complete"===document.readyState?init():(S.push(on("DOMContentLoaded",()=>{Zl({type:Nl.DomContentLoaded,data:{}}),"DOMContentLoaded"===re&&init()})),S.push(on("load",()=>{Zl({type:Nl.Load,data:{}}),"load"===re&&init()},window))),()=>{S.forEach(S=>S()),Se.destroy(),sc=!1,function unregisterErrorHandler(){jl=void 0}()}}catch(S){console.warn(S)}}var nc,ic;record.addCustomEvent=(S,b)=>{if(!sc)throw new Error("please add custom event after start recording");Zl({type:Nl.Custom,data:{tag:S,payload:b}})},record.freezePage=()=>{ql.forEach(S=>S.freeze())},record.takeFullSnapshot=S=>{if(!sc)throw new Error("please take full snapshot after start recording");ec(S)},record.mirror=rc,(ic=nc||(nc={}))[ic.NotStarted=0]="NotStarted",ic[ic.Running=1]="Running",ic[ic.Stopped=2]="Stopped";const oc=createLogger("RRWeb-Loader");let ac=null,cc=null;try{record?(ac=record,cc={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;"),oc.log("rrweb record() statically imported and ready")):console.error("[TraceScout] ❌ rrweb record import found but not a function")}catch($){console.error("[TraceScout] ❌ Static rrweb record import failed:",$.message),oc.warn("Static rrweb record import failed:",$.message)}async function loadRRWeb(){if(!cc||!cc.record)throw new Error("rrweb record not available - bundling failed");return cc}function getRRWeb(){return cc}function getRecord(){return ac}function isRRWebLoaded(){return!!cc}function getRRWebSource(){return{isBundled:!0,source:"bundled",details:"@rrweb/record bundled with SDK",isRecordOnly:!0}}var uc=Uint8Array,hc=Uint16Array,dc=Int32Array,gc=new uc([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]),pc=new uc([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]),fc=new uc([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 hc(31),x=0;x<31;++x)I[x]=b+=1<<S[x-1];var R=new dc(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}},mc=freb(gc,2),yc=mc.b,vc=mc.r;yc[28]=258,vc[258]=28;for(var Sc=freb(pc,0),wc=Sc.b,bc=Sc.r,Cc=new hc(32768),kc=0;kc<32768;++kc){var Ic=(43690&kc)>>1|(21845&kc)<<1;Ic=(61680&(Ic=(52428&Ic)>>2|(13107&Ic)<<2))>>4|(3855&Ic)<<4,Cc[kc]=((65280&Ic)>>8|(255&Ic)<<8)>>1}var hMap=function(S,b,I){for(var x=S.length,R=0,A=new hc(b);R<x;++R)S[R]&&++A[S[R]-1];var _,D=new hc(b);for(R=1;R<b;++R)D[R]=D[R-1]+A[R-1]<<1;if(I){_=new hc(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 hc(x),R=0;R<x;++R)S[R]&&(_[R]=Cc[D[S[R]-1]++]>>15-S[R]);return _},Ec=new uc(288);for(kc=0;kc<144;++kc)Ec[kc]=8;for(kc=144;kc<256;++kc)Ec[kc]=9;for(kc=256;kc<280;++kc)Ec[kc]=7;for(kc=280;kc<288;++kc)Ec[kc]=8;var xc=new uc(32);for(kc=0;kc<32;++kc)xc[kc]=5;var Mc=hMap(Ec,9,0),Rc=hMap(Ec,9,1),Tc=hMap(xc,5,0),Ac=hMap(xc,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 uc(S.subarray(b,I))},_c=["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||_c[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:Dc,l:0};if(1==R){var _=new uc(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 hc(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 uc(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 hc(++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 hc(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[fc[ae-1]];--ae);var le,ce,ue,he,de=B+5<<3,ge=clen(R,Ec)+clen(A,xc)+_,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[fc[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=Mc,ce=Ec,ue=Tc,he=xc;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+=gc[Se]);var be=31&we;wbits16(b,U,ue[be]),U+=he[be],be>3&&(wbits16(b,U,we>>5&8191),U+=pc[be])}else wbits16(b,U,le[we]),U+=ce[we]}return wbits16(b,U,le[256]),U+ce[256]},Oc=new dc([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Dc=new uc(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 uc(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 uc(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 $=Oc[b-1],j=$>>13,W=8191&$,H=(1<<I)-1,V=A.p||new hc(32768),Q=A.h||new hc(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 dc(25e3),Y=new hc(288),ee=new hc(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|vc[de]<<18|bc[ge];var Ie=31&vc[de],Ee=31&bc[ge];se+=gc[Ie]+pc[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 uc(0);var _=!I,D=_||2!=b.i,L=b.i;_&&(I=new uc(3*R));var cbuf=function(S){var b=I.length;if(S>b){var x=new uc(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=Rc,W=Ac,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 uc(te),re=new uc(19),ne=0;ne<ee;++ne)re[fc[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=gc[ne=ye-257];ve=bits(S,U,(1<<Se)-1)+yc[ne],U+=Se}var we=W[bits16(S,U)&fe],be=we>>4;if(we||err(3),U+=15&we,ge=wc[be],be>3&&(Se=pc[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 Fc="undefined"!=typeof TextEncoder&&new TextEncoder,Nc="undefined"!=typeof TextDecoder&&new TextDecoder;try{Nc.decode(Dc,{stream:!0})}catch($){}function strToU8(S,b){if(b){for(var I=new uc(S.length),x=0;x<S.length;++x)I[x]=S.charCodeAt(x);return I}if(Fc)return Fc.encode(S);var R=S.length,A=new uc(S.length+(S.length>>1)),_=0,w=function(S){A[_++]=S};for(x=0;x<R;++x){if(_+5>A.length){var D=new uc(_+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(Nc)return Nc.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 Lc=["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 Lc)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||[]}const Pc=4;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 Bc={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 Bc[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 $c});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 zc={MINIMAL:"minimal",STANDARD:"standard",DETAILED:"detailed",FULL:"full"},Uc="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(Uc)){const S=b.createObjectStore(Uc,{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([Uc],"readwrite"),x=I.objectStore(Uc),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([Uc],"readonly"),I=b.objectStore(Uc).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([Uc],"readonly").objectStore(Uc),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([Uc],"readwrite"),x=I.objectStore(Uc).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([Uc],"readwrite").objectStore(Uc),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([Uc],"readwrite"),I=b.objectStore(Uc).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([Uc],"readonly"),I=b.objectStore(Uc).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 $c=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 jc=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:zc,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=ot,ot.setTransport=TraceScoutMonitoringCore.setTransport.bind(TraceScoutMonitoringCore));export{Ge as BODY_REDACTED_VALUE,BaseInterceptor,BeaconSender,Pc as CHUNK_FORMAT_VERSION,B as CORE_WEB_VITALS_DEFAULTS,CheckpointManager,ChunkManager,ChunkedCompressedStorage,CircuitBreaker,ConfigManager,ConsoleInterceptor,CoreWebVitalsMonitor,A as DEFAULT_CONFIG,L as DEFAULT_FIELD_PATTERNS,Ke as DEFAULT_MAX_BODY_BYTES,Qe as DEFAULT_MAX_BODY_SIZE,Xe as DEFAULT_SENSITIVE_FIELDS,D as EVENT_TYPES,ErrorFingerprint,ErrorHandler,EventManager,EventOptimizer,FetchInterceptor,InactivityManager,IndexedDBQueue,R as LOCAL_STORAGE_KEYS,LogBuffer,LogManager,Logger,LoggingManager,Je as MAX_BODY_BYTES_CEILING,NetworkMonitor,PageLifecycleManager,ge as PerformanceMonitor,PerformanceResourceObserver,PostMessageInterceptor,QueueMemoryManager,qe as REDACTED_VALUE,_ as REPORTER_LOG_PREFIX,We as RESOURCE_EXTENSIONS,Recorder,RecorderMemoryManager,zc as RecorderPresets,RemoteConfigService,ResourceInterceptor,SDKContext,je as SENSITIVE_HEADERS,Ze as SENSITIVE_QUERY_PARAMS,ServiceLogger,ServiceManager,SessionManager,SessionStorage,TraceScoutMonitoringCore,UploadQueue,UserProfileManager,XHRInterceptor,analyzeSnapshotsInEvents,buildFieldDenylist,buildSnapshotIndex,captureRequestBody,captureResponseBody,chunkHasSnapshot,classifyMime,collectDeviceMetadata,createChunk,createLogger,createSensitiveHeaderSet,debounce,deepClone,ot as default,detectDeviceType,detectTouchCapability,extractConsoleRef,extractNetworkFull,extractNetworkRef,extractRequestDetails,extractResourceRef,filterSensitiveHeaders,findNearestSnapshotBefore,generateConsoleId,generateId,generateNetworkId,generateResourceId,getConnectionInfo,getEventsAfterSnapshot,getMemoryInfo,getRRWeb,getRRWebSource,getRecord,getResourceType,getSensitiveHeadersList,getSnapshotTimestamps,handleRequestBody,handleResponseBody,hashCode,initializeErrorHandler,isApiEndpoint,isCompatibleVersion,isRRWebLoaded,isResourceUrl,isSensitiveField,isSensitiveHeader,isStaticResource,isTextualContentType,loadRRWeb,U as loggingManager,ot as monitoringCore,parseBrowserInfo,parseFormData,parseOSInfo,parseRequestUrl,parseUrl,redactFormUrlEncoded,redactObject,safeJsonParse,safeJsonStringify,safeMime,safeParseConsoleArgs,b as safeSessionStorage,S as safeStorage,safeStringify,splitSanitizedUrl,stripNetworkPayload,throttle$1 as throttle,truncateToBytes,I as typeUtils,utf8Bytes,x as utils,validateDomains,validateEndpoints,validateService};
|