/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/api-reporter@1.1.7/dist/api-reporter.umd.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).apiReporter=t()}(this,function(){"use strict";const e=()=>{try{if(crypto?.randomUUID)return crypto.randomUUID()}catch(e){}return"xxxx-xxxx-4xxx-yxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})},t=e=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return null}},r={get:(e,t,r)=>{const o=t.split(".");let i=e;for(const e of o)if(i=i?.[e],void 0===i)return r;return i},isEmpty:e=>null==e||("string"==typeof e||Array.isArray(e)?0===e.length:"object"==typeof e&&0===Object.keys(e).length),isObject:e=>null!=e&&"object"==typeof e&&!Array.isArray(e),isNull:e=>null===e,isString:e=>"string"==typeof e,isArray:e=>Array.isArray(e),isFunction:e=>"function"==typeof e,merge:(e,...t)=>{if(!e||"object"!=typeof e)return e;for(const o of t)if(o&&"object"==typeof o)for(const t in o)o.hasOwnProperty(t)&&(r.isObject(e[t])&&r.isObject(o[t])?e[t]=r.merge(e[t],o[t]):e[t]=o[t]);return e},defaults:(e,...t)=>{if(!e||"object"!=typeof e)return e;for(const r of t)if(r&&"object"==typeof r)for(const t in r)r.hasOwnProperty(t)&&void 0===e[t]&&(e[t]=r[t]);return e},entries:e=>e&&"object"==typeof e?Object.entries(e):[],values:e=>e&&"object"==typeof e?Object.values(e):[],find:(e,t)=>{if(Array.isArray(e))return e.find(t)},filter:(e,t)=>Array.isArray(e)?e.filter(t):[],map:(e,t)=>Array.isArray(e)?e.map(t):[],flatten:e=>Array.isArray(e)?e.flat():[],sortBy:(e,t)=>Array.isArray(e)?[...e].sort((e,r)=>{const o="string"==typeof t?e[t]:t(e),i="string"==typeof t?r[t]:t(r);return o<i?-1:o>i?1:0}):[],some:(e,t)=>!!Array.isArray(e)&&e.some(t),toLower:e=>"string"!=typeof e?"":e.toLowerCase(),cloneDeep:e=>{if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array)return e.map(e=>r.cloneDeep(e));if(e instanceof RegExp)return new RegExp(e);if("object"==typeof e){const t={};for(const o in e)e.hasOwnProperty(o)&&(t[o]=r.cloneDeep(e[o]));return t}return e}},o=(e,t,r={})=>{let o,i,s,n=0;const{leading:a=!1,trailing:l=!0,maxWait:c}=r,h=t=>{const r=p,o=f;return p=f=void 0,n=t,e.apply(o,r)},g=e=>{const r=e-i;return void 0===i||r>=t||r<0||void 0!==c&&e-n>=c},u=()=>{const e=Date.now();if(g(e))return d(e);o=setTimeout(u,(e=>{const r=e-n,o=t-(e-i);return void 0!==c?Math.min(o,c-r):o})(e))},d=e=>{if(o=void 0,l&&p)return h(e);p=f=void 0};let p,f;const m=function(...e){const r=Date.now(),s=g(r);if(p=e,f=this,i=r,s){if(void 0===o)return(e=>(n=e,o=setTimeout(u,t),a?h(e):void 0))(i);if(void 0!==c)return o=setTimeout(u,t),h(i)}void 0===o&&(o=setTimeout(u,t))};return m.cancel=()=>{void 0!==o&&clearTimeout(o),void 0!==s&&clearTimeout(s),n=0,p=i=f=o=s=void 0},m.flush=()=>void 0===o?void 0:d(Date.now()),m};class i{constructor(e="",t=!1){this.prefix=e,this.debug=Boolean(t),this.colors={"[ApiReporter]":"color: #009688; font-weight: bold;","[EventManager]":"color: #4CAF50; font-weight: bold;","[UserProfileManager]":"color: #FF9800; font-weight: bold;","[ServiceManager]":"color: #9C27B0; font-weight: bold;","[SumoLogicService]":"color: #00BCD4; font-weight: bold;","[ConfigManager]":"color: #607D8B; font-weight: bold;","[fetchInterceptor]":"color: #8BC34A; font-weight: bold;","[xhrInterceptor]":"color: #FFC107; font-weight: bold;","[resourceInterceptor]":"color: #E91E63; font-weight: bold;","[postMessageInterceptor]":"color: #3F51B5; font-weight: bold;",default:"color: #666; font-weight: bold;"},this.prefixColor=this.colors[this.prefix]||this.colors.default,this.unifiedPrefix="[ApiReporter]"===this.prefix?"[ApiReporter]":`[ApiReporter]${this.prefix}`}updateDebugMode(e){this.debug=Boolean(e)}log(...e){this.debug&&console.log(`%c${this.unifiedPrefix}`,this.prefixColor,...e)}warn(...e){this.debug&&console.warn(`%c${this.unifiedPrefix}`,"color: #FF5722; font-weight: bold;",...e)}error(...e){console.error(`%c${this.unifiedPrefix}`,"color: #F44336; font-weight: bold;",...e)}info(...e){this.debug&&console.info(`%c${this.unifiedPrefix}`,"color: #00BCD4; font-weight: bold;",...e)}success(...e){this.debug&&console.log(`%c${this.unifiedPrefix}`,"color: #4CAF50; font-weight: bold;",...e)}important(...e){console.log(`%c${this.unifiedPrefix}`,"color: #E91E63; font-weight: bold; font-size: 14px;",...e)}}class s{constructor(e={}){this.config=e,this.debug=r.get(e,"debug",!1),this.logger=new i(`[${this.constructor.name}]`,this.debug)}async send(e){throw new Error("send() method must be implemented by service subclass")}updateDebugMode(e){this.debug=e,this.logger.updateDebugMode(e)}validateEvents(e){if(!r.isArray(e))throw new Error("Events must be an array");if(0===e.length)throw new Error("Events array cannot be empty");return!0}preparePayload(e){return e}}class n extends s{constructor(e,t=!1){super({debug:t}),this.sumoLogicEndpoint=e,this._originalFetch=window.fetch.bind(window)}async send(e){if(this.logger.log("Attempting to send event:",e),!this.sumoLogicEndpoint||this.sumoLogicEndpoint.includes("YOUR_UNIQUE_COLLECTOR_CODE"))throw this.logger.error("SumoLogic endpoint is not configured. Cannot send event."),new Error("SumoLogic endpoint not configured.");try{const t=await this._originalFetch(this.sumoLogicEndpoint,{method:"POST",headers:{"Content-Type":"application/json","X-Sumo-Host":window.location.hostname},body:JSON.stringify(e)});if(!t.ok){const e=await t.text().catch(()=>"No response body");throw this.logger.error(`SumoLogic API send failed: HTTP ${t.status} - ${e}`),new Error(`SumoLogic API response error: ${t.status}`)}this.logger.log("Successfully sent event to SumoLogic")}catch(e){throw this.logger.error("Network/Fetch error during SumoLogic send attempt:",e),new Error(`Network/API error during SumoLogic reporting: ${e.message}`)}}}class a{constructor(e,t){this.reporter=e,this.interceptorName=t,this.logger=new i(`[${this.interceptorName}Interceptor]`,this.reporter.config?.debug||!1)}updateDebugMode(e){this.logger.updateDebugMode(e)}shouldMonitor(e){return this.reporter.isMonitoredEndpoint?.(e)||!1}shouldExtractFields(e,t){return this.reporter.shouldExtractFields?.(e,t)||!1}isResourceUrl(e,t=""){return(e=>{const t=e.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(e=>t.endsWith(e))})(e,t)}extractRequestDetails(e,t,r,o,i){const s=((e,t=location.origin)=>{try{const r=new URL(e,t);return{hostname:r.hostname,pathname:r.pathname,search:r.search,protocol:r.protocol,origin:r.origin}}catch{return{hostname:"",pathname:"",search:"",protocol:"",origin:""}}})(e);return{method:t.toUpperCase(),url:e,domain:s.hostname,path:s.pathname,status:r,statusText:o,response:i,interceptor:this.interceptorName}}logEvent(t){const r={id:e(),timestamp:Date.now(),...t};this.reporter.logEvent&&"function"==typeof this.reporter.logEvent&&this.reporter.logEvent(r)}updateUserProfileFromContext({url:e,source:t,data:r}){try{if(this.reporter.extractUserContextFromBody&&"function"==typeof this.reporter.extractUserContextFromBody){const o=this.reporter.extractUserContextFromBody({url:e,source:t,data:r});if(Object.keys(o).length>0){let e={};this.reporter._getUserProfile&&"function"==typeof this.reporter._getUserProfile?e=this.reporter._getUserProfile():this.reporter.getUserProfile&&"function"==typeof this.reporter.getUserProfile&&(e=this.reporter.getUserProfile());const t={...e,...o};JSON.stringify(e)!==JSON.stringify(t)&&this.reporter.setUserProfile&&"function"==typeof this.reporter.setUserProfile&&this.reporter.setUserProfile(t)}}}catch(e){this.logger.warn("Failed to update user profile context:",e)}}handleRequestData(e,t){if(this.shouldExtractFields(e,"request")&&t)try{let r=null;if("string"==typeof t)try{r=JSON.parse(t)}catch(e){if(r=function(e){try{const t=new URLSearchParams(e),r={};for(const[e,o]of t)r[e]=o;return r}catch(e){return null}}(t),!r)return void this.logger.warn("Could not parse request body as JSON or form data")}else r=t;this.updateUserProfileFromContext({url:e,source:"request",data:r})}catch(e){this.logger.warn("Error handling request data:",e)}}handleResponseData(e,t){this.shouldExtractFields(e,"response")&&t&&this.updateUserProfileFromContext({url:e,source:"response",data:t})}handleResourceError(e,t,r,o,i,s=""){if(!this.isResourceUrl(e,s))return this.logger.log(`Not a resource: ${e}`),!1;const n=0===r||r>=400||r>=200&&r<300&&this.isResourceCorrupted(i,s);if(this.logger.log(`Resource error check: ${e}, status: ${r}, isError: ${n}`),n){const n={type:"resource_load_error",request:{...this.extractRequestDetails(e,t,r,o,i),interceptor:"resource"},extraData:{resourceType:this.getResourceType(e,s),contentType:s,isHttpResource:!0,failureReason:this.getResourceFailureReason(r,i,s)},context:{forceLog:!0,isMonitored:!0,scriptOrigin:isUndefined(window)?"unknown":window.origin,pageUrl:isUndefined(window)?"unknown":window.location.href}};return this.logger.log("Creating resource error event:",n),this.logEvent(n),this.logger.log(`Resource failed to load: ${e} [${this.getResourceType(e,s)}] - Status: ${r}`),!0}return!1}handleHttpError(e,t,r,o,i,s){const n="OPTIONS"===t;return this.isResourceUrl(e)?this.handleResourceError(e,t,r,o,i):!(n&&!this.reporter.config?.logPreflight||!(r>=400))&&(this.logEvent({type:s,request:this.extractRequestDetails(e,t,r,o,i)}),!0)}handleNetworkError(e,t,r,o){const i=this.isResourceUrl(e),s=i?"resource_load_error":o;i?this.logger.log(`Network error for RESOURCE: ${e} -> ${s}`):this.logger.log(`Network error for API: ${e} -> ${s}`);const n={type:s,request:this.extractRequestDetails(e,t,0,"",r.message||"Network error"),extraData:{stack:r.stack||""}};i&&(n.request.interceptor="resource",n.extraData.resourceType=this.getResourceType(e),n.extraData.isHttpResource=!0,n.extraData.failureReason="network_error",n.context={forceLog:!0,isMonitored:!0}),this.logEvent(n)}getResourceType(e,t=""){const r=e.toLowerCase();return r.includes(".js")||t.includes("javascript")?"javascript":r.includes(".css")||t.includes("css")?"stylesheet":r.match(/\.(png|jpg|jpeg|gif|svg|webp|ico)/)||t.includes("image/")?"image":r.match(/\.(woff|woff2|ttf|eot|otf)/)||t.includes("font")?"font":r.endsWith(".json")||t.includes("json")&&r.includes("/static/")?"data":r.match(/\.(mp4|mp3|wav)/)||t.includes("video/")||t.includes("audio/")?"media":"unknown"}getResourceFailureReason(e,t,r){return 0===e?"network_failure":404===e?"not_found":403===e?"forbidden":500===e?"server_error":e>=400?"http_error":this.isResourceCorrupted(t,r)?"corrupted_content":"unknown"}isResourceCorrupted(e,t){try{return t.includes("json")&&e&&"string"==typeof e&&JSON.parse(e),!(!t.includes("javascript")||"string"!=typeof e||!e.trim().startsWith("<!DOCTYPE")&&!e.trim().startsWith("<html"))}catch{return!0}}handleSilentLoginFailure(e,t,r,o,i,s){e.toLowerCase().includes("/MyAva/Login")&&(r>=200&&r<300)&&null==i?.LoginToken&&this.logEvent({type:s,request:this.extractRequestDetails(e,t,r,o,i),extraData:i})}}const l=window.fetch.bind(window);class c extends a{constructor(e){super(e,"fetch"),this.originalFetch=l}setup(){const e=this;window._apiReporter_originalFetch||(window._apiReporter_originalFetch=this.originalFetch),window.fetch=async function(...t){const r=t[0]instanceof Request?t[0].url:String(t[0]),o=t[1]?.method?String(t[1].method).toUpperCase():"GET",i="string"==typeof t[1]?.body?t[1].body:null,s=r.includes("sumologic.com/receiver"),n=!s&&e.shouldMonitor(r),a=e.isResourceUrl(r);let l=null;n&&e.reporter.performanceMonitor&&e.reporter.config?.monitorPerformance&&(l=e.reporter.performanceMonitor.generateRequestId(),e.reporter.performanceMonitor.startTracking(l,r,o)),a||s||e.handleRequestData(r,i);try{const i=await e.originalFetch.apply(window,t);let c=null;return l&&(c=e.reporter.performanceMonitor.endTracking(l,i.status)),!s&&(a||n||e.shouldExtractFields(r,"response"))&&await e.handleResponse(i,r,o,c),i}catch(t){throw l&&e.reporter.performanceMonitor.endTracking(l,0),s||e.handleNetworkError(r,o,t,"fetch_network_error"),t}},this.logger.log("Fetch interceptor setup complete")}async handleResponse(e,t,r,o){const i=e.clone(),s=i.headers.get("content-type")||"";let n=null;if(s.includes("application/json"))try{n=await i.json()}catch{n={message:e.statusText||"Invalid JSON response",raw:await i.text().catch(()=>"")}}else if(s.includes("text/"))try{n=await i.text()}catch{n="Failed to read response text"}const a=this.isResourceUrl(t,s);if(!a&&o?.isSlowRequest&&e.status>=200&&e.status<300&&this.logSlowRequest(t,r,e.status,e.statusText,n,o),o?.performanceAlert&&this.logPerformanceAlert(o.metrics),a)this.handleResourceError(t,r,e.status,e.statusText,n,s);else if(this.shouldMonitor(t)){this.handleHttpError(t,r,e.status,e.statusText,n,"fetch_http_error",o)||this.handleSilentLoginFailure(t,r,e.status,e.statusText,n,"fetch_silent_login_failure")}a||!n||"object"!=typeof n&&"string"!=typeof n||this.handleResponseData(t,n)}logSlowRequest(e,t,r,o,i,s){const n={type:"fetch_slow_request",request:this.extractRequestDetails(e,t,r,o,i),performance:{duration:s.duration,durationSeconds:s.durationSeconds,threshold:2,endpoint:s.endpoint},context:{isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logger.log(`Slow request detected: ${e} took ${s.durationSeconds}s`),this.logEvent(n)}logPerformanceAlert(e){const t={type:e.type,severity:e.severity,metrics:{currentAverage:e.averageSeconds,currentMedian:e.medianSeconds,threshold:2.5,sessionRequests:e.totalRequests,slowRequestCount:e.slowRequests,slowRequestPercentage:e.slowRequestPercentage,slowestEndpoints:e.slowestEndpoints},message:e.message,context:{forceLog:!0,isMonitored:!0,timestamp:e.timestamp}};this.logEvent(t)}handleHttpError(e,t,r,o,i,s,n){const a="OPTIONS"===t;if(this.isResourceUrl(e))return this.handleResourceError(e,t,r,o,i);if((!a||this.reporter.config?.logPreflight)&&r>=400){const a={type:s,request:this.extractRequestDetails(e,t,r,o,i)};return n&&(a.performance={duration:n.duration,durationSeconds:n.durationSeconds}),this.logEvent(a),!0}return!1}destroy(){this.originalFetch&&(window.fetch=this.originalFetch,delete window._apiReporter_originalFetch,this.logger.log("Fetch interceptor destroyed"))}}class h extends a{constructor(e){super(e,"xhr"),this.originalOpen=XMLHttpRequest.prototype.open,this.originalSend=XMLHttpRequest.prototype.send}setup(){const e=this;XMLHttpRequest.prototype.open=function(t,r,...o){return this._apiReporterUrl=r,this._apiReporterMethod=t.toUpperCase(),e.originalOpen.call(this,t,r,...o)},XMLHttpRequest.prototype.send=function(...t){const r=this,{_apiReporterUrl:o,_apiReporterMethod:i}=r,s=e.shouldMonitor(o),n=e.isResourceUrl(o),a=t[0];let l=null;return s&&e.reporter.performanceMonitor&&e.reporter.config?.monitorPerformance&&(l=e.reporter.performanceMonitor.generateRequestId(),r._apiReporterRequestId=l,e.reporter.performanceMonitor.startTracking(l,o,i)),n||e.handleRequestData(o,a),(n||s)&&(r.addEventListener("load",()=>e.handleXHRLoad(r,o,i)),r.addEventListener("error",()=>{r._apiReporterRequestId&&e.reporter.performanceMonitor.endTracking(r._apiReporterRequestId,0),e.handleNetworkError(o,i,new Error("Network error"),"xhr_network_error")}),r.addEventListener("timeout",()=>{r._apiReporterRequestId&&e.reporter.performanceMonitor.endTracking(r._apiReporterRequestId,0),e.handleNetworkError(o,i,new Error("Request timed out"),"xhr_timeout_error")}),r.addEventListener("abort",()=>{r._apiReporterRequestId&&e.reporter.performanceMonitor.endTracking(r._apiReporterRequestId,0),e.handleNetworkError(o,i,new Error("Request aborted"),"xhr_aborted_error")})),e.originalSend.apply(r,t)},this.logger.log("XHR interceptor setup complete")}handleXHRLoad(e,t,r){let o=null;e._apiReporterRequestId&&(o=this.reporter.performanceMonitor.endTracking(e._apiReporterRequestId,e.status));let i=null;const s=e.getResponseHeader("content-type")||"";try{if(""===e.responseType||"text"===e.responseType){if(e.responseText)try{i=s.includes("application/json")?JSON.parse(e.responseText):e.responseText}catch(t){i=e.responseText}}else i="json"===e.responseType||"document"===e.responseType?e.response:"blob"===e.responseType||"arraybuffer"===e.responseType?`[${e.responseType.toUpperCase()} data]`:e.response}catch(r){this.logger.warn(`Failed to read XHR response for ${t}:`,r),i={error:"Failed to read response",responseType:e.responseType,readyState:e.readyState,status:e.status}}const n=this.isResourceUrl(t,s);if(!n&&o?.isSlowRequest&&e.status>=200&&e.status<300&&this.logSlowRequest(t,r,e.status,e.statusText,i,o),o?.performanceAlert&&this.logPerformanceAlert(o.metrics),n)this.handleResourceError(t,r,e.status,e.statusText,i,s);else if(this.shouldMonitor(t)){this.handleHttpError(t,r,e.status,e.statusText,i,"xhr_http_error",o)||this.handleSilentLoginFailure(t,r,e.status,e.statusText,i,"xhr_silent_login_failure")}!n&&i&&"object"==typeof i&&this.handleResponseData(t,i)}logSlowRequest(e,t,r,o,i,s){const n={type:"xhr_slow_request",request:this.extractRequestDetails(e,t,r,o,i),performance:{duration:s.duration,durationSeconds:s.durationSeconds,threshold:2,endpoint:s.endpoint},context:{isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logger.log(`Slow XHR request detected: ${e} took ${s.durationSeconds}s`),this.logEvent(n)}logPerformanceAlert(e){const t={type:e.type,severity:e.severity,metrics:{currentAverage:e.averageSeconds,currentMedian:e.medianSeconds,threshold:2.5,sessionRequests:e.totalRequests,slowRequestCount:e.slowRequests,slowRequestPercentage:e.slowRequestPercentage,slowestEndpoints:e.slowestEndpoints},message:e.message,context:{forceLog:!0,isMonitored:!0,timestamp:e.timestamp}};this.logEvent(t)}handleHttpError(e,t,r,o,i,s,n){const a="OPTIONS"===t;if(this.isResourceUrl(e))return this.handleResourceError(e,t,r,o,i);if((!a||this.reporter.config?.logPreflight)&&r>=400){const a={type:s,request:this.extractRequestDetails(e,t,r,o,i)};return n&&(a.performance={duration:n.duration,durationSeconds:n.durationSeconds}),this.logEvent(a),!0}return!1}destroy(){this.originalOpen&&this.originalSend&&(XMLHttpRequest.prototype.open=this.originalOpen,XMLHttpRequest.prototype.send=this.originalSend,this.logger.log("XHR interceptor destroyed"))}}class g extends a{constructor(e){super(e,"resource"),this.boundErrorHandler=this.handleResourceError.bind(this)}setup(){window.addEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor setup complete")}handleResourceError(e){const t=e.target;if(t instanceof HTMLScriptElement||t instanceof HTMLLinkElement||t instanceof HTMLImageElement){const e=t.src||t.href||"",r=t.tagName.toLowerCase(),o={type:"resource_load_error",request:{method:"GET",url:e,domain:this.#e(e),path:this.#t(e),status:0,statusText:"Resource failed to load",response:`${r} element failed to load`,headers:{},interceptor:"resource"},extraData:{tag:r,elementType:t.constructor.name,errorType:"resource_load_failure",resourceType:this.#r(r),crossOrigin:this.#o(e),isDomElement:!0},context:{forceLog:!0,isMonitored:!0,scriptOrigin:window.origin,pageUrl:window.location.href,userAgent:navigator.userAgent}};this.logger.log(`Creating resource error event: ${e} [${r}]`),this.reporter&&this.reporter.logEvent?(this.reporter.logEvent(o),this.logger.log(`Resource error event sent for: ${e}`)):this.logger.error("Could not send resource error - reporter.logEvent not available"),this.logger.log(`Resource failed to load: ${e} [${r}]`)}}#e(e){try{return new URL(e,location.origin).hostname}catch{return""}}#t(e){try{return new URL(e,location.origin).pathname}catch{return""}}#r(e){switch(e.toLowerCase()){case"script":return"javascript";case"link":return"stylesheet";case"img":return"image";default:return"unknown"}}#o(e){try{return new URL(e,location.origin).origin!==location.origin}catch{return!1}}destroy(){window.removeEventListener("error",this.boundErrorHandler,!0),this.logger.log("Resource interceptor destroyed")}}class u extends a{constructor(e){super(e,"postMessage"),this.originalPostMessage=window.postMessage,this.boundMessageHandler=this.handleMessage.bind(this),this.messageCounter=0}setup(){const e=this;this.config=this.reporter.config?.monitorPostMessages||{},this.whitelist=this.config.postMessageOriginWhitelist||[],window.postMessage=function(t,r,...o){const i=window.location.origin;if(e.shouldMonitor(r,"outgoing",t)){const o=e.getEventType(t);e.logger.log(`Outgoing PostMessage [${o}]: ${i} -> ${r}`),e.logPostMessage({direction:"outgoing",message:t,targetOrigin:r,sourceOrigin:i,eventType:o})}return e.originalPostMessage.call(this,t,r,...o)},window.addEventListener("message",this.boundMessageHandler),this.logger.log("PostMessage interceptor setup complete")}handleMessage(e){if(this.shouldMonitor(e.origin,"incoming",e.data))try{const t=this.getEventType(e.data);this.logger.log(`Incoming PostMessage [${t}]: ${e.origin} -> ${window.location.origin}`),this.logPostMessage({direction:"incoming",message:e.data,sourceOrigin:e.origin,targetOrigin:window.location.origin,source:this.getSourceInfo(e.source),eventType:t}),this.shouldExtractFields("postmessage","message")&&this.extractUserData(e.origin,e.data)}catch(e){this.logger.error("Error handling message:",e)}}shouldMonitor(e,t,r){if(!this.config||"object"!=typeof this.config)return!1;if(this.whitelist.length>0&&!this.isOriginWhitelisted(e))return!1;const o=this.getEventType(r),i=(this.config.excludePostMessagesEvents||[]).includes(o),s=this.config.monitorSpecificPostMessagesEvents||[];return!i&&(0===s.length||s.includes(o))}isOriginWhitelisted(e){if(this.whitelist.includes("*"))return!0;if("null"===e&&this.whitelist.includes("null"))return!0;try{const t=new URL(e).hostname.toLowerCase();return this.whitelist.some(r=>{const o=r.toLowerCase();return o.includes("://")?e.toLowerCase()===o:t===o||t.endsWith(`.${o}`)})}catch{return this.whitelist.includes(e)}}getEventType(e){if(null==e)return"null_message";let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch{return"string_message"}if("object"!=typeof t)return typeof t+"_message";const r=["event_type","type","action","event","command"];for(const e of r)if(t[e])return String(t[e]);return!0===t.init?"init":"object_message"}logPostMessage(e){const t=this.parseMessage(e.message),r=e.sourceOrigin!==e.targetOrigin;this.logEvent({type:r?"postmessage_cross_origin":"postmessage_communication",request:{method:"POSTMESSAGE",url:"outgoing"===e.direction?e.targetOrigin:e.sourceOrigin,domain:this.getDomain("outgoing"===e.direction?e.targetOrigin:e.sourceOrigin),path:null,status:null,statusText:null,response:t,interceptor:"postMessage"},extraData:{messageId:`pm_${e.direction}_${Date.now()}_${++this.messageCounter}`,direction:e.direction,sourceOrigin:e.sourceOrigin,targetOrigin:e.targetOrigin,messageSize:this.getSize(e.message),messageType:typeof e.message,detectedEventType:e.eventType,source:e.source||"unknown",isCrossOrigin:r},context:{forceLog:!0,isMonitored:!0}})}parseMessage(e){if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}getSize(e){try{return"string"==typeof e?e.length:JSON.stringify(e).length}catch{return-1}}getSourceInfo(e){try{return e===window?"same-window":e===window.parent?"parent-window":e===window.opener?"opener-window":e instanceof Window?"other-window":"unknown-source"}catch{return"unknown-source"}}getDomain(e){try{return"*"===e||"null"===e?e:new URL(e).hostname}catch{return"unknown"}}extractUserData(e,t){try{const r=this.parseMessage(t);r&&"object"==typeof r&&this.updateUserProfileFromContext({url:`postmessage://${e}`,source:"message",data:r})}catch(e){this.logger.warn("Failed to extract user data:",e)}}destroy(){this.originalPostMessage&&(window.postMessage=this.originalPostMessage),window.removeEventListener("message",this.boundMessageHandler),this.logger.log("PostMessage interceptor destroyed")}}function d(e){const t=new c(e);return t.setup(),t}function p(e){const t=new h(e);return t.setup(),t}class f{constructor(e={},t=null){this.logger=t||new i("[P1FlowMonitor]",e.debug),this.config=e,this.flows=e.flows||[],this.flowRequests=new Map,this.flowTimers=new Map,this.enabled=!1!==e.enabled,this.consoleErrors=[],this.maxConsoleErrors=50,!1!==e.captureConsoleErrors&&this.setupConsoleErrorCapture()}setupConsoleErrorCapture(){const e=console.error,t=this;console.error=function(...r){e.apply(console,r),t.consoleErrors.push({timestamp:Date.now(),message:r.map(e=>{try{return"object"==typeof e?JSON.stringify(e):String(e)}catch{return String(e)}}).join(" ")}),t.consoleErrors.length>t.maxConsoleErrors&&t.consoleErrors.shift()}}async captureScreenshot(){try{if(void 0===window.html2canvas&&await this.loadHtml2Canvas(),void 0===window.html2canvas)return this.logger.warn("html2canvas not available, skipping screenshot"),null;const e=this.config.screenshotScale||.5,t=this.config.screenshotQuality||.7,r=this.maskSensitiveData();try{const r=await window.html2canvas(document.body,{logging:!1,useCORS:!0,allowTaint:!1,scale:e,width:window.innerWidth,height:window.innerHeight,windowWidth:window.innerWidth,windowHeight:window.innerHeight,ignoreElements:e=>e.hasAttribute&&e.hasAttribute("data-p1-ignore")});let o=r.toDataURL("image/jpeg",t);const i=this.config.maxScreenshotSize||5e5;if(o.length>i){let e=.5*t;for(;o.length>i&&e>.1;)o=r.toDataURL("image/jpeg",e),e*=.8}return o}finally{this.unmaskSensitiveData(r)}}catch(e){return this.logger.error("Failed to capture screenshot:",e),null}}async loadHtml2Canvas(){try{const e=document.createElement("script");return e.src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js",e.async=!0,new Promise((t,r)=>{e.onload=t,e.onerror=r,document.head.appendChild(e)})}catch(e){this.logger.warn("Failed to load html2canvas:",e)}}maskSensitiveData(){const e=[];return document.querySelectorAll(['input[type="password"]','input[type="credit-card"]','[data-sensitive="true"]','[data-mask="true"]',".credit-card-number",".cvv",".ssn",".bank-account"].join(", ")).forEach(t=>{const r={element:t,filter:t.style.filter,color:t.style.color,backgroundColor:t.style.backgroundColor};e.push(r),t.style.filter="blur(10px)",t.style.backgroundColor="#000",t.style.color="#000"}),e}unmaskSensitiveData(e){e.forEach(({element:e,filter:t,color:r,backgroundColor:o})=>{e.style.filter=t,e.style.color=r,e.style.backgroundColor=o})}captureDomSnapshot(){try{const e=document.documentElement.cloneNode(!0);e.querySelectorAll('input[type="password"], [data-sensitive="true"], .credit-card-number').forEach(e=>{"INPUT"===e.tagName?e.setAttribute("value","[REDACTED]"):e.textContent="[REDACTED]"});return e.querySelectorAll("script").forEach(e=>e.remove()),e.outerHTML}catch(e){return this.logger.error("Failed to capture DOM snapshot:",e),null}}getRecentConsoleErrors(){return this.consoleErrors.slice(-10)}getPerformanceMetrics(){try{const e=performance.getEntriesByType("navigation")[0],t=performance.getEntriesByType("paint");return{domContentLoaded:e?.domContentLoadedEventEnd-e?.domContentLoadedEventStart,loadComplete:e?.loadEventEnd-e?.loadEventStart,firstPaint:t.find(e=>"first-paint"===e.name)?.startTime,firstContentfulPaint:t.find(e=>"first-contentful-paint"===e.name)?.startTime,memoryUsage:performance.memory?{usedJSHeapSize:Math.round(performance.memory.usedJSHeapSize/1048576),totalJSHeapSize:Math.round(performance.memory.totalJSHeapSize/1048576),jsHeapSizeLimit:Math.round(performance.memory.jsHeapSizeLimit/1048576)}:null}}catch(e){return this.logger.error("Failed to get performance metrics:",e),{}}}async captureP1Context(){const e={screenshot:null,domSnapshot:null,consoleErrors:[],performanceMetrics:{},viewport:{width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio},timestamp:Date.now()};return!1!==this.config.captureScreenshot&&(this.logger.log("Capturing screenshot for P1 incident..."),e.screenshot=await this.captureScreenshot(),e.screenshot&&this.logger.log(`Screenshot captured: ${Math.round(e.screenshot.length/1024)}KB`)),!0===this.config.captureDomSnapshot&&(this.logger.log("Capturing DOM snapshot for P1 incident..."),e.domSnapshot=this.captureDomSnapshot(),e.domSnapshot&&this.logger.log(`DOM snapshot captured: ${Math.round(e.domSnapshot.length/1024)}KB`)),!1!==this.config.captureConsoleErrors&&(e.consoleErrors=this.getRecentConsoleErrors(),this.logger.log(`Captured ${e.consoleErrors.length} recent console errors`)),e.performanceMetrics=this.getPerformanceMetrics(),e}isP1Flow(e){if(!this.enabled)return null;try{const t=new URL(e,window.location.origin).pathname,r=window.location.pathname;return this.flows.find(e=>{if(!e.enabled)return!1;if(!r.includes(e.flow))return!1;const o=e.exclude?.some(e=>t.includes(e));return!o})}catch(e){return this.logger.error("Error checking P1 flow:",e),null}}getCurrentFlow(){if(!this.enabled)return null;const e=window.location.pathname;return this.flows.find(t=>t.enabled&&e.includes(t.flow))}trackRequest(e){if(!this.enabled)return;const t=this.isP1Flow(e.url);if(!t)return;const r=t.flow;this.flowRequests.has(r)||this.initializeFlow(r,t);const o=this.flowRequests.get(r),i=e.status>=400||0===e.status,s=t.criticalEndpoints?.some(t=>{if(t.startsWith("http"))return e.url.includes(t)||e.url===t;try{const r=new URL(e.url);return r.pathname.includes(t)||r.href.includes(t)}catch{return e.url.includes(t)}})||!1;s&&o.requests.push({url:e.url,method:e.method,status:e.status,timestamp:Date.now(),isError:i,isCritical:s,type:"http"}),i&&s&&this.checkP1Trigger(r)}trackPostMessage(e){if(!this.enabled)return;const t=this.getCurrentFlow();if(!t)return;const r=t.flow;this.flowRequests.has(r)||this.initializeFlow(r,t);const o=this.flowRequests.get(r),i=t.criticalPostMessageEvents?.includes(e.eventType),s=e.eventType?.includes("error")||e.eventType?.includes("failed");o.postMessageEvents.push({eventType:e.eventType,origin:e.origin,timestamp:Date.now(),isError:i||s,isCritical:i,direction:e.direction,type:"postMessage"}),(i||s)&&(this.logger.warn(`Critical PostMessage event detected: ${e.eventType}`),this.checkP1Trigger(r))}initializeFlow(e,t){this.flowRequests.set(e,{requests:[],postMessageEvents:[],startTime:Date.now(),flow:t});const r=setTimeout(()=>{this.checkFlowCompletion(e)},t.completionWindow||3e4);this.flowTimers.set(e,r)}checkP1Trigger(e){const t=this.flowRequests.get(e);if(!t||t.p1Triggered)return;const r=t.flow,o=t.requests.filter(e=>e.isError),i=o.filter(e=>e.isCritical),s=t.postMessageEvents.filter(e=>e.isCritical),n=t.postMessageEvents.filter(e=>e.isError);let a=!1,l="";if(s.length>0){a=!0;const e=s.map(e=>e.eventType).join(", ");l=`Critical PostMessage event(s) failed: ${e}`}else if(i.length>0){a=!0;const e=i.map(e=>{try{return new URL(e.url).pathname}catch{return e.url}}).join(", ");l=`Critical API(s) failed: ${e}`}else{const e=o.length+n.length;if(e>=r.failureThreshold){a=!0;const t=o.map(e=>{try{return`${new URL(e.url).pathname} (${e.status})`}catch{return`${e.url} (${e.status})`}}),r=n.map(e=>e.eventType);let i=[];t.length>0&&i.push(`API failures: ${t.join(", ")}`),r.length>0&&i.push(`PostMessage failures: ${r.join(", ")}`),l=`${e} total failures - ${i.join("; ")}`}}a&&(t.p1Triggered=!0,this.logP1Event(e,l,t))}async logP1Event(e,t,r){const o=r.postMessageEvents.filter(e=>e.isError),i=r.requests.filter(e=>e.isError);r.flow;const s=i,n=await this.captureP1Context(),a={flow:e,reason:t,timestamp:Date.now(),metrics:{totalRequests:r.requests.length,failedRequests:i.length,totalPostMessages:r.postMessageEvents.length,failedPostMessages:o.length,successRate:this.calculateSuccessRate(r)},failedEndpoints:s.map(e=>({url:e.url,status:e.status,method:e.method,type:"http",isCritical:e.isCritical||!1})).concat(o.map(e=>({url:e.origin,status:0,method:"POSTMESSAGE",eventType:e.eventType,type:"postMessage",isCritical:e.isCritical||!1}))),userContext:this.getUserContext(),visualContext:n};this.logger.warn(`⚠️ P1 EVENT LOGGED for flow: ${e}`,a);try{window.apiReporter&&"function"==typeof window.apiReporter.logEvent&&window.apiReporter.logEvent({type:"p1_incident_event",severity:"critical",message:`P1 Event: ${a.flow} - ${a.reason}`,p1Data:{flow:a.flow,reason:a.reason,failedEndpoints:a.failedEndpoints,criticalFailures:a.failedEndpoints.filter(e=>e.isCritical),flowConfig:{failureThreshold:r.flow.failureThreshold,criticalEndpoints:r.flow.criticalEndpoints||[],criticalPostMessageEvents:r.flow.criticalPostMessageEvents||[]},userContext:a.userContext,visualContext:{hasScreenshot:!!n.screenshot,screenshotSize:n.screenshot?Math.round(n.screenshot.length/1024):0,hasDomSnapshot:!!n.domSnapshot,domSnapshotSize:n.domSnapshot?Math.round(n.domSnapshot.length/1024):0,consoleErrorCount:n.consoleErrors.length,viewport:n.viewport,performanceMetrics:n.performanceMetrics}},metrics:a.metrics,context:{forceLog:!0,isP1:!0,flowStartTime:r.startTime,flowDuration:Date.now()-r.startTime,failedCriticalApis:a.failedEndpoints.filter(e=>e.isCritical).map(e=>e.url).join(", ")}})}catch(e){this.logger.error("Failed to log P1 event",e)}this.logger.info("P1 event processing completed.")}async uploadScreenshot(e){try{const t=await fetch(this.config.screenshotUploadEndpoint,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.config.apiKey||""},body:JSON.stringify({screenshot:e,timestamp:Date.now()})});if(!t.ok)throw new Error(`Screenshot upload failed: ${t.status}`);return(await t.json()).url}catch(e){return this.logger.error("Failed to upload screenshot:",e),null}}calculateSuccessRate(e){const t=e.requests.length+e.postMessageEvents.length;if(0===t)return 100;const r=e.requests.filter(e=>!e.isError).length,o=e.postMessageEvents.filter(e=>!e.isError).length;return((r+o)/t*100).toFixed(1)}checkFlowCompletion(e){const t=this.flowRequests.get(e);if(!t)return;this.logger.log(`Flow completed: ${e}`,{totalRequests:t.requests.length,failedRequests:t.requests.filter(e=>e.isError).length,totalPostMessages:t.postMessageEvents.length,failedPostMessages:t.postMessageEvents.filter(e=>e.isError).length,p1Triggered:t.p1Triggered||!1}),this.flowRequests.delete(e);const r=this.flowTimers.get(e);r&&(clearTimeout(r),this.flowTimers.delete(e))}getUserContext(){try{const e=window.apiReporter?.getUserProfile()||{};let t={};if(window.apiReporter?.config?.addCustomUserData&&"function"==typeof window.apiReporter.config.addCustomUserData)try{t=window.apiReporter.config.addCustomUserData()||{}}catch(e){this.logger.warn("Failed to get custom user data for P1:",e)}return{...e,...t}}catch(e){return this.logger.error("Failed to get user context for P1:",e),{}}}updateConfig(e){this.config={...this.config,...e},this.flows=e.flows||this.flows,this.enabled=!1!==e.enabled,this.logger.log("P1 config updated",{enabled:this.enabled,flows:this.flows.map(e=>e.flow)})}destroy(){for(const e of this.flowTimers.values())clearTimeout(e);this.flowRequests.clear(),this.flowTimers.clear()}}class m{constructor(e={}){this.config=e,this.logger=new i("[CoreWebVitalsMonitor]",e.debug),this.enabled=!1!==e.enabled,this.metrics=new Map,this.observers=[],this.callbacks=[],this.useWebVitalsLibrary=!1!==e.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},...e.thresholds},this.collectMetrics={lcp:!1!==e.collectLCP,fid:!1!==e.collectFID,cls:!1!==e.collectCLS,inp:!1!==e.collectINP,ttfb:!1!==e.collectTTFB,fcp:!1!==e.collectFCP},this.reportingEnabled=!1!==e.reportingEnabled,this.reportThreshold=e.reportThreshold||"needsImprovement",this.enabled&&"undefined"!=typeof window&&this.init()}async init(){if(this.logger.log("Initializing Core Web Vitals monitoring..."),this.useWebVitalsLibrary)try{return await this.initWithWebVitalsLibrary(),void this.logger.log("Core Web Vitals monitoring initialized with web-vitals library")}catch(e){this.logger.warn("Failed to load web-vitals library, falling back to custom implementation:",e)}this.initCustomImplementation(),this.logger.log("Core Web Vitals monitoring initialized with custom implementation")}async initWithWebVitalsLibrary(){const e=await Promise.resolve().then(function(){return ce});this.collectMetrics.lcp&&e.onLCP&&e.onLCP(e=>this.handleWebVitalsMetric("lcp",e)),this.collectMetrics.fid&&e.onFID&&e.onFID(e=>this.handleWebVitalsMetric("fid",e)),this.collectMetrics.cls&&e.onCLS&&e.onCLS(e=>this.handleWebVitalsMetric("cls",e)),this.collectMetrics.inp&&e.onINP&&e.onINP(e=>this.handleWebVitalsMetric("inp",e)),this.collectMetrics.ttfb&&e.onTTFB&&e.onTTFB(e=>this.handleWebVitalsMetric("ttfb",e)),this.collectMetrics.fcp&&e.onFCP&&e.onFCP(e=>this.handleWebVitalsMetric("fcp",e)),this.setupVisibilityChangeHandler()}handleWebVitalsMetric(e,t){const r={type:e,value:t.value,id:t.id,timestamp:Date.now(),rating:this.getRating(e,t.value),delta:t.delta,entries:t.entries?.length||0,navigationType:t.navigationType,..."lcp"===e&&t.entries?.[0]&&{element:t.entries[0].element?.tagName||"unknown",url:t.entries[0].url||window.location.href},..."fid"===e&&t.entries?.[0]&&{eventType:t.entries[0].name},..."inp"===e&&t.entries?.[0]&&{eventType:t.entries[0].name,interactionId:t.entries[0].interactionId}};this.recordProcessedMetric(r)}initCustomImplementation(){this.initLCP(),this.initFID(),this.initCLS(),this.initINP(),this.initTTFB(),this.initFCP(),this.setupVisibilityChangeHandler()}initLCP(){if(this.collectMetrics.lcp&&"PerformanceObserver"in window)try{const e=new PerformanceObserver(e=>{const t=e.getEntries(),r=t[t.length-1];this.recordMetric("lcp",{value:r.startTime,element:r.element?.tagName||"unknown",url:r.url||window.location.href,timestamp:Date.now()})});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch(e){this.logger.warn("Failed to initialize LCP observer:",e)}}initFID(){if(this.collectMetrics.fid&&"PerformanceObserver"in window)try{const e=new PerformanceObserver(e=>{e.getEntries().forEach(e=>{this.recordMetric("fid",{value:e.processingStart-e.startTime,eventType:e.name,timestamp:Date.now()})})});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch(e){this.logger.warn("Failed to initialize FID observer:",e)}}initCLS(){if(!this.collectMetrics.cls||!("PerformanceObserver"in window))return;let e=0,t=0,r=[];try{const o=new PerformanceObserver(o=>{o.getEntries().forEach(o=>{if(!o.hadRecentInput){const i=r[0],s=r[r.length-1];t&&o.startTime-s.startTime<1e3&&o.startTime-i.startTime<5e3?(t+=o.value,r.push(o)):(t=o.value,r=[o]),t>e&&(e=t,this.recordMetric("cls",{value:e,entries:r.length,timestamp:Date.now()}))}})});o.observe({type:"layout-shift",buffered:!0}),this.observers.push(o)}catch(e){this.logger.warn("Failed to initialize CLS observer:",e)}}initINP(){if(!this.collectMetrics.inp||!("PerformanceObserver"in window))return;let e=0;try{const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{if(t.interactionId){const r=t.processingEnd-t.startTime;r>e&&(e=r,this.recordMetric("inp",{value:r,eventType:t.name,interactionId:t.interactionId,timestamp:Date.now()}))}})});t.observe({type:"event",buffered:!0}),this.observers.push(t)}catch(e){this.logger.warn("Failed to initialize INP observer:",e),this.initINPFallback()}}initINPFallback(){let e=0,t=0;["click","keydown","pointerdown"].forEach(r=>{document.addEventListener(r,o=>{e=performance.now();const i=()=>{const o=performance.now()-e;o>t&&(t=o,this.recordMetric("inp",{value:o,eventType:r,timestamp:Date.now(),fallback:!0}))};window.requestIdleCallback?requestIdleCallback(i):setTimeout(i,0)},{passive:!0})})}initTTFB(){if(this.collectMetrics.ttfb)try{const e=performance.getEntriesByType("navigation")[0];if(e){const t=e.responseStart-e.requestStart;this.recordMetric("ttfb",{value:t,timestamp:Date.now()})}if("PerformanceObserver"in window){const e=new PerformanceObserver(e=>{e.getEntries().forEach(e=>{const t=e.responseStart-e.requestStart;this.recordMetric("ttfb",{value:t,timestamp:Date.now()})})});e.observe({type:"navigation",buffered:!0}),this.observers.push(e)}}catch(e){this.logger.warn("Failed to initialize TTFB measurement:",e)}}initFCP(){if(this.collectMetrics.fcp&&"PerformanceObserver"in window)try{const e=new PerformanceObserver(e=>{e.getEntries().forEach(e=>{this.recordMetric("fcp",{value:e.startTime,timestamp:Date.now()})})});e.observe({type:"paint",buffered:!0}),this.observers.push(e)}catch(e){this.logger.warn("Failed to initialize FCP observer:",e)}}recordMetric(e,t){const r={type:e,...t,rating:this.getRating(e,t.value),id:this.generateMetricId()};this.recordProcessedMetric(r)}recordProcessedMetric(e){this.metrics.set(e.type,e);const t="cls"===e.type?e.value.toFixed(3):`${e.value.toFixed(2)}ms`;this.logger.log(`${e.type.toUpperCase()}: ${t} (${e.rating})`),this.callbacks.forEach(t=>{try{t(e)}catch(e){this.logger.warn("Error in metric callback:",e)}}),this.shouldReport(e)&&this.reportMetric(e)}getRating(e,t){const r=this.thresholds[e];return r?t<=r.good?"good":t<=r.needsImprovement?"needs-improvement":"poor":"unknown"}shouldReport(e){if(!this.reportingEnabled)return!1;const t={good:1,"needs-improvement":2,poor:3},r=t[this.reportThreshold]||2;return(t[e.rating]||1)>=r}reportMetric(e){this.logger.log(`Reporting ${e.type} metric:`,e)}setupVisibilityChangeHandler(){document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.reportFinalMetrics()}),window.addEventListener("beforeunload",()=>{this.reportFinalMetrics()})}reportFinalMetrics(){const e=this.getAllMetrics();Object.keys(e).length>0&&(this.logger.log("Final Core Web Vitals:",e),this.callbacks.forEach(t=>{try{t({type:"final-report",metrics:e})}catch(e){this.logger.warn("Error in final report callback:",e)}}))}getAllMetrics(){const e={};return this.metrics.forEach((t,r)=>{e[r]=t}),e}getMetric(e){return this.metrics.get(e)}onMetric(e){"function"==typeof e&&this.callbacks.push(e)}generateMetricId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getThresholds(){return{...this.thresholds}}updateThresholds(e){this.thresholds={...this.thresholds,...e},this.logger.log("Updated thresholds:",this.thresholds)}destroy(){this.observers.forEach(e=>{try{e.disconnect()}catch(e){this.logger.warn("Error disconnecting observer:",e)}}),this.observers=[],this.callbacks=[],this.metrics.clear(),this.logger.log("Core Web Vitals monitor destroyed")}getPerformanceInsights(){const e=this.getAllMetrics(),t={overall:"good",issues:[],recommendations:[],summary:{}};let r=0,o=0,i=0;Object.values(e).forEach(e=>{if(i++,t.summary[e.type]={value:e.value,rating:e.rating,threshold:this.thresholds[e.type]},"poor"===e.rating){r++;const o="cls"===e.type?e.value.toFixed(3):`${e.value.toFixed(2)}ms`;t.issues.push(`${e.type.toUpperCase()} is poor (${o})`)}else if("needs-improvement"===e.rating){o++;const r="cls"===e.type?e.value.toFixed(3):`${e.value.toFixed(2)}ms`;t.issues.push(`${e.type.toUpperCase()} needs improvement (${r})`)}}),r>0?t.overall="poor":o>0&&(t.overall="needs-improvement"),e.lcp&&"good"!==e.lcp.rating&&(t.recommendations.push("Optimize images and reduce server response times to improve LCP"),t.recommendations.push("Consider lazy loading images below the fold"),t.recommendations.push("Use a CDN to serve static assets faster")),e.fid&&"good"!==e.fid.rating&&(t.recommendations.push("Reduce JavaScript execution time and break up long tasks to improve FID"),t.recommendations.push("Use code splitting to reduce initial bundle size"),t.recommendations.push("Consider using a web worker for heavy computations")),e.cls&&"good"!==e.cls.rating&&(t.recommendations.push("Set size attributes on images and avoid inserting content above existing content to improve CLS"),t.recommendations.push("Use CSS aspect-ratio or explicit dimensions for media elements"),t.recommendations.push("Avoid inserting content above existing content except in response to user interaction")),e.inp&&"good"!==e.inp.rating&&(t.recommendations.push("Optimize event handlers and reduce main thread blocking to improve INP"),t.recommendations.push("Use requestIdleCallback for non-critical tasks"),t.recommendations.push("Debounce expensive operations triggered by user input")),e.ttfb&&"good"!==e.ttfb.rating&&(t.recommendations.push("Optimize server response times and use CDN to improve TTFB"),t.recommendations.push("Consider server-side caching strategies"),t.recommendations.push("Optimize database queries and API responses")),e.fcp&&"good"!==e.fcp.rating&&(t.recommendations.push("Optimize critical rendering path to improve FCP"),t.recommendations.push("Minimize render-blocking resources"),t.recommendations.push("Prioritize above-the-fold content"));const s=i-o-r;return t.score=Math.round(s/i*100),t}generateReport(){const e=this.getAllMetrics(),t=this.getPerformanceInsights();return{timestamp:Date.now(),url:window.location.href,userAgent:navigator.userAgent,metrics:e,insights:t,thresholds:this.thresholds,config:{collectMetrics:this.collectMetrics,reportThreshold:this.reportThreshold,useWebVitalsLibrary:this.useWebVitalsLibrary}}}}const w={EVENTS:"__api_reporter_events__",USER_PROFILE:"__api_reporter_user_profile__"},v={RETRY_INTERVAL_MS:3e4,DEDUPLICATION_WINDOW_MS:6e4,MAX_QUEUE_SIZE:1e3,MAX_RETRIES:3,BATCH_SIZE:10,DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS:[]};class y{constructor(e,t=[],r=!1){this.storageKey=e,this.fieldsToExtract=t,this.logger=new i("[UserProfileManager]",r)}getProfile(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):{}}catch(e){return this.logger.warn("Failed to read user profile:",e),{}}}setProfile(e={}){if(!r.isObject(e))return this.logger.warn("Invalid profile object provided"),!1;try{const t=this.getProfile(),o=r.merge(t,e);return localStorage.setItem(this.storageKey,JSON.stringify(o)),this.logger.log("User profile updated:",o),!0}catch(e){return"QuotaExceededError"===e.name?this.logger.warn("Storage quota exceeded for user profile"):this.logger.error("Failed to save user profile:",e),!1}}ensureProfile(){try{const t=this.getProfile();if(r.isEmpty(r.get(t,"uniqId"))){const o=r.merge(t,{uniqId:e(),createdAt:(new Date).toISOString()});this.setProfile(o),this.logger.log("Generated new user profile:",r.get(o,"uniqId"))}}catch(e){this.logger.error("Failed to ensure user profile:",e)}}extractContextFromData({data:e,source:t="response",url:o=""}){const i={};try{if(!r.isObject(e)||!r.isArray(this.fieldsToExtract))return i;const s=r.toLower(o);return this.fieldsToExtract.forEach(n=>{try{const a=r.toLower(r.get(n,"api","")),l=r.get(n,"source",""),c="*"===a||s.includes(a);if(!c||!("*"===l||l===t))return;const h=r.get(n,"fields",[]);r.isArray(h)?h.forEach(r=>{try{this.recursiveFieldMatch({context:i,matchRule:r,data:e,source:t,url:o})}catch(e){this.logger.warn(`Failed to extract field with pattern "${r}":`,e)}}):r.isObject(h)&&r.entries(h).forEach(([r,s])=>{try{this.recursiveFieldMatchWithMapping({context:i,newKey:r,matchRule:s,data:e,source:t,url:o})}catch(e){this.logger.warn(`Failed to extract field with mapping "${r}": "${s}":`,e)}})}catch(e){this.logger.warn("Error processing extraction rule:",e)}}),i}catch(e){return this.logger.error("Error in extractContextFromData:",e),{}}}updateFromContext({url:e,source:t,data:r}){try{const o=this.extractContextFromData({url:e,source:t,data:r});if(Object.keys(o).length>0){const e=this.getProfile(),t={...e,...o};if(JSON.stringify(e)!==JSON.stringify(t))return this.setProfile(t),!0}return!1}catch(e){return this.logger.warn("Failed to update user profile context:",e),!1}}recursiveFieldMatch({context:e,matchRule:t,data:o,source:i,url:s}){try{if(!r.isObject(o))return;if(r.isString(t)){const i=r.find(r.entries(o),([e])=>r.toLower(e)===r.toLower(t));if(i){const[t,r]=i;return e[t]=r,void this.logger.log(`Found field by name: ${t} = ${JSON.stringify(r)}`)}}if(t instanceof RegExp){const i=r.find(r.entries(o),([e,o])=>r.isString(o)&&t.test(o));if(i){const[t,r]=i;return e[t]=r,void this.logger.log(`Found field by value pattern: ${t} = ${r}`)}}r.values(o).forEach(o=>{r.isObject(o)&&!r.isNull(o)&&this.recursiveFieldMatch({context:e,matchRule:t,data:o,source:i,url:s})})}catch(e){this.logger.warn("Error in recursive field matching:",e)}}recursiveFieldMatchWithMapping({context:e,newKey:t,matchRule:o,data:i,source:s,url:n}){try{if(!r.isObject(i))return;if(r.isString(o)){const s=r.find(r.entries(i),([e])=>r.toLower(e)===r.toLower(o));if(s){const[r,o]=s;return e[t]=o,void this.logger.log(`Found field with mapping: ${r} -> ${t} = ${JSON.stringify(o)}`)}}if(o instanceof RegExp){const s=r.find(r.entries(i),([e,t])=>r.isString(t)&&o.test(t));if(s){const[r,o]=s;return e[t]=o,void this.logger.log(`Found field by pattern with mapping: ${r} -> ${t} = ${o}`)}}r.values(i).forEach(i=>{r.isObject(i)&&!r.isNull(i)&&this.recursiveFieldMatchWithMapping({context:e,newKey:t,matchRule:o,data:i,source:s,url:n})})}catch(e){this.logger.warn("Error in recursive field matching with mapping:",e)}}}class b{constructor(e={}){this.defaultConfig=e,this.config={}}validate(e={}){const t=[];try{const o=function(e){if(!e)return!1;const t=Array.isArray(e)?e:[e];return t.length>0&&t.every(e=>"string"==typeof e&&e.length>0)}(e.endpoints),i=function(e){if(!e)return!1;const t=Array.isArray(e)?e:[e];return t.length>0&&t.every(e=>"string"==typeof e&&e.length>0)}(e.domainsToTrack);o||i||t.push("Either endpoints or domainsToTrack must be provided"),e.service&&!("string"==typeof(r=e.service)?["sumologic"].includes(r.toLowerCase()):r&&"object"==typeof r&&"function"==typeof r.send)&&t.push('Invalid service: must be "sumologic" or an object with send() method');const s={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(s).forEach(([r,{min:o,max:i}])=>{const s=e[r];void 0!==s&&("number"!=typeof s||s<o||s>i)&&t.push(`${r} must be a number between ${o} and ${i}`)}),void 0!==e.monitorPostMessages)if("object"!=typeof e.monitorPostMessages||null===e.monitorPostMessages)t.push("monitorPostMessages must be an object");else{const r=e.monitorPostMessages;void 0!==r.postMessageOriginWhitelist&&(Array.isArray(r.postMessageOriginWhitelist)?r.postMessageOriginWhitelist.every(e=>"string"==typeof e)||t.push("postMessageOriginWhitelist must contain only strings"):t.push("postMessageOriginWhitelist must be an array")),void 0===r.excludePostMessagesEvents||Array.isArray(r.excludePostMessagesEvents)||t.push("excludePostMessagesEvents must be an array"),void 0===r.monitorSpecificPostMessagesEvents||Array.isArray(r.monitorSpecificPostMessagesEvents)||t.push("monitorSpecificPostMessagesEvents must be an array")}if(void 0!==e.monitorPerformance&&"boolean"!=typeof e.monitorPerformance&&t.push("monitorPerformance must be a boolean"),void 0!==e.slowRequestThreshold&&("number"!=typeof e.slowRequestThreshold||e.slowRequestThreshold<100||e.slowRequestThreshold>3e4)&&t.push("slowRequestThreshold must be a number between 100 and 30000 milliseconds"),void 0!==e.averageAlertThreshold&&("number"!=typeof e.averageAlertThreshold||e.averageAlertThreshold<100||e.averageAlertThreshold>3e4)&&t.push("averageAlertThreshold must be a number between 100 and 30000 milliseconds"),t.length>0)throw new Error(`Configuration validation failed: ${t.join(", ")}`);return!0}catch(e){throw e}var r}apply(e={}){this.validate(e);try{return this.config=r.merge({},this.defaultConfig,e,{debug:"boolean"==typeof r.get(e,"debug")?r.get(e,"debug"):Boolean(r.get(e,"debug")),retryIntervalMs:Math.max(1e3,r.get(e,"retryIntervalMs",this.defaultConfig.retryIntervalMs)),deduplicationWindowMs:Math.max(100,r.get(e,"deduplicationWindowMs",this.defaultConfig.deduplicationWindowMs))}),this.config.endpoints=this.normalizeArray(e.endpoints),this.config.domainsToTrack=this.normalizeDomains(e.domainsToTrack),this.config.fieldsToExtract=Array.isArray(e.fieldsToExtract)?e.fieldsToExtract:[],this.config.localStorageEnrichmentKeys=r.flatten([r.get(this.defaultConfig,"DEFAULT_LOCAL_STORAGE_ENRICHMENT_KEYS",[]),Array.isArray(r.get(e,"localStorageEnrichmentKeys"))?r.get(e,"localStorageEnrichmentKeys"):[]]),this.config}catch(e){throw new Error(`Configuration application failed: ${e.message}`)}}get(e,t){try{return r.get(this.config,e,t)}catch(e){return t}}update(e,t){try{this.config[e]=t}catch(e){}}normalizeArray(e){try{return Array.isArray(e)?e:r.isEmpty(e)?[]:[e]}catch(e){return[]}}evaluateDynamicDomain(e){if("string"!=typeof e)return e;const t={"window.location.hostname":()=>{try{return"undefined"!=typeof window&&window.location?window.location.hostname:e}catch(t){return e}},"location.hostname":()=>{try{return"undefined"!=typeof window&&window.location?window.location.hostname:e}catch(t){return e}}};return t[e]?t[e]():e}normalizeDomains(e){try{return this.normalizeArray(e).map(e=>this.evaluateDynamicDomain(e))}catch(e){return[]}}}class E{constructor(e={},t={}){this.config=e,this.storageKeys=t,this.logger=new i("[EventManager]",e.debug),this.eventQueue=[],this.eventOccurrenceTracker=new Map,this.debouncedSave=o(this.saveToLocal.bind(this),100)}addEvent(e){try{return!!this.shouldLogEvent(e)&&(this.deduplicateEvent(e)?(this.eventQueue.length>=this.config.maxQueueSize&&(this.eventQueue.shift(),this.logger.warn("Queue size limit reached, removing oldest event")),this.eventQueue.push(e),this.debouncedSave(),this.logger.log("Event added:",e.type),!0):(this.logger.log("Event deduplicated"),!1))}catch(e){return this.logger.error("Failed to add event:",e),!1}}getEvents(){try{return r.sortBy(r.cloneDeep(this.eventQueue),"timestamp")}catch(e){return this.logger.error("Failed to get events:",e),[]}}removeEvents(e){try{const t=new Set(e);this.eventQueue=r.filter(this.eventQueue,e=>!t.has(e.id)),this.debouncedSave()}catch(e){this.logger.error("Failed to remove events:",e)}}clearEvents(){try{this.eventQueue.length=0,this.eventOccurrenceTracker.clear(),this.clearLocal(),this.logger.log("All events cleared")}catch(e){this.logger.error("Failed to clear events:",e)}}getQueueSize(){return this.eventQueue.length}shouldLogEvent(e){try{const t=e.context?.isMonitored,r=e.context?.forceLog;if(!(t||r))return!1;return!(this.config.ignoreEventTypes||[]).includes(e.type)}catch(e){return this.logger.error("Error in shouldLogEvent:",e),!1}}deduplicateEvent(e){try{const t=this.generateDedupeKey(e),r=this.eventOccurrenceTracker.get(t),o=Date.now();return!(r&&o-r<this.config.deduplicationWindowMs)&&(this.eventOccurrenceTracker.set(t,o),!0)}catch(e){return this.logger.error("Error in deduplicateEvent:",e),!0}}generateDedupeKey(e){try{const t=Math.floor(e.timestamp/1e3);return r.toLower(r.flatten([e.type,e.request?.method,e.request?.url,e.request?.status,t]).join("|"))}catch(e){return this.logger.error("Error generating deduplication key:",e),null}}cleanDeduplicationTracker(){try{const e=Date.now()-2*this.config.deduplicationWindowMs;for(const[t,r]of this.eventOccurrenceTracker.entries())r<e&&this.eventOccurrenceTracker.delete(t)}catch(e){this.logger.error("Error cleaning deduplication tracker:",e)}}loadFromLocal(){try{const e=localStorage.getItem(this.storageKeys.EVENTS);if(!r.isEmpty(e)){const t=JSON.parse(e).events||[];Array.isArray(t)&&(this.eventQueue.push(...t),this.logger.log(`Loaded ${t.length} events from localStorage`))}}catch(e){this.logger.error("Failed to load events from localStorage:",e),this.clearLocal()}}saveToLocal(){try{const e={events:this.eventQueue,lastSaved:Date.now()};localStorage.setItem(this.storageKeys.EVENTS,JSON.stringify(e))}catch(e){"QuotaExceededError"===e.name?(this.logger.warn("Storage quota exceeded, clearing old data"),this.clearLocal()):this.logger.error("Failed to save events to localStorage:",e)}}clearLocal(){try{localStorage.removeItem(this.storageKeys.EVENTS)}catch(e){this.logger.error("Failed to clear localStorage:",e)}}}class M{constructor(e={},t=null){this.config=e,this.logger=t||new i("[ServiceManager]",e.debug),this.service=null,this.isSending=!1,this.retryCount=0,this.maxRetries=r.get(e,"maxRetries",3),this.initializeService()}initializeService(){if(!r.get(this.config,"service"))throw new Error("Service configuration is required");this.setService(r.get(this.config,"service"),r.get(this.config,"serviceOptions",{}))}setService(e,t={}){if(r.isString(e)){if("sumologic"!==r.toLower(e))throw new Error(`Unknown service: ${e}. Supported services: sumologic`);if(r.isEmpty(r.get(t,"endpoint")))throw new Error("SumoLogic endpoint is required in serviceOptions");this.service=new n(r.get(t,"endpoint"),r.get(this.config,"debug"))}else{if(!r.isObject(e)||!r.isFunction(r.get(e,"send")))throw new Error("Invalid service: must be a string or object with send() method");this.service=e}this.logger.log(`Service initialized: ${this.getServiceName()}`)}async sendEvents(e){if(this.isSending||r.isEmpty(e)||!this.service)return[];this.isSending=!0;try{const t=[];for(const r of e)try{await this.sendSingleEvent(r),t.push({event:r,success:!0}),this.logger.log(`Event sent successfully: ${r.type}`)}catch(e){this.logger.error(`Event failed: ${r.type}`,e),t.push({event:r,success:!1,error:e})}return this.retryCount=0,t}catch(t){return this.logger.error("Failed to send events:",t),this.retryCount++,r.map(e,e=>({event:e,success:!1,error:t}))}finally{this.isSending=!1}}async sendSingleEvent(e){let t;for(let r=1;r<=this.maxRetries;r++)try{return void await this.service.send(e)}catch(o){t=o,this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for event ${e.id}:`,o.message),r<this.maxRetries&&await this.delay(this.getRetryDelay(r))}throw t}getRetryDelay(e){return Math.min(1e3*Math.pow(2,e-1),1e4)}delay(e){return new Promise(t=>setTimeout(t,e))}getServiceName(){if(!this.service)return"none";if(this.service.constructor&&this.service.constructor.name){return this.service.constructor.name}return this.service.sumoLogicEndpoint?"SumoLogicService":"function"==typeof this.service.send?"CustomService":"unknown"}getStatus(){return{serviceName:this.getServiceName(),isSending:this.isSending,retryCount:this.retryCount,maxRetries:this.maxRetries,hasService:!!this.service}}updateDebugMode(e){this.logger.updateDebugMode(e),this.service&&r.isFunction(r.get(this.service,"updateDebugMode"))&&this.service.updateDebugMode(e)}destroy(){this.service=null,this.isSending=!1,this.retryCount=0,this.logger.log("ServiceManager destroyed")}}class S{constructor(e={}){this.slowRequestThreshold=e.slowRequestThreshold||2e3,this.averageAlertThreshold=e.averageAlertThreshold||2500,this.maxRequests=e.maxRequestHistory||1e3,this.debug=e.debug||!1,this.logger=new i("[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(e,t,r){this.requestIdMap.set(e,{url:t,method:r,startTime:performance.now(),endpoint:this.getEndpointPattern(t)})}endTracking(e,t){const r=this.requestIdMap.get(e);if(!r)return null;const o=performance.now()-r.startTime;this.requestIdMap.delete(e),this.addRequest(o,r.endpoint);const i=o>this.slowRequestThreshold;i&&this.logSlowRequest(r.url,o);const s=this.checkAverageThreshold();return{duration:o,durationSeconds:Number((o/1e3).toFixed(2)),isSlowRequest:i,endpoint:r.endpoint,performanceAlert:s.alert,metrics:s.metrics}}addRequest(e,t){this.requests.push({duration:e,endpoint:t,timestamp:Date.now()}),this.requests.length>this.maxRequests&&this.requests.shift(),this.endpointStats.has(t)||this.endpointStats.set(t,[]);const r=this.endpointStats.get(t);r.push(e),r.length>100&&r.shift()}checkAverageThreshold(){const e=this.calculateMetrics();return e.average>this.averageAlertThreshold&&!this.alertSent?(this.alertSent=!0,this.logger.warn(`Performance degradation detected! Average: ${e.averageSeconds}s`),{alert:!0,metrics:{...e,type:"performance_degradation_alert",severity:"warning",message:`Average request duration (${e.averageSeconds}s) exceeded threshold (${(this.averageAlertThreshold/1e3).toFixed(1)}s)`,timestamp:Date.now()}}):(e.average<=this.averageAlertThreshold&&this.alertSent&&(this.alertSent=!1,this.logger.log(`Performance recovered. Average: ${e.averageSeconds}s`)),{alert:!1,metrics:e})}calculateMetrics(){if(0===this.requests.length)return{average:0,averageSeconds:0,median:0,medianSeconds:0,totalRequests:0,slowRequests:0,slowRequestPercentage:0,slowestEndpoints:[]};const e=this.requests.map(e=>e.duration),t=e.reduce((e,t)=>e+t,0)/e.length,r=[...e].sort((e,t)=>e-t),o=r[Math.floor(r.length/2)],i=this.requests.filter(e=>e.duration>this.slowRequestThreshold).length,s=this.getSlowestEndpoints();return{average:t,averageSeconds:Number((t/1e3).toFixed(2)),median:o,medianSeconds:Number((o/1e3).toFixed(2)),totalRequests:this.requests.length,slowRequests:i,slowRequestPercentage:Number((i/this.requests.length*100).toFixed(1)),slowestEndpoints:s,sessionDuration:Date.now()-this.sessionStart}}getSlowestEndpoints(e=3){const t=[];for(const[e,r]of this.endpointStats)if(r.length>0){const o=r.reduce((e,t)=>e+t,0)/r.length;t.push({endpoint:e,avgDuration:Number((o/1e3).toFixed(2)),requestCount:r.length})}return t.sort((e,t)=>t.avgDuration-e.avgDuration).slice(0,e)}getEndpointPattern(e){try{return new URL(e).pathname.replace(/\/\d+/g,"/:id").replace(/\/[a-f0-9-]{36}/gi,"/:uuid").replace(/\/[a-f0-9]{24}/g,"/:objectId")}catch{return e}}logSlowRequest(e,t){const r=(t/1e3).toFixed(2);this.logger.error(`🐌 [Slowness] Request to ${e} took ${r}s`);const o=this.calculateMetrics();this.logger.info(`📊 Current average: ${o.averageSeconds}s (median: ${o.medianSeconds}s)`)}generateRequestId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}clear(){this.requests=[],this.endpointStats.clear(),this.requestIdMap.clear(),this.alertSent=!1}updateDebugMode(e){this.debug=e,this.logger.updateDebugMode(e)}}function T(e){try{return new URL(e,location.origin)}catch(e){return null}}class C{#i=!1;#s=null;#n=null;#a=null;#l=null;#c=null;#h=null;#g=null;#u=null;#d=null;#p=null;#f=null;#m=null;#w=null;#v=null;#y=null;#b=null;constructor(){this.config=r.defaults({retryIntervalMs:r.get(v,"RETRY_INTERVAL_MS",5e3),deduplicationWindowMs:r.get(v,"DEDUPLICATION_WINDOW_MS",3e4),maxQueueSize:r.get(v,"MAX_QUEUE_SIZE",1e3),maxRetries:r.get(v,"MAX_RETRIES",3),batchSize:r.get(v,"BATCH_SIZE",10),debug:!1,logPreflight:!1,logResourceErrors:!1},{}),this.#s=new i("[ApiReporter]",this.config.debug);try{this.#n=new b(this.config)}catch(e){this.#s.error("Failed to initialize ConfigManager:",e)}this.appContext={appVersion:this.#E(),environment:"unknown"},this.#p=this.#M.bind(this),this.#f=this.#S.bind(this),this.#m=((e,t,r={})=>{const{leading:i=!0,trailing:s=!0}=r;return o(e,t,{leading:i,trailing:s,maxWait:t})})(this.sendEvents.bind(this),1e3)}async init(e={}){if(this.#i)this.#s.warn("ApiReporter already initialized");else try{if(!r.isObject(e))throw new Error("Options must be an object");this.#b=e,this.#y=e.remoteConfigUrl||e.backendConfigUrl||null;const t=await this.#T(),o=this.#C(t,e);this.config=this.#n.apply(o),this.config.appName&&(this.appContext.appName=this.config.appName),this.config.environment?(this.appContext.environment=this.config.environment,this.#s.log(`Environment set: ${this.config.environment}`)):this.#s.log(`Environment defaulted to: ${this.appContext.environment}`),this.#s.updateDebugMode(this.config.debug),this.#R(),this.config.enableP1FlowMonitoring&&this.config.p1Config&&(this.#g=new f(this.config.p1Config,this.#s),this.#s.log("P1 Flow Monitor initialized",{enabled:this.config.p1Config.enabled,flows:this.config.p1Config.flows?.map(e=>e.flow)})),!1!==this.config.enableCoreWebVitals&&(this.#u=new m({...this.config.coreWebVitalsConfig,debug:this.config.debug}),this.#u.onMetric(e=>{this.logEvent({type:"core_web_vital",metric_type:e.type,value:e.value,rating:e.rating,timestamp:e.timestamp,element:e.element,event_type:e.eventType,interaction_id:e.interactionId,entries_count:e.entries,navigation_type:e.navigationType,delta:e.delta})}),this.#s.log("Core Web Vitals Monitor initialized")),this.#P(),this.#x(),this.#F(),this.#a.loadFromLocal(),this.#c.ensureProfile(),this.#i=!0,this.#s.log("ApiReporter initialized successfully",{configSource:t?"backend":"local",configVersion:this.config.configVersion||"local",config:this.config}),this.#a.getQueueSize()>0&&this.#m()}catch(e){throw this.#s.error("Failed to initialize ApiReporter:",e),e}}destroy(){if(this.#i)try{this.#D(),this.#L(),this.#I(),this.#S(),this.#l&&this.#l.destroy(),this.#h&&(this.#h.clear(),this.#h=null,this.performanceMonitor=null),this.#g&&(this.#g.destroy(),this.#g=null),this.#u&&(this.#u.destroy(),this.#u=null),this.#i=!1,this.#s.log("ApiReporter destroyed")}catch(e){this.#s.error("Error during destroy:",e)}}debugMode(e){const t="boolean"==typeof e?e:Boolean(e);this.config.debug=t,this.#q(t),this.#s.log("Debug mode "+(t?"enabled":"disabled"))}setUserProfile(e={}){if(this.#c)if(r.isObject(e))try{this.#c.setProfile(e)}catch(e){this.#s.error("Failed to set user profile:",e)}else this.#s.warn("Invalid profile: must be an object");else this.#s.warn("UserProfileManager not initialized")}getUserProfile(){if(!this.#c)return this.#s.warn("UserProfileManager not initialized"),{};try{return this.#c.getProfile()}catch(e){return this.#s.error("Failed to get user profile:",e),{}}}_getUserProfile(){return this.getUserProfile()}logEvent(e){if(this.#i||this.#s.warn("ApiReporter not initialized, queuing event"),this.#a)if(r.isObject(e))try{const t=this.#A(e);if(this.#g&&(e.request&&"POSTMESSAGE"!==e.request.method&&this.#g.trackRequest(e.request),e.request&&"POSTMESSAGE"===e.request.method&&e.extraData&&this.#g.trackPostMessage({eventType:e.extraData.detectedEventType||e.postMessageEvent||"unknown",origin:e.extraData.sourceOrigin||e.request.url,direction:e.extraData.direction||"unknown",timestamp:e.timestamp||Date.now()})),this.#a.addEvent(t)){"undefined"==typeof navigator||!1!==navigator.onLine?this.#m():this.#s.log("Offline - event queued for later sending")}}catch(e){this.#s.error("Failed to log event:",e)}else this.#s.warn("Invalid event data: must be an object");else this.#s.error("EventManager not initialized")}async sendEvents(){if(!this.#l||!this.#a)return void this.#s.warn("Managers not initialized");if("undefined"!=typeof navigator&&!1===navigator.onLine)return void this.#s.log("Offline - skipping send attempt");const e=this.#a.getEvents();if(!r.isEmpty(e))try{const t=await this.#l.sendEvents(e);this.#O(t),0===this.#a.getQueueSize()&&(this.#a.clearLocal(),this.#s.log("All events sent successfully"))}catch(e){this.#s.error("Failed to send events:",e)}}clearEvents(){if(this.#a)try{this.#a.clearEvents()}catch(e){this.#s.error("Failed to clear events:",e)}}getQueueStatus(){return{queueSize:this.#a?.getQueueSize()||0,isSending:this.#l?.getStatus().isSending||!1,isInitialized:this.#i,service:this.#l?.getStatus().serviceName||"none",configSource:this.config?.configSource||"unknown",configVersion:this.config?.configVersion||"unknown"}}getPerformanceMetrics(){if(!this.#h)return this.#s.warn("Performance monitoring not enabled"),null;try{return this.#h.calculateMetrics()}catch(e){return this.#s.error("Failed to get performance metrics:",e),null}}getP1FlowMonitor(){return this.#g}isMonitoredEndpoint(e){if("string"!=typeof e||r.isEmpty(e))return!1;try{const t=this.config.endpoints||[],o=this.config.domainsToTrack||[];if(t.includes("*")||"*"===t)return!0;const i=T(e.toLowerCase());if(!i)return!1;if(!r.isEmpty(o)){const e=i.hostname;if(r.some(o,t=>e===t.toLowerCase()||e.endsWith(`.${t.toLowerCase()}`)))return!0}const s=i.pathname;return r.some(t,e=>s.includes(e.toLowerCase()))}catch(e){return this.#s.warn("Error checking monitored endpoint:",e),!1}}shouldExtractFields(e="",t="response"){if(!Array.isArray(this.config.fieldsToExtract))return!1;try{const o=e.toLowerCase(),i=t.toLowerCase();return r.some(this.config.fieldsToExtract,e=>{const t=r.get(e,"api","").toLowerCase(),s=r.get(e,"source","").toLowerCase();return("*"===t||o.includes(t))&&("*"===s||s===i)})}catch(e){return this.#s.warn("Error checking field extraction:",e),!1}}extractUserContextFromBody({data:e,source:t="response",url:r=""}){if(!this.#c)return{};try{return this.#c.extractContextFromData({data:e,source:t,url:r})}catch(e){return this.#s.error("Failed to extract user context:",e),{}}}#k(e){this.#d&&Object.values(this.#d).forEach(t=>{t&&"function"==typeof t.updateDebugMode&&t.updateDebugMode(e)})}#q(e){this.#s.updateDebugMode(e),this.#l&&this.#l.updateDebugMode(e),this.#c&&this.#c.logger&&this.#c.logger.updateDebugMode(e),this.#a&&this.#a.logger&&this.#a.logger.updateDebugMode(e),this.#h&&this.#h.updateDebugMode(e),this.#g&&this.#g.logger&&this.#g.logger.updateDebugMode(e),this.#k(e)}#R(){try{this.#c=new y(r.get(w,"USER_PROFILE"),this.config.fieldsToExtract,this.config.debug),this.#a=new E({...this.config,debug:this.config.debug},w),this.#l=new M(this.config,this.#s),this.config.monitorPerformance&&(this.performanceMonitor=new S({slowRequestThreshold:this.config.slowRequestThreshold||2e3,averageAlertThreshold:this.config.averageAlertThreshold||2500,debug:this.config.debug}),this.#h=this.performanceMonitor),this.#q(this.config.debug)}catch(e){throw this.#s.error("Failed to initialize managers:",e),e}}#P(){if("undefined"!=typeof window)try{window.addEventListener("apiError",this.#p),window.addEventListener("beforeunload",this.#f),this.#s.log("Event listeners setup complete")}catch(e){this.#s.error("Failed to setup event listeners:",e)}}#D(){if("undefined"!=typeof window)try{window.removeEventListener("apiError",this.#p),window.removeEventListener("beforeunload",this.#f),this.#s.log("Event listeners removed")}catch(e){this.#s.error("Failed to remove event listeners:",e)}}#x(){try{this.#d={fetch:d(this),xhr:p(this),resource:null,postMessage:null},this.config.logResourceErrors&&(this.#d.resource=function(e){const t=new g(e);return t.setup(),t}(this)),this.config.monitorPostMessages&&"object"==typeof this.config.monitorPostMessages&&(this.#d.postMessage=function(e){const t=new u(e);return t.setup(),t}(this)),this.#k(this.config.debug),this.#s.log("Interceptors setup complete")}catch(e){this.#s.error("Failed to setup interceptors:",e)}}#I(){if(this.#d)try{e=this.#d,e?.fetch&&e.fetch.destroy(),e?.xhr&&e.xhr.destroy(),e?.resource&&e.resource.destroy(),e?.postMessage&&e.postMessage.destroy(),this.#d=null,this.#s.log("Interceptors destroyed")}catch(e){this.#s.error("Failed to destroy interceptors:",e)}var e}#F(){try{this.#w=setInterval(()=>{const e="undefined"==typeof navigator||!1!==navigator.onLine;this.#a?.getQueueSize()>0&&!this.#l?.getStatus().isSending&&e?(this.#s.log("Retry interval triggered"),this.sendEvents()):e||this.#s.log("Offline - skipping retry interval")},this.config.retryIntervalMs),this.#v=setInterval(()=>{this.#a&&this.#a.cleanDeduplicationTracker()},this.config.deduplicationWindowMs),this.#s.log("Intervals started")}catch(e){this.#s.error("Failed to start intervals:",e)}}#L(){try{this.#w&&(clearInterval(this.#w),this.#w=null),this.#v&&(clearInterval(this.#v),this.#v=null),this.#s.log("Intervals cleared")}catch(e){this.#s.error("Failed to clear intervals:",e)}}#M(e){try{this.logEvent(r.merge(r.get(e,"detail",{}),{type:r.get(e,"detail.type","custom_api_error")}))}catch(e){this.#s.error("Failed to handle custom API error:",e)}}#S(){try{this.#a?.getQueueSize()>0&&this.#a.debouncedSave.flush()}catch(e){this.#s.error("Failed to handle before unload:",e)}}#_(){try{if(!this.config.addCustomUserData||"function"!=typeof this.config.addCustomUserData)return{};const e=this.config.addCustomUserData();return e&&r.isObject(e)?e:{}}catch(e){return this.#s.warn("Failed to get custom user data:",e),{}}}#A(t){try{const o=r.get(t,"request",{}),i=this.getUserProfile(),s=this.#U(),n=this.#_(),a={scriptOrigin:"undefined"!=typeof window?window.origin:"unknown",scriptOriginPath:"undefined"!=typeof window?window.location.pathname:"unknown",pageUrl:"undefined"!=typeof window?window.location.href:"unknown",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",user:r.merge({},i,n),localStorage:s,isMonitored:this.isMonitoredEndpoint(r.get(o,"url"))},l=r.merge(a,r.get(t,"context",{}),r.get(t,"extraData",{})),c={id:e(),type:r.get(t,"type","unknown_error"),timestamp:Date.now(),appVersion:r.get(this.appContext,"appVersion"),appName:r.get(this.appContext,"appName")||"unknown",environment:r.get(this.appContext,"environment"),interceptor:r.get(o,"interceptor","manual"),request:this.#$(o),context:l,...l?.detectedEventType?{postMessageEvent:l.detectedEventType}:{}};return"p1_incident_event"===t.type&&t.p1Data&&(c.p1Data={flow:t.p1Data.flow,reason:t.p1Data.reason,failedEndpoints:t.p1Data.failedEndpoints,flowConfig:t.p1Data.flowConfig}),t.performance&&(c.performance=t.performance),t.metrics&&(c.metrics=t.metrics),t.severity&&(c.severity=t.severity),t.message&&(c.message=t.message),c}catch(e){return this.#s.error("Failed to create event:",e),{id:safeGenerateId(),type:"event_creation_error",timestamp:Date.now(),error:e.message}}}#$(e){try{const t=T(r.get(e,"url",""));return r.defaults(e,{method:"UNKNOWN",url:"",domain:t?.hostname||"",path:t?.pathname||"",status:0,statusText:"",response:"",headers:{}})}catch(t){return this.#s.error("Failed to normalize request:",t),r.defaults(e,{method:"UNKNOWN",url:"",domain:"",path:"",status:0,statusText:"",response:"",headers:{}})}}#O(e){if(this.#a)try{const t=e.filter(e=>e.success),o=e.filter(e=>!e.success);if(!r.isEmpty(t)){const e=t.map(e=>e.event.id);this.#a.removeEvents(e),this.#s.log(`Successfully sent ${t.length} events`)}r.isEmpty(o)||this.#s.warn(`Failed to send ${o.length} events`)}catch(e){this.#s.error("Failed to process results:",e)}}#U(){const e={};return(this.config.localStorageEnrichmentKeys||[]).forEach(o=>{try{const i=t(o);r.isEmpty(i)||(e[o]=i)}catch(e){this.#s.warn(`Failed to read localStorage key '${o}':`,e)}}),e}#E(){return"1.1.7"}async#T(){if(!this.#y)return this.#s.log("No remote config URL provided, using local config only"),null;try{this.#s.log(`Fetching remote config from: ${this.#y}`);const e=new URLSearchParams;"undefined"!=typeof window&&window?.location?.hostname&&e.append("hostname",window.location.hostname),this.#b?.appName&&e.append("appName",this.#b.appName);try{const t=localStorage.getItem(w.USER_PROFILE),r=t?JSON.parse(t):{};r.username&&e.append("email",r.username),r.CustomerID&&e.append("customerId",r.CustomerID),this.#s.log("Preparing config request params",{hasHostname:e.has("hostname"),hasAppName:e.has("appName"),hasUsername:!!r.username,hasCustomerId:!!r.CustomerID})}catch(e){this.#s.warn("Could not read user profile from localStorage for config request:",e)}const t=`${this.#y}${e.toString()?"?"+e.toString():""}`,r=await fetch(t,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"},signal:AbortSignal.timeout?AbortSignal.timeout(5e3):void 0});if(!r.ok)throw new Error(`Config fetch failed: ${r.status} ${r.statusText}`);const o=await r.json();if(!o||"object"!=typeof o)throw new Error("Invalid config response format");return this.#s.log("Remote config fetched successfully",{configVersion:o.configVersion,configSource:o.configSource,config:o}),o}catch(e){return this.#s.warn("Failed to fetch remote config, using local config as fallback:",e.message),null}}#C(e,t){try{let o={};e&&"object"==typeof e&&(o={...e},this.#s.log("Using remote config as base"));const i=["appName","environment","addCustomUserData","localStorageEnrichmentKeys"];i.forEach(e=>{void 0!==t[e]&&(o[e]=t[e])}),(t.service||t.serviceOptions)&&(t.service&&(o.service=t.service),t.serviceOptions&&(o.serviceOptions={...o.serviceOptions||{},...t.serviceOptions}));const s=["endpoints"];if(s.forEach(e=>{if(t[e]&&o[e]){const r=[...o[e]||[],...t[e]||[]];o[e]=[...new Set(r)]}else t[e]&&(o[e]=t[e])}),t.domainsToTrack&&o.domainsToTrack){const e=e=>e.map(e=>{if("window.location.hostname"===e||"location.hostname"===e)try{return"undefined"!=typeof window&&window.location?window.location.hostname:e}catch(t){return e}return e}),r=e(o.domainsToTrack||[]),i=e(t.domainsToTrack||[]),s=[...r,...i];o.domainsToTrack=[...new Set(s)]}else t.domainsToTrack?o.domainsToTrack=t.domainsToTrack.map(e=>{if("window.location.hostname"===e||"location.hostname"===e)try{return"undefined"!=typeof window&&window.location?window.location.hostname:e}catch(t){return e}return e}):o.domainsToTrack&&(o.domainsToTrack=o.domainsToTrack.map(e=>{if("window.location.hostname"===e||"location.hostname"===e)try{return"undefined"!=typeof window&&window.location?window.location.hostname:e}catch(t){return e}return e}));if(t.p1Config?.flows&&o.p1Config?.flows){const e=new Map;(o.p1Config.flows||[]).forEach(t=>{e.set(t.flow,t)}),(t.p1Config.flows||[]).forEach(t=>{e.set(t.flow,t)}),o.p1Config.flows=Array.from(e.values())}else t.p1Config?.flows&&(o.p1Config||(o.p1Config={}),o.p1Config.flows=t.p1Config.flows);t.p1Config&&(o.p1Config={...o.p1Config||{},...t.p1Config,flows:o.p1Config?.flows||t.p1Config.flows}),t.monitorPostMessages&&(o.monitorPostMessages=r.merge({},o.monitorPostMessages||{},t.monitorPostMessages));const n=[...i,...s,"service","serviceOptions","p1Config","monitorPostMessages"];return Object.keys(t).forEach(e=>{void 0!==o[e]||n.includes(e)||(o[e]=t[e])}),void 0!==t.debug&&(o.debug=t.debug),this.#s.log("Configuration merged successfully",{hasRemoteConfig:!!e,configSource:e?"backend+local":"local",configVersion:o.configVersion||"local"}),o}catch(e){return this.#s.error("Error merging configurations, using local config:",e),t}}getCoreWebVitalsMonitor(){return this.#u}getCoreWebVitalsMetrics(){return this.#u?this.#u.getAllMetrics():(this.#s.warn("Core Web Vitals monitor not initialized"),null)}getCoreWebVitalsInsights(){return this.#u?this.#u.getPerformanceInsights():(this.#s.warn("Core Web Vitals monitor not initialized"),null)}generateCoreWebVitalsReport(){return this.#u?this.#u.generateReport():(this.#s.warn("Core Web Vitals monitor not initialized"),null)}updateCoreWebVitalsThresholds(e){this.#u?this.#u.updateThresholds(e):this.#s.warn("Core Web Vitals monitor not initialized")}}let R;try{R=new C}catch(e){R={init:()=>Promise.reject(new Error("ApiReporter failed to initialize")),logEvent:()=>{},destroy:()=>{},debugMode:()=>{},setUserProfile:()=>{},getUserProfile:()=>({}),getQueueStatus:()=>({error:"Not available"}),getPerformanceMetrics:()=>null,getP1FlowMonitor:()=>null,getCoreWebVitalsMonitor:()=>null,getCoreWebVitalsMetrics:()=>null,getCoreWebVitalsInsights:()=>null,generateCoreWebVitalsReport:()=>null,updateCoreWebVitalsThresholds:()=>{}}}if("undefined"!=typeof window)try{window.apiReporter=R}catch(e){}const P=new C;console.log("[ApiReporter] Public entry point initialized.");let x=-1;const F=e=>{addEventListener("pageshow",t=>{t.persisted&&(x=t.timeStamp,e(t))},!0)},D=(e,t,r,o)=>{let i,s;return n=>{t.value>=0&&(n||o)&&(s=t.value-(i??0),(s||void 0===i)&&(i=t.value,t.delta=s,t.rating=((e,t)=>e>t[1]?"poor":e>t[0]?"needs-improvement":"good")(t.value,r),e(t)))}},L=e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))},I=()=>{const e=performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},q=()=>{const e=I();return e?.activationStart??0},A=(e,t=-1)=>{const r=I();let o="navigate";return x>=0?o="back-forward-cache":r&&(document.prerendering||q()>0?o="prerender":document.wasDiscarded?o="restore":r.type&&(o=r.type.replace(/_/g,"-"))),{name:e,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:o}},O=new WeakMap;function k(e,t){return O.get(e)||O.set(e,new t),O.get(e)}class _{t;i=0;o=[];h(e){if(e.hadRecentInput)return;const t=this.o[0],r=this.o.at(-1);this.i&&t&&r&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}}const U=(e,t,r={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){const o=new PerformanceObserver(e=>{Promise.resolve().then(()=>{t(e.getEntries())})});return o.observe({type:e,buffered:!0,...r}),o}}catch{}},$=e=>{let t=!1;return()=>{t||(e(),t=!0)}};let N=-1;const j=new Set,W=()=>"hidden"!==document.visibilityState||document.prerendering?1/0:0,z=e=>{if("hidden"===document.visibilityState){if("visibilitychange"===e.type)for(const e of j)e();isFinite(N)||(N="visibilitychange"===e.type?e.timeStamp:0,removeEventListener("prerenderingchange",z,!0))}},V=()=>{if(N<0){const e=q(),t=document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>"hidden"===t.name&&t.startTime>e)[0]?.startTime;N=t??W(),addEventListener("visibilitychange",z,!0),addEventListener("prerenderingchange",z,!0),F(()=>{setTimeout(()=>{N=W()})})}return{get firstHiddenTime(){return N},onHidden(e){j.add(e)}}},H=e=>{document.prerendering?addEventListener("prerenderingchange",()=>e(),!0):e()},B=[1800,3e3],Q=(e,t={})=>{H(()=>{const r=V();let o,i=A("FCP");const s=U("paint",e=>{for(const t of e)"first-contentful-paint"===t.name&&(s.disconnect(),t.startTime<r.firstHiddenTime&&(i.value=Math.max(t.startTime-q(),0),i.entries.push(t),o(!0)))});s&&(o=D(e,i,B,t.reportAllChanges),F(r=>{i=A("FCP"),o=D(e,i,B,t.reportAllChanges),L(()=>{i.value=performance.now()-r.timeStamp,o(!0)})}))})},J=[.1,.25];let K=0,X=1/0,G=0;const Y=e=>{for(const t of e)t.interactionId&&(X=Math.min(X,t.interactionId),G=Math.max(G,t.interactionId),K=G?(G-X)/7+1:0)};let Z;const ee=()=>Z?K:performance.interactionCount??0;let te=0;class re{u=[];l=new Map;m;p;v(){te=ee(),this.u.length=0,this.l.clear()}L(){const e=Math.min(this.u.length-1,Math.floor((ee()-te)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&"first-input"!==e.entryType)return;const t=this.u.at(-1);let r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.P){if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort((e,t)=>t.P-e.P),this.u.length>10){const e=this.u.splice(10);for(const t of e)this.l.delete(t.id)}this.p?.(r)}}}const oe=e=>{const t=globalThis.requestIdleCallback||setTimeout;"hidden"===document.visibilityState?e():(e=$(e),addEventListener("visibilitychange",e,{once:!0,capture:!0}),t(()=>{e(),removeEventListener("visibilitychange",e,{capture:!0})}))},ie=[200,500];class se{m;h(e){this.m?.(e)}}const ne=[2500,4e3],ae=[800,1800],le=e=>{document.prerendering?H(()=>le(e)):"complete"!==document.readyState?addEventListener("load",()=>le(e),!0):setTimeout(e)};var ce=Object.freeze({__proto__:null,CLSThresholds:J,FCPThresholds:B,INPThresholds:ie,LCPThresholds:ne,TTFBThresholds:ae,onCLS:(e,t={})=>{const r=V();Q($(()=>{let o,i=A("CLS",0);const s=k(t,_),n=e=>{for(const t of e)s.h(t);s.i>i.value&&(i.value=s.i,i.entries=s.o,o())},a=U("layout-shift",n);a&&(o=D(e,i,J,t.reportAllChanges),r.onHidden(()=>{n(a.takeRecords()),o(!0)}),F(()=>{s.i=0,i=A("CLS",0),o=D(e,i,J,t.reportAllChanges),L(()=>o())}),setTimeout(o))}))},onFCP:Q,onINP:(e,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const r=V();H(()=>{"interactionCount"in performance||Z||(Z=U("event",Y,{type:"event",buffered:!0,durationThreshold:0}));let o,i=A("INP");const s=k(t,re),n=e=>{oe(()=>{for(const t of e)s.h(t);const t=s.L();t&&t.P!==i.value&&(i.value=t.P,i.entries=t.entries,o())})},a=U("event",n,{durationThreshold:t.durationThreshold??40});o=D(e,i,ie,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),r.onHidden(()=>{n(a.takeRecords()),o(!0)}),F(()=>{s.v(),i=A("INP"),o=D(e,i,ie,t.reportAllChanges)}))})},onLCP:(e,t={})=>{H(()=>{const r=V();let o,i=A("LCP");const s=k(t,se),n=e=>{t.reportAllChanges||(e=e.slice(-1));for(const t of e)s.h(t),t.startTime<r.firstHiddenTime&&(i.value=Math.max(t.startTime-q(),0),i.entries=[t],o())},a=U("largest-contentful-paint",n);if(a){o=D(e,i,ne,t.reportAllChanges);const r=$(()=>{n(a.takeRecords()),a.disconnect(),o(!0)}),s=e=>{e.isTrusted&&(oe(r),removeEventListener(e.type,s,{capture:!0}))};for(const e of["keydown","click","visibilitychange"])addEventListener(e,s,{capture:!0});F(r=>{i=A("LCP"),o=D(e,i,ne,t.reportAllChanges),L(()=>{i.value=performance.now()-r.timeStamp,o(!0)})})}})},onTTFB:(e,t={})=>{let r=A("TTFB"),o=D(e,r,ae,t.reportAllChanges);le(()=>{const i=I();i&&(r.value=Math.max(i.responseStart-q(),0),r.entries=[i],o(!0),F(()=>{r=A("TTFB",0),o=D(e,r,ae,t.reportAllChanges),o(!0)}))})}});return P});
