@groundcover/browser 0.0.73 → 0.0.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -193,6 +193,15 @@ interface SDKOptions {
193
193
  excludedUrls?: Array<string | RegExp>;
194
194
  beforeSend?: (event: EventTypes[keyof EventTypes]) => boolean;
195
195
  enrichEvent?: (event: EventTypes[keyof EventTypes]) => EventTypes[keyof EventTypes];
196
+ sessionReplay?: {
197
+ /**
198
+ * CSS selectors whose matching elements (and their subtrees) are
199
+ * excluded from session recording. Matching elements appear in the
200
+ * replay as empty placeholders of their original size. Useful for
201
+ * skipping noisy DOM injected by browser extensions (e.g. Grammarly).
202
+ */
203
+ blockedSelectors?: string[];
204
+ };
196
205
  }
197
206
  interface SDKConfigInput {
198
207
  apiKey: string;
@@ -266,4 +275,4 @@ declare const groundcover: {
266
275
  stopReplayRecording: typeof stopReplayRecording;
267
276
  };
268
277
 
269
- export { type EventTypes, groundcover as default };
278
+ export { type EventTypes, type SDKOptions, groundcover as default };
package/dist/index.d.ts CHANGED
@@ -193,6 +193,15 @@ interface SDKOptions {
193
193
  excludedUrls?: Array<string | RegExp>;
194
194
  beforeSend?: (event: EventTypes[keyof EventTypes]) => boolean;
195
195
  enrichEvent?: (event: EventTypes[keyof EventTypes]) => EventTypes[keyof EventTypes];
196
+ sessionReplay?: {
197
+ /**
198
+ * CSS selectors whose matching elements (and their subtrees) are
199
+ * excluded from session recording. Matching elements appear in the
200
+ * replay as empty placeholders of their original size. Useful for
201
+ * skipping noisy DOM injected by browser extensions (e.g. Grammarly).
202
+ */
203
+ blockedSelectors?: string[];
204
+ };
196
205
  }
197
206
  interface SDKConfigInput {
198
207
  apiKey: string;
@@ -266,4 +275,4 @@ declare const groundcover: {
266
275
  stopReplayRecording: typeof stopReplayRecording;
267
276
  };
268
277
 
269
- export { type EventTypes, groundcover as default };
278
+ export { type EventTypes, type SDKOptions, groundcover as default };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("fflate"),t=require("error-stack-parser"),n=require("web-vitals"),i=require("rrweb"),s=require("@rrweb/packer");function r(e){return e&&e.__esModule?e:{default:e}}var a=r(t),o=console.log.bind(console),l=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&o(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},c=l.getInstance();function d(e){c.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var h="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},g=1e6,u=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)p[e]=Math.floor(16*Math.random())+48,p[e]>=58&&(p[e]+=39);return f+String.fromCharCode.apply(null,p.slice(0,16))},this.generateSpanId=m(8),this.generateId=m(16)}},p=Array(32);function m(e){return function(){for(let t=0;t<2*e;t++)p[t]=Math.floor(16*Math.random())+48,p[t]>=58&&(p[t]+=39);return String.fromCharCode.apply(null,p.slice(0,2*e))}}var f="0000000000000000";var v={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,enableCompression:!0,maskFields:[],enableMasking:!1,enabledEvents:[],tracePropagationUrls:[],tracePropagationHeaders:[],tracePropagationTraceIdHeaderName:"",tracePropagationSpanIdHeaderName:"",traceOrigin:{name:"",value:""}},y=class{constructor(e){this.dsn=e?.dsn||"",this.appId=e?.appId||"",this.cluster=e?.cluster||"",this.apiKey=e?.apiKey||"",this.environment=e?.environment||"",this.namespace=e?.namespace||"",this.releaseId=e?.releaseId,this.userIdentifier=e?.userIdentifier||null,this.options={...v,...e?.options||{}}}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(e){e.options&&(this.options={...this.options,...e.options}),e.userIdentifier&&(this.userIdentifier={...this.userIdentifier,...e.userIdentifier}),e.appId&&(this.appId=e.appId),e.dsn&&(this.dsn=e.dsn),e.apiKey&&(this.apiKey=e.apiKey),e.cluster&&(this.cluster=e.cluster),e.environment&&(this.environment=e.environment),e.namespace&&(this.namespace=e.namespace),e.releaseId&&(this.releaseId=e.releaseId)}};function E(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return d(e),null}}function b(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){d(e)}}function I(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){d(e)}}var S=class e{constructor(){this.config=null,this.logger=l.getInstance(),this.sessionId=null,this.sessionStartTime=null}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new y(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;return E("gcId")||""}setSessionId(e){this.sessionId=e,b("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:function(e,t=0){const n=E(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,b("gcStartTime",String(e))}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e)),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},T=S.getInstance(),w=new u,N=l.getInstance();function R(){const e=T?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function L(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:null!=(s=e)&&"number"==typeof s.nodeType&&"string"==typeof s.nodeName?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,r])=>{const a=t?`${t}.${s}`:s;return"object"==typeof r&&null!==r?Array.isArray(r)?e[a]=r.map(((e,t)=>"object"==typeof e&&null!==e?L(e,`${a}[${t}]`,n,i+1):e)):Object.assign(e,L(r,a,n,i+1)):e[a]=r,e}),{}))}catch(e){return N.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}var s}function C(e){const t=Date.now()*g,n=w.generateId(),i=e.spanId||w.generateSpanId(),s=e.traceId||w.generateTraceId(),r=e.parentSpanId||"",a=L(e.attributes||{}),o=function(){const e=h?.location;return e?{path:e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/")?e.hash:e.pathname,url:e.href,title:h?.document?.title||""}:{path:"",url:"",title:h?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:r,traceId:s,attributes:{...a,location:o}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var _=class{constructor(){this.logger=l.getInstance(),this.config=S.getInstance()}compress(t){const n=this.config.getConfig();if(!n?.options?.enableCompression)return{data:(new TextEncoder).encode(t),isCompressed:!1};try{const n=e.strToU8(t);return{data:e.gzipSync(n),isCompressed:!0}}catch(e){return{data:(new TextEncoder).encode(t),isCompressed:!1}}}async send(e){const t=this.config.getConfig();if(t)try{t?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,i=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");const s=JSON.stringify(e),{data:r,isCompressed:a}=this.compress(s);fetch(i,{method:"POST",headers:{"Content-Type":"application/json",apikey:n,"Content-Encoding":a?"gzip":""},body:r,keepalive:!0}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},z=["navigation","dom.event"],H=class e{constructor(){this.events=[],this.timeoutId=null,this.config=S.getInstance(),this.logger=l.getInstance(),this.initialized=!1,this.transporter=new _}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.flush()})),this.initialized=!0}catch(e){d(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend,n=this.config.getConfig()?.options?.enrichEvent;if(t&&!t(e))return;n&&(e=n(e)),this.events.push(e);const i=this.config.getConfig()?.options?.batchSize||100;this.events.length>=i&&!z.includes(e.type)&&this.flush()}catch(e){d(e)}}flush(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){d(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){d(e)}}scheduleFlush(){try{null!==this.timeoutId&&(h.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=h.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){d(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:i,language:navigator.language,mobile:s}}getSessionAttributes(){const e=this.detectBrowser(),t=this.config.getConfig();return{cluster:t?.cluster||"",env:t?.environment||"",namespace:t?.namespace||"",releaseId:t?.releaseId||"",session_id:this.config.getSessionId(),session_start_time:this.config.getSessionStartTime(),user:t?.userIdentifier||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};H.instance=null;var q=H,k=class{constructor(){this.logger=l.getInstance(),this.eventsPool=q.getInstance()}};function x({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var P="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function D(e,t){try{return e.getAttribute(t)||""}catch{return""}}function M(e){try{const t=P?.call(e);return"string"==typeof t?t:""}catch{return""}}var A=class extends k{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=S.getInstance(),this.getShouldMaskText=e=>{const t=this.config.getConfig(),n=t?.options?.maskFields||[],i=t?.options?.enableMasking||!1;return(["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.hasAttribute("data-private")].some((e=>e))||n.some((t=>e.target?.id?.toLowerCase().includes(t))))&&i},this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>{const t=e.target,n=this.config.getConfig();return n?.options?.enableMasking||!1?"*":x({text:t.innerText||""})},this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){d(e)}};this.eventHandlers.push({type:e,handler:t}),h?.addEventListener(e,t)}))}catch(e){d(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!R())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){d(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),i=e.target,s=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return C({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:s,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:D(i,"id"),tagName:M(i),className:D(i,"class"),text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,i=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===M(e).toLowerCase())return"html";let r="",a=0,o=e;const l=[];for(;o&&o!==n&&o!==document.documentElement&&a<i;){let e=M(o).toLowerCase();try{const t=o.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(o.classList?.length){const t=Array.from(o.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=o.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=M(o).toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{o=o.parentElement}catch(e){break}a++}return r||"*"}},F=["log","info","warn","error","assert","trace"],O=class extends k{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),F.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){d(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){d(e)}}destroy(){try{if(!this.isInitialized)return;F.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){d(e)}}handleEvent(e,t){try{if(!R())return;const n=this.formatMessage(Array.isArray(e)?e:[e],t);if(!n||n?.includes("groundcoverIgnore"))return;const i=this.buildEvent({message:n,level:t});this.queueEvent(i)}catch(e){d(e)}}buildEvent({message:e,level:t}){return C({type:"log",attributes:{message:x({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return d(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{F.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){d(e)}return e}};function U(e){try{if(null==e)return"";if("string"==typeof e)return e;if(e instanceof FormData)return"[form data]";if(e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if("undefined"!=typeof Document){if(e instanceof Document)return"[document data]";const t=e;if(9===t?.nodeType)return"[document data]"}if(e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return d(`Failed to format body: ${e}`),"[unreadable body]"}}var j,$=class extends k{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=S.getInstance(),this.idGenerator=new u,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!R())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){d(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const i=this.formatHeaders(e.request.headers),s=this.formatHeaders(e.response.headers),r=e.method?.toUpperCase()||"UNKNOWN",{traceId:a,spanId:o}=this.extractTraceIds(e.request.headers),l=x({text:e.request.body,maxLength:this.maxBodyLength}),c=x({text:e.response.body,maxLength:this.maxBodyLength}),d={type:"HTTP",operation:{name:r},resource_name:t,status:e.status?.toString(),subType:r,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:i,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:l},response:{body:c}}},h={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?e.timestamp*g:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?e.end_time*g:void 0,span_name:`${e.method} ${t}`,attributes:d};return a&&(h.traceId=a),o&&(h.spanId=o),C(h)}}async getResponseBody(e){let t;try{const n=e.clone().body;if(n){let e,i=n.getReader(),s=new TextDecoder,r="";for(;!(e=await i.read()).done;){let t=e.value;r+=s.decode(t)}t=r}else t=""}catch(e){t=`Unable to clone response: ${e}`}return t}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{const t=this.config.getConfig()?.getEndpoint();if(t&&e.includes(t))return!0;if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return d(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,i=globalThis.XMLHttpRequest.prototype.setRequestHeader;let s;globalThis.XMLHttpRequest.prototype.open=function(n,i,r=!0,a,o){if(s=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,r,a,o]);const l=new URL(i.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,i,r,a,o])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),i.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const i=this._requestUrl?.toString();if(!i||e.shouldIgnoreRequest(i))return n.apply(this,t);if(e.shouldAddTraceHeader(i)){const t=e.config.getConfig(),n=e.getTraceIds();t?.options?.traceOrigin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),n&&(t?.options?.tracePropagationTraceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracePropagationHeaders)&&t?.options?.tracePropagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracePropagationHeaders?.length||e.addHeaderToXhrRequest({request:this,headerName:"traceparent",headerValue:n.traceparent}))}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,i]=e.split(": ");t&&i&&(n[t.trim()]=i.trim())}));const i=U(this._requestBody),r=U(""===this.responseType||"text"===this.responseType?this.responseText:this.response),a={timestamp:s,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:r}};e.handleEvent(a)})),n.apply(this,t)}}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){const t=this.config.getConfig(),n=this.getTraceIds();if(t?.options?.traceOrigin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),!n)return;t?.options?.tracePropagationTraceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracePropagationHeaders;(i?.length?i:["traceparent"]).forEach((t=>{this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n.traceparent})}))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[i,s]=t;s={...s||{}},t[1]=s;const r=i instanceof Request,a=s?.method||"GET",o=s?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);s||(t[1]={},s=t[1]),s.headers=this.normalizeHeaders(r?i.headers:void 0,s.headers),c&&this.addTraceHeaders(s);const d=this.extractHeadersRecord(s.headers),h=U(o);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i=e.clone(),s={};i.headers.forEach(((e,t)=>{s[t]=e}));const r={method:a,url:l,timestamp:n,body:h,status:i.status,end_time:t,request:{headers:d,body:h},response:{headers:s,body:""}};try{s["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(i).then((e=>{r.response.body=e,this.handleEvent(r)})).catch((e=>{r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}))}catch(e){r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}return e})).catch((e=>{const t=Date.now();let n="NetworkError";const i=e.message||"Unknown network error";e instanceof TypeError&&i.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":i.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":i.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const s={method:a,url:l,body:h,status:0,end_time:t,request:{headers:d,body:h},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(s),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,i])=>{const s=n.toLowerCase();return t.includes(s)||/(token|key|secret|password)/i.test(s)?e[n]="[REDACTED]":e[n]=x({text:i}),e}),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracePropagationTraceIdHeaderName){const i=e[t.options.tracePropagationTraceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracePropagationSpanIdHeaderName){const n=e[t.options.tracePropagationSpanIdHeaderName];n&&"string"==typeof n&&(i=n)}if(!n||!i){const t=this.extractTraceparentHeader(e);if(t){const e=t.split("-");4===e.length&&"00"===e[0]&&(!n&&e[1]&&32===e[1].length&&(n=e[1]),!i&&e[2]&&16===e[2].length&&(i=e[2]))}}return{traceId:n,spanId:i}}extractTraceparentHeader(e){const t=this.config.getConfig();if(t?.options?.tracePropagationHeaders?.length)for(const n of t.options.tracePropagationHeaders){const t=e[n];if(t&&"string"==typeof t)return t}const n=e.traceparent;return n&&"string"==typeof n?n:""}getTraceIds(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();let n,i;try{n=BigInt("0x"+t).toString(10),i=BigInt("0x"+e).toString(10)}catch(s){this.logger.log("[network-events-listener.getTraceIds] error",{error:s}),n=t,i=e}return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e,decimalTraceId:n,decimalSpanId:i}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}isValidHeaderName(e){if(!e||"string"!=typeof e)return!1;return/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t?.options?.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),s=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(s)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},K=class extends k{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const i=this.buildEvent(n,t);this.queueEvent(i)}catch(e){d(e)}}}initialize(){h?.addEventListener("error",this.handleEvent),h?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){h?.removeEventListener("error",this.handleEvent),h?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return C({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${x({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:t?.metadata}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}enhanceError(e,t){const{filename:n,lineno:i,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return a.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},X=class extends k{constructor({isEnabled:e}){if(super(),this.currentUrl="",this.originalPushState=null,this.originalReplaceState=null,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&e)try{this.isAutomaticNavigationEnabled=e,this.currentUrl=h.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){d(e)}}isInBrowserEnvironment(){try{return void 0!==h&&void 0!==h.location&&void 0!==h.history&&"function"==typeof h.addEventListener}catch(e){return d(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||!this.originalPushState||!this.originalReplaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");const e=this.originalPushState,t=this.originalReplaceState;history.pushState=(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n},history.replaceState=(...e)=>{const n=t.apply(history,e);return this.handleLocationChange(),n},h&&"function"==typeof h.addEventListener&&(h.addEventListener("popstate",this.popStateHandler),h.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){d(e)}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.isInitialized&&this.originalPushState&&this.originalReplaceState&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState),h&&"function"==typeof h.removeEventListener&&(h.removeEventListener("popstate",this.popStateHandler),h.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){d(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){d(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",h.location.href);return C({type:"navigation",attributes:{page_url:h.location.href,metadata:this.activeNavigation?.metadata,duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}startNavigation(e){this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:h.location.href,metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}endNavigation(e){this.logger.log("[navigation-listener.endNavigation] called",e),this.activeNavigation?(this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()):this.logger.log("[navigation-listener.endNavigation] no active navigation found")}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===h.location.href)return;let e,t;try{e=new URL(h.location.href),t=new URL(this.currentUrl)}catch(e){return void d(e)}const n=e=>e.startsWith("#/"),i=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||i&&e.hash!==t.hash)&&(this.currentUrl=h.location.href,this.handleEvent())}catch(e){d(e)}}},B=class extends k{constructor(){super(),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",h),"complete"===h?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):h?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),d(e)}}destroy(){h?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){d(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),i={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,r=t.initiatorType;i.totalSize+=n,i.totalDuration+=s,i.byType[r]||(i.byType[r]={count:0,size:0,duration:0}),i.byType[r].count++,i.byType[r].size+=n,i.byType[r].duration+=s}));return C({type:"pageload",attributes:{page_url:h?.location?.href||"",page_load_time:t,page_referrer:h?.document?.referrer||"",page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}},V=class extends k{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!R())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){d(e)}}}initialize(){n.onCLS(this.handleEvent),n.onLCP(this.handleEvent),n.onFCP(this.handleEvent),n.onTTFB(this.handleEvent),n.onINP(this.handleEvent)}destroy(){}buildEvent(e){return C({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}},G=class{constructor(e){this.logger=l.getInstance(),this.eventsPool=q.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.inactivityTimer=null,this.onInactivityStop=e??null}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.stopFn=i.record({slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},packFn:s.pack,checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{if(t||this.resetInactivityTimer(),this.events.push(e),t&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),this.events.length>=this.batchSize)try{this.sendBatch()}catch(e){d(e),this.logger.log("[session-replay-listener] failed to send batch in emit callback:",e)}}catch(e){d(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.resetInactivityTimer(),this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){d(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout((()=>{this.logger.log("[session-replay-listener] stopping recording due to inactivity"),this.stopRecording();try{this.onInactivityStop?.()}catch(e){d(e),this.logger.log("[session-replay-listener] onInactivityStop error:",e)}}),18e5)}clearInactivityTimer(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null)}sendBatch(){if(0!==this.events.length)try{const e=[...this.events],t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp,i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const s=C({type:"replay",attributes:i});this.eventsPool.addEvent(s),this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){d(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording&&this.stopFn)try{this.clearInactivityTimer(),this.stopFn(),this.isRecording=!1;const e=this.events.length;if(e>0)try{const t={_gc_replay_data:{events:[...this.events]}};this.batchContainsFullSnapshot&&(t.replay_is_full_snapshot=!0,t.replay_full_snapshot_timestamp=this.fullSnapshotTimestamp);const n=C({type:"replay",attributes:t});this.eventsPool.addEvent(n),this.logger.log("[session-replay-listener] sent final replay event with",e,"events")}catch(e){d(e),this.logger.log("[session-replay-listener] failed to encode and send final replay event:",e)}this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){d(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},W=class{constructor(){this.logger=l.getInstance(),this.eventsPool=q.getInstance(),this.configManager=S.getInstance(),this.idGenerator=new u,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called");const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new B,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new A,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new O,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new K,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new $,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new V,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new X({isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),i.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",i)}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=C({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){d(e)}}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){d(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}startReplayRecording(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new G((()=>{this.handleReplayInactivityStop()}));e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){d(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}handleReplayInactivityStop(){this.logger.log("[instrumentation-manager] replay stopped due to inactivity, rotating session");try{this.eventsPool.flush()}catch(e){d(e),this.logger.log("[instrumentation-manager] failed to flush events before session rotation:",e)}try{const e=this.idGenerator.generateId(),t=Date.now()*g;this.configManager.setSessionId(e),this.configManager.setSessionStartTime(t)}catch(e){d(e),this.logger.log("[instrumentation-manager] failed to rotate session after inactivity:",e)}finally{this.sessionReplayListener=null}}stopReplayRecording(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy()}},J="gcSample",Y=class{constructor(e){this.initialized=!1,this.logger=l.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new W,this.idGenerator=new u;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=S.getInstance();t.initialize(e);q.getInstance().initialize();const n=e.sessionId,i=t.getSessionId();n?(t.setSessionId(n),this.logger.log("[session-manager] using provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId()),t.getSessionStartTime()||t.setSessionStartTime(Date.now()*g),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=E(J);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return b(J,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");S.getInstance().updateConfig({userIdentifier:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");S.getInstance().updateConfig(e)}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.initialized?this.instrumentationManager.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.initialized?this.instrumentationManager.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.initialized?this.instrumentationManager.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}getSessionId(){return this.initialized?S.getInstance().getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.initialized)try{const t=q.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=S.getInstance();i.setSessionId(n),i.setSessionStartTime(Date.now()*g),this.logger.log("[session-manager] session ID set successfully:",n)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.initialized?this.instrumentationManager.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.initialized?this.instrumentationManager.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),I("gcId"),I("gcStartTime"),this.initialized=!1)}};var Z={init:function(e){try{j=new Y({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",userIdentifier:e?.userIdentifier,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId})}catch(e){d(e)}},identifyUser:function(e){j?j.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){j&&j.sendCustomEvent(e)},captureException:function(e,t){j&&j.captureException(e,t)},updateConfig:function(e){j&&j.updateConfig(e)},startNavigation:function(e){j?j.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){j?j.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return j?j.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(j)try{await j.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){j?j.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){j?j.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Z}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var Q=Z;module.exports=Q;
1
+ "use strict";var e=require("fflate"),t=require("error-stack-parser"),n=require("web-vitals"),i=require("rrweb"),s=require("@rrweb/packer");function r(e){return e&&e.__esModule?e:{default:e}}var a=r(t),o=console.log.bind(console),l=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&o(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},c=l.getInstance();function d(e){c.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var h="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},g=1e6,u=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)p[e]=Math.floor(16*Math.random())+48,p[e]>=58&&(p[e]+=39);return f+String.fromCharCode.apply(null,p.slice(0,16))},this.generateSpanId=m(8),this.generateId=m(16)}},p=Array(32);function m(e){return function(){for(let t=0;t<2*e;t++)p[t]=Math.floor(16*Math.random())+48,p[t]>=58&&(p[t]+=39);return String.fromCharCode.apply(null,p.slice(0,2*e))}}var f="0000000000000000";var v={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,enableCompression:!0,maskFields:[],enableMasking:!1,enabledEvents:[],tracePropagationUrls:[],tracePropagationHeaders:[],tracePropagationTraceIdHeaderName:"",tracePropagationSpanIdHeaderName:"",traceOrigin:{name:"",value:""}},y=class{constructor(e){this.dsn=e?.dsn||"",this.appId=e?.appId||"",this.cluster=e?.cluster||"",this.apiKey=e?.apiKey||"",this.environment=e?.environment||"",this.namespace=e?.namespace||"",this.releaseId=e?.releaseId,this.userIdentifier=e?.userIdentifier||null,this.options={...v,...e?.options||{}}}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(e){e.options&&(this.options={...this.options,...e.options}),e.userIdentifier&&(this.userIdentifier={...this.userIdentifier,...e.userIdentifier}),e.appId&&(this.appId=e.appId),e.dsn&&(this.dsn=e.dsn),e.apiKey&&(this.apiKey=e.apiKey),e.cluster&&(this.cluster=e.cluster),e.environment&&(this.environment=e.environment),e.namespace&&(this.namespace=e.namespace),e.releaseId&&(this.releaseId=e.releaseId)}};function E(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return d(e),null}}function b(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){d(e)}}function I(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){d(e)}}var S=class e{constructor(){this.config=null,this.logger=l.getInstance(),this.sessionId=null,this.sessionStartTime=null}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new y(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;return E("gcId")||""}setSessionId(e){this.sessionId=e,b("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:function(e,t=0){const n=E(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,b("gcStartTime",String(e))}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e)),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},T=S.getInstance(),w=new u,R=l.getInstance();function N(){const e=T?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function L(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:null!=(s=e)&&"number"==typeof s.nodeType&&"string"==typeof s.nodeName?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,r])=>{const a=t?`${t}.${s}`:s;return"object"==typeof r&&null!==r?Array.isArray(r)?e[a]=r.map(((e,t)=>"object"==typeof e&&null!==e?L(e,`${a}[${t}]`,n,i+1):e)):Object.assign(e,L(r,a,n,i+1)):e[a]=r,e}),{}))}catch(e){return R.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}var s}function C(e){const t=Date.now()*g,n=w.generateId(),i=e.spanId||w.generateSpanId(),s=e.traceId||w.generateTraceId(),r=e.parentSpanId||"",a=L(e.attributes||{}),o=function(){const e=h?.location;return e?{path:e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/")?e.hash:e.pathname,url:e.href,title:h?.document?.title||""}:{path:"",url:"",title:h?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:r,traceId:s,attributes:{...a,location:o}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var z=class{constructor(){this.logger=l.getInstance(),this.config=S.getInstance()}compress(t){const n=this.config.getConfig();if(!n?.options?.enableCompression)return{data:(new TextEncoder).encode(t),isCompressed:!1};try{const n=e.strToU8(t);return{data:e.gzipSync(n),isCompressed:!0}}catch(e){return{data:(new TextEncoder).encode(t),isCompressed:!1}}}async send(e){const t=this.config.getConfig();if(t)try{t?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,i=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");const s=JSON.stringify(e),{data:r,isCompressed:a}=this.compress(s);fetch(i,{method:"POST",headers:{"Content-Type":"application/json",apikey:n,"Content-Encoding":a?"gzip":""},body:r}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},H=["navigation","dom.event"],_=class e{constructor(){this.events=[],this.timeoutId=null,this.config=S.getInstance(),this.logger=l.getInstance(),this.initialized=!1,this.transporter=new z}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.flush()})),this.initialized=!0}catch(e){d(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend,n=this.config.getConfig()?.options?.enrichEvent;if(t&&!t(e))return;n&&(e=n(e)),this.events.push(e);const i=this.config.getConfig()?.options?.batchSize||100;this.events.length>=i&&!H.includes(e.type)&&this.flush()}catch(e){d(e)}}flush(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){d(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){d(e)}}scheduleFlush(){try{null!==this.timeoutId&&(h.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=h.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){d(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:i,language:navigator.language,mobile:s}}getSessionAttributes(){const e=this.detectBrowser(),t=this.config.getConfig();return{cluster:t?.cluster||"",env:t?.environment||"",namespace:t?.namespace||"",releaseId:t?.releaseId||"",session_id:this.config.getSessionId(),session_start_time:this.config.getSessionStartTime(),user:t?.userIdentifier||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};_.instance=null;var q=_,k=class{constructor(){this.logger=l.getInstance(),this.eventsPool=q.getInstance()}};function x({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var P="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function D(e,t){try{return e.getAttribute(t)||""}catch{return""}}function M(e){try{const t=P?.call(e);return"string"==typeof t?t:""}catch{return""}}var A=class extends k{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=S.getInstance(),this.getShouldMaskText=e=>{const t=this.config.getConfig(),n=t?.options?.maskFields||[],i=t?.options?.enableMasking||!1;return(["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.hasAttribute("data-private")].some((e=>e))||n.some((t=>e.target?.id?.toLowerCase().includes(t))))&&i},this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>{const t=e.target,n=this.config.getConfig();return n?.options?.enableMasking||!1?"*":x({text:t.innerText||""})},this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){d(e)}};this.eventHandlers.push({type:e,handler:t}),h?.addEventListener(e,t)}))}catch(e){d(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!N())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){d(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),i=e.target,s=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return C({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:s,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:D(i,"id"),tagName:M(i),className:D(i,"class"),text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,i=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===M(e).toLowerCase())return"html";let r="",a=0,o=e;const l=[];for(;o&&o!==n&&o!==document.documentElement&&a<i;){let e=M(o).toLowerCase();try{const t=o.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(o.classList?.length){const t=Array.from(o.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=o.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=M(o).toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{o=o.parentElement}catch(e){break}a++}return r||"*"}},F=["log","info","warn","error","assert","trace"],O=class extends k{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),F.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){d(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){d(e)}}destroy(){try{if(!this.isInitialized)return;F.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){d(e)}}handleEvent(e,t){try{if(!N())return;const n=this.formatMessage(Array.isArray(e)?e:[e],t);if(!n||n?.includes("groundcoverIgnore"))return;const i=this.buildEvent({message:n,level:t});this.queueEvent(i)}catch(e){d(e)}}buildEvent({message:e,level:t}){return C({type:"log",attributes:{message:x({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return d(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{F.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){d(e)}return e}};function U(e){try{if(null==e)return"";if("string"==typeof e)return e;if(e instanceof FormData)return"[form data]";if(e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if("undefined"!=typeof Document){if(e instanceof Document)return"[document data]";const t=e;if(9===t?.nodeType)return"[document data]"}if(e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return d(`Failed to format body: ${e}`),"[unreadable body]"}}var j,$=class extends k{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=S.getInstance(),this.idGenerator=new u,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!N())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){d(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const i=this.formatHeaders(e.request.headers),s=this.formatHeaders(e.response.headers),r=e.method?.toUpperCase()||"UNKNOWN",{traceId:a,spanId:o}=this.extractTraceIds(e.request.headers),l=x({text:e.request.body,maxLength:this.maxBodyLength}),c=x({text:e.response.body,maxLength:this.maxBodyLength}),d={type:"HTTP",operation:{name:r},resource_name:t,status:e.status?.toString(),subType:r,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:i,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:l},response:{body:c}}},h={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?e.timestamp*g:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?e.end_time*g:void 0,span_name:`${e.method} ${t}`,attributes:d};return a&&(h.traceId=a),o&&(h.spanId=o),C(h)}}async getResponseBody(e){let t;try{const n=e.clone().body;if(n){let e,i=n.getReader(),s=new TextDecoder,r="";for(;!(e=await i.read()).done;){let t=e.value;r+=s.decode(t)}t=r}else t=""}catch(e){t=`Unable to clone response: ${e}`}return t}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{const t=this.config.getConfig()?.getEndpoint();if(t&&e.includes(t))return!0;if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return d(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,i=globalThis.XMLHttpRequest.prototype.setRequestHeader;let s;globalThis.XMLHttpRequest.prototype.open=function(n,i,r=!0,a,o){if(s=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,r,a,o]);const l=new URL(i.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,i,r,a,o])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),i.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const i=this._requestUrl?.toString();if(!i||e.shouldIgnoreRequest(i))return n.apply(this,t);if(e.shouldAddTraceHeader(i)){const t=e.config.getConfig(),n=e.getTraceIds();t?.options?.traceOrigin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),n&&(t?.options?.tracePropagationTraceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracePropagationHeaders)&&t?.options?.tracePropagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracePropagationHeaders?.length||e.addHeaderToXhrRequest({request:this,headerName:"traceparent",headerValue:n.traceparent}))}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,i]=e.split(": ");t&&i&&(n[t.trim()]=i.trim())}));const i=U(this._requestBody),r=U(""===this.responseType||"text"===this.responseType?this.responseText:this.response),a={timestamp:s,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:r}};e.handleEvent(a)})),n.apply(this,t)}}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){const t=this.config.getConfig(),n=this.getTraceIds();if(t?.options?.traceOrigin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),!n)return;t?.options?.tracePropagationTraceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracePropagationHeaders;(i?.length?i:["traceparent"]).forEach((t=>{this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n.traceparent})}))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[i,s]=t;s={...s||{}},t[1]=s;const r=i instanceof Request,a=s?.method||"GET",o=s?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);s||(t[1]={},s=t[1]),s.headers=this.normalizeHeaders(r?i.headers:void 0,s.headers),c&&this.addTraceHeaders(s);const d=this.extractHeadersRecord(s.headers),h=U(o);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i=e.clone(),s={};i.headers.forEach(((e,t)=>{s[t]=e}));const r={method:a,url:l,timestamp:n,body:h,status:i.status,end_time:t,request:{headers:d,body:h},response:{headers:s,body:""}};try{s["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(i).then((e=>{r.response.body=e,this.handleEvent(r)})).catch((e=>{r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}))}catch(e){r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}return e})).catch((e=>{const t=Date.now();let n="NetworkError";const i=e.message||"Unknown network error";e instanceof TypeError&&i.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":i.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":i.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const s={method:a,url:l,body:h,status:0,end_time:t,request:{headers:d,body:h},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(s),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,i])=>{const s=n.toLowerCase();return t.includes(s)||/(token|key|secret|password)/i.test(s)?e[n]="[REDACTED]":e[n]=x({text:i}),e}),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracePropagationTraceIdHeaderName){const i=e[t.options.tracePropagationTraceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracePropagationSpanIdHeaderName){const n=e[t.options.tracePropagationSpanIdHeaderName];n&&"string"==typeof n&&(i=n)}if(!n||!i){const t=this.extractTraceparentHeader(e);if(t){const e=t.split("-");4===e.length&&"00"===e[0]&&(!n&&e[1]&&32===e[1].length&&(n=e[1]),!i&&e[2]&&16===e[2].length&&(i=e[2]))}}return{traceId:n,spanId:i}}extractTraceparentHeader(e){const t=this.config.getConfig();if(t?.options?.tracePropagationHeaders?.length)for(const n of t.options.tracePropagationHeaders){const t=e[n];if(t&&"string"==typeof t)return t}const n=e.traceparent;return n&&"string"==typeof n?n:""}getTraceIds(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();let n,i;try{n=BigInt("0x"+t).toString(10),i=BigInt("0x"+e).toString(10)}catch(s){this.logger.log("[network-events-listener.getTraceIds] error",{error:s}),n=t,i=e}return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e,decimalTraceId:n,decimalSpanId:i}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}isValidHeaderName(e){if(!e||"string"!=typeof e)return!1;return/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t?.options?.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),s=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(s)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},B=class extends k{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const i=this.buildEvent(n,t);this.queueEvent(i)}catch(e){d(e)}}}initialize(){h?.addEventListener("error",this.handleEvent),h?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){h?.removeEventListener("error",this.handleEvent),h?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return C({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${x({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:t?.metadata}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}enhanceError(e,t){const{filename:n,lineno:i,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return a.default.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},K=class extends k{constructor({isEnabled:e}){if(super(),this.currentUrl="",this.originalPushState=null,this.originalReplaceState=null,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&e)try{this.isAutomaticNavigationEnabled=e,this.currentUrl=h.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){d(e)}}isInBrowserEnvironment(){try{return void 0!==h&&void 0!==h.location&&void 0!==h.history&&"function"==typeof h.addEventListener}catch(e){return d(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||!this.originalPushState||!this.originalReplaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");const e=this.originalPushState,t=this.originalReplaceState;history.pushState=(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n},history.replaceState=(...e)=>{const n=t.apply(history,e);return this.handleLocationChange(),n},h&&"function"==typeof h.addEventListener&&(h.addEventListener("popstate",this.popStateHandler),h.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){d(e)}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.isInitialized&&this.originalPushState&&this.originalReplaceState&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState),h&&"function"==typeof h.removeEventListener&&(h.removeEventListener("popstate",this.popStateHandler),h.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){d(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){d(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",h.location.href);return C({type:"navigation",attributes:{page_url:h.location.href,metadata:this.activeNavigation?.metadata,duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}startNavigation(e){this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:h.location.href,metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}endNavigation(e){this.logger.log("[navigation-listener.endNavigation] called",e),this.activeNavigation?(this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()):this.logger.log("[navigation-listener.endNavigation] no active navigation found")}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===h.location.href)return;let e,t;try{e=new URL(h.location.href),t=new URL(this.currentUrl)}catch(e){return void d(e)}const n=e=>e.startsWith("#/"),i=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||i&&e.hash!==t.hash)&&(this.currentUrl=h.location.href,this.handleEvent())}catch(e){d(e)}}},X=class extends k{constructor(){super(),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",h),"complete"===h?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):h?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),d(e)}}destroy(){h?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){d(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),i={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,r=t.initiatorType;i.totalSize+=n,i.totalDuration+=s,i.byType[r]||(i.byType[r]={count:0,size:0,duration:0}),i.byType[r].count++,i.byType[r].size+=n,i.byType[r].duration+=s}));return C({type:"pageload",attributes:{page_url:h?.location?.href||"",page_load_time:t,page_referrer:h?.document?.referrer||"",page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}},V=class extends k{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!N())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){d(e)}}}initialize(){n.onCLS(this.handleEvent),n.onLCP(this.handleEvent),n.onFCP(this.handleEvent),n.onTTFB(this.handleEvent),n.onINP(this.handleEvent)}destroy(){}buildEvent(e){return C({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){d(e)}}},G=class{constructor(e){this.logger=l.getInstance(),this.eventsPool=q.getInstance(),this.configManager=S.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.inactivityTimer=null,this.sendTimerId=null,this.onInactivityStop=e??null}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0;const e=this.configManager.getConfig()?.options?.sessionReplay?.blockedSelectors?.filter(Boolean),t=e?.length?e.join(", "):void 0;this.stopFn=i.record({...t?{blockSelector:t}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{t||this.resetInactivityTimer(),this.events.push(e),t&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),this.events.length>=this.batchSize&&this.scheduleSendBatch()}catch(e){d(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.resetInactivityTimer(),this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){d(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=h.setTimeout((()=>{if(this.sendTimerId=null,this.isRecording)try{this.sendBatch()}catch(e){d(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}}),0))}clearScheduledSend(){null!==this.sendTimerId&&(h.clearTimeout(this.sendTimerId),this.sendTimerId=null)}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout((()=>{this.logger.log("[session-replay-listener] stopping recording due to inactivity"),this.stopRecording();try{this.onInactivityStop?.()}catch(e){d(e),this.logger.log("[session-replay-listener] onInactivityStop error:",e)}}),18e5)}clearInactivityTimer(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null)}sendBatch(){if(0!==this.events.length)try{const e=this.events.map((e=>s.pack(e))),t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp,i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const r=C({type:"replay",attributes:i});this.eventsPool.addEvent(r),this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){d(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearInactivityTimer(),this.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatch(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){d(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},W=class{constructor(){this.logger=l.getInstance(),this.eventsPool=q.getInstance(),this.configManager=S.getInstance(),this.idGenerator=new u,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called");const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new X,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new A,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new O,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new B,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new $,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new V,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new K({isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),i.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",i)}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=C({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){d(e)}}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){d(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}startReplayRecording(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new G((()=>{this.handleReplayInactivityStop()}));e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){d(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}handleReplayInactivityStop(){this.logger.log("[instrumentation-manager] replay stopped due to inactivity, rotating session");try{this.eventsPool.flush()}catch(e){d(e),this.logger.log("[instrumentation-manager] failed to flush events before session rotation:",e)}try{const e=this.idGenerator.generateId(),t=Date.now()*g;this.configManager.setSessionId(e),this.configManager.setSessionStartTime(t)}catch(e){d(e),this.logger.log("[instrumentation-manager] failed to rotate session after inactivity:",e)}finally{this.sessionReplayListener=null}}stopReplayRecording(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy()}},J="gcSample",Y=class{constructor(e){this.initialized=!1,this.logger=l.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new W,this.idGenerator=new u;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=S.getInstance();t.initialize(e);q.getInstance().initialize();const n=e.sessionId,i=t.getSessionId();n?(t.setSessionId(n),this.logger.log("[session-manager] using provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId()),t.getSessionStartTime()||t.setSessionStartTime(Date.now()*g),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=E(J);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return b(J,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");S.getInstance().updateConfig({userIdentifier:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");S.getInstance().updateConfig(e)}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.initialized?this.instrumentationManager.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.initialized?this.instrumentationManager.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.initialized?this.instrumentationManager.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}getSessionId(){return this.initialized?S.getInstance().getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.initialized)try{const t=q.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=S.getInstance();i.setSessionId(n),i.setSessionStartTime(Date.now()*g),this.logger.log("[session-manager] session ID set successfully:",n)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.initialized?this.instrumentationManager.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.initialized?this.instrumentationManager.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),I("gcId"),I("gcStartTime"),this.initialized=!1)}};var Z={init:function(e){try{j=new Y({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",userIdentifier:e?.userIdentifier,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId})}catch(e){d(e)}},identifyUser:function(e){j?j.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){j&&j.sendCustomEvent(e)},captureException:function(e,t){j&&j.captureException(e,t)},updateConfig:function(e){j&&j.updateConfig(e)},startNavigation:function(e){j?j.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){j?j.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return j?j.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(j)try{await j.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){j?j.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){j?j.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Z}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var Q=Z;module.exports=Q;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{strToU8 as e,gzipSync as t}from"fflate";import n from"error-stack-parser";import{onCLS as i,onLCP as s,onFCP as r,onTTFB as a,onINP as o}from"web-vitals";import{record as l}from"rrweb";import{pack as c}from"@rrweb/packer";var d=console.log.bind(console),h=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&d(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},g=h.getInstance();function u(e){g.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var p="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},m=1e6,f=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)v[e]=Math.floor(16*Math.random())+48,v[e]>=58&&(v[e]+=39);return E+String.fromCharCode.apply(null,v.slice(0,16))},this.generateSpanId=y(8),this.generateId=y(16)}},v=Array(32);function y(e){return function(){for(let t=0;t<2*e;t++)v[t]=Math.floor(16*Math.random())+48,v[t]>=58&&(v[t]+=39);return String.fromCharCode.apply(null,v.slice(0,2*e))}}var E="0000000000000000";var b={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,enableCompression:!0,maskFields:[],enableMasking:!1,enabledEvents:[],tracePropagationUrls:[],tracePropagationHeaders:[],tracePropagationTraceIdHeaderName:"",tracePropagationSpanIdHeaderName:"",traceOrigin:{name:"",value:""}},I=class{constructor(e){this.dsn=e?.dsn||"",this.appId=e?.appId||"",this.cluster=e?.cluster||"",this.apiKey=e?.apiKey||"",this.environment=e?.environment||"",this.namespace=e?.namespace||"",this.releaseId=e?.releaseId,this.userIdentifier=e?.userIdentifier||null,this.options={...b,...e?.options||{}}}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(e){e.options&&(this.options={...this.options,...e.options}),e.userIdentifier&&(this.userIdentifier={...this.userIdentifier,...e.userIdentifier}),e.appId&&(this.appId=e.appId),e.dsn&&(this.dsn=e.dsn),e.apiKey&&(this.apiKey=e.apiKey),e.cluster&&(this.cluster=e.cluster),e.environment&&(this.environment=e.environment),e.namespace&&(this.namespace=e.namespace),e.releaseId&&(this.releaseId=e.releaseId)}};function S(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return u(e),null}}function T(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){u(e)}}function w(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){u(e)}}var R=class e{constructor(){this.config=null,this.logger=h.getInstance(),this.sessionId=null,this.sessionStartTime=null}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new I(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;return S("gcId")||""}setSessionId(e){this.sessionId=e,T("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:function(e,t=0){const n=S(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,T("gcStartTime",String(e))}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e)),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},N=R.getInstance(),L=new f,_=h.getInstance();function C(){const e=N?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function z(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:null!=(s=e)&&"number"==typeof s.nodeType&&"string"==typeof s.nodeName?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,r])=>{const a=t?`${t}.${s}`:s;return"object"==typeof r&&null!==r?Array.isArray(r)?e[a]=r.map(((e,t)=>"object"==typeof e&&null!==e?z(e,`${a}[${t}]`,n,i+1):e)):Object.assign(e,z(r,a,n,i+1)):e[a]=r,e}),{}))}catch(e){return _.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}var s}function H(e){const t=Date.now()*m,n=L.generateId(),i=e.spanId||L.generateSpanId(),s=e.traceId||L.generateTraceId(),r=e.parentSpanId||"",a=z(e.attributes||{}),o=function(){const e=p?.location;return e?{path:e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/")?e.hash:e.pathname,url:e.href,title:p?.document?.title||""}:{path:"",url:"",title:p?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:r,traceId:s,attributes:{...a,location:o}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var q=class{constructor(){this.logger=h.getInstance(),this.config=R.getInstance()}compress(n){const i=this.config.getConfig();if(!i?.options?.enableCompression)return{data:(new TextEncoder).encode(n),isCompressed:!1};try{const i=e(n);return{data:t(i),isCompressed:!0}}catch(e){return{data:(new TextEncoder).encode(n),isCompressed:!1}}}async send(e){const t=this.config.getConfig();if(t)try{t?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,i=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");const s=JSON.stringify(e),{data:r,isCompressed:a}=this.compress(s);fetch(i,{method:"POST",headers:{"Content-Type":"application/json",apikey:n,"Content-Encoding":a?"gzip":""},body:r,keepalive:!0}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},k=["navigation","dom.event"],x=class e{constructor(){this.events=[],this.timeoutId=null,this.config=R.getInstance(),this.logger=h.getInstance(),this.initialized=!1,this.transporter=new q}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.flush()})),this.initialized=!0}catch(e){u(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend,n=this.config.getConfig()?.options?.enrichEvent;if(t&&!t(e))return;n&&(e=n(e)),this.events.push(e);const i=this.config.getConfig()?.options?.batchSize||100;this.events.length>=i&&!k.includes(e.type)&&this.flush()}catch(e){u(e)}}flush(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){u(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){u(e)}}scheduleFlush(){try{null!==this.timeoutId&&(p.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=p.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){u(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:i,language:navigator.language,mobile:s}}getSessionAttributes(){const e=this.detectBrowser(),t=this.config.getConfig();return{cluster:t?.cluster||"",env:t?.environment||"",namespace:t?.namespace||"",releaseId:t?.releaseId||"",session_id:this.config.getSessionId(),session_start_time:this.config.getSessionStartTime(),user:t?.userIdentifier||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};x.instance=null;var P=x,D=class{constructor(){this.logger=h.getInstance(),this.eventsPool=P.getInstance()}};function M({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var A="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function F(e,t){try{return e.getAttribute(t)||""}catch{return""}}function O(e){try{const t=A?.call(e);return"string"==typeof t?t:""}catch{return""}}var U=class extends D{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=R.getInstance(),this.getShouldMaskText=e=>{const t=this.config.getConfig(),n=t?.options?.maskFields||[],i=t?.options?.enableMasking||!1;return(["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.hasAttribute("data-private")].some((e=>e))||n.some((t=>e.target?.id?.toLowerCase().includes(t))))&&i},this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>{const t=e.target,n=this.config.getConfig();return n?.options?.enableMasking||!1?"*":M({text:t.innerText||""})},this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){u(e)}};this.eventHandlers.push({type:e,handler:t}),p?.addEventListener(e,t)}))}catch(e){u(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!C())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),i=e.target,s=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return H({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:s,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:F(i,"id"),tagName:O(i),className:F(i,"class"),text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,i=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===O(e).toLowerCase())return"html";let r="",a=0,o=e;const l=[];for(;o&&o!==n&&o!==document.documentElement&&a<i;){let e=O(o).toLowerCase();try{const t=o.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(o.classList?.length){const t=Array.from(o.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=o.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=O(o).toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{o=o.parentElement}catch(e){break}a++}return r||"*"}},j=["log","info","warn","error","assert","trace"],$=class extends D{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),j.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){u(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){u(e)}}destroy(){try{if(!this.isInitialized)return;j.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){u(e)}}handleEvent(e,t){try{if(!C())return;const n=this.formatMessage(Array.isArray(e)?e:[e],t);if(!n||n?.includes("groundcoverIgnore"))return;const i=this.buildEvent({message:n,level:t});this.queueEvent(i)}catch(e){u(e)}}buildEvent({message:e,level:t}){return H({type:"log",attributes:{message:M({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return u(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{j.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){u(e)}return e}};function K(e){try{if(null==e)return"";if("string"==typeof e)return e;if(e instanceof FormData)return"[form data]";if(e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if("undefined"!=typeof Document){if(e instanceof Document)return"[document data]";const t=e;if(9===t?.nodeType)return"[document data]"}if(e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return u(`Failed to format body: ${e}`),"[unreadable body]"}}var X,B=class extends D{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=R.getInstance(),this.idGenerator=new f,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!C())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const i=this.formatHeaders(e.request.headers),s=this.formatHeaders(e.response.headers),r=e.method?.toUpperCase()||"UNKNOWN",{traceId:a,spanId:o}=this.extractTraceIds(e.request.headers),l=M({text:e.request.body,maxLength:this.maxBodyLength}),c=M({text:e.response.body,maxLength:this.maxBodyLength}),d={type:"HTTP",operation:{name:r},resource_name:t,status:e.status?.toString(),subType:r,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:i,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:l},response:{body:c}}},h={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?e.timestamp*m:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?e.end_time*m:void 0,span_name:`${e.method} ${t}`,attributes:d};return a&&(h.traceId=a),o&&(h.spanId=o),H(h)}}async getResponseBody(e){let t;try{const n=e.clone().body;if(n){let e,i=n.getReader(),s=new TextDecoder,r="";for(;!(e=await i.read()).done;){let t=e.value;r+=s.decode(t)}t=r}else t=""}catch(e){t=`Unable to clone response: ${e}`}return t}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{const t=this.config.getConfig()?.getEndpoint();if(t&&e.includes(t))return!0;if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return u(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,i=globalThis.XMLHttpRequest.prototype.setRequestHeader;let s;globalThis.XMLHttpRequest.prototype.open=function(n,i,r=!0,a,o){if(s=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,r,a,o]);const l=new URL(i.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,i,r,a,o])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),i.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const i=this._requestUrl?.toString();if(!i||e.shouldIgnoreRequest(i))return n.apply(this,t);if(e.shouldAddTraceHeader(i)){const t=e.config.getConfig(),n=e.getTraceIds();t?.options?.traceOrigin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),n&&(t?.options?.tracePropagationTraceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracePropagationHeaders)&&t?.options?.tracePropagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracePropagationHeaders?.length||e.addHeaderToXhrRequest({request:this,headerName:"traceparent",headerValue:n.traceparent}))}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,i]=e.split(": ");t&&i&&(n[t.trim()]=i.trim())}));const i=K(this._requestBody),r=K(""===this.responseType||"text"===this.responseType?this.responseText:this.response),a={timestamp:s,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:r}};e.handleEvent(a)})),n.apply(this,t)}}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){const t=this.config.getConfig(),n=this.getTraceIds();if(t?.options?.traceOrigin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),!n)return;t?.options?.tracePropagationTraceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracePropagationHeaders;(i?.length?i:["traceparent"]).forEach((t=>{this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n.traceparent})}))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[i,s]=t;s={...s||{}},t[1]=s;const r=i instanceof Request,a=s?.method||"GET",o=s?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);s||(t[1]={},s=t[1]),s.headers=this.normalizeHeaders(r?i.headers:void 0,s.headers),c&&this.addTraceHeaders(s);const d=this.extractHeadersRecord(s.headers),h=K(o);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i=e.clone(),s={};i.headers.forEach(((e,t)=>{s[t]=e}));const r={method:a,url:l,timestamp:n,body:h,status:i.status,end_time:t,request:{headers:d,body:h},response:{headers:s,body:""}};try{s["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(i).then((e=>{r.response.body=e,this.handleEvent(r)})).catch((e=>{r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}))}catch(e){r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}return e})).catch((e=>{const t=Date.now();let n="NetworkError";const i=e.message||"Unknown network error";e instanceof TypeError&&i.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":i.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":i.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const s={method:a,url:l,body:h,status:0,end_time:t,request:{headers:d,body:h},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(s),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,i])=>{const s=n.toLowerCase();return t.includes(s)||/(token|key|secret|password)/i.test(s)?e[n]="[REDACTED]":e[n]=M({text:i}),e}),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracePropagationTraceIdHeaderName){const i=e[t.options.tracePropagationTraceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracePropagationSpanIdHeaderName){const n=e[t.options.tracePropagationSpanIdHeaderName];n&&"string"==typeof n&&(i=n)}if(!n||!i){const t=this.extractTraceparentHeader(e);if(t){const e=t.split("-");4===e.length&&"00"===e[0]&&(!n&&e[1]&&32===e[1].length&&(n=e[1]),!i&&e[2]&&16===e[2].length&&(i=e[2]))}}return{traceId:n,spanId:i}}extractTraceparentHeader(e){const t=this.config.getConfig();if(t?.options?.tracePropagationHeaders?.length)for(const n of t.options.tracePropagationHeaders){const t=e[n];if(t&&"string"==typeof t)return t}const n=e.traceparent;return n&&"string"==typeof n?n:""}getTraceIds(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();let n,i;try{n=BigInt("0x"+t).toString(10),i=BigInt("0x"+e).toString(10)}catch(s){this.logger.log("[network-events-listener.getTraceIds] error",{error:s}),n=t,i=e}return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e,decimalTraceId:n,decimalSpanId:i}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}isValidHeaderName(e){if(!e||"string"!=typeof e)return!1;return/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t?.options?.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),s=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(s)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},V=class extends D{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const i=this.buildEvent(n,t);this.queueEvent(i)}catch(e){u(e)}}}initialize(){p?.addEventListener("error",this.handleEvent),p?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){p?.removeEventListener("error",this.handleEvent),p?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return H({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${M({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:t?.metadata}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}enhanceError(e,t){const{filename:n,lineno:i,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return n.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},G=class extends D{constructor({isEnabled:e}){if(super(),this.currentUrl="",this.originalPushState=null,this.originalReplaceState=null,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&e)try{this.isAutomaticNavigationEnabled=e,this.currentUrl=p.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){u(e)}}isInBrowserEnvironment(){try{return void 0!==p&&void 0!==p.location&&void 0!==p.history&&"function"==typeof p.addEventListener}catch(e){return u(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||!this.originalPushState||!this.originalReplaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");const e=this.originalPushState,t=this.originalReplaceState;history.pushState=(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n},history.replaceState=(...e)=>{const n=t.apply(history,e);return this.handleLocationChange(),n},p&&"function"==typeof p.addEventListener&&(p.addEventListener("popstate",this.popStateHandler),p.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){u(e)}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.isInitialized&&this.originalPushState&&this.originalReplaceState&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState),p&&"function"==typeof p.removeEventListener&&(p.removeEventListener("popstate",this.popStateHandler),p.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){u(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){u(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",p.location.href);return H({type:"navigation",attributes:{page_url:p.location.href,metadata:this.activeNavigation?.metadata,duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}startNavigation(e){this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:p.location.href,metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}endNavigation(e){this.logger.log("[navigation-listener.endNavigation] called",e),this.activeNavigation?(this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()):this.logger.log("[navigation-listener.endNavigation] no active navigation found")}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===p.location.href)return;let e,t;try{e=new URL(p.location.href),t=new URL(this.currentUrl)}catch(e){return void u(e)}const n=e=>e.startsWith("#/"),i=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||i&&e.hash!==t.hash)&&(this.currentUrl=p.location.href,this.handleEvent())}catch(e){u(e)}}},W=class extends D{constructor(){super(),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",p),"complete"===p?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):p?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),u(e)}}destroy(){p?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){u(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),i={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,r=t.initiatorType;i.totalSize+=n,i.totalDuration+=s,i.byType[r]||(i.byType[r]={count:0,size:0,duration:0}),i.byType[r].count++,i.byType[r].size+=n,i.byType[r].duration+=s}));return H({type:"pageload",attributes:{page_url:p?.location?.href||"",page_load_time:t,page_referrer:p?.document?.referrer||"",page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}},J=class extends D{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!C())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}}}initialize(){i(this.handleEvent),s(this.handleEvent),r(this.handleEvent),a(this.handleEvent),o(this.handleEvent)}destroy(){}buildEvent(e){return H({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}},Y=class{constructor(e){this.logger=h.getInstance(),this.eventsPool=P.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.inactivityTimer=null,this.onInactivityStop=e??null}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.stopFn=l({slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},packFn:c,checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{if(t||this.resetInactivityTimer(),this.events.push(e),t&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),this.events.length>=this.batchSize)try{this.sendBatch()}catch(e){u(e),this.logger.log("[session-replay-listener] failed to send batch in emit callback:",e)}}catch(e){u(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.resetInactivityTimer(),this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){u(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout((()=>{this.logger.log("[session-replay-listener] stopping recording due to inactivity"),this.stopRecording();try{this.onInactivityStop?.()}catch(e){u(e),this.logger.log("[session-replay-listener] onInactivityStop error:",e)}}),18e5)}clearInactivityTimer(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null)}sendBatch(){if(0!==this.events.length)try{const e=[...this.events],t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp,i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const s=H({type:"replay",attributes:i});this.eventsPool.addEvent(s),this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){u(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording&&this.stopFn)try{this.clearInactivityTimer(),this.stopFn(),this.isRecording=!1;const e=this.events.length;if(e>0)try{const t={_gc_replay_data:{events:[...this.events]}};this.batchContainsFullSnapshot&&(t.replay_is_full_snapshot=!0,t.replay_full_snapshot_timestamp=this.fullSnapshotTimestamp);const n=H({type:"replay",attributes:t});this.eventsPool.addEvent(n),this.logger.log("[session-replay-listener] sent final replay event with",e,"events")}catch(e){u(e),this.logger.log("[session-replay-listener] failed to encode and send final replay event:",e)}this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){u(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},Z=class{constructor(){this.logger=h.getInstance(),this.eventsPool=P.getInstance(),this.configManager=R.getInstance(),this.idGenerator=new f,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called");const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new W,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new U,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new $,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new V,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new B,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new J,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new G({isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),i.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",i)}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=H({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){u(e)}}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){u(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}startReplayRecording(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Y((()=>{this.handleReplayInactivityStop()}));e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){u(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}handleReplayInactivityStop(){this.logger.log("[instrumentation-manager] replay stopped due to inactivity, rotating session");try{this.eventsPool.flush()}catch(e){u(e),this.logger.log("[instrumentation-manager] failed to flush events before session rotation:",e)}try{const e=this.idGenerator.generateId(),t=Date.now()*m;this.configManager.setSessionId(e),this.configManager.setSessionStartTime(t)}catch(e){u(e),this.logger.log("[instrumentation-manager] failed to rotate session after inactivity:",e)}finally{this.sessionReplayListener=null}}stopReplayRecording(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy()}},Q="gcSample",ee=class{constructor(e){this.initialized=!1,this.logger=h.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new Z,this.idGenerator=new f;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=R.getInstance();t.initialize(e);P.getInstance().initialize();const n=e.sessionId,i=t.getSessionId();n?(t.setSessionId(n),this.logger.log("[session-manager] using provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId()),t.getSessionStartTime()||t.setSessionStartTime(Date.now()*m),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=S(Q);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return T(Q,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");R.getInstance().updateConfig({userIdentifier:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");R.getInstance().updateConfig(e)}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.initialized?this.instrumentationManager.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.initialized?this.instrumentationManager.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.initialized?this.instrumentationManager.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}getSessionId(){return this.initialized?R.getInstance().getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.initialized)try{const t=P.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=R.getInstance();i.setSessionId(n),i.setSessionStartTime(Date.now()*m),this.logger.log("[session-manager] session ID set successfully:",n)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.initialized?this.instrumentationManager.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.initialized?this.instrumentationManager.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),w("gcId"),w("gcStartTime"),this.initialized=!1)}};var te={init:function(e){try{X=new ee({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",userIdentifier:e?.userIdentifier,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId})}catch(e){u(e)}},identifyUser:function(e){X?X.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){X&&X.sendCustomEvent(e)},captureException:function(e,t){X&&X.captureException(e,t)},updateConfig:function(e){X&&X.updateConfig(e)},startNavigation:function(e){X?X.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){X?X.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return X?X.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(X)try{await X.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){X?X.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){X?X.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=te}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var ne=te;export{ne as default};
1
+ import{strToU8 as e,gzipSync as t}from"fflate";import n from"error-stack-parser";import{onCLS as i,onLCP as s,onFCP as r,onTTFB as a,onINP as o}from"web-vitals";import{record as l}from"rrweb";import{pack as c}from"@rrweb/packer";var d=console.log.bind(console),h=class e{constructor(){this.isDebugEnabled=!1,this.prefix=""}static initialize(t){return e.instance||(e.instance=new e),t&&(e.instance.isDebugEnabled=t.debug??!1,e.instance.prefix=t.prefix??""),e.instance}static getInstance(t){return e?.instance||e.initialize(t)}formatMessage(e){return`[${(new Date).toISOString()}] ${this.prefix} ${e}`}log(e,...t){this.isDebugEnabled&&d(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},g=h.getInstance();function u(e){g.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var p="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},m=1e6,f=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)v[e]=Math.floor(16*Math.random())+48,v[e]>=58&&(v[e]+=39);return E+String.fromCharCode.apply(null,v.slice(0,16))},this.generateSpanId=y(8),this.generateId=y(16)}},v=Array(32);function y(e){return function(){for(let t=0;t<2*e;t++)v[t]=Math.floor(16*Math.random())+48,v[t]>=58&&(v[t]+=39);return String.fromCharCode.apply(null,v.slice(0,2*e))}}var E="0000000000000000";var b={batchSize:10,batchTimeout:1e4,eventSampleRate:1,sessionSampleRate:1,environment:"development",debug:!1,enableCompression:!0,maskFields:[],enableMasking:!1,enabledEvents:[],tracePropagationUrls:[],tracePropagationHeaders:[],tracePropagationTraceIdHeaderName:"",tracePropagationSpanIdHeaderName:"",traceOrigin:{name:"",value:""}},I=class{constructor(e){this.dsn=e?.dsn||"",this.appId=e?.appId||"",this.cluster=e?.cluster||"",this.apiKey=e?.apiKey||"",this.environment=e?.environment||"",this.namespace=e?.namespace||"",this.releaseId=e?.releaseId,this.userIdentifier=e?.userIdentifier||null,this.options={...b,...e?.options||{}}}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(e){e.options&&(this.options={...this.options,...e.options}),e.userIdentifier&&(this.userIdentifier={...this.userIdentifier,...e.userIdentifier}),e.appId&&(this.appId=e.appId),e.dsn&&(this.dsn=e.dsn),e.apiKey&&(this.apiKey=e.apiKey),e.cluster&&(this.cluster=e.cluster),e.environment&&(this.environment=e.environment),e.namespace&&(this.namespace=e.namespace),e.releaseId&&(this.releaseId=e.releaseId)}};function S(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return u(e),null}}function T(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){u(e)}}function w(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){u(e)}}var R=class e{constructor(){this.config=null,this.logger=h.getInstance(),this.sessionId=null,this.sessionStartTime=null}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.config||(this.config=new I(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getSessionId(){if(this.sessionId)return this.sessionId;return S("gcId")||""}setSessionId(e){this.sessionId=e,T("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:function(e,t=0){const n=S(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,T("gcStartTime",String(e))}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?(e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e)),e?.userIdentifier&&(this.logger.log("[config-manager] updating user identifier"),this.config.userIdentifier={...this.config.userIdentifier,...e.userIdentifier})):this.logger.log("[config-manager] configuration not initialized")}},N=R.getInstance(),L=new f,C=h.getInstance();function z(){const e=N?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function H(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:null!=(s=e)&&"number"==typeof s.nodeType&&"string"==typeof s.nodeName?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[s,r])=>{const a=t?`${t}.${s}`:s;return"object"==typeof r&&null!==r?Array.isArray(r)?e[a]=r.map(((e,t)=>"object"==typeof e&&null!==e?H(e,`${a}[${t}]`,n,i+1):e)):Object.assign(e,H(r,a,n,i+1)):e[a]=r,e}),{}))}catch(e){return C.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}var s}function _(e){const t=Date.now()*m,n=L.generateId(),i=e.spanId||L.generateSpanId(),s=e.traceId||L.generateTraceId(),r=e.parentSpanId||"",a=H(e.attributes||{}),o=function(){const e=p?.location;return e?{path:e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/")?e.hash:e.pathname,url:e.href,title:p?.document?.title||""}:{path:"",url:"",title:p?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:r,traceId:s,attributes:{...a,location:o}};return e.span_name&&(l.span_name=e.span_name),"network"===e.type?(l.start_timestamp=e.timestamp||t,l.end_timestamp=e?.end_timestamp):l.timestamp=t,l}var q=class{constructor(){this.logger=h.getInstance(),this.config=R.getInstance()}compress(n){const i=this.config.getConfig();if(!i?.options?.enableCompression)return{data:(new TextEncoder).encode(n),isCompressed:!1};try{const i=e(n);return{data:t(i),isCompressed:!0}}catch(e){return{data:(new TextEncoder).encode(n),isCompressed:!1}}}async send(e){const t=this.config.getConfig();if(t)try{t?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const n=t.apiKey,i=this.buildEndpoint();if(!n)return void this.logger.log("No API key found");const s=JSON.stringify(e),{data:r,isCompressed:a}=this.compress(s);fetch(i,{method:"POST",headers:{"Content-Type":"application/json",apikey:n,"Content-Encoding":a?"gzip":""},body:r}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){t.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();if(!e)return"";const{dsn:t}=e;return`${t}/json/rum`}},k=["navigation","dom.event"],x=class e{constructor(){this.events=[],this.timeoutId=null,this.config=R.getInstance(),this.logger=h.getInstance(),this.initialized=!1,this.transporter=new q}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(){try{if(this.initialized)return;this.scheduleFlush(),"undefined"!=typeof document&&document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.flush()})),this.initialized=!0}catch(e){u(e)}}addEvent(e){if(e&&this.initialized)try{const t=this.config.getConfig()?.options?.beforeSend,n=this.config.getConfig()?.options?.enrichEvent;if(t&&!t(e))return;n&&(e=n(e)),this.events.push(e);const i=this.config.getConfig()?.options?.batchSize||100;this.events.length>=i&&!k.includes(e.type)&&this.flush()}catch(e){u(e)}}flush(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[],this.scheduleFlush()}catch(e){u(e)}}async flushSync(){try{if(!this.events?.length||!this.initialized)return;if(!this.config.getConfig()?.cluster)return void this.logger.log("[events-pool.flush] skipping flush: no cluster");await this.transporter.send({sessionAttributes:this.getSessionAttributes(),events:this.events}),this.events=[]}catch(e){u(e)}}scheduleFlush(){try{null!==this.timeoutId&&(p.clearTimeout(this.timeoutId),this.timeoutId=null);const e=this.config.getConfig()?.options?.batchTimeout;if(!e)return;this.timeoutId=p.setTimeout((()=>{this.timeoutId=null,this.flush()}),e)}catch(e){u(e)}}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",s=/Mobile|Android|iPhone|iPad|iPod/i.test(e);return/Edg/.test(e)?(t="Edge",n=e.match(/Edg\/([\d.]+)/)?.[1]||n):/Chrome/.test(e)&&!/Chromium/.test(e)?(t="Chrome",n=e.match(/Chrome\/([\d.]+)/)?.[1]||n):/Firefox/.test(e)?(t="Firefox",n=e.match(/Firefox\/([\d.]+)/)?.[1]||n):/Safari/.test(e)&&!/Chrome/.test(e)?(t="Safari",n=e.match(/Version\/([\d.]+)/)?.[1]||n):/Trident/.test(e)?(t="Internet Explorer",n=/rv:([^)]+)\)/i.test(e)?e.match(/rv:([^)]+)\)/i)?.[1]||n:e.match(/MSIE ([^;]+)/)?.[1]||n):/OPR/.test(e)&&(t="Opera",n=e.match(/OPR\/([\d.]+)/)?.[1]||n),{name:t,version:n,platform:i,language:navigator.language,mobile:s}}getSessionAttributes(){const e=this.detectBrowser(),t=this.config.getConfig();return{cluster:t?.cluster||"",env:t?.environment||"",namespace:t?.namespace||"",releaseId:t?.releaseId||"",session_id:this.config.getSessionId(),session_start_time:this.config.getSessionStartTime(),user:t?.userIdentifier||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};x.instance=null;var P=x,D=class{constructor(){this.logger=h.getInstance(),this.eventsPool=P.getInstance()}};function M({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var A="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function O(e,t){try{return e.getAttribute(t)||""}catch{return""}}function j(e){try{const t=A?.call(e);return"string"==typeof t?t:""}catch{return""}}var F=class extends D{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=R.getInstance(),this.getShouldMaskText=e=>{const t=this.config.getConfig(),n=t?.options?.maskFields||[],i=t?.options?.enableMasking||!1;return(["password"===e.target?.type,e.target?.id?.toLowerCase().includes("password"),e.target?.id?.toLowerCase().includes("credit-card"),e.target?.id?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("cc"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.className?.toLowerCase().includes("credit-card"),e.target?.hasAttribute("data-private")].some((e=>e))||n.some((t=>e.target?.id?.toLowerCase().includes(t))))&&i},this.getKeyCode=e=>{if(e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key){const t=this.getShouldMaskText({target:e.target});return t||t?"*":e.key}return""},this.getText=e=>{const t=e.target,n=this.config.getConfig();return n?.options?.enableMasking||!1?"*":M({text:t.innerText||""})},this.getSelector=e=>e.target instanceof Element&&this.generateSelector(e.target)||"",this.getCoordinates=e=>{if({mouseup:!0,mousedown:!0,mousemove:!0,mouseover:!0}[e.type]){const{clientX:t,clientY:n}=e||{};return{clientX:t,clientY:n}}return null}}initialize(){try{this.logger.log("[dom-events-listener.initialize] called"),this.capturedEvents?.forEach((e=>{const t=e=>{try{this.handleEvent(e)}catch(e){u(e)}};this.eventHandlers.push({type:e,handler:t}),p?.addEventListener(e,t)}))}catch(e){u(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!z())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),i=e.target,s=this.getKeyCode(e),r=this.getText(e);this.logger.log("[dom-events-listener.buildEvent] called");return _({type:"dom.event",attributes:{dom_event_selector:t,dom_event_key_code:s,dom_event_type:e.type,dom_event_coordinates:n||{clientX:0,clientY:0},dom_event_target:{id:O(i,"id"),tagName:j(i),className:O(i,"class"),text:r}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}generateSelector(e,t={}){if(!e||!e.nodeType||e.nodeType!==Node.ELEMENT_NODE)return"";const n=t.root||document.body||document.documentElement,i=t.maxAttempts||10,s=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===j(e).toLowerCase())return"html";let r="",a=0,o=e;const l=[];for(;o&&o!==n&&o!==document.documentElement&&a<i;){let e=j(o).toLowerCase();try{const t=o.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(o.classList?.length){const t=Array.from(o.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of s)if("id"!==t&&"class"!==t)try{const n=o.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=j(o).toLowerCase()||"*"}l.unshift(e||"*"),r=l.join(" > ");try{if(1===n.querySelectorAll(r).length)return r}catch(e){l.shift(),r=l.join(" > ")}try{o=o.parentElement}catch(e){break}a++}return r||"*"}},U=["log","info","warn","error","assert","trace"],$=class extends D{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),U.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){u(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){u(e)}}destroy(){try{if(!this.isInitialized)return;U.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){u(e)}}handleEvent(e,t){try{if(!z())return;const n=this.formatMessage(Array.isArray(e)?e:[e],t);if(!n||n?.includes("groundcoverIgnore"))return;const i=this.buildEvent({message:n,level:t});this.queueEvent(i)}catch(e){u(e)}}buildEvent({message:e,level:t}){return _({type:"log",attributes:{message:M({text:e}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}formatMessage(e,t){if(!Array.isArray(e))return String(e);try{return e.map((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if("object"==typeof e){if(e instanceof Error)try{return"error"===t&&e.stack||e.toString()}catch{try{const t={name:e.name,message:e.message,stack:e.stack};return JSON.stringify(t)}catch{return Object.prototype.toString.call(e)}}try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return String(e)})).join(" ")}catch(e){return u(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{U.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){u(e)}return e}};function B(e){try{if(null==e)return"";if("string"==typeof e)return e;if(e instanceof FormData)return"[form data]";if(e instanceof Blob)return"[blob data]";if(e instanceof ArrayBuffer)return"[arraybuffer data]";if("undefined"!=typeof Document){if(e instanceof Document)return"[document data]";const t=e;if(9===t?.nodeType)return"[document data]"}if(e instanceof URLSearchParams)try{return e.toString()}catch{return"[unreadable body]"}return Array.isArray(e)||"object"==typeof e?JSON.stringify(e):String(e)}catch(e){return u(`Failed to format body: ${e}`),"[unreadable body]"}}var K,X=class extends D{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=R.getInstance(),this.idGenerator=new f,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!z())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});try{t=new URL(e.url).pathname}catch(t){n=new URL(e.url,globalThis.location.href).href}this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const i=this.formatHeaders(e.request.headers),s=this.formatHeaders(e.response.headers),r=e.method?.toUpperCase()||"UNKNOWN",{traceId:a,spanId:o}=this.extractTraceIds(e.request.headers),l=M({text:e.request.body,maxLength:this.maxBodyLength}),c=M({text:e.response.body,maxLength:this.maxBodyLength}),d={type:"HTTP",operation:{name:r},resource_name:t,status:e.status?.toString(),subType:r,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:i,method:e.method},response:{headers:s,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:l},response:{body:c}}},h={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?e.timestamp*m:void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?e.end_time*m:void 0,span_name:`${e.method} ${t}`,attributes:d};return a&&(h.traceId=a),o&&(h.spanId=o),_(h)}}async getResponseBody(e){let t;try{const n=e.clone().body;if(n){let e,i=n.getReader(),s=new TextDecoder,r="";for(;!(e=await i.read()).done;){let t=e.value;r+=s.decode(t)}t=r}else t=""}catch(e){t=`Unable to clone response: ${e}`}return t}initialize(){this.logger.log("[network-events-listener.initialize] called"),this.patchXHR(),this.patchFetch()}destroy(){globalThis.XMLHttpRequest.prototype.open=globalThis.XMLHttpRequest.prototype.open,globalThis.XMLHttpRequest.prototype.send=globalThis.XMLHttpRequest.prototype.send,globalThis.fetch=globalThis.fetch}shouldIgnoreRequest(e){try{const t=this.config.getConfig()?.getEndpoint();if(t&&e.includes(t))return!0;if([".tsx",".jsx",".css"].some((t=>e.toLowerCase().endsWith(t))))return!0;return(this.config.getConfig()?.options?.excludedUrls||[]).some((t=>{if(t instanceof RegExp)return t.test(e);if("string"==typeof t&&(t.includes("*")||t.includes("?"))){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(n).test(e)}return e===t}))}catch(e){return u(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,i=globalThis.XMLHttpRequest.prototype.setRequestHeader;let s;globalThis.XMLHttpRequest.prototype.open=function(n,i,r=!0,a,o){if(s=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,r,a,o]);const l=new URL(i.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,i,r,a,o])},globalThis.XMLHttpRequest.prototype.setRequestHeader=function(e,t){return this._requestHeaders&&(this._requestHeaders[e]=t),i.apply(this,[e,t])},globalThis.XMLHttpRequest.prototype.send=function(...t){const i=this._requestUrl?.toString();if(!i||e.shouldIgnoreRequest(i))return n.apply(this,t);if(e.shouldAddTraceHeader(i)){const t=e.config.getConfig(),n=e.getTraceIds();t?.options?.traceOrigin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),n&&(t?.options?.tracePropagationTraceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracePropagationHeaders)&&t?.options?.tracePropagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracePropagationHeaders?.length||e.addHeaderToXhrRequest({request:this,headerName:"traceparent",headerValue:n.traceparent}))}return this._requestBody=t[0]||"",this.addEventListener("load",(()=>{const t=Date.now(),n={};this.getAllResponseHeaders().split(/\r?\n/).forEach((e=>{const[t,i]=e.split(": ");t&&i&&(n[t.trim()]=i.trim())}));const i=B(this._requestBody),r=B(""===this.responseType||"text"===this.responseType?this.responseText:this.response),a={timestamp:s,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:r}};e.handleEvent(a)})),n.apply(this,t)}}normalizeHeaders(e,t){try{const n=e?new Headers(e):new Headers;return t?(t instanceof Headers?t.forEach(((e,t)=>n.set(t,e))):Array.isArray(t)?new Headers(t).forEach(((e,t)=>n.set(t,e))):"object"==typeof t&&Object.entries(t).forEach((([e,t])=>n.set(e,t))),n):n}catch{return new Headers}}addTraceHeaders(e){const t=this.config.getConfig(),n=this.getTraceIds();if(t?.options?.traceOrigin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.traceOrigin.name,headerValue:t.options.traceOrigin.value}),!n)return;t?.options?.tracePropagationTraceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationTraceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracePropagationSpanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracePropagationSpanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracePropagationHeaders;(i?.length?i:["traceparent"]).forEach((t=>{this.addHeaderToFetchRequest({init:e,headerName:t,headerValue:n.traceparent})}))}extractHeadersRecord(e){const t={};return e instanceof Headers&&e.forEach(((e,n)=>{t[n]=e})),t}patchFetch(){const e=globalThis.fetch;globalThis.fetch=(...t)=>{const n=Date.now();let[i,s]=t;s={...s||{}},t[1]=s;const r=i instanceof Request,a=s?.method||"GET",o=s?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);s||(t[1]={},s=t[1]),s.headers=this.normalizeHeaders(r?i.headers:void 0,s.headers),c&&this.addTraceHeaders(s);const d=this.extractHeadersRecord(s.headers),h=B(o);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i=e.clone(),s={};i.headers.forEach(((e,t)=>{s[t]=e}));const r={method:a,url:l,timestamp:n,body:h,status:i.status,end_time:t,request:{headers:d,body:h},response:{headers:s,body:""}};try{s["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(i).then((e=>{r.response.body=e,this.handleEvent(r)})).catch((e=>{r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}))}catch(e){r.response.body="[unreadable response body]",this.handleEvent(r),this.logger.log("[network-events-listener.patchFetch] error",{error:e})}return e})).catch((e=>{const t=Date.now();let n="NetworkError";const i=e.message||"Unknown network error";e instanceof TypeError&&i.includes("Failed to fetch")?n="ERR_NETWORK_FAILURE":i.includes("Name not resolved")?n="ERR_NAME_NOT_RESOLVED":i.includes("Connection refused")&&(n="ERR_CONNECTION_REFUSED");const s={method:a,url:l,body:h,status:0,end_time:t,request:{headers:d,body:h},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(s),e}))}}formatHeaders(e){const t=["authorization","cookie","set-cookie"];return Object.entries(e)?.reduce(((e,[n,i])=>{const s=n.toLowerCase();return t.includes(s)||/(token|key|secret|password)/i.test(s)?e[n]="[REDACTED]":e[n]=M({text:i}),e}),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracePropagationTraceIdHeaderName){const i=e[t.options.tracePropagationTraceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracePropagationSpanIdHeaderName){const n=e[t.options.tracePropagationSpanIdHeaderName];n&&"string"==typeof n&&(i=n)}if(!n||!i){const t=this.extractTraceparentHeader(e);if(t){const e=t.split("-");4===e.length&&"00"===e[0]&&(!n&&e[1]&&32===e[1].length&&(n=e[1]),!i&&e[2]&&16===e[2].length&&(i=e[2]))}}return{traceId:n,spanId:i}}extractTraceparentHeader(e){const t=this.config.getConfig();if(t?.options?.tracePropagationHeaders?.length)for(const n of t.options.tracePropagationHeaders){const t=e[n];if(t&&"string"==typeof t)return t}const n=e.traceparent;return n&&"string"==typeof n?n:""}getTraceIds(){const e=this.idGenerator.generateSpanId(),t=this.idGenerator.generateTraceId();let n,i;try{n=BigInt("0x"+t).toString(10),i=BigInt("0x"+e).toString(10)}catch(s){this.logger.log("[network-events-listener.getTraceIds] error",{error:s}),n=t,i=e}return{traceparent:`00-${t}-${e}-01`,traceId:t,spanId:e,decimalTraceId:n,decimalSpanId:i}}addHeaderToXhrRequest({request:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToXhrRequest] called",{request:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.setRequestHeader(t,n),e._requestHeaders[t]=n}catch(e){this.logger.log("[network-events-listener.addHeaderToXhrRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToXhrRequest] Invalid header name",{headerName:t})}addHeaderToFetchRequest({init:e,headerName:t,headerValue:n}){if(this.logger.log("[network-events-listener.addHeaderToFetchRequest] called",{init:e,headerName:t,headerValue:n}),this.isValidHeaderName(t))try{e.headers instanceof Headers?e.headers.set(t,n):e.headers={...e.headers,[t]:n}}catch(e){this.logger.log("[network-events-listener.addHeaderToFetchRequest] Error setting header",{error:e,headerName:t,headerValue:n})}else this.logger.log("[network-events-listener.addHeaderToFetchRequest] Invalid header name",{headerName:t})}isValidHeaderName(e){if(!e||"string"!=typeof e)return!1;return/^[a-zA-Z0-9!#$&'*+\-.^_`|~]+$/.test(e)}shouldAddTraceHeader(e){const t=this.config.getConfig();if(this.logger.log("[network-events-listener.shouldAddTraceHeader] called",{url:e,config:t}),!t?.options?.tracePropagationUrls?.length)return!1;const n=t.options.tracePropagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),s=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(s)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},V=class extends D{constructor(){super(...arguments),this.handleEvent=(e,t)=>{this.logger.log("[errors-events-listener.handleEvent] called");try{let n;if(e instanceof Error)n=e,this.enhanceError(n);else if(e instanceof ErrorEvent){if(n=e.error||new Error(e.message||"Unknown error"),/Script error\.?/.test(n.message))return;this.enhanceError(n,e)}else{if(!(e instanceof PromiseRejectionEvent))return;n=this.createUnhandledRejectionError(e)}const i=this.buildEvent(n,t);this.queueEvent(i)}catch(e){u(e)}}}initialize(){p?.addEventListener("error",this.handleEvent),p?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){p?.removeEventListener("error",this.handleEvent),p?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){return _({type:"exception",attributes:{error_type:e.name||"Error",error_message:e.message||"Unknown error",error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${M({text:e.message,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:t?.metadata}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}enhanceError(e,t){const{filename:n,lineno:i,colno:s}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),s&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:s})}createUnhandledRejectionError(e){let t;if(e.reason instanceof Error)t=e.reason;else{const n="object"==typeof e.reason?JSON.stringify(e.reason,null,2):String(e.reason);t=new Error(n),t.name="UnhandledRejection",Object.defineProperty(t,"originalReason",{value:e.reason,enumerable:!1})}return t}buildStackTrace(e){if(!e)return[];try{return n.parse(e).map((e=>({filename:e.fileName||"unknown",function:e.functionName||"anonymous",lineno:e.lineNumber||0,colno:e.columnNumber||0})))}catch(e){return[]}}},G=class extends D{constructor({isEnabled:e}){if(super(),this.currentUrl="",this.originalPushState=null,this.originalReplaceState=null,this.isInitialized=!1,this.isAutomaticNavigationEnabled=!1,this.activeNavigation=null,this.popStateHandler=()=>{this.handleLocationChange()},this.hashChangeHandler=()=>{this.handleLocationChange()},this.isInBrowserEnvironment()&&e)try{this.isAutomaticNavigationEnabled=e,this.currentUrl=p.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){u(e)}}isInBrowserEnvironment(){try{return void 0!==p&&void 0!==p.location&&void 0!==p.history&&"function"==typeof p.addEventListener}catch(e){return u(e),!1}}initialize(){try{if(this.logger.log("[navigation-listener.initialize] called"),!this.isInBrowserEnvironment()||!this.originalPushState||!this.originalReplaceState)return void this.logger.log("[navigation-listener.initialize] Browser environment not available, skipping initialization");if(!this.isAutomaticNavigationEnabled)return void this.logger.log("[navigation-listener.initialize] Automatic navigation is disabled, skipping initialization");const e=this.originalPushState,t=this.originalReplaceState;history.pushState=(...t)=>{const n=e.apply(history,t);return this.handleLocationChange(),n},history.replaceState=(...e)=>{const n=t.apply(history,e);return this.handleLocationChange(),n},p&&"function"==typeof p.addEventListener&&(p.addEventListener("popstate",this.popStateHandler),p.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){u(e)}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.isInitialized&&this.originalPushState&&this.originalReplaceState&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState),p&&"function"==typeof p.removeEventListener&&(p.removeEventListener("popstate",this.popStateHandler),p.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){u(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){u(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",p.location.href);return _({type:"navigation",attributes:{page_url:p.location.href,metadata:this.activeNavigation?.metadata,duration_ms:this.activeNavigation?.duration_ms||0,start_timestamp:this.activeNavigation?.startTime||0,end_timestamp:this.activeNavigation?.endTime||0}})}queueEvent(e){try{this.logger.log("[navigation-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}startNavigation(e){this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:p.location.href,metadata:e,startTime:Date.now(),endTime:0,duration_ms:0}}endNavigation(e){this.logger.log("[navigation-listener.endNavigation] called",e),this.activeNavigation?(this.logger.log("[navigation-listener.endNavigation] active navigation",this.activeNavigation),this.activeNavigation.endTime=Date.now(),this.activeNavigation.duration_ms=this.activeNavigation.endTime-this.activeNavigation.startTime,this.handleEvent()):this.logger.log("[navigation-listener.endNavigation] no active navigation found")}handleLocationChange(){try{if(!this.isInitialized)return;if(this.logger.log("[navigation-listener.handleLocationChange] called"),this.currentUrl===p.location.href)return;let e,t;try{e=new URL(p.location.href),t=new URL(this.currentUrl)}catch(e){return void u(e)}const n=e=>e.startsWith("#/"),i=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||i&&e.hash!==t.hash)&&(this.currentUrl=p.location.href,this.handleEvent())}catch(e){u(e)}}},W=class extends D{constructor(){super(),this.loadEventHandler=()=>{this.logger.log("load event"),this.handleEvent()}}initialize(){try{this.logger.log("[page-load-listener.initialize] called"),this.logger.log("globalThis",p),"complete"===p?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):p?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),u(e)}}destroy(){p?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){u(e)}}buildEvent(){const e=performance.getEntriesByType("navigation")[0],t=e?e.loadEventEnd-e.startTime:0,n=performance.getEntriesByType("resource"),i={count:n.length,totalSize:0,totalDuration:0,byType:{}};n.forEach((e=>{const t=e,n=t.transferSize||0,s=t.duration,r=t.initiatorType;i.totalSize+=n,i.totalDuration+=s,i.byType[r]||(i.byType[r]={count:0,size:0,duration:0}),i.byType[r].count++,i.byType[r].size+=n,i.byType[r].duration+=s}));return _({type:"pageload",attributes:{page_url:p?.location?.href||"",page_load_time:t,page_referrer:p?.document?.referrer||"",page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}},J=class extends D{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!z())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}}}initialize(){i(this.handleEvent),s(this.handleEvent),r(this.handleEvent),a(this.handleEvent),o(this.handleEvent)}destroy(){}buildEvent(e){return _({type:"performance",attributes:{performance_metric_name:e.name,performance_metric_value:e.value,performance_metric_id:e.id,performance_metric_navigation_type:e.navigationType||""}})}queueEvent(e){try{this.logger.log("[performance-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}},Y=class{constructor(e){this.logger=h.getInstance(),this.eventsPool=P.getInstance(),this.configManager=R.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.inactivityTimer=null,this.sendTimerId=null,this.onInactivityStop=e??null}initialize(){this.logger.log("[session-replay-listener] initialize called"),this.isRecording?this.logger.log("[session-replay-listener] already recording"):this.startRecording()}startRecording(){try{this.startTime=Date.now(),this.events=[],this.isRecording=!0,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0;const e=this.configManager.getConfig()?.options?.sessionReplay?.blockedSelectors?.filter(Boolean),t=e?.length?e.join(", "):void 0;this.stopFn=l({...t?{blockSelector:t}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{t||this.resetInactivityTimer(),this.events.push(e),t&&(this.batchContainsFullSnapshot=!0,this.fullSnapshotTimestamp=Date.now(),this.logger.log("[session-replay-listener] full snapshot captured at",this.fullSnapshotTimestamp)),this.events.length>=this.batchSize&&this.scheduleSendBatch()}catch(e){u(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.resetInactivityTimer(),this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){u(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=p.setTimeout((()=>{if(this.sendTimerId=null,this.isRecording)try{this.sendBatch()}catch(e){u(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}}),0))}clearScheduledSend(){null!==this.sendTimerId&&(p.clearTimeout(this.sendTimerId),this.sendTimerId=null)}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityTimer=setTimeout((()=>{this.logger.log("[session-replay-listener] stopping recording due to inactivity"),this.stopRecording();try{this.onInactivityStop?.()}catch(e){u(e),this.logger.log("[session-replay-listener] onInactivityStop error:",e)}}),18e5)}clearInactivityTimer(){this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null)}sendBatch(){if(0!==this.events.length)try{const e=this.events.map((e=>c(e))),t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp,i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const s=_({type:"replay",attributes:i});this.eventsPool.addEvent(s),this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){u(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearInactivityTimer(),this.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatch(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){u(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},Z=class{constructor(){this.logger=h.getInstance(),this.eventsPool=P.getInstance(),this.configManager=R.getInstance(),this.idGenerator=new f,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called");const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new W,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new F,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new $,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new V,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new X,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new J,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new G({isEnabled:n||t?.includes("navigation")}),this.navigationListener.initialize(),i.push("navigation"),this.logger.log("[instrumentation-manager.instrument] initialized listeners based on config:",i)}sendCustomEvent(e){this.logger.log("[instrumentation-manager.sendCustomEvent] called",e);try{const t=_({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){u(e)}}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){u(e)}}isNavigationTrackingEnabled(){const e=this.configManager.getConfig();return e?.options?.enabledEvents?.includes("navigation")||0===e?.options?.enabledEvents?.length}startNavigation(e){this.logger.log("[instrumentation-manager.startNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.startNavigation] startNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.startNavigation(e)}endNavigation(e){this.logger.log("[instrumentation-manager.endNavigation] called",e),this.isNavigationTrackingEnabled()?this.logger.log("[instrumentation-manager.endNavigation] endNavigation called while navigation tracking is enabled. Ignoring. If you wish to track navigations manually, please disable navigation tracking via the enabledEvents array in the config."):this.navigationListener?.endNavigation(e)}startReplayRecording(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Y((()=>{this.handleReplayInactivityStop()}));e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){u(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}handleReplayInactivityStop(){this.logger.log("[instrumentation-manager] replay stopped due to inactivity, rotating session");try{this.eventsPool.flush()}catch(e){u(e),this.logger.log("[instrumentation-manager] failed to flush events before session rotation:",e)}try{const e=this.idGenerator.generateId(),t=Date.now()*m;this.configManager.setSessionId(e),this.configManager.setSessionStartTime(t)}catch(e){u(e),this.logger.log("[instrumentation-manager] failed to rotate session after inactivity:",e)}finally{this.sessionReplayListener=null}}stopReplayRecording(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy()}},Q="gcSample",ee=class{constructor(e){this.initialized=!1,this.logger=h.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new Z,this.idGenerator=new f;if(!this.getSamplingDecision(e.options?.sessionSampleRate))return void this.logger.log("[session-manager] session is not sampled");if(this.initialized)return void this.logger.log("[session-manager] SDK already initialized");const t=R.getInstance();t.initialize(e);P.getInstance().initialize();const n=e.sessionId,i=t.getSessionId();n?(t.setSessionId(n),this.logger.log("[session-manager] using provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId()),t.getSessionStartTime()||t.setSessionStartTime(Date.now()*m),this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=S(Q);if(t){const e="1"===t;return this.logger.log("[session-manager] using stored sampling decision:",e),e}const n=!e||Math.random()<e;return T(Q,n?"1":"0"),this.logger.log("[session-manager] stored new sampling decision:",n),n}catch(t){this.logger.log("[session-manager] session storage access failed:",t);const n=!e||Math.random()<e;return this.logger.log("[session-manager] using fallback sampling decision:",n),n}}identifyUser(e){if(this.logger.log("[session-manager] identifyUser called"),!this.initialized)return void this.logger.log("[session-manager] cannot identify user: SDK not initialized");R.getInstance().updateConfig({userIdentifier:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");R.getInstance().updateConfig(e)}sendCustomEvent(e){this.initialized?this.instrumentationManager.sendCustomEvent(e):this.logger.log("[session-manager] cannot send custom event: SDK not initialized")}startNavigation(e){this.initialized?this.instrumentationManager.startNavigation(e):this.logger.log("[session-manager] cannot start navigation: SDK not initialized")}endNavigation(e){this.initialized?this.instrumentationManager.endNavigation(e):this.logger.log("[session-manager] cannot end navigation: SDK not initialized")}captureException(e,t){this.initialized?this.instrumentationManager.captureException(e,t):this.logger.log("[session-manager] Cannot capture exception: SDK not initialized")}getSessionId(){return this.initialized?R.getInstance().getSessionId():(this.logger.log("[session-manager] cannot get session ID: SDK not initialized"),"")}async setSessionId(e){if(this.logger.log("[session-manager] setSessionId called"),this.initialized)try{const t=P.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=R.getInstance();i.setSessionId(n),i.setSessionStartTime(Date.now()*m),this.logger.log("[session-manager] session ID set successfully:",n)}catch(e){this.logger.log("[session-manager] failed to set session ID:",e)}else this.logger.log("[session-manager] cannot set session ID: SDK not initialized")}startReplayRecording(){this.initialized?this.instrumentationManager.startReplayRecording():this.logger.log("[session-manager] cannot start replay recording: SDK not initialized")}stopReplayRecording(){this.initialized?this.instrumentationManager.stopReplayRecording():this.logger.log("[session-manager] cannot stop replay recording: SDK not initialized")}destroy(){this.initialized&&(this.instrumentationManager.uninstrument(),w("gcId"),w("gcStartTime"),this.initialized=!1)}};var te={init:function(e){try{K=new ee({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",userIdentifier:e?.userIdentifier,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId})}catch(e){u(e)}},identifyUser:function(e){K?K.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){K&&K.sendCustomEvent(e)},captureException:function(e,t){K&&K.captureException(e,t)},updateConfig:function(e){K&&K.updateConfig(e)},startNavigation:function(e){K?K.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){K?K.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return K?K.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(K)try{await K.setSessionId(e)}catch(e){console.error("[groundcover] setSessionId: failed to set session ID:",e)}else console.warn("[groundcover] setSessionId: groundcover is not initialized. please call init() first")},startReplayRecording:function(){K?K.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){K?K.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=te}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var ne=te;export{ne as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@groundcover/browser",
3
- "version": "0.0.73",
3
+ "version": "0.0.75",
4
4
  "description": "groundcover browser SDK",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",