@groundcover/browser 1.0.2 → 1.0.4

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/README.md CHANGED
@@ -24,6 +24,7 @@ for the full product guide.
24
24
 
25
25
  - [Quick start](#quick-start)
26
26
  - [Configuration reference](#configuration-reference)
27
+ - [HTTP client integration](#http-client-integration)
27
28
  - [Privacy & data masking](#privacy--data-masking)
28
29
  - [Session replay](#session-replay)
29
30
  - [Architecture](#architecture)
@@ -54,8 +55,9 @@ groundcover.init({
54
55
  ```
55
56
 
56
57
  That single call installs every instrumentation (page loads, DOM interactions, network requests,
57
- errors, console logs, navigation, performance, and session replay) and starts sending data. From
58
- here you can enrich it:
58
+ errors, console logs, navigation, and performance) and starts sending data. Session replay is the
59
+ one exception — it must be started explicitly with
60
+ [`startReplayRecording()`](#session-replay). From here you can enrich it:
59
61
 
60
62
  ```ts
61
63
  // Tie events to a user
@@ -121,7 +123,7 @@ groundcover.init({
121
123
  | `debug` | `boolean` | `false` | Verbose SDK console logging. |
122
124
  | `sessionSampleRate` | `number` | `1` | Fraction of sessions captured (0–1). |
123
125
  | `eventSampleRate` | `number` | `1` | Fraction of events captured (0–1). |
124
- | `enabledEvents` | `Array<…>` | `[]` | Instrumentations to enable. **Empty = all.** Members: `dom`, `network`, `exceptions`, `logs`, `pageload`, `navigation`, `performance`, `replay`. |
126
+ | `enabledEvents` | `Array<…>` | `[]` | Instrumentations to enable. **Empty = all.** Members: `dom`, `network`, `exceptions`, `logs`, `pageload`, `navigation`, `performance`, `replay`. Note: `replay` still requires an explicit [`startReplayRecording()`](#session-replay) call — it never auto-starts. |
125
127
  | `excludedUrls` | `Array<string \| RegExp>` | — | Network requests matching these are not captured. |
126
128
  | `sessionMaxDuration` | `number` | `4h` | Target max session length in ms (1 min – 8 h). See [session lifecycle](#session-lifecycle). |
127
129
  | `beforeSend` | `(event) => boolean` | — | Drop gate — return `false` to discard an event. Runs after redaction/enrichment; see [event lifecycle](#architecture). |
@@ -196,6 +198,46 @@ and passing `null` clears it (e.g. on logout).
196
198
 
197
199
  ---
198
200
 
201
+ ## HTTP client integration
202
+
203
+ The SDK instruments network requests by wrapping the global `fetch` and `XMLHttpRequest` on
204
+ `init()`. Most clients are captured automatically, but *how* a client resolves `fetch` decides
205
+ whether it gets instrumented.
206
+
207
+ **Initialize `groundcover.init()` before constructing fetch-based clients.** `init()` replaces
208
+ `globalThis.fetch` with an instrumented wrapper. Libraries that capture a reference to
209
+ `globalThis.fetch` at construction time — e.g. [`openapi-fetch`](https://openapi-ts.dev/openapi-fetch/)'s
210
+ `createClient()`, whose `fetch` option defaults to `globalThis.fetch` — freeze the *native* fetch if
211
+ they are built first, so their requests bypass RUM. Two ways to avoid this:
212
+
213
+ ```ts
214
+ // 1) Init the SDK before you build the client
215
+ groundcover.init({ /* ... */ });
216
+ const client = createClient({ baseUrl: "/" });
217
+
218
+ // 2) Or late-bind fetch so the client resolves the wrapped fetch per request
219
+ // (forward both args so method/headers/body/signal from an `init` are preserved)
220
+ const client = createClient({
221
+ baseUrl: "/",
222
+ fetch: (input, init) => globalThis.fetch(input, init),
223
+ });
224
+ ```
225
+
226
+ Option 2 is the robust choice when import order is hard to guarantee: bundlers evaluate a module's
227
+ static imports before its body, so a client built at module scope is often constructed *before* your
228
+ `init()` call runs.
229
+
230
+ **XHR-based clients (e.g. axios) are always instrumented** regardless of init order — the SDK patches
231
+ `XMLHttpRequest.prototype`, so every request created after `init()` is covered.
232
+
233
+ **`Request`-object calls have their HTTP method captured.** Clients that call
234
+ `fetch(new Request(url, { method, body }))` (openapi-fetch does) carry the method on the `Request`
235
+ rather than in an `init` argument; the SDK reads it from either (since 1.0.4). Note: the request
236
+ *body* for the `Request`-object form is not captured yet — the method, URL, headers, status, and
237
+ response body are.
238
+
239
+ ---
240
+
199
241
  ## Privacy & data masking
200
242
 
201
243
  Masking is **on by default** (`privacy.level: 'mask-sensitive'`). A single `level` is the master
@@ -263,8 +305,8 @@ record-time masking from your [`privacy`](#privacy--data-masking) config:
263
305
  - `privacy.replay.maskTextFn` / `maskInputFn` → rrweb `maskTextFn` / `maskInputFn`
264
306
  - `options.replay.blockedSelectors` → rrweb `blockSelector` (noise reduction)
265
307
 
266
- Recording starts automatically when `replay` is enabled (it is, by default — empty `enabledEvents`).
267
- You can also control it manually:
308
+ Replay recording does **not** start automatically — even when `replay` is in `enabledEvents`. You
309
+ must start it explicitly (e.g. after obtaining user consent):
268
310
 
269
311
  ```ts
270
312
  groundcover.startReplayRecording();
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"),r=require("@rrweb/packer");function s(e){return e&&e.__esModule?e:{default:e}}var a=s(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 h(e){c.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var d="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},g=1e6;function u(e){return e*g}function f(e){return e/g}function p(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var v=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)m[e]=Math.floor(16*Math.random())+48,m[e]>=58&&(m[e]+=39);return b+String.fromCharCode.apply(null,m.slice(0,16))},this.generateSpanId=y(8),this.generateId=y(16)}},m=Array(32);function y(e){return function(){for(let t=0;t<2*e;t++)m[t]=Math.floor(16*Math.random())+48,m[t]>=58&&(m[t]+=39);return String.fromCharCode.apply(null,m.slice(0,2*e))}}var b="0000000000000000";var w=144e5,E=288e5,k=18e5,S={eventSampleRate:1,sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},replay:{},sessionMaxDuration:w};function I(e){try{console.warn(e)}catch{}}function T(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var R=["privacy","tracing","transport","replay"],M={tracing:"origin",privacy:"replay"};function L(e,t,n){const i={...e,...t};if(n){const r=e?.[n],s=t[n];T(r)&&T(s)?i[n]={...r,...s}:Object.hasOwn(t,n)&&!T(s)&&(i[n]=r)}return i}function N(e,t){const n={...e,...t},i=t,r=e;for(const e of R){if(!Object.hasOwn(i,e))continue;const t=i[e];T(t)?n[e]=L(r[e],t,M[e]):n[e]=r[e]}return n}var q=class e{constructor(t){this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=N(S,t?.options||{}),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),e.warnRemovedOptions(t?.options),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)}static stripRemovedOptions(t){const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&delete n[t]}static warnRemovedOptions(t){if(!t||"object"!=typeof t)return;const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&I(`[groundcover] \`options.${t}\` was removed in 1.0.0 and is ignored. Configure masking via \`options.privacy\` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100`)}static normalizeSessionMaxDuration(e){return void 0===e?w:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>E?(I("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),w):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){t.options&&(e.warnRemovedOptions(t.options),this.providedOptions=N(this.providedOptions||{},t.options),this.options=N(this.options,t.options),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)),void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}};q.REMOVED_OPTION_KEYS=["enableMasking","maskFields"];var A=q;function x(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function z(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return h(e),null}}function C(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){h(e)}}function _(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){h(e)}}function H(e,t=0){const n=z(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}var P=class e{constructor(){this.config=null,this.logger=l.getInstance(),this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.privacyCache=null,this.flushActivityOnHide=()=>{try{if("undefined"!=typeof document&&"hidden"!==document.visibilityState)return;this.persistLastActivity()}catch(e){h(e)}},this.activityPersistHooked=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){if(!this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!0;try{document.addEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){h(e)}}this.config||(this.config=new A(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){return this.privacyCache||(this.privacyCache=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",i="allow"===n,r=x(t?.maskSelectors),s=t?.replay,a="function"==typeof s?.maskTextFn?s.maskTextFn:void 0,o="function"==typeof s?.maskInputFn?s.maskInputFn:void 0;let l;l="mask-all"===n||!i&&void 0!==a?["*",...r].join(", "):"mask-sensitive"===n?["[data-private]",...r].join(", "):void 0;const c=e=>!i&&(e??!0),h=c(t?.maskNetworkBodies),d=c(t?.maskNetworkQueryParams),g=c(t?.maskLogs),u=c(t?.maskErrors);return{level:n,maskTextSelector:l,maskSelectors:r,maskInputs:!i,maskNetworkBodies:h,maskNetworkQueryParams:d,maskLogs:g,maskErrors:u,shouldMaskNetworkBodies:!i&&h,shouldMaskNetworkQueryParams:!i&&d,shouldMaskLogs:!i&&g,shouldMaskErrors:!i&&u,sensitiveKeys:x(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0,maskTextFn:a,maskInputFn:o}}(this.config?.providedOptions)),this.privacyCache}getSessionId(){if(this.sessionId)return this.sessionId;return z("gcId")||""}setSessionId(e){this.sessionId=e,C("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:H("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,C("gcStartTime",String(e)),this.setLastActivityMs(Date.now())}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:H("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,C("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs();return t>0&&e-t>=k}clearSessionState(){if(this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!1;try{document.removeEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){h(e)}}_("gcId"),_("gcStartTime"),_("gcLastActivity")}getSessionMaxDuration(){return this.config?.options?.sessionMaxDuration??w}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-f(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}},D="[REDACTED]",O=["authorization","cookie","set-cookie"],F=/(token|key|secret|passwd|password|auth|bearer|credential)/i,j=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,K=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),U=1e5;function B(e,t){if(!e)return!1;if(j.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function Y(e,t){return K.has(e.toLowerCase())||B(e,t)}function $(e){return e.includes("-")&&F.test(e)}function Q(e,t){return B(e,t)||$(e)}function X(e,t){const n=e.sensitive?D:e.value;if(!t)return n;try{const i=t(e);return void 0===i?n:i}catch(e){return h(e),n}}function W(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const i=e.slice(0,n),r=e.slice(n+1);let s=i;try{s=decodeURIComponent(i)}catch{}let a=r;try{a=decodeURIComponent(r)}catch{}const o=Y(s,t.sensitiveKeys),l=X({key:s,value:a,path:[s],kind:t.kind??"query",sensitive:o},t.redact);return l===a?e:`${i}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function V(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${W(e.slice(n+1),t)}`}function J(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},i=e.indexOf("#"),r=-1===i?e:e.slice(0,i),s=-1===i?"":e.slice(i+1),a=V(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${D}@`))}(r),n);return-1===i?a:`${a}#${V(s,n)}`}function G(e,t,n,i,r,s){const a=!!e&&B(e,i.sensitiveKeys);if(null!==t&&"object"==typeof t){if(a||r>8)return D;if(p(t))return D;if(s.has(t))return D;s.add(t);try{if(Array.isArray(t))return t.map((t=>G(e,t,n,i,r+1,s)));const a={};for(const[e,o]of Object.entries(t))a[e]=G(e,o,[...n,e],i,r+1,s);return a}catch(e){return h(e),D}finally{s.delete(t)}}return X({key:e,value:t,path:n,kind:i.kind??"log",sensitive:a},i.redact)}function Z(e,t={}){if(!e)return e;if(e.length>U)return`${Z(e.slice(0,U),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>Q(n,t.sensitiveKeys)?`"${n}":"${D}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return Y(e,t)||$(e)}(n,t.sensitiveKeys)?`${n}=${D}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>Q(n,t.sensitiveKeys)?`${n}: ${D}`:e))}catch(t){h(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){h(e)}return n}function ee(e,t={}){try{const n=G("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return h(e),{}}}function te(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const i={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log"};return{message:Z(t,i),attributes:n?ee(n,i):n}}var ne=P.getInstance(),ie=new v,re=l.getInstance();function se(){const e=ne?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function ae(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:p(e)?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[r,s])=>{const a=t?`${t}.${r}`:r;return"object"==typeof s&&null!==s?Array.isArray(s)?e[a]=s.map(((e,t)=>"object"==typeof e&&null!==e?ae(e,`${a}[${t}]`,n,i+1):e)):Object.assign(e,ae(s,a,n,i+1)):e[a]=s,e}),{}))}catch(e){return re.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}function oe(e){const t=u(Date.now()),n=ie.generateId(),i=e.spanId||ie.generateSpanId(),r=e.traceId||ie.generateTraceId(),s=e.parentSpanId||"",a=ae(e.attributes||{}),o=function(){const e=d?.location;if(!e)return{path:"",url:"",title:d?.document?.title||""};const t=e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/"),n=t?e.hash:e.pathname,i=ne.getPrivacy(),r=i.shouldMaskNetworkQueryParams,s={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:r&&t?J(n,s):n,url:r?J(e.href,s):e.href,title:d?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:s,traceId:r,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}function le({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var ce=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=l.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,i){const r=e.getInstance();if(!r.isAvailable)return n();try{return await t(r)}catch(e){return l.getInstance().log(`[${i}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,i=this.worker;return new Promise(((r,s)=>{const a=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),s(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:r,reject:s,timeoutId:a});try{i.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(a),this.pending.delete(n),s(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};ce.instance=null;var he=ce,de=class{constructor(){this.logger=l.getInstance(),this.config=P.getInstance()}compressInline(t,n){if(!n)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}}}compressAsync(e,t){return he.withFallback((n=>n.encodeBatch(e,t)),(()=>this.compressInline(e,t)),"transporter")}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const i=n.apiKey,r=this.buildEndpoint();if(!i)return void this.logger.log("No API key found");const s=JSON.stringify(e),a=!!n?.options?.transport?.compression,{data:o,isCompressed:l}=t?this.compressInline(s,a):await this.compressAsync(s,a);fetch(r,{method:"POST",headers:{"Content-Type":"application/json",apikey:i,"Content-Encoding":l?"gzip":""},body:o}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},ge=["navigation","dom.event"],ue=S.transport?.batchSize??10,fe=S.transport?.batchTimeout??1e4;var pe=class e{constructor(){this.events=[],this.timeoutId=null,this.config=P.getInstance(),this.logger=l.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.onBeforeEnqueue=null,this.visibilityHandler=()=>{"hidden"===document.visibilityState&&this.flush({lifecycle:!0})},this.transporter=new de}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",this.visibilityHandler),this.initialized=!0}catch(e){h(e)}}destroy(){try{null!==this.timeoutId&&(d.clearTimeout(this.timeoutId),this.timeoutId=null),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.events=[],this.initialized=!1}catch(e){h(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,i=this.config.getConfig()?.options?.enrichEvent;if(n&&!n(e))return;if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(e)}catch(e){h(e)}i&&(e=i(e)),this.events.push(e);const r=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:ue);this.events.length>=r&&!ge.includes(e.type)&&this.flush()}catch(e){h(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),this.events=[],this.scheduleFlush()}catch(e){h(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){h(e)}}scheduleFlush(){try{null!==this.timeoutId&&(d.clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:fe);this.timeoutId=d.setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){h(e)}var e}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",r=/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:r}}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?.user||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};pe.instance=null;var ve=pe,me=class{constructor(){this.logger=l.getInstance(),this.eventsPool=ve.getInstance()}},ye="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function be(e,t){try{return e.getAttribute(t)||""}catch{return""}}function we(e){try{const t=ye?.call(e);return"string"==typeof t?t:""}catch{return""}}function Ee(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function ke(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>be(e,t))).filter(Boolean)}(e).some((e=>B(e,t))))}function Se(e,t){return"allow"!==t.level&&(!!e&&(!!Ee(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>Ee(e,t))))||("mask-all"===t.level||function(e){const t=we(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&ke(e,t.sensitiveKeys)))))}var Ie=class extends me{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=P.getInstance(),this.getShouldMaskText=e=>Se(e.target,this.config.getPrivacy()),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getText=(e,t)=>{const n=e.target;return t?"*":le({text:n?.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){h(e)}};this.eventHandlers.push({type:e,handler:t}),d?.addEventListener(e,t)}))}catch(e){h(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!se())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),i=e.target,r=this.getShouldMaskText({target:i||null}),s=this.getKeyCode(e,r),a=this.getText(e,r);this.logger.log("[dom-events-listener.buildEvent] called");return oe({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:be(i,"id"),tagName:we(i),className:be(i,"class"),text:a}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(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,r=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===we(e).toLowerCase())return"html";let s="",a=0,o=e;const l=[];for(;o&&o!==n&&o!==document.documentElement&&a<i;){let e=we(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 r)if("id"!==t&&"class"!==t)try{const n=o.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=we(o).toLowerCase()||"*"}l.unshift(e||"*"),s=l.join(" > ");try{if(1===n.querySelectorAll(s).length)return s}catch(e){l.shift(),s=l.join(" > ")}try{o=o.parentElement}catch(e){break}a++}return s||"*"}},Te=["log","info","warn","error","debug","assert","trace"],Re=class extends me{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1,this.config=P.getInstance()}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),Te.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){h(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){h(e)}}destroy(){try{if(!this.isInitialized)return;Te.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){h(e)}}handleEvent(e,t){try{if(!se())return;const n=Array.isArray(e)?e:[e],i=this.formatMessage(n,t);if(!i||i?.includes("groundcoverIgnore"))return;const r=this.extractAttributes(n),s=this.buildEvent({message:i,level:t,attributes:r});this.queueEvent(s)}catch(e){h(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:i,attributes:r}=te(this.config.getPrivacy(),e,n);return oe({type:"log",attributes:{...r,message:le({text:i}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);return delete t.message,delete t.level,delete t.location,t}catch(e){return void h(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 h(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{Te.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){h(e)}return e}};function Me(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 h(`Failed to format body: ${e}`),"[unreadable body]"}}var Le,Ne=class extends me{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=P.getInstance(),this.idGenerator=new v,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!se())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});const i=this.config.getPrivacy(),r={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};try{t=new URL(e.url).pathname}catch(s){n=new URL(e.url,globalThis.location.href).href,i.shouldMaskNetworkQueryParams&&(t=J(t,r))}i.shouldMaskNetworkQueryParams&&(n=J(n,r)),this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),a=this.formatHeaders(e.response.headers),o=e.method?.toUpperCase()||"UNKNOWN",{traceId:l,spanId:c}=this.extractTraceIds(e.request.headers),h=(e,t)=>i.shouldMaskNetworkBodies?function(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=U&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(G("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?W(e,t):Z(e,t)}(e,{sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:t}):e,d=le({text:h(e.request.body,"request-body"),maxLength:this.maxBodyLength}),g=le({text:h(e.response.body,"response-body"),maxLength:this.maxBodyLength}),f={type:"HTTP",operation:{name:o},resource_name:t,status:e.status?.toString(),subType:o,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:a,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:d},response:{body:g}}},p={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?u(e.timestamp):void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?u(e.end_time):void 0,span_name:`${e.method} ${t}`,attributes:f};return l&&(p.traceId=l),c&&(p.spanId=c),oe(p)}}async getResponseBody(e){const t=e.body;if(!t)return"";const n=t.getReader(),i=new TextDecoder;let r="",s=0;for(;;){const{done:e,value:t}=await n.read();if(e)break;if(s+t.byteLength>=this.maxBodyLength){const e=t.subarray(0,this.maxBodyLength-s);r+=i.decode(e,{stream:!0}),n.cancel().catch((()=>{}));break}s+=t.byteLength,r+=i.decode(t,{stream:!0})}return r+=i.decode(),r}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 h(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,i=globalThis.XMLHttpRequest.prototype.setRequestHeader;let r;globalThis.XMLHttpRequest.prototype.open=function(n,i,s=!0,a,o){if(r=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,s,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,s,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?.tracing?.origin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),n&&(t?.options?.tracing?.traceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracing?.propagationHeaders)&&t?.options?.tracing?.propagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracing?.propagationHeaders?.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=Me(this._requestBody),s=Me(""===this.responseType||"text"===this.responseType?this.responseText:this.response),a={timestamp:r,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:s}};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?.tracing?.origin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),!n)return;t?.options?.tracing?.traceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracing?.propagationHeaders;(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,r]=t;r={...r||{}},t[1]=r;const s=i instanceof Request,a=r?.method||"GET",o=r?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);r||(t[1]={},r=t[1]),r.headers=this.normalizeHeaders(s?i.headers:void 0,r.headers),c&&this.addTraceHeaders(r);const h=this.extractHeadersRecord(r.headers),d=Me(o);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i={};e.headers.forEach(((e,t)=>{i[t]=e}));const r={method:a,url:l,timestamp:n,body:d,status:e.status,end_time:t,request:{headers:h,body:d},response:{headers:i,body:""}};try{i["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(e.clone()).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 r={method:a,url:l,body:d,status:0,end_time:t,request:{headers:h,body:d},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(r),e}))}}formatHeaders(e){const t=this.config.getPrivacy(),n="allow"===t.level,i=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,i])=>{const r=n.toLowerCase(),s=X({key:n,value:i,path:[n],kind:"header",sensitive:O.includes(r)||F.test(r)||B(n,t.sensitiveKeys)},t.redact);return e[n]=null===s?"":String(s),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact});return Object.entries(i)?.reduce(((e,[t,n])=>(e[t]=le({text:n}),e)),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracing?.traceIdHeaderName){const i=e[t.options.tracing.traceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracing?.spanIdHeaderName){const n=e[t.options.tracing.spanIdHeaderName];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?.tracing?.propagationHeaders?.length)for(const n of t.options.tracing.propagationHeaders){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(r){this.logger.log("[network-events-listener.getTraceIds] error",{error:r}),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?.tracing?.propagationUrls?.length)return!1;const n=t.options.tracing.propagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),r=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(r)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},qe=class extends me{constructor(){super(...arguments),this.config=P.getInstance(),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){h(e)}}}initialize(){d?.addEventListener("error",this.handleEvent),d?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){d?.removeEventListener("error",this.handleEvent),d?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){const n=this.config.getPrivacy(),i=n.shouldMaskErrors,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error"},s=e.message||"Unknown error",a=i?Z(s,r):s,o=i&&t?.metadata?ee(t.metadata,r):t?.metadata;return oe({type:"exception",attributes:{error_type:e.name||"Error",error_message:a,error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${le({text:a,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:o}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}enhanceError(e,t){const{filename:n,lineno:i,colno:r}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),r&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:r})}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[]}}},Ae=class extends me{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=d.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){h(e)}}isInBrowserEnvironment(){try{return void 0!==d&&void 0!==d.location&&void 0!==d.history&&"function"==typeof d.addEventListener}catch(e){return h(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},d&&"function"==typeof d.addEventListener&&(d.addEventListener("popstate",this.popStateHandler),d.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){h(e)}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.isInitialized&&this.originalPushState&&this.originalReplaceState&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState),d&&"function"==typeof d.removeEventListener&&(d.removeEventListener("popstate",this.popStateHandler),d.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){h(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",d.location.href);const e=P.getInstance().getPrivacy(),t="allow"===e.level,n=d.location.href,i=this.activeNavigation?.metadata;return oe({type:"navigation",attributes:{page_url:e.shouldMaskNetworkQueryParams?J(n,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):n,metadata:!t&&i?ee(i,{sensitiveKeys:e.sensitiveKeys,redact:e.redact}):i,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){h(e)}}startNavigation(e){this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:d.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===d.location.href)return;let e,t;try{e=new URL(d.location.href),t=new URL(this.currentUrl)}catch(e){return void h(e)}const n=e=>e.startsWith("#/"),i=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||i&&e.hash!==t.hash)&&(this.currentUrl=d.location.href,this.handleEvent())}catch(e){h(e)}}},xe=class extends me{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",d),"complete"===d?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):d?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),h(e)}}destroy(){d?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(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,r=t.duration,s=t.initiatorType;i.totalSize+=n,i.totalDuration+=r,i.byType[s]||(i.byType[s]={count:0,size:0,duration:0}),i.byType[s].count++,i.byType[s].size+=n,i.byType[s].duration+=r}));const r=P.getInstance().getPrivacy(),s=r.shouldMaskNetworkQueryParams,a={sensitiveKeys:r.sensitiveKeys,redact:r.redact,kind:"query"},o=d?.location?.href||"",l=d?.document?.referrer||"";return oe({type:"pageload",attributes:{page_url:s?J(o,a):o,page_load_time:t,page_referrer:s?J(l,a):l,page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}},ze=class extends me{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!se())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(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 oe({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){h(e)}}},Ce=class{constructor(){this.logger=l.getInstance(),this.eventsPool=ve.getInstance(),this.configManager=P.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=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?.replay?.blockedSelectors?.filter(Boolean),t=e?.length?e.join(", "):void 0,n=this.configManager.getPrivacy(),r=n.maskInputFn??("allow"===n.level?void 0:(e,t)=>Se(t,n)?"*".repeat(e.length):e);this.stopFn=i.record({...t?{blockSelector:t}:{},...n.maskTextSelector?{maskTextSelector:n.maskTextSelector}:{},maskAllInputs:n.maskInputs,...n.maskTextFn?{maskTextFn:n.maskTextFn}:{},...r?{maskInputFn:r}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{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){h(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=d.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{h(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(d.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.configManager.getSessionId(),n=he.getInstance();let i;if(n.isAvailable)try{i=await n.packReplay(e.events)}catch(t){h(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),i=e.events.map((e=>r.pack(e)))}else i=e.events.map((e=>r.pack(e)));this.configManager.getSessionId()===t?this.enqueueReplayEvent(i,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:i.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>r.pack(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const r=oe({type:"replay",attributes:i});this.eventsPool.addEvent(r),this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){h(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},_e=["pointerdown","keydown","scroll","touchstart","mousemove"],He=class{constructor(e){this.logger=l.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){h(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,_e.forEach((e=>{try{d.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){h(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",k,"ms");try{this.callbacks.onIdle()}catch(e){h(e)}}),k)}catch(e){h(e)}}destroy(){if(this.installed){this.installed=!1,_e.forEach((e=>{try{d.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){h(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){h(e)}finally{this.idleTimer=null}}}},Pe=new Set(["dom.event","navigation","pageload"]),De=class{constructor(){this.logger=l.getInstance(),this.eventsPool=ve.getInstance(),this.configManager=P.getInstance(),this.idGenerator=new v,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.isRotating=!1,this.replayDesired=!1,this.presenceMonitor=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.eventsPool.setBeforeEnqueueHook((e=>this.reconcileSessionOnEnqueue(e))),this.presenceMonitor?.destroy(),this.presenceMonitor=new He({onPresence:e=>this.reconcileSession(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new xe,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new Ie,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new Re,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new qe,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new Ne,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new ze,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new Ae({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=oe({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){h(e)}}emitLog(e,t,n){if(this.logEventsListener){this.logger.log("[instrumentation-manager.emitLog] called",{message:e,level:t,attributes:n});try{const i={...n||{}};delete i.message,delete i.level,delete i.location;const{message:r,attributes:s}=te(P.getInstance().getPrivacy(),e,i),a=oe({type:"log",attributes:{...s,message:le({text:r}),level:t}});this.eventsPool.addEvent(a)}catch(e){h(e)}}}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){h(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)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){if(this.replayDesired=!0,this.isReplayRecording())return void this.logger.log("[instrumentation-manager] replay recording already started");const e=Date.now();(this.configManager.isSessionInactive(e)||this.configManager.isSessionExpired(e))&&this.rotateSession({reason:"replay start into stale session"}),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer()}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] user present and replay desired — starting replay"),this.startReplayListener())}pauseReplayOnIdle(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Ce;e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){h(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}reconcileSession(e,t){if(this.isRotating)return;t&&this.configManager.isSessionInactive(e)&&this.rotateSession({reason:"inactivity gap"});const n=this.configManager.getSessionElapsedMs(e),i=this.configManager.getSessionMaxDuration(),r=n>=i;this.logger.log("[instrumentation-manager] session reconcile",{userPresent:t,elapsedMs:n,maxDurationMs:i,expired:r}),r&&this.rotateSession({reason:"max session duration"}),this.syncReplayState(t),t&&(this.configManager.setLastActivityMs(e),this.presenceMonitor?.notePresence(e))}reconcileSessionOnEnqueue(e){this.isRotating||("replay"!==e.type?this.reconcileSession(Date.now(),Pe.has(e.type)):this.logger.log("[instrumentation-manager] enqueue rotation check: ignoring replay event"))}rotateSession(e){if(this.isRotating)return;this.isRotating=!0;const t=this.configManager.getSessionId(),n=this.isReplayRecording();this.logger.log("[instrumentation-manager] session rotation start",{reason:e.reason,previousId:t,wasReplayActive:n});const i=(e,t)=>{try{this.logger.log(`[instrumentation-manager] session rotation: ${e}`),t()}catch(t){h(t),this.logger.log(`[instrumentation-manager] failed to ${e} during session rotation:`,t)}};try{i("stop replay",(()=>this.stopReplayListener())),i("flush events",(()=>this.eventsPool.flush())),i("rotate session ids",(()=>{const e=this.idGenerator.generateId();this.configManager.setSessionId(e),this.configManager.setSessionStartTime(u(Date.now())),this.logger.log("[instrumentation-manager] session id rotated",{from:t,to:e})})),i("sync replay",(()=>this.syncReplayState(n)))}finally{this.isRotating=!1,this.logger.log("[instrumentation-manager] session rotation complete",{reason:e.reason})}}stopReplayListener(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.eventsPool.setBeforeEnqueueHook(null),this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}},Oe="gcSample",Fe=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 De,this.idGenerator=new v;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=P.getInstance();t.initialize(e);ve.getInstance().initialize(),he.getInstance();const n=e.sessionId,i=t.getSessionId();n&&n!==i?(t.setSessionId(n),t.setSessionStartTime(u(Date.now())),this.logger.log("[session-manager] using provided sessionId:",n)):n?(t.setSessionId(n),this.logger.log("[session-manager] continuing provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId());const r=Date.now(),s=f(t.getSessionStartTime());if(s>0&&r-s>=-6e4){if(t.isSessionExpired(r)||t.isSessionInactive(r)){const e=t.isSessionExpired(r)?"persisted session past cap":"inactivity gap across reload",n=t.getSessionId(),i=this.idGenerator.generateId();t.setSessionId(i),t.setSessionStartTime(u(r)),this.logger.log(`[session-manager] init-time rotation: ${e}`,{from:n,to:i})}}else t.setSessionStartTime(u(r));this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=z(Oe);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 C(Oe,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");P.getInstance().updateConfig({user:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");P.getInstance().updateConfig(e);const t=e.options,n=!!t&&"privacy"in t,i=!!t&&"object"==typeof t.replay&&null!==t.replay&&"blockedSelectors"in t.replay;(n||i)&&this.instrumentationManager.restartReplayForConfigChange()}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")}emitLog(e,t,n){this.initialized?this.instrumentationManager.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.initialized?P.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{this.instrumentationManager.flushPendingReplay();const t=ve.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=P.getInstance();i.setSessionId(n),i.setSessionStartTime(u(Date.now())),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(),ve.getInstance().destroy(),he.getInstance().terminate(),P.getInstance().clearSessionState(),this.initialized=!1)}},je=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var Ke={init:function(e){try{Le=new Fe({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",user:e?.user,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId}),je.manager=Le}catch(e){h(e)}},identifyUser:function(e){Le?Le.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){Le&&Le.sendCustomEvent(e)},captureException:function(e,t){Le&&Le.captureException(e,t)},logger:je,updateConfig:function(e){if(Le)try{Le.updateConfig(e)}catch(e){h(e)}},startNavigation:function(e){Le?Le.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){Le?Le.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return Le?Le.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(Le)try{await Le.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(){Le?Le.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){Le?Le.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Ke}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var Ue=Ke;module.exports=Ue;
1
+ "use strict";var e=require("fflate"),t=require("error-stack-parser"),n=require("web-vitals"),i=require("rrweb"),r=require("@rrweb/packer");function s(e){return e&&e.__esModule?e:{default:e}}var a=s(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 h(e){c.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var d="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},g=1e6;function u(e){return e*g}function f(e){return e/g}function p(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var v=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)m[e]=Math.floor(16*Math.random())+48,m[e]>=58&&(m[e]+=39);return b+String.fromCharCode.apply(null,m.slice(0,16))},this.generateSpanId=y(8),this.generateId=y(16)}},m=Array(32);function y(e){return function(){for(let t=0;t<2*e;t++)m[t]=Math.floor(16*Math.random())+48,m[t]>=58&&(m[t]+=39);return String.fromCharCode.apply(null,m.slice(0,2*e))}}var b="0000000000000000";var w=144e5,E=288e5,k=18e5,S={eventSampleRate:1,sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},replay:{},sessionMaxDuration:w};function I(e){try{console.warn(e)}catch{}}function T(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var R=["privacy","tracing","transport","replay"],M={tracing:"origin",privacy:"replay"};function L(e,t,n){const i={...e,...t};if(n){const r=e?.[n],s=t[n];T(r)&&T(s)?i[n]={...r,...s}:Object.hasOwn(t,n)&&!T(s)&&(i[n]=r)}return i}function N(e,t){const n={...e,...t},i=t,r=e;for(const e of R){if(!Object.hasOwn(i,e))continue;const t=i[e];T(t)?n[e]=L(r[e],t,M[e]):n[e]=r[e]}return n}var q=class e{constructor(t){this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=N(S,t?.options||{}),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),e.warnRemovedOptions(t?.options),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)}static stripRemovedOptions(t){const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&delete n[t]}static warnRemovedOptions(t){if(!t||"object"!=typeof t)return;const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&I(`[groundcover] \`options.${t}\` was removed in 1.0.0 and is ignored. Configure masking via \`options.privacy\` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100`)}static normalizeSessionMaxDuration(e){return void 0===e?w:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>E?(I("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),w):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){t.options&&(e.warnRemovedOptions(t.options),this.providedOptions=N(this.providedOptions||{},t.options),this.options=N(this.options,t.options),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)),void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}};q.REMOVED_OPTION_KEYS=["enableMasking","maskFields"];var A=q;function x(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function z(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return h(e),null}}function C(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){h(e)}}function _(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){h(e)}}function H(e,t=0){const n=z(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}var P=class e{constructor(){this.config=null,this.logger=l.getInstance(),this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.privacyCache=null,this.flushActivityOnHide=()=>{try{if("undefined"!=typeof document&&"hidden"!==document.visibilityState)return;this.persistLastActivity()}catch(e){h(e)}},this.activityPersistHooked=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){if(!this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!0;try{document.addEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){h(e)}}this.config||(this.config=new A(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){return this.privacyCache||(this.privacyCache=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",i="allow"===n,r=x(t?.maskSelectors),s=t?.replay,a="function"==typeof s?.maskTextFn?s.maskTextFn:void 0,o="function"==typeof s?.maskInputFn?s.maskInputFn:void 0;let l;l="mask-all"===n||!i&&void 0!==a?["*",...r].join(", "):"mask-sensitive"===n?["[data-private]",...r].join(", "):void 0;const c=e=>!i&&(e??!0),h=c(t?.maskNetworkBodies),d=c(t?.maskNetworkQueryParams),g=c(t?.maskLogs),u=c(t?.maskErrors);return{level:n,maskTextSelector:l,maskSelectors:r,maskInputs:!i,maskNetworkBodies:h,maskNetworkQueryParams:d,maskLogs:g,maskErrors:u,shouldMaskNetworkBodies:!i&&h,shouldMaskNetworkQueryParams:!i&&d,shouldMaskLogs:!i&&g,shouldMaskErrors:!i&&u,sensitiveKeys:x(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0,maskTextFn:a,maskInputFn:o}}(this.config?.providedOptions)),this.privacyCache}getSessionId(){if(this.sessionId)return this.sessionId;return z("gcId")||""}setSessionId(e){this.sessionId=e,C("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:H("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,C("gcStartTime",String(e)),this.setLastActivityMs(Date.now())}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:H("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,C("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs();return t>0&&e-t>=k}clearSessionState(){if(this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!1;try{document.removeEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){h(e)}}_("gcId"),_("gcStartTime"),_("gcLastActivity")}getSessionMaxDuration(){return this.config?.options?.sessionMaxDuration??w}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-f(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}},D="[REDACTED]",O=["authorization","cookie","set-cookie"],F=/(token|key|secret|passwd|password|auth|bearer|credential)/i,j=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,K=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),U=1e5;function B(e,t){if(!e)return!1;if(j.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function Y(e,t){return K.has(e.toLowerCase())||B(e,t)}function $(e){return e.includes("-")&&F.test(e)}function Q(e,t){return B(e,t)||$(e)}function X(e,t){const n=e.sensitive?D:e.value;if(!t)return n;try{const i=t(e);return void 0===i?n:i}catch(e){return h(e),n}}function W(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const i=e.slice(0,n),r=e.slice(n+1);let s=i;try{s=decodeURIComponent(i)}catch{}let a=r;try{a=decodeURIComponent(r)}catch{}const o=Y(s,t.sensitiveKeys),l=X({key:s,value:a,path:[s],kind:t.kind??"query",sensitive:o},t.redact);return l===a?e:`${i}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function V(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${W(e.slice(n+1),t)}`}function J(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},i=e.indexOf("#"),r=-1===i?e:e.slice(0,i),s=-1===i?"":e.slice(i+1),a=V(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${D}@`))}(r),n);return-1===i?a:`${a}#${V(s,n)}`}function G(e,t,n,i,r,s){const a=!!e&&B(e,i.sensitiveKeys);if(null!==t&&"object"==typeof t){if(a||r>8)return D;if(p(t))return D;if(s.has(t))return D;s.add(t);try{if(Array.isArray(t))return t.map((t=>G(e,t,n,i,r+1,s)));const a={};for(const[e,o]of Object.entries(t))a[e]=G(e,o,[...n,e],i,r+1,s);return a}catch(e){return h(e),D}finally{s.delete(t)}}return X({key:e,value:t,path:n,kind:i.kind??"log",sensitive:a},i.redact)}function Z(e,t={}){if(!e)return e;if(e.length>U)return`${Z(e.slice(0,U),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>Q(n,t.sensitiveKeys)?`"${n}":"${D}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return Y(e,t)||$(e)}(n,t.sensitiveKeys)?`${n}=${D}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>Q(n,t.sensitiveKeys)?`${n}: ${D}`:e))}catch(t){h(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){h(e)}return n}function ee(e,t={}){try{const n=G("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return h(e),{}}}function te(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const i={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log"};return{message:Z(t,i),attributes:n?ee(n,i):n}}var ne=P.getInstance(),ie=new v,re=l.getInstance();function se(){const e=ne?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function ae(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:p(e)?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[r,s])=>{const a=t?`${t}.${r}`:r;return"object"==typeof s&&null!==s?Array.isArray(s)?e[a]=s.map(((e,t)=>"object"==typeof e&&null!==e?ae(e,`${a}[${t}]`,n,i+1):e)):Object.assign(e,ae(s,a,n,i+1)):e[a]=s,e}),{}))}catch(e){return re.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}function oe(e){const t=u(Date.now()),n=ie.generateId(),i=e.spanId||ie.generateSpanId(),r=e.traceId||ie.generateTraceId(),s=e.parentSpanId||"",a=ae(e.attributes||{}),o=function(){const e=d?.location;if(!e)return{path:"",url:"",title:d?.document?.title||""};const t=e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/"),n=t?e.hash:e.pathname,i=ne.getPrivacy(),r=i.shouldMaskNetworkQueryParams,s={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:r&&t?J(n,s):n,url:r?J(e.href,s):e.href,title:d?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:s,traceId:r,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}function le({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var ce=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=l.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,i){const r=e.getInstance();if(!r.isAvailable)return n();try{return await t(r)}catch(e){return l.getInstance().log(`[${i}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,i=this.worker;return new Promise(((r,s)=>{const a=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),s(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:r,reject:s,timeoutId:a});try{i.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(a),this.pending.delete(n),s(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};ce.instance=null;var he=ce,de=class{constructor(){this.logger=l.getInstance(),this.config=P.getInstance()}compressInline(t,n){if(!n)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}}}compressAsync(e,t){return he.withFallback((n=>n.encodeBatch(e,t)),(()=>this.compressInline(e,t)),"transporter")}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const i=n.apiKey,r=this.buildEndpoint();if(!i)return void this.logger.log("No API key found");const s=JSON.stringify(e),a=!!n?.options?.transport?.compression,{data:o,isCompressed:l}=t?this.compressInline(s,a):await this.compressAsync(s,a);fetch(r,{method:"POST",headers:{"Content-Type":"application/json",apikey:i,"Content-Encoding":l?"gzip":""},body:o}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},ge=["navigation","dom.event"],ue=S.transport?.batchSize??10,fe=S.transport?.batchTimeout??1e4;var pe=class e{constructor(){this.events=[],this.timeoutId=null,this.config=P.getInstance(),this.logger=l.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.onBeforeEnqueue=null,this.visibilityHandler=()=>{"hidden"===document.visibilityState&&this.flush({lifecycle:!0})},this.transporter=new de}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",this.visibilityHandler),this.initialized=!0}catch(e){h(e)}}destroy(){try{null!==this.timeoutId&&(d.clearTimeout(this.timeoutId),this.timeoutId=null),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.events=[],this.initialized=!1}catch(e){h(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,i=this.config.getConfig()?.options?.enrichEvent;if(n&&!n(e))return;if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(e)}catch(e){h(e)}i&&(e=i(e)),this.events.push(e);const r=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:ue);this.events.length>=r&&!ge.includes(e.type)&&this.flush()}catch(e){h(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),this.events=[],this.scheduleFlush()}catch(e){h(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){h(e)}}scheduleFlush(){try{null!==this.timeoutId&&(d.clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:fe);this.timeoutId=d.setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){h(e)}var e}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",r=/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:r}}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?.user||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};pe.instance=null;var ve=pe,me=class{constructor(){this.logger=l.getInstance(),this.eventsPool=ve.getInstance()}},ye="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function be(e,t){try{return e.getAttribute(t)||""}catch{return""}}function we(e){try{const t=ye?.call(e);return"string"==typeof t?t:""}catch{return""}}function Ee(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function ke(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>be(e,t))).filter(Boolean)}(e).some((e=>B(e,t))))}function Se(e,t){return"allow"!==t.level&&(!!e&&(!!Ee(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>Ee(e,t))))||("mask-all"===t.level||function(e){const t=we(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&ke(e,t.sensitiveKeys)))))}var Ie=class extends me{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=P.getInstance(),this.getShouldMaskText=e=>Se(e.target,this.config.getPrivacy()),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getText=(e,t)=>{const n=e.target;return t?"*":le({text:n?.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){h(e)}};this.eventHandlers.push({type:e,handler:t}),d?.addEventListener(e,t)}))}catch(e){h(e)}}destroy(){this.eventHandlers.forEach((({type:e,handler:t})=>{global?.removeEventListener?.(e,t)})),this.eventHandlers=[]}handleEvent(e){try{if(!se())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}}buildEvent(e){const t=this.getSelector(e),n=this.getCoordinates(e),i=e.target,r=this.getShouldMaskText({target:i||null}),s=this.getKeyCode(e,r),a=this.getText(e,r);this.logger.log("[dom-events-listener.buildEvent] called");return oe({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:be(i,"id"),tagName:we(i),className:be(i,"class"),text:a}}})}queueEvent(e){try{this.logger.log("[dom-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(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,r=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===we(e).toLowerCase())return"html";let s="",a=0,o=e;const l=[];for(;o&&o!==n&&o!==document.documentElement&&a<i;){let e=we(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 r)if("id"!==t&&"class"!==t)try{const n=o.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=we(o).toLowerCase()||"*"}l.unshift(e||"*"),s=l.join(" > ");try{if(1===n.querySelectorAll(s).length)return s}catch(e){l.shift(),s=l.join(" > ")}try{o=o.parentElement}catch(e){break}a++}return s||"*"}},Te=["log","info","warn","error","debug","assert","trace"],Re=class extends me{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1,this.config=P.getInstance()}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),Te.forEach((e=>{e in console&&(console[e]=(...t)=>{try{this.handleEvent(t,e)}catch(e){h(e)}finally{this.originalConsole?.[e]&&this.originalConsole[e](...t)}})})),this.isInitialized=!0}catch(e){h(e)}}destroy(){try{if(!this.isInitialized)return;Te.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){h(e)}}handleEvent(e,t){try{if(!se())return;const n=Array.isArray(e)?e:[e],i=this.formatMessage(n,t);if(!i||i?.includes("groundcoverIgnore"))return;const r=this.extractAttributes(n),s=this.buildEvent({message:i,level:t,attributes:r});this.queueEvent(s)}catch(e){h(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:i,attributes:r}=te(this.config.getPrivacy(),e,n);return oe({type:"log",attributes:{...r,message:le({text:i}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);return delete t.message,delete t.level,delete t.location,t}catch(e){return void h(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 h(e),"[Error formatting console message]"}}captureConsoleMethods(){const e={};try{Te.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){h(e)}return e}};function Me(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 h(`Failed to format body: ${e}`),"[unreadable body]"}}var Le,Ne=class extends me{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=P.getInstance(),this.idGenerator=new v,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!se())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(e)}},this.buildEvent=e=>{let t=e.url,n=e.url;this.logger.log("[network-events-listener.buildEvent] called",{event:e});const i=this.config.getPrivacy(),r={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};try{t=new URL(e.url).pathname}catch(s){n=new URL(e.url,globalThis.location.href).href,i.shouldMaskNetworkQueryParams&&(t=J(t,r))}i.shouldMaskNetworkQueryParams&&(n=J(n,r)),this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),a=this.formatHeaders(e.response.headers),o=e.method?.toUpperCase()||"UNKNOWN",{traceId:l,spanId:c}=this.extractTraceIds(e.request.headers),h=(e,t)=>i.shouldMaskNetworkBodies?function(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=U&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(G("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?W(e,t):Z(e,t)}(e,{sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:t}):e,d=le({text:h(e.request.body,"request-body"),maxLength:this.maxBodyLength}),g=le({text:h(e.response.body,"response-body"),maxLength:this.maxBodyLength}),f={type:"HTTP",operation:{name:o},resource_name:t,status:e.status?.toString(),subType:o,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:a,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:d},response:{body:g}}},p={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?u(e.timestamp):void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?u(e.end_time):void 0,span_name:`${e.method} ${t}`,attributes:f};return l&&(p.traceId=l),c&&(p.spanId=c),oe(p)}}async getResponseBody(e){const t=e.body;if(!t)return"";const n=t.getReader(),i=new TextDecoder;let r="",s=0;for(;;){const{done:e,value:t}=await n.read();if(e)break;if(s+t.byteLength>=this.maxBodyLength){const e=t.subarray(0,this.maxBodyLength-s);r+=i.decode(e,{stream:!0}),n.cancel().catch((()=>{}));break}s+=t.byteLength,r+=i.decode(t,{stream:!0})}return r+=i.decode(),r}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 h(e),!1}}queueEvent(e){try{this.logger.log("[network-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}patchXHR(){const e=this,t=globalThis.XMLHttpRequest.prototype.open,n=globalThis.XMLHttpRequest.prototype.send,i=globalThis.XMLHttpRequest.prototype.setRequestHeader;let r;globalThis.XMLHttpRequest.prototype.open=function(n,i,s=!0,a,o){if(r=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,s,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,s,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?.tracing?.origin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),n&&(t?.options?.tracing?.traceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracing?.propagationHeaders)&&t?.options?.tracing?.propagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracing?.propagationHeaders?.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=Me(this._requestBody),s=Me(""===this.responseType||"text"===this.responseType?this.responseText:this.response),a={timestamp:r,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:s}};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?.tracing?.origin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),!n)return;t?.options?.tracing?.traceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracing?.propagationHeaders;(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,r]=t;r={...r||{}},t[1]=r;const s=i instanceof Request,a=r?.method||(s?i.method:"GET"),o=r?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);r||(t[1]={},r=t[1]),r.headers=this.normalizeHeaders(s?i.headers:void 0,r.headers),c&&this.addTraceHeaders(r);const h=this.extractHeadersRecord(r.headers),d=Me(o);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i={};e.headers.forEach(((e,t)=>{i[t]=e}));const r={method:a,url:l,timestamp:n,body:d,status:e.status,end_time:t,request:{headers:h,body:d},response:{headers:i,body:""}};try{i["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(e.clone()).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 r={method:a,url:l,body:d,status:0,end_time:t,request:{headers:h,body:d},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(r),e}))}}formatHeaders(e){const t=this.config.getPrivacy(),n="allow"===t.level,i=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,i])=>{const r=n.toLowerCase(),s=X({key:n,value:i,path:[n],kind:"header",sensitive:O.includes(r)||F.test(r)||B(n,t.sensitiveKeys)},t.redact);return e[n]=null===s?"":String(s),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact});return Object.entries(i)?.reduce(((e,[t,n])=>(e[t]=le({text:n}),e)),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracing?.traceIdHeaderName){const i=e[t.options.tracing.traceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracing?.spanIdHeaderName){const n=e[t.options.tracing.spanIdHeaderName];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?.tracing?.propagationHeaders?.length)for(const n of t.options.tracing.propagationHeaders){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(r){this.logger.log("[network-events-listener.getTraceIds] error",{error:r}),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?.tracing?.propagationUrls?.length)return!1;const n=t.options.tracing.propagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),r=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(r)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},qe=class extends me{constructor(){super(...arguments),this.config=P.getInstance(),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){h(e)}}}initialize(){d?.addEventListener("error",this.handleEvent),d?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){d?.removeEventListener("error",this.handleEvent),d?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){const n=this.config.getPrivacy(),i=n.shouldMaskErrors,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error"},s=e.message||"Unknown error",a=i?Z(s,r):s,o=i&&t?.metadata?ee(t.metadata,r):t?.metadata;return oe({type:"exception",attributes:{error_type:e.name||"Error",error_message:a,error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${le({text:a,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:o}})}queueEvent(e){try{this.logger.log("[errors-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}enhanceError(e,t){const{filename:n,lineno:i,colno:r}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),r&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:r})}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[]}}},Ae=class extends me{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=d.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){h(e)}}isInBrowserEnvironment(){try{return void 0!==d&&void 0!==d.location&&void 0!==d.history&&"function"==typeof d.addEventListener}catch(e){return h(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},d&&"function"==typeof d.addEventListener&&(d.addEventListener("popstate",this.popStateHandler),d.addEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!0}catch(e){h(e)}}destroy(){try{this.logger.log("[navigation-listener.destroy] called"),this.isInitialized&&this.originalPushState&&this.originalReplaceState&&(history.pushState=this.originalPushState,history.replaceState=this.originalReplaceState),d&&"function"==typeof d.removeEventListener&&(d.removeEventListener("popstate",this.popStateHandler),d.removeEventListener("hashchange",this.hashChangeHandler)),this.isInitialized=!1}catch(e){h(e)}}handleEvent(){try{this.logger.log("[navigation-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(e)}}buildEvent(){this.logger.log("[navigation-listener.buildEvent] called",d.location.href);const e=P.getInstance().getPrivacy(),t="allow"===e.level,n=d.location.href,i=this.activeNavigation?.metadata;return oe({type:"navigation",attributes:{page_url:e.shouldMaskNetworkQueryParams?J(n,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):n,metadata:!t&&i?ee(i,{sensitiveKeys:e.sensitiveKeys,redact:e.redact}):i,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){h(e)}}startNavigation(e){this.logger.log("[navigation-listener.startNavigation] called",e),this.activeNavigation={page_url:d.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===d.location.href)return;let e,t;try{e=new URL(d.location.href),t=new URL(this.currentUrl)}catch(e){return void h(e)}const n=e=>e.startsWith("#/"),i=n(e.hash)||n(t.hash);(e.pathname!==t.pathname||i&&e.hash!==t.hash)&&(this.currentUrl=d.location.href,this.handleEvent())}catch(e){h(e)}}},xe=class extends me{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",d),"complete"===d?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):d?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),h(e)}}destroy(){d?.removeEventListener("load",this.loadEventHandler)}handleEvent(){try{this.logger.log("[page-load-listener.handleEvent] called");const e=this.buildEvent();this.queueEvent(e)}catch(e){h(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,r=t.duration,s=t.initiatorType;i.totalSize+=n,i.totalDuration+=r,i.byType[s]||(i.byType[s]={count:0,size:0,duration:0}),i.byType[s].count++,i.byType[s].size+=n,i.byType[s].duration+=r}));const r=P.getInstance().getPrivacy(),s=r.shouldMaskNetworkQueryParams,a={sensitiveKeys:r.sensitiveKeys,redact:r.redact,kind:"query"},o=d?.location?.href||"",l=d?.document?.referrer||"";return oe({type:"pageload",attributes:{page_url:s?J(o,a):o,page_load_time:t,page_referrer:s?J(l,a):l,page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){h(e)}}},ze=class extends me{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!se())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){h(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 oe({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){h(e)}}},Ce=class{constructor(){this.logger=l.getInstance(),this.eventsPool=ve.getInstance(),this.configManager=P.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=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?.replay?.blockedSelectors?.filter(Boolean),t=e?.length?e.join(", "):void 0,n=this.configManager.getPrivacy(),r=n.maskInputFn??("allow"===n.level?void 0:(e,t)=>Se(t,n)?"*".repeat(e.length):e);this.stopFn=i.record({...t?{blockSelector:t}:{},...n.maskTextSelector?{maskTextSelector:n.maskTextSelector}:{},maskAllInputs:n.maskInputs,...n.maskTextFn?{maskTextFn:n.maskTextFn}:{},...r?{maskInputFn:r}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{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){h(e),this.logger.log("[session-replay-listener] failed to process event in emit callback:",e)}}})||null,this.logger.log("[session-replay-listener] started recording with full snapshot interval:",3e4,"ms")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to start recording:",e),this.isRecording=!1}}scheduleSendBatch(){null===this.sendTimerId&&(this.sendTimerId=d.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{h(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(d.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.configManager.getSessionId(),n=he.getInstance();let i;if(n.isAvailable)try{i=await n.packReplay(e.events)}catch(t){h(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),i=e.events.map((e=>r.pack(e)))}else i=e.events.map((e=>r.pack(e)));this.configManager.getSessionId()===t?this.enqueueReplayEvent(i,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:i.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>r.pack(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const r=oe({type:"replay",attributes:i});this.eventsPool.addEvent(r),this.logger.log("[session-replay-listener] sent batch with",e.length,"events",t?"(includes full snapshot)":"")}catch(e){h(e),this.logger.log("[session-replay-listener] failed to send batch:",e)}}stopRecording(){if(this.isRecording)try{this.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),this.stopFn=null,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0}catch(e){h(e),this.logger.log("[session-replay-listener] failed to stop recording:",e)}}destroy(){this.stopRecording()}},_e=["pointerdown","keydown","scroll","touchstart","mousemove"],He=class{constructor(e){this.logger=l.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){h(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,_e.forEach((e=>{try{d.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){h(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",k,"ms");try{this.callbacks.onIdle()}catch(e){h(e)}}),k)}catch(e){h(e)}}destroy(){if(this.installed){this.installed=!1,_e.forEach((e=>{try{d.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){h(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){h(e)}finally{this.idleTimer=null}}}},Pe=new Set(["dom.event","navigation","pageload"]),De=class{constructor(){this.logger=l.getInstance(),this.eventsPool=ve.getInstance(),this.configManager=P.getInstance(),this.idGenerator=new v,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.isRotating=!1,this.replayDesired=!1,this.presenceMonitor=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.eventsPool.setBeforeEnqueueHook((e=>this.reconcileSessionOnEnqueue(e))),this.presenceMonitor?.destroy(),this.presenceMonitor=new He({onPresence:e=>this.reconcileSession(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new xe,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new Ie,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new Re,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new qe,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new Ne,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new ze,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new Ae({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=oe({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){h(e)}}emitLog(e,t,n){if(this.logEventsListener){this.logger.log("[instrumentation-manager.emitLog] called",{message:e,level:t,attributes:n});try{const i={...n||{}};delete i.message,delete i.level,delete i.location;const{message:r,attributes:s}=te(P.getInstance().getPrivacy(),e,i),a=oe({type:"log",attributes:{...s,message:le({text:r}),level:t}});this.eventsPool.addEvent(a)}catch(e){h(e)}}}captureException(e,t){try{this.logger.log("[instrumentation-manager.captureException] called",e),this.errorsEventsListener?.handleEvent(e,{handled:!0,metadata:t})}catch(e){h(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)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){if(this.replayDesired=!0,this.isReplayRecording())return void this.logger.log("[instrumentation-manager] replay recording already started");const e=Date.now();(this.configManager.isSessionInactive(e)||this.configManager.isSessionExpired(e))&&this.rotateSession({reason:"replay start into stale session"}),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer()}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] user present and replay desired — starting replay"),this.startReplayListener())}pauseReplayOnIdle(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Ce;e.initialize(),this.sessionReplayListener=e,this.logger.log("[instrumentation-manager] started replay recording")}catch(e){h(e),this.logger.log("[instrumentation-manager] failed to start replay recording:",e)}}reconcileSession(e,t){if(this.isRotating)return;t&&this.configManager.isSessionInactive(e)&&this.rotateSession({reason:"inactivity gap"});const n=this.configManager.getSessionElapsedMs(e),i=this.configManager.getSessionMaxDuration(),r=n>=i;this.logger.log("[instrumentation-manager] session reconcile",{userPresent:t,elapsedMs:n,maxDurationMs:i,expired:r}),r&&this.rotateSession({reason:"max session duration"}),this.syncReplayState(t),t&&(this.configManager.setLastActivityMs(e),this.presenceMonitor?.notePresence(e))}reconcileSessionOnEnqueue(e){this.isRotating||("replay"!==e.type?this.reconcileSession(Date.now(),Pe.has(e.type)):this.logger.log("[instrumentation-manager] enqueue rotation check: ignoring replay event"))}rotateSession(e){if(this.isRotating)return;this.isRotating=!0;const t=this.configManager.getSessionId(),n=this.isReplayRecording();this.logger.log("[instrumentation-manager] session rotation start",{reason:e.reason,previousId:t,wasReplayActive:n});const i=(e,t)=>{try{this.logger.log(`[instrumentation-manager] session rotation: ${e}`),t()}catch(t){h(t),this.logger.log(`[instrumentation-manager] failed to ${e} during session rotation:`,t)}};try{i("stop replay",(()=>this.stopReplayListener())),i("flush events",(()=>this.eventsPool.flush())),i("rotate session ids",(()=>{const e=this.idGenerator.generateId();this.configManager.setSessionId(e),this.configManager.setSessionStartTime(u(Date.now())),this.logger.log("[instrumentation-manager] session id rotated",{from:t,to:e})})),i("sync replay",(()=>this.syncReplayState(n)))}finally{this.isRotating=!1,this.logger.log("[instrumentation-manager] session rotation complete",{reason:e.reason})}}stopReplayListener(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.eventsPool.setBeforeEnqueueHook(null),this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}},Oe="gcSample",Fe=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 De,this.idGenerator=new v;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=P.getInstance();t.initialize(e);ve.getInstance().initialize(),he.getInstance();const n=e.sessionId,i=t.getSessionId();n&&n!==i?(t.setSessionId(n),t.setSessionStartTime(u(Date.now())),this.logger.log("[session-manager] using provided sessionId:",n)):n?(t.setSessionId(n),this.logger.log("[session-manager] continuing provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId());const r=Date.now(),s=f(t.getSessionStartTime());if(s>0&&r-s>=-6e4){if(t.isSessionExpired(r)||t.isSessionInactive(r)){const e=t.isSessionExpired(r)?"persisted session past cap":"inactivity gap across reload",n=t.getSessionId(),i=this.idGenerator.generateId();t.setSessionId(i),t.setSessionStartTime(u(r)),this.logger.log(`[session-manager] init-time rotation: ${e}`,{from:n,to:i})}}else t.setSessionStartTime(u(r));this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=z(Oe);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 C(Oe,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");P.getInstance().updateConfig({user:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");P.getInstance().updateConfig(e);const t=e.options,n=!!t&&"privacy"in t,i=!!t&&"object"==typeof t.replay&&null!==t.replay&&"blockedSelectors"in t.replay;(n||i)&&this.instrumentationManager.restartReplayForConfigChange()}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")}emitLog(e,t,n){this.initialized?this.instrumentationManager.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.initialized?P.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{this.instrumentationManager.flushPendingReplay();const t=ve.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=P.getInstance();i.setSessionId(n),i.setSessionStartTime(u(Date.now())),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(),ve.getInstance().destroy(),he.getInstance().terminate(),P.getInstance().clearSessionState(),this.initialized=!1)}},je=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var Ke={init:function(e){try{Le=new Fe({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",user:e?.user,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId}),je.manager=Le}catch(e){h(e)}},identifyUser:function(e){Le?Le.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){Le&&Le.sendCustomEvent(e)},captureException:function(e,t){Le&&Le.captureException(e,t)},logger:je,updateConfig:function(e){if(Le)try{Le.updateConfig(e)}catch(e){h(e)}},startNavigation:function(e){Le?Le.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){Le?Le.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return Le?Le.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(Le)try{await Le.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(){Le?Le.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){Le?Le.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Ke}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var Ue=Ke;module.exports=Ue;
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 r,onFCP as s,onTTFB as o,onINP as a}from"web-vitals";import{record as l}from"rrweb";import{pack as c}from"@rrweb/packer";var h=console.log.bind(console),d=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&&h(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},g=d.getInstance();function u(e){g.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var f="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},p=1e6;function v(e){return e*p}function m(e){return e/p}function y(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var b=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)w[e]=Math.floor(16*Math.random())+48,w[e]>=58&&(w[e]+=39);return k+String.fromCharCode.apply(null,w.slice(0,16))},this.generateSpanId=E(8),this.generateId=E(16)}},w=Array(32);function E(e){return function(){for(let t=0;t<2*e;t++)w[t]=Math.floor(16*Math.random())+48,w[t]>=58&&(w[t]+=39);return String.fromCharCode.apply(null,w.slice(0,2*e))}}var k="0000000000000000";var S=144e5,I=288e5,T=18e5,R={eventSampleRate:1,sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},replay:{},sessionMaxDuration:S};function M(e){try{console.warn(e)}catch{}}function L(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var N=["privacy","tracing","transport","replay"],A={tracing:"origin",privacy:"replay"};function q(e,t,n){const i={...e,...t};if(n){const r=e?.[n],s=t[n];L(r)&&L(s)?i[n]={...r,...s}:Object.hasOwn(t,n)&&!L(s)&&(i[n]=r)}return i}function x(e,t){const n={...e,...t},i=t,r=e;for(const e of N){if(!Object.hasOwn(i,e))continue;const t=i[e];L(t)?n[e]=q(r[e],t,A[e]):n[e]=r[e]}return n}var z=class e{constructor(t){this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=x(R,t?.options||{}),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),e.warnRemovedOptions(t?.options),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)}static stripRemovedOptions(t){const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&delete n[t]}static warnRemovedOptions(t){if(!t||"object"!=typeof t)return;const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&M(`[groundcover] \`options.${t}\` was removed in 1.0.0 and is ignored. Configure masking via \`options.privacy\` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100`)}static normalizeSessionMaxDuration(e){return void 0===e?S:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>I?(M("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),S):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){t.options&&(e.warnRemovedOptions(t.options),this.providedOptions=x(this.providedOptions||{},t.options),this.options=x(this.options,t.options),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)),void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}};z.REMOVED_OPTION_KEYS=["enableMasking","maskFields"];var C=z;function _(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function H(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return u(e),null}}function P(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){u(e)}}function D(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){u(e)}}function O(e,t=0){const n=H(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}var F=class e{constructor(){this.config=null,this.logger=d.getInstance(),this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.privacyCache=null,this.flushActivityOnHide=()=>{try{if("undefined"!=typeof document&&"hidden"!==document.visibilityState)return;this.persistLastActivity()}catch(e){u(e)}},this.activityPersistHooked=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){if(!this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!0;try{document.addEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){u(e)}}this.config||(this.config=new C(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){return this.privacyCache||(this.privacyCache=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",i="allow"===n,r=_(t?.maskSelectors),s=t?.replay,o="function"==typeof s?.maskTextFn?s.maskTextFn:void 0,a="function"==typeof s?.maskInputFn?s.maskInputFn:void 0;let l;l="mask-all"===n||!i&&void 0!==o?["*",...r].join(", "):"mask-sensitive"===n?["[data-private]",...r].join(", "):void 0;const c=e=>!i&&(e??!0),h=c(t?.maskNetworkBodies),d=c(t?.maskNetworkQueryParams),g=c(t?.maskLogs),u=c(t?.maskErrors);return{level:n,maskTextSelector:l,maskSelectors:r,maskInputs:!i,maskNetworkBodies:h,maskNetworkQueryParams:d,maskLogs:g,maskErrors:u,shouldMaskNetworkBodies:!i&&h,shouldMaskNetworkQueryParams:!i&&d,shouldMaskLogs:!i&&g,shouldMaskErrors:!i&&u,sensitiveKeys:_(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0,maskTextFn:o,maskInputFn:a}}(this.config?.providedOptions)),this.privacyCache}getSessionId(){if(this.sessionId)return this.sessionId;return H("gcId")||""}setSessionId(e){this.sessionId=e,P("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:O("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,P("gcStartTime",String(e)),this.setLastActivityMs(Date.now())}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:O("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,P("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs();return t>0&&e-t>=T}clearSessionState(){if(this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!1;try{document.removeEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){u(e)}}D("gcId"),D("gcStartTime"),D("gcLastActivity")}getSessionMaxDuration(){return this.config?.options?.sessionMaxDuration??S}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-m(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}},j="[REDACTED]",K=["authorization","cookie","set-cookie"],U=/(token|key|secret|passwd|password|auth|bearer|credential)/i,B=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,Y=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),$=1e5;function Q(e,t){if(!e)return!1;if(B.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function X(e,t){return Y.has(e.toLowerCase())||Q(e,t)}function W(e){return e.includes("-")&&U.test(e)}function V(e,t){return Q(e,t)||W(e)}function J(e,t){const n=e.sensitive?j:e.value;if(!t)return n;try{const i=t(e);return void 0===i?n:i}catch(e){return u(e),n}}function G(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const i=e.slice(0,n),r=e.slice(n+1);let s=i;try{s=decodeURIComponent(i)}catch{}let o=r;try{o=decodeURIComponent(r)}catch{}const a=X(s,t.sensitiveKeys),l=J({key:s,value:o,path:[s],kind:t.kind??"query",sensitive:a},t.redact);return l===o?e:`${i}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function Z(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${G(e.slice(n+1),t)}`}function ee(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},i=e.indexOf("#"),r=-1===i?e:e.slice(0,i),s=-1===i?"":e.slice(i+1),o=Z(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${j}@`))}(r),n);return-1===i?o:`${o}#${Z(s,n)}`}function te(e,t,n,i,r,s){const o=!!e&&Q(e,i.sensitiveKeys);if(null!==t&&"object"==typeof t){if(o||r>8)return j;if(y(t))return j;if(s.has(t))return j;s.add(t);try{if(Array.isArray(t))return t.map((t=>te(e,t,n,i,r+1,s)));const o={};for(const[e,a]of Object.entries(t))o[e]=te(e,a,[...n,e],i,r+1,s);return o}catch(e){return u(e),j}finally{s.delete(t)}}return J({key:e,value:t,path:n,kind:i.kind??"log",sensitive:o},i.redact)}function ne(e,t={}){if(!e)return e;if(e.length>$)return`${ne(e.slice(0,$),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>V(n,t.sensitiveKeys)?`"${n}":"${j}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return X(e,t)||W(e)}(n,t.sensitiveKeys)?`${n}=${j}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>V(n,t.sensitiveKeys)?`${n}: ${j}`:e))}catch(t){u(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){u(e)}return n}function ie(e,t={}){try{const n=te("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return u(e),{}}}function re(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const i={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log"};return{message:ne(t,i),attributes:n?ie(n,i):n}}var se=F.getInstance(),oe=new b,ae=d.getInstance();function le(){const e=se?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function ce(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:y(e)?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[r,s])=>{const o=t?`${t}.${r}`:r;return"object"==typeof s&&null!==s?Array.isArray(s)?e[o]=s.map(((e,t)=>"object"==typeof e&&null!==e?ce(e,`${o}[${t}]`,n,i+1):e)):Object.assign(e,ce(s,o,n,i+1)):e[o]=s,e}),{}))}catch(e){return ae.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}function he(e){const t=v(Date.now()),n=oe.generateId(),i=e.spanId||oe.generateSpanId(),r=e.traceId||oe.generateTraceId(),s=e.parentSpanId||"",o=ce(e.attributes||{}),a=function(){const e=f?.location;if(!e)return{path:"",url:"",title:f?.document?.title||""};const t=e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/"),n=t?e.hash:e.pathname,i=se.getPrivacy(),r=i.shouldMaskNetworkQueryParams,s={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:r&&t?ee(n,s):n,url:r?ee(e.href,s):e.href,title:f?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:s,traceId:r,attributes:{...o,location:a}};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}function de({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var ge=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=d.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,i){const r=e.getInstance();if(!r.isAvailable)return n();try{return await t(r)}catch(e){return d.getInstance().log(`[${i}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,i=this.worker;return new Promise(((r,s)=>{const o=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),s(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:r,reject:s,timeoutId:o});try{i.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(o),this.pending.delete(n),s(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};ge.instance=null;var ue=ge,fe=class{constructor(){this.logger=d.getInstance(),this.config=F.getInstance()}compressInline(n,i){if(!i)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}}}compressAsync(e,t){return ue.withFallback((n=>n.encodeBatch(e,t)),(()=>this.compressInline(e,t)),"transporter")}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const i=n.apiKey,r=this.buildEndpoint();if(!i)return void this.logger.log("No API key found");const s=JSON.stringify(e),o=!!n?.options?.transport?.compression,{data:a,isCompressed:l}=t?this.compressInline(s,o):await this.compressAsync(s,o);fetch(r,{method:"POST",headers:{"Content-Type":"application/json",apikey:i,"Content-Encoding":l?"gzip":""},body:a}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},pe=["navigation","dom.event"],ve=R.transport?.batchSize??10,me=R.transport?.batchTimeout??1e4;var ye=class e{constructor(){this.events=[],this.timeoutId=null,this.config=F.getInstance(),this.logger=d.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.onBeforeEnqueue=null,this.visibilityHandler=()=>{"hidden"===document.visibilityState&&this.flush({lifecycle:!0})},this.transporter=new fe}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",this.visibilityHandler),this.initialized=!0}catch(e){u(e)}}destroy(){try{null!==this.timeoutId&&(f.clearTimeout(this.timeoutId),this.timeoutId=null),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.events=[],this.initialized=!1}catch(e){u(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,i=this.config.getConfig()?.options?.enrichEvent;if(n&&!n(e))return;if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(e)}catch(e){u(e)}i&&(e=i(e)),this.events.push(e);const r=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:ve);this.events.length>=r&&!pe.includes(e.type)&&this.flush()}catch(e){u(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),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&&(f.clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:me);this.timeoutId=f.setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){u(e)}var e}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",r=/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:r}}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?.user||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};ye.instance=null;var be=ye,we=class{constructor(){this.logger=d.getInstance(),this.eventsPool=be.getInstance()}},Ee="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function ke(e,t){try{return e.getAttribute(t)||""}catch{return""}}function Se(e){try{const t=Ee?.call(e);return"string"==typeof t?t:""}catch{return""}}function Ie(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function Te(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>ke(e,t))).filter(Boolean)}(e).some((e=>Q(e,t))))}function Re(e,t){return"allow"!==t.level&&(!!e&&(!!Ie(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>Ie(e,t))))||("mask-all"===t.level||function(e){const t=Se(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&Te(e,t.sensitiveKeys)))))}var Me=class extends we{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=F.getInstance(),this.getShouldMaskText=e=>Re(e.target,this.config.getPrivacy()),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getText=(e,t)=>{const n=e.target;return t?"*":de({text:n?.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}),f?.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(!le())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,r=this.getShouldMaskText({target:i||null}),s=this.getKeyCode(e,r),o=this.getText(e,r);this.logger.log("[dom-events-listener.buildEvent] called");return he({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:ke(i,"id"),tagName:Se(i),className:ke(i,"class"),text:o}}})}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,r=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===Se(e).toLowerCase())return"html";let s="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<i;){let e=Se(a).toLowerCase();try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of r)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=Se(a).toLowerCase()||"*"}l.unshift(e||"*"),s=l.join(" > ");try{if(1===n.querySelectorAll(s).length)return s}catch(e){l.shift(),s=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return s||"*"}},Le=["log","info","warn","error","debug","assert","trace"],Ne=class extends we{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1,this.config=F.getInstance()}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),Le.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;Le.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){u(e)}}handleEvent(e,t){try{if(!le())return;const n=Array.isArray(e)?e:[e],i=this.formatMessage(n,t);if(!i||i?.includes("groundcoverIgnore"))return;const r=this.extractAttributes(n),s=this.buildEvent({message:i,level:t,attributes:r});this.queueEvent(s)}catch(e){u(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:i,attributes:r}=re(this.config.getPrivacy(),e,n);return he({type:"log",attributes:{...r,message:de({text:i}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);return delete t.message,delete t.level,delete t.location,t}catch(e){return void 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{Le.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){u(e)}return e}};function Ae(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 qe,xe=class extends we{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=F.getInstance(),this.idGenerator=new b,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!le())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});const i=this.config.getPrivacy(),r={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};try{t=new URL(e.url).pathname}catch(s){n=new URL(e.url,globalThis.location.href).href,i.shouldMaskNetworkQueryParams&&(t=ee(t,r))}i.shouldMaskNetworkQueryParams&&(n=ee(n,r)),this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),o=this.formatHeaders(e.response.headers),a=e.method?.toUpperCase()||"UNKNOWN",{traceId:l,spanId:c}=this.extractTraceIds(e.request.headers),h=(e,t)=>i.shouldMaskNetworkBodies?function(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=$&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(te("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?G(e,t):ne(e,t)}(e,{sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:t}):e,d=de({text:h(e.request.body,"request-body"),maxLength:this.maxBodyLength}),g=de({text:h(e.response.body,"response-body"),maxLength:this.maxBodyLength}),u={type:"HTTP",operation:{name:a},resource_name:t,status:e.status?.toString(),subType:a,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:o,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:d},response:{body:g}}},f={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?v(e.timestamp):void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?v(e.end_time):void 0,span_name:`${e.method} ${t}`,attributes:u};return l&&(f.traceId=l),c&&(f.spanId=c),he(f)}}async getResponseBody(e){const t=e.body;if(!t)return"";const n=t.getReader(),i=new TextDecoder;let r="",s=0;for(;;){const{done:e,value:t}=await n.read();if(e)break;if(s+t.byteLength>=this.maxBodyLength){const e=t.subarray(0,this.maxBodyLength-s);r+=i.decode(e,{stream:!0}),n.cancel().catch((()=>{}));break}s+=t.byteLength,r+=i.decode(t,{stream:!0})}return r+=i.decode(),r}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 r;globalThis.XMLHttpRequest.prototype.open=function(n,i,s=!0,o,a){if(r=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,s,o,a]);const l=new URL(i.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,i,s,o,a])},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?.tracing?.origin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),n&&(t?.options?.tracing?.traceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracing?.propagationHeaders)&&t?.options?.tracing?.propagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracing?.propagationHeaders?.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=Ae(this._requestBody),s=Ae(""===this.responseType||"text"===this.responseType?this.responseText:this.response),o={timestamp:r,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:s}};e.handleEvent(o)})),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?.tracing?.origin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),!n)return;t?.options?.tracing?.traceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracing?.propagationHeaders;(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,r]=t;r={...r||{}},t[1]=r;const s=i instanceof Request,o=r?.method||"GET",a=r?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);r||(t[1]={},r=t[1]),r.headers=this.normalizeHeaders(s?i.headers:void 0,r.headers),c&&this.addTraceHeaders(r);const h=this.extractHeadersRecord(r.headers),d=Ae(a);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i={};e.headers.forEach(((e,t)=>{i[t]=e}));const r={method:o,url:l,timestamp:n,body:d,status:e.status,end_time:t,request:{headers:h,body:d},response:{headers:i,body:""}};try{i["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(e.clone()).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 r={method:o,url:l,body:d,status:0,end_time:t,request:{headers:h,body:d},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(r),e}))}}formatHeaders(e){const t=this.config.getPrivacy(),n="allow"===t.level,i=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,i])=>{const r=n.toLowerCase(),s=J({key:n,value:i,path:[n],kind:"header",sensitive:K.includes(r)||U.test(r)||Q(n,t.sensitiveKeys)},t.redact);return e[n]=null===s?"":String(s),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact});return Object.entries(i)?.reduce(((e,[t,n])=>(e[t]=de({text:n}),e)),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracing?.traceIdHeaderName){const i=e[t.options.tracing.traceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracing?.spanIdHeaderName){const n=e[t.options.tracing.spanIdHeaderName];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?.tracing?.propagationHeaders?.length)for(const n of t.options.tracing.propagationHeaders){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(r){this.logger.log("[network-events-listener.getTraceIds] error",{error:r}),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?.tracing?.propagationUrls?.length)return!1;const n=t.options.tracing.propagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),r=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(r)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},ze=class extends we{constructor(){super(...arguments),this.config=F.getInstance(),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(){f?.addEventListener("error",this.handleEvent),f?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){f?.removeEventListener("error",this.handleEvent),f?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){const n=this.config.getPrivacy(),i=n.shouldMaskErrors,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error"},s=e.message||"Unknown error",o=i?ne(s,r):s,a=i&&t?.metadata?ie(t.metadata,r):t?.metadata;return he({type:"exception",attributes:{error_type:e.name||"Error",error_message:o,error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${de({text:o,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:a}})}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:r}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),r&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:r})}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[]}}},Ce=class extends we{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=f.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){u(e)}}isInBrowserEnvironment(){try{return void 0!==f&&void 0!==f.location&&void 0!==f.history&&"function"==typeof f.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},f&&"function"==typeof f.addEventListener&&(f.addEventListener("popstate",this.popStateHandler),f.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),f&&"function"==typeof f.removeEventListener&&(f.removeEventListener("popstate",this.popStateHandler),f.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",f.location.href);const e=F.getInstance().getPrivacy(),t="allow"===e.level,n=f.location.href,i=this.activeNavigation?.metadata;return he({type:"navigation",attributes:{page_url:e.shouldMaskNetworkQueryParams?ee(n,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):n,metadata:!t&&i?ie(i,{sensitiveKeys:e.sensitiveKeys,redact:e.redact}):i,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:f.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===f.location.href)return;let e,t;try{e=new URL(f.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=f.location.href,this.handleEvent())}catch(e){u(e)}}},_e=class extends we{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",f),"complete"===f?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):f?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),u(e)}}destroy(){f?.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,r=t.duration,s=t.initiatorType;i.totalSize+=n,i.totalDuration+=r,i.byType[s]||(i.byType[s]={count:0,size:0,duration:0}),i.byType[s].count++,i.byType[s].size+=n,i.byType[s].duration+=r}));const r=F.getInstance().getPrivacy(),s=r.shouldMaskNetworkQueryParams,o={sensitiveKeys:r.sensitiveKeys,redact:r.redact,kind:"query"},a=f?.location?.href||"",l=f?.document?.referrer||"";return he({type:"pageload",attributes:{page_url:s?ee(a,o):a,page_load_time:t,page_referrer:s?ee(l,o):l,page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}},He=class extends we{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!le())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}}}initialize(){i(this.handleEvent),r(this.handleEvent),s(this.handleEvent),o(this.handleEvent),a(this.handleEvent)}destroy(){}buildEvent(e){return he({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)}}},Pe=class{constructor(){this.logger=d.getInstance(),this.eventsPool=be.getInstance(),this.configManager=F.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=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?.replay?.blockedSelectors?.filter(Boolean),t=e?.length?e.join(", "):void 0,n=this.configManager.getPrivacy(),i=n.maskInputFn??("allow"===n.level?void 0:(e,t)=>Re(t,n)?"*".repeat(e.length):e);this.stopFn=l({...t?{blockSelector:t}:{},...n.maskTextSelector?{maskTextSelector:n.maskTextSelector}:{},maskAllInputs:n.maskInputs,...n.maskTextFn?{maskTextFn:n.maskTextFn}:{},...i?{maskInputFn:i}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{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.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=f.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{u(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(f.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.configManager.getSessionId(),n=ue.getInstance();let i;if(n.isAvailable)try{i=await n.packReplay(e.events)}catch(t){u(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),i=e.events.map((e=>c(e)))}else i=e.events.map((e=>c(e)));this.configManager.getSessionId()===t?this.enqueueReplayEvent(i,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:i.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>c(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const r=he({type:"replay",attributes:i});this.eventsPool.addEvent(r),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.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),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()}},De=["pointerdown","keydown","scroll","touchstart","mousemove"],Oe=class{constructor(e){this.logger=d.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){u(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,De.forEach((e=>{try{f.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){u(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",T,"ms");try{this.callbacks.onIdle()}catch(e){u(e)}}),T)}catch(e){u(e)}}destroy(){if(this.installed){this.installed=!1,De.forEach((e=>{try{f.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){u(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){u(e)}finally{this.idleTimer=null}}}},Fe=new Set(["dom.event","navigation","pageload"]),je=class{constructor(){this.logger=d.getInstance(),this.eventsPool=be.getInstance(),this.configManager=F.getInstance(),this.idGenerator=new b,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.isRotating=!1,this.replayDesired=!1,this.presenceMonitor=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.eventsPool.setBeforeEnqueueHook((e=>this.reconcileSessionOnEnqueue(e))),this.presenceMonitor?.destroy(),this.presenceMonitor=new Oe({onPresence:e=>this.reconcileSession(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new _e,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new Me,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new Ne,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new ze,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new xe,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new He,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new Ce({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=he({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){u(e)}}emitLog(e,t,n){if(this.logEventsListener){this.logger.log("[instrumentation-manager.emitLog] called",{message:e,level:t,attributes:n});try{const i={...n||{}};delete i.message,delete i.level,delete i.location;const{message:r,attributes:s}=re(F.getInstance().getPrivacy(),e,i),o=he({type:"log",attributes:{...s,message:de({text:r}),level:t}});this.eventsPool.addEvent(o)}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)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){if(this.replayDesired=!0,this.isReplayRecording())return void this.logger.log("[instrumentation-manager] replay recording already started");const e=Date.now();(this.configManager.isSessionInactive(e)||this.configManager.isSessionExpired(e))&&this.rotateSession({reason:"replay start into stale session"}),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer()}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] user present and replay desired — starting replay"),this.startReplayListener())}pauseReplayOnIdle(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Pe;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)}}reconcileSession(e,t){if(this.isRotating)return;t&&this.configManager.isSessionInactive(e)&&this.rotateSession({reason:"inactivity gap"});const n=this.configManager.getSessionElapsedMs(e),i=this.configManager.getSessionMaxDuration(),r=n>=i;this.logger.log("[instrumentation-manager] session reconcile",{userPresent:t,elapsedMs:n,maxDurationMs:i,expired:r}),r&&this.rotateSession({reason:"max session duration"}),this.syncReplayState(t),t&&(this.configManager.setLastActivityMs(e),this.presenceMonitor?.notePresence(e))}reconcileSessionOnEnqueue(e){this.isRotating||("replay"!==e.type?this.reconcileSession(Date.now(),Fe.has(e.type)):this.logger.log("[instrumentation-manager] enqueue rotation check: ignoring replay event"))}rotateSession(e){if(this.isRotating)return;this.isRotating=!0;const t=this.configManager.getSessionId(),n=this.isReplayRecording();this.logger.log("[instrumentation-manager] session rotation start",{reason:e.reason,previousId:t,wasReplayActive:n});const i=(e,t)=>{try{this.logger.log(`[instrumentation-manager] session rotation: ${e}`),t()}catch(t){u(t),this.logger.log(`[instrumentation-manager] failed to ${e} during session rotation:`,t)}};try{i("stop replay",(()=>this.stopReplayListener())),i("flush events",(()=>this.eventsPool.flush())),i("rotate session ids",(()=>{const e=this.idGenerator.generateId();this.configManager.setSessionId(e),this.configManager.setSessionStartTime(v(Date.now())),this.logger.log("[instrumentation-manager] session id rotated",{from:t,to:e})})),i("sync replay",(()=>this.syncReplayState(n)))}finally{this.isRotating=!1,this.logger.log("[instrumentation-manager] session rotation complete",{reason:e.reason})}}stopReplayListener(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.eventsPool.setBeforeEnqueueHook(null),this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}},Ke="gcSample",Ue=class{constructor(e){this.initialized=!1,this.logger=d.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new je,this.idGenerator=new b;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=F.getInstance();t.initialize(e);be.getInstance().initialize(),ue.getInstance();const n=e.sessionId,i=t.getSessionId();n&&n!==i?(t.setSessionId(n),t.setSessionStartTime(v(Date.now())),this.logger.log("[session-manager] using provided sessionId:",n)):n?(t.setSessionId(n),this.logger.log("[session-manager] continuing provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId());const r=Date.now(),s=m(t.getSessionStartTime());if(s>0&&r-s>=-6e4){if(t.isSessionExpired(r)||t.isSessionInactive(r)){const e=t.isSessionExpired(r)?"persisted session past cap":"inactivity gap across reload",n=t.getSessionId(),i=this.idGenerator.generateId();t.setSessionId(i),t.setSessionStartTime(v(r)),this.logger.log(`[session-manager] init-time rotation: ${e}`,{from:n,to:i})}}else t.setSessionStartTime(v(r));this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=H(Ke);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 P(Ke,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");F.getInstance().updateConfig({user:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");F.getInstance().updateConfig(e);const t=e.options,n=!!t&&"privacy"in t,i=!!t&&"object"==typeof t.replay&&null!==t.replay&&"blockedSelectors"in t.replay;(n||i)&&this.instrumentationManager.restartReplayForConfigChange()}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")}emitLog(e,t,n){this.initialized?this.instrumentationManager.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.initialized?F.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{this.instrumentationManager.flushPendingReplay();const t=be.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=F.getInstance();i.setSessionId(n),i.setSessionStartTime(v(Date.now())),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(),be.getInstance().destroy(),ue.getInstance().terminate(),F.getInstance().clearSessionState(),this.initialized=!1)}},Be=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var Ye={init:function(e){try{qe=new Ue({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",user:e?.user,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId}),Be.manager=qe}catch(e){u(e)}},identifyUser:function(e){qe?qe.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){qe&&qe.sendCustomEvent(e)},captureException:function(e,t){qe&&qe.captureException(e,t)},logger:Be,updateConfig:function(e){if(qe)try{qe.updateConfig(e)}catch(e){u(e)}},startNavigation:function(e){qe?qe.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){qe?qe.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return qe?qe.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(qe)try{await qe.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(){qe?qe.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){qe?qe.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Ye}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var $e=Ye;export{$e as default};
1
+ import{strToU8 as e,gzipSync as t}from"fflate";import n from"error-stack-parser";import{onCLS as i,onLCP as r,onFCP as s,onTTFB as o,onINP as a}from"web-vitals";import{record as l}from"rrweb";import{pack as c}from"@rrweb/packer";var h=console.log.bind(console),d=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&&h(this.formatMessage(e),...t)}updateConfig(e){this.isDebugEnabled=e.debug??this.isDebugEnabled,this.prefix=e.prefix??this.prefix}},g=d.getInstance();function u(e){g.log("[error-handler.handleError] called",e,{groundcoverIgnore:!0})}var f="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},p=1e6;function v(e){return e*p}function m(e){return e/p}function y(e){if(null==e||"object"!=typeof e)return!1;try{return"number"==typeof e.nodeType&&"string"==typeof e.nodeName&&"ownerDocument"in e}catch{return!1}}var b=class{constructor(){this.generateTraceId=function(){for(let e=0;e<16;e++)w[e]=Math.floor(16*Math.random())+48,w[e]>=58&&(w[e]+=39);return k+String.fromCharCode.apply(null,w.slice(0,16))},this.generateSpanId=E(8),this.generateId=E(16)}},w=Array(32);function E(e){return function(){for(let t=0;t<2*e;t++)w[t]=Math.floor(16*Math.random())+48,w[t]>=58&&(w[t]+=39);return String.fromCharCode.apply(null,w.slice(0,2*e))}}var k="0000000000000000";var S=144e5,I=288e5,T=18e5,R={eventSampleRate:1,sessionSampleRate:1,debug:!1,privacy:{level:"mask-sensitive"},enabledEvents:[],tracing:{propagationUrls:[],propagationHeaders:[],traceIdHeaderName:"",spanIdHeaderName:"",origin:{name:"",value:""}},transport:{batchSize:10,batchTimeout:1e4,compression:!0},replay:{},sessionMaxDuration:S};function M(e){try{console.warn(e)}catch{}}function L(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var N=["privacy","tracing","transport","replay"],A={tracing:"origin",privacy:"replay"};function q(e,t,n){const i={...e,...t};if(n){const r=e?.[n],s=t[n];L(r)&&L(s)?i[n]={...r,...s}:Object.hasOwn(t,n)&&!L(s)&&(i[n]=r)}return i}function x(e,t){const n={...e,...t},i=t,r=e;for(const e of N){if(!Object.hasOwn(i,e))continue;const t=i[e];L(t)?n[e]=q(r[e],t,A[e]):n[e]=r[e]}return n}var z=class e{constructor(t){this.dsn=t?.dsn||"",this.appId=t?.appId||"",this.cluster=t?.cluster||"",this.apiKey=t?.apiKey||"",this.environment=t?.environment||"",this.namespace=t?.namespace||"",this.releaseId=t?.releaseId,this.user=t?.user||null,this.providedOptions={...t?.options||{}},this.options=x(R,t?.options||{}),this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t?.options?.sessionMaxDuration),e.warnRemovedOptions(t?.options),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)}static stripRemovedOptions(t){const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&delete n[t]}static warnRemovedOptions(t){if(!t||"object"!=typeof t)return;const n=t;for(const t of e.REMOVED_OPTION_KEYS)Object.hasOwn(n,t)&&M(`[groundcover] \`options.${t}\` was removed in 1.0.0 and is ignored. Configure masking via \`options.privacy\` instead — see the migration guide: https://github.com/groundcover-com/rum/tree/main/packages/browser#migrating-to-100`)}static normalizeSessionMaxDuration(e){return void 0===e?S:"number"!=typeof e||!Number.isFinite(e)||e<6e4||e>I?(M("[groundcover] sessionMaxDuration must be a finite number between 60000 ms (1 minute) and 28800000 ms (8 hours); falling back to the 4-hour default"),S):e}getEndpoint(){return this.dsn?.startsWith("http")?this.dsn:`https://${this.dsn}`}updateConfig(t){t.options&&(e.warnRemovedOptions(t.options),this.providedOptions=x(this.providedOptions||{},t.options),this.options=x(this.options,t.options),void 0!==t.options.sessionMaxDuration&&(this.options.sessionMaxDuration=e.normalizeSessionMaxDuration(t.options.sessionMaxDuration)),e.stripRemovedOptions(this.providedOptions),e.stripRemovedOptions(this.options)),void 0!==t.user&&(this.user=null===t.user?null:{...this.user,...t.user}),t.appId&&(this.appId=t.appId),t.dsn&&(this.dsn=t.dsn),t.apiKey&&(this.apiKey=t.apiKey),t.cluster&&(this.cluster=t.cluster),t.environment&&(this.environment=t.environment),t.namespace&&(this.namespace=t.namespace),t.releaseId&&(this.releaseId=t.releaseId)}};z.REMOVED_OPTION_KEYS=["enableMasking","maskFields"];var C=z;function _(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter((e=>e.length>0)):[]}function H(e){try{return globalThis?.sessionStorage?.getItem(e)??null}catch(e){return u(e),null}}function P(e,t){try{globalThis?.sessionStorage?.setItem(e,t)}catch(e){u(e)}}function D(e){try{globalThis?.sessionStorage?.removeItem(e)}catch(e){u(e)}}function O(e,t=0){const n=H(e);if(null===n)return t;const i=Number(n);return Number.isFinite(i)?i:t}var F=class e{constructor(){this.config=null,this.logger=d.getInstance(),this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.privacyCache=null,this.flushActivityOnHide=()=>{try{if("undefined"!=typeof document&&"hidden"!==document.visibilityState)return;this.persistLastActivity()}catch(e){u(e)}},this.activityPersistHooked=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){if(!this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!0;try{document.addEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){u(e)}}this.config||(this.config=new C(e))}getConfig(){return this.config?this.config:(this.logger.log("[config-manager] configuration not initialized"),null)}getPrivacy(){return this.privacyCache||(this.privacyCache=function(e){const t=e?.privacy,n=function(e){return"mask-sensitive"===e||"mask-all"===e||"allow"===e?e:void 0}(t?.level)??"mask-sensitive",i="allow"===n,r=_(t?.maskSelectors),s=t?.replay,o="function"==typeof s?.maskTextFn?s.maskTextFn:void 0,a="function"==typeof s?.maskInputFn?s.maskInputFn:void 0;let l;l="mask-all"===n||!i&&void 0!==o?["*",...r].join(", "):"mask-sensitive"===n?["[data-private]",...r].join(", "):void 0;const c=e=>!i&&(e??!0),h=c(t?.maskNetworkBodies),d=c(t?.maskNetworkQueryParams),g=c(t?.maskLogs),u=c(t?.maskErrors);return{level:n,maskTextSelector:l,maskSelectors:r,maskInputs:!i,maskNetworkBodies:h,maskNetworkQueryParams:d,maskLogs:g,maskErrors:u,shouldMaskNetworkBodies:!i&&h,shouldMaskNetworkQueryParams:!i&&d,shouldMaskLogs:!i&&g,shouldMaskErrors:!i&&u,sensitiveKeys:_(t?.sensitiveKeys),redact:"function"==typeof t?.redact?t.redact:void 0,maskTextFn:o,maskInputFn:a}}(this.config?.providedOptions)),this.privacyCache}getSessionId(){if(this.sessionId)return this.sessionId;return H("gcId")||""}setSessionId(e){this.sessionId=e,P("gcId",e)}getSessionStartTime(){return this.sessionStartTime?this.sessionStartTime:O("gcStartTime",0)}setSessionStartTime(e){this.sessionStartTime=e,P("gcStartTime",String(e)),this.setLastActivityMs(Date.now())}getLastActivityMs(){return null!==this.lastActivityMs?this.lastActivityMs:O("gcLastActivity",0)}setLastActivityMs(e){this.lastActivityMs=e,e-this.lastPersistedActivityMs>=6e4&&this.persistLastActivity()}persistLastActivity(){null!==this.lastActivityMs&&(this.lastPersistedActivityMs=this.lastActivityMs,P("gcLastActivity",String(this.lastActivityMs)))}isSessionInactive(e=Date.now()){const t=this.getLastActivityMs();return t>0&&e-t>=T}clearSessionState(){if(this.sessionId=null,this.sessionStartTime=null,this.lastActivityMs=null,this.lastPersistedActivityMs=0,this.activityPersistHooked&&"undefined"!=typeof document){this.activityPersistHooked=!1;try{document.removeEventListener("visibilitychange",this.flushActivityOnHide)}catch(e){u(e)}}D("gcId"),D("gcStartTime"),D("gcLastActivity")}getSessionMaxDuration(){return this.config?.options?.sessionMaxDuration??S}getSessionElapsedMs(e=Date.now()){const t=this.getSessionStartTime();return t?e-m(t):0}isSessionExpired(e=Date.now()){return this.getSessionElapsedMs(e)>=this.getSessionMaxDuration()}updateConfig(e){this.logger.log("[config-manager] updateConfig called"),this.config?e&&(this.logger.log("[config-manager] updating options"),this.config.updateConfig(e),this.privacyCache=null):this.logger.log("[config-manager] configuration not initialized")}},j="[REDACTED]",K=["authorization","cookie","set-cookie"],U=/(token|key|secret|passwd|password|auth|bearer|credential)/i,B=/(token|secret|passwd|password|api[_-]?key|access[_-]?key|write[_-]?key|auth|bearer|credential|cvv|ssn|credit[_-]?card|card[_-]?number)/i,Y=new Set(["code","state","session_state","id_token","access_token","refresh_token","token"]),$=1e5;function Q(e,t){if(!e)return!1;if(B.test(e))return!0;if(t?.length){const n=e.toLowerCase();return t.some((e=>e&&n.includes(e.toLowerCase())))}return!1}function X(e,t){return Y.has(e.toLowerCase())||Q(e,t)}function W(e){return e.includes("-")&&U.test(e)}function V(e,t){return Q(e,t)||W(e)}function J(e,t){const n=e.sensitive?j:e.value;if(!t)return n;try{const i=t(e);return void 0===i?n:i}catch(e){return u(e),n}}function G(e,t={}){if(!e)return e;try{return e.split("&").map((e=>{const n=e.indexOf("=");if(-1===n)return e;const i=e.slice(0,n),r=e.slice(n+1);let s=i;try{s=decodeURIComponent(i)}catch{}let o=r;try{o=decodeURIComponent(r)}catch{}const a=X(s,t.sensitiveKeys),l=J({key:s,value:o,path:[s],kind:t.kind??"query",sensitive:a},t.redact);return l===o?e:`${i}=${encodeURIComponent(null===l?"":String(l))}`})).join("&")}catch{return e}}function Z(e,t){const n=e.indexOf("?");return-1===n?e:`${e.slice(0,n)}?${G(e.slice(n+1),t)}`}function ee(e,t={}){if(!e)return e;const n={...t,kind:t.kind??"query"},i=e.indexOf("#"),r=-1===i?e:e.slice(0,i),s=-1===i?"":e.slice(i+1),o=Z(function(e){return e.replace(/^([a-zA-Z][\w+.-]*:\/\/)[^/?#@]*@/,((e,t)=>`${t}${j}@`))}(r),n);return-1===i?o:`${o}#${Z(s,n)}`}function te(e,t,n,i,r,s){const o=!!e&&Q(e,i.sensitiveKeys);if(null!==t&&"object"==typeof t){if(o||r>8)return j;if(y(t))return j;if(s.has(t))return j;s.add(t);try{if(Array.isArray(t))return t.map((t=>te(e,t,n,i,r+1,s)));const o={};for(const[e,a]of Object.entries(t))o[e]=te(e,a,[...n,e],i,r+1,s);return o}catch(e){return u(e),j}finally{s.delete(t)}}return J({key:e,value:t,path:n,kind:i.kind??"log",sensitive:o},i.redact)}function ne(e,t={}){if(!e)return e;if(e.length>$)return`${ne(e.slice(0,$),t)}…`;let n=e;try{n=n.replace(/"([\w.-]{1,64})"\s*:\s*("(?:[^"\\]|\\.)*"|[^\s,}\]]+)/g,((e,n)=>V(n,t.sensitiveKeys)?`"${n}":"${j}"`:e)),n=n.replace(/([\w.-]{1,64})=([^\s&,;?]+)/g,((e,n)=>function(e,t){return X(e,t)||W(e)}(n,t.sensitiveKeys)?`${n}=${j}`:e)),n=n.replace(/([\w.-]{1,64}):[ \t]*([^\n,;&]{1,4096})/g,((e,n)=>V(n,t.sensitiveKeys)?`${n}: ${j}`:e))}catch(t){u(t),n=e}if(t.redact)try{const n=t.redact({key:"",value:e,path:[],kind:t.kind??"log",sensitive:!1});if(void 0!==n)return null===n?"":String(n)}catch(e){u(e)}return n}function ie(e,t={}){try{const n=te("",e,[],t,0,new WeakSet);return null!==n&&"object"==typeof n?n:{}}catch(e){return u(e),{}}}function re(e,t,n){if(!e.shouldMaskLogs)return{message:t,attributes:n};const i={sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"log"};return{message:ne(t,i),attributes:n?ie(n,i):n}}var se=F.getInstance(),oe=new b,ae=d.getInstance();function le(){const e=se?.getConfig()?.options?.eventSampleRate;return!(void 0!==e&&!Number.isNaN(e))||Math.random()<=e}function ce(e,t="",n=new WeakSet,i=0){try{return i>=10?{[t||"depth_limit"]:"[Depth Limit]"}:y(e)?{[t||"dom_node"]:`[${e?.constructor?.name||"DomNode"}]`}:n.has(e)?{[t||"circular_reference"]:"[Circular]"}:(n.add(e),Object.entries(e).reduce(((e,[r,s])=>{const o=t?`${t}.${r}`:r;return"object"==typeof s&&null!==s?Array.isArray(s)?e[o]=s.map(((e,t)=>"object"==typeof e&&null!==e?ce(e,`${o}[${t}]`,n,i+1):e)):Object.assign(e,ce(s,o,n,i+1)):e[o]=s,e}),{}))}catch(e){return ae.log("[events-processors.formatEventObject] Error formatting event object",e),{[t||"format_error"]:"[Error formatting object]"}}finally{n.delete(e)}}function he(e){const t=v(Date.now()),n=oe.generateId(),i=e.spanId||oe.generateSpanId(),r=e.traceId||oe.generateTraceId(),s=e.parentSpanId||"",o=ce(e.attributes||{}),a=function(){const e=f?.location;if(!e)return{path:"",url:"",title:f?.document?.title||""};const t=e.hash&&!e.hash.match(/^#[a-z0-9-]+$/i)&&e.hash.startsWith("#/"),n=t?e.hash:e.pathname,i=se.getPrivacy(),r=i.shouldMaskNetworkQueryParams,s={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};return{path:r&&t?ee(n,s):n,url:r?ee(e.href,s):e.href,title:f?.document?.title||""}}(),l={type:e.type,id:n,spanId:i,parentSpanId:s,traceId:r,attributes:{...o,location:a}};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}function de({text:e,maxLength:t=1e4}){return e?e.length<=t||"string"!=typeof e?e:e.substring(0,t):""}var ge=class e{constructor(){if(this.worker=null,this.pending=new Map,this.nextId=0,this.consecutiveTimeouts=0,this.isAvailable=!1,this.logger=d.getInstance(),"undefined"==typeof Worker||"undefined"==typeof URL||"undefined"==typeof Blob)return;const e=new Blob(['!function(){"use strict";var r=Uint8Array,n=Uint16Array,e=Int32Array,t=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(r,t){for(var f=new n(31),o=0;o<31;++o)f[o]=t+=1<<r[o-1];var a=new e(f[30]);for(o=1;o<30;++o)for(var i=f[o];i<f[o+1];++i)a[i]=i-f[o]<<5|o;return{b:f,r:a}},i=a(t,2),u=i.b,v=i.r;u[28]=258,v[258]=28;var s=a(f,0).r,l=new n(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>1|(21845&Y)<<1))>>2|(13107&Q)<<2))>>4|(3855&Q)<<4,l[Y]=((65280&Q)>>8|(255&Q)<<8)>>1;var c=function(r,e,t){for(var f=r.length,o=0,a=new n(e);o<f;++o)r[o]&&++a[r[o]-1];var i,u=new n(e);for(o=1;o<e;++o)u[o]=u[o-1]+a[o-1]<<1;for(i=new n(f),o=0;o<f;++o)r[o]&&(i[o]=l[u[r[o]-1]++]>>15-r[o]);return i},h=new r(288);for(Y=0;Y<144;++Y)h[Y]=8;for(Y=144;Y<256;++Y)h[Y]=9;for(Y=256;Y<280;++Y)h[Y]=7;for(Y=280;Y<288;++Y)h[Y]=8;var w=new r(32);for(Y=0;Y<32;++Y)w[Y]=5;var g=c(h,9),d=c(w,5),m=function(r){return(r+7)/8|0},p=function(n,e,t){return(null==t||t>n.length)&&(t=n.length),new r(n.subarray(e,t))},y=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8},M=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>8,r[t+2]|=e>>16},b=function(e,t){for(var f=[],o=0;o<e.length;++o)e[o]&&f.push({s:o,f:e[o]});var a=f.length,i=f.slice();if(!a)return{t:U,l:0};if(1==a){var u=new r(f[0].s+1);return u[f[0].s]=1,{t:u,l:1}}f.sort((function(r,n){return r.f-n.f})),f.push({s:-1,f:25001});var v=f[0],s=f[1],l=0,c=1,h=2;for(f[0]={s:-1,f:v.f+s.f,l:v,r:s};c!=a-1;)v=f[f[l].f<f[h].f?l++:h++],s=f[l!=c&&f[l].f<f[h].f?l++:h++],f[c++]={s:-1,f:v.f+s.f,l:v,r:s};var w=i[0].s;for(o=1;o<a;++o)i[o].s>w&&(w=i[o].s);var g=new n(w+1),d=k(f[c-1],g,0);if(d>t){o=0;var m=0,p=d-t,y=1<<p;for(i.sort((function(r,n){return g[n.s]-g[r.s]||r.f-n.f}));o<a;++o){var M=i[o].s;if(!(g[M]>t))break;m+=y-(1<<d-g[M]),g[M]=t}for(m>>=p;m>0;){var b=i[o].s;g[b]<t?m-=1<<t-g[b]++-1:++o}for(;o>=0&&m;--o){var x=i[o].s;g[x]==t&&(--g[x],++m)}d=t}return{t:new r(g),l:d}},k=function(r,n,e){return-1==r.s?Math.max(k(r.l,n,e+1),k(r.r,n,e+1)):n[r.s]=e},x=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new n(++e),f=0,o=r[0],a=1,i=function(r){t[f++]=r},u=1;u<=e;++u)if(r[u]==o&&u!=e)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[u]}return{c:t.subarray(0,f),n:e}},A=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},C=function(r,n,e){var t=e.length,f=m(n+2);r[f]=255&t,r[f+1]=t>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},T=function(r,e,a,i,u,v,s,l,m,p,k){y(e,k++,a),++u[256];for(var T=b(u,15),E=T.t,U=T.l,D=b(v,15),S=D.t,I=D.l,j=x(E),z=j.c,J=j.n,N=x(S),O=N.c,q=N.n,B=new n(19),F=0;F<z.length;++F)++B[31&z[F]];for(F=0;F<O.length;++F)++B[31&O[F]];for(var G=b(B,7),H=G.t,K=G.l,L=19;L>4&&!H[o[L-1]];--L);var P,Q,R,V,W=p+5<<3,X=A(u,h)+A(v,w)+s,Y=A(u,E)+A(v,S)+s+14+3*L+A(B,H)+2*B[16]+3*B[17]+7*B[18];if(m>=0&&W<=X&&W<=Y)return C(e,k,r.subarray(m,m+p));if(y(e,k,1+(Y<X)),k+=2,Y<X){P=c(E,U),Q=E,R=c(S,I),V=S;var Z=c(H,K);y(e,k,J-257),y(e,k+5,q-1),y(e,k+10,L-4),k+=14;for(F=0;F<L;++F)y(e,k+3*F,H[o[F]]);k+=3*L;for(var $=[z,O],_=0;_<2;++_){var rr=$[_];for(F=0;F<rr.length;++F){var nr=31&rr[F];y(e,k,Z[nr]),k+=H[nr],nr>15&&(y(e,k,rr[F]>>5&127),k+=rr[F]>>12)}}}else P=g,Q=h,R=d,V=w;for(F=0;F<l;++F){var er=i[F];if(er>255){M(e,k,P[(nr=er>>18&31)+257]),k+=Q[nr+257],nr>7&&(y(e,k,er>>23&31),k+=t[nr]);var tr=31&er;M(e,k,R[tr]),k+=V[tr],tr>3&&(M(e,k,er>>5&8191),k+=f[tr])}else M(e,k,P[er]),k+=Q[er]}return M(e,k,P[256]),k+Q[256]},E=new e([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),U=new r(0),D=function(){for(var r=new Int32Array(256),n=0;n<256;++n){for(var e=n,t=9;--t;)e=(1&e&&-306674912)^e>>>1;r[n]=e}return r}(),S=function(o,a,i,u,l){if(!l&&(l={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),h=new r(c.length+o.length);h.set(c),h.set(o,c.length),o=h,l.w=c.length}return function(o,a,i,u,l,c){var h=c.z||o.length,w=new r(u+h+5*(1+Math.ceil(h/7e3))+l),g=w.subarray(u,w.length-l),d=c.l,y=7&(c.r||0);if(a){y&&(g[0]=c.r>>3);for(var M=E[a-1],b=M>>13,k=8191&M,x=(1<<i)-1,A=c.p||new n(32768),U=c.h||new n(x+1),D=Math.ceil(i/3),S=2*D,I=function(r){return(o[r]^o[r+1]<<D^o[r+2]<<S)&x},j=new e(25e3),z=new n(288),J=new n(32),N=0,O=0,q=c.i||0,B=0,F=c.w||0,G=0;q+2<h;++q){var H=I(q),K=32767&q,L=U[H];if(A[K]=L,U[H]=K,F<=q){var P=h-q;if((N>7e3||B>24576)&&(P>423||!d)){y=T(o,g,0,j,z,J,O,B,G,q-G,y),B=N=O=0,G=q;for(var Q=0;Q<286;++Q)z[Q]=0;for(Q=0;Q<30;++Q)J[Q]=0}var R=2,V=0,W=k,X=K-L&32767;if(P>2&&H==I(q-X))for(var Y=Math.min(b,P)-1,Z=Math.min(32767,q),$=Math.min(258,P);X<=Z&&--W&&K!=L;){if(o[q+R]==o[q+R-X]){for(var _=0;_<$&&o[q+_]==o[q+_-X];++_);if(_>R){if(R=_,V=X,_>Y)break;var rr=Math.min(X,_-2),nr=0;for(Q=0;Q<rr;++Q){var er=q-X+Q&32767,tr=er-A[er]&32767;tr>nr&&(nr=tr,L=er)}}}X+=(K=L)-(L=A[K])&32767}if(V){j[B++]=268435456|v[R]<<18|s[V];var fr=31&v[R],or=31&s[V];O+=t[fr]+f[or],++z[257+fr],++J[or],F=q+R,++N}else j[B++]=o[q],++z[o[q]]}}for(q=Math.max(q,F);q<h;++q)j[B++]=o[q],++z[o[q]];y=T(o,g,d,j,z,J,O,B,G,q-G,y),d||(c.r=7&y|g[y/8|0]<<3,y-=7,c.h=U,c.p=A,c.i=q,c.w=F)}else{for(q=c.w||0;q<h+d;q+=65535){var ar=q+65535;ar>=h&&(g[y/8|0]=d,ar=h),y=C(g,y+1,o.subarray(q,ar))}c.i=h}return p(w,0,u+m(y)+l)}(o,null==a.level?6:a.level,null==a.mem?l.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(o.length)))):20:12+a.mem,i,u,l)},I=function(r,n,e){for(;e;++n)r[n]=e,e>>>=8};function j(r,n){n||(n={});var e=function(){var r=-1;return{p:function(n){for(var e=r,t=0;t<n.length;++t)e=D[255&e^n[t]]^e>>>8;r=e},d:function(){return~r}}}(),t=r.length;e.p(r);var f,o=S(r,n,10+((f=n).filename?f.filename.length+1:0),8),a=o.length;return function(r,n){var e=n.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=n.level<2?4:9==n.level?2:0,r[9]=3,0!=n.mtime&&I(r,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),e){r[3]=8;for(var t=0;t<=e.length;++t)r[t+10]=e.charCodeAt(t)}}(o,n),I(o,a-8,e.d()),I(o,a-4,t),o}var z="undefined"!=typeof TextEncoder&&new TextEncoder,J="undefined"!=typeof TextDecoder&&new TextDecoder;try{J.decode(U,{stream:!0})}catch(r){}var N=Uint8Array,O=Uint16Array,q=Uint32Array,B=new N([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),F=new N([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),G=new N([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),H=function(r,n){for(var e=new O(31),t=0;t<31;++t)e[t]=n+=1<<r[t-1];var f=new q(e[30]);for(t=1;t<30;++t)for(var o=e[t];o<e[t+1];++o)f[o]=o-e[t]<<5|t;return[e,f]},K=H(B,2),L=K[0],P=K[1];L[28]=258,P[258]=28;var Q,R=H(F,0)[1],V=new O(32768);for(Y=0;Y<32768;++Y)Q=(61680&(Q=(52428&(Q=(43690&Y)>>>1|(21845&Y)<<1))>>>2|(13107&Q)<<2))>>>4|(3855&Q)<<4,V[Y]=((65280&Q)>>>8|(255&Q)<<8)>>>1;var W=function(r,n,e){for(var t=r.length,f=0,o=new O(n);f<t;++f)++o[r[f]-1];var a,i=new O(n);for(f=0;f<n;++f)i[f]=i[f-1]+o[f-1]<<1;for(a=new O(t),f=0;f<t;++f)a[f]=V[i[r[f]-1]++]>>>15-r[f];return a},X=new N(288);for(Y=0;Y<144;++Y)X[Y]=8;for(Y=144;Y<256;++Y)X[Y]=9;for(Y=256;Y<280;++Y)X[Y]=7;for(Y=280;Y<288;++Y)X[Y]=8;var Y,Z=new N(32);for(Y=0;Y<32;++Y)Z[Y]=5;var $=W(X,9),_=W(Z,5),rr=function(r){return(r/8|0)+(7&r&&1)},nr=function(r,n,e){(null==e||e>r.length)&&(e=r.length);var t=new(r instanceof O?O:r instanceof q?q:N)(e-n);return t.set(r.subarray(n,e)),t},er=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8},tr=function(r,n,e){e<<=7&n;var t=n/8|0;r[t]|=e,r[t+1]|=e>>>8,r[t+2]|=e>>>16},fr=function(r,n){for(var e=[],t=0;t<r.length;++t)r[t]&&e.push({s:t,f:r[t]});var f=e.length,o=e.slice();if(!f)return[new N(0),0];if(1==f){var a=new N(e[0].s+1);return a[e[0].s]=1,[a,1]}e.sort((function(r,n){return r.f-n.f})),e.push({s:-1,f:25001});var i=e[0],u=e[1],v=0,s=1,l=2;for(e[0]={s:-1,f:i.f+u.f,l:i,r:u};s!=f-1;)i=e[e[v].f<e[l].f?v++:l++],u=e[v!=s&&e[v].f<e[l].f?v++:l++],e[s++]={s:-1,f:i.f+u.f,l:i,r:u};var c=o[0].s;for(t=1;t<f;++t)o[t].s>c&&(c=o[t].s);var h=new O(c+1),w=or(e[s-1],h,0);if(w>n){t=0;var g=0,d=w-n,m=1<<d;for(o.sort((function(r,n){return h[n.s]-h[r.s]||r.f-n.f}));t<f;++t){var p=o[t].s;if(!(h[p]>n))break;g+=m-(1<<w-h[p]),h[p]=n}for(g>>>=d;g>0;){var y=o[t].s;h[y]<n?g-=1<<n-h[y]++-1:++t}for(;t>=0&&g;--t){var M=o[t].s;h[M]==n&&(--h[M],++g)}w=n}return[new N(h),w]},or=function(r,n,e){return-1==r.s?Math.max(or(r.l,n,e+1),or(r.r,n,e+1)):n[r.s]=e},ar=function(r){for(var n=r.length;n&&!r[--n];);for(var e=new O(++n),t=0,f=r[0],o=1,a=function(r){e[t++]=r},i=1;i<=n;++i)if(r[i]==f&&i!=n)++o;else{if(!f&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(f),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(f);o=1,f=r[i]}return[e.subarray(0,t),n]},ir=function(r,n){for(var e=0,t=0;t<n.length;++t)e+=r[t]*n[t];return e},ur=function(r,n,e){var t=e.length,f=rr(n+2);r[f]=255&t,r[f+1]=t>>>8,r[f+2]=255^r[f],r[f+3]=255^r[f+1];for(var o=0;o<t;++o)r[f+o+4]=e[o];return 8*(f+4+t)},vr=function(r,n,e,t,f,o,a,i,u,v,s){er(n,s++,e),++f[256];for(var l=fr(f,15),c=l[0],h=l[1],w=fr(o,15),g=w[0],d=w[1],m=ar(c),p=m[0],y=m[1],M=ar(g),b=M[0],k=M[1],x=new O(19),A=0;A<p.length;++A)x[31&p[A]]++;for(A=0;A<b.length;++A)x[31&b[A]]++;for(var C=fr(x,7),T=C[0],E=C[1],U=19;U>4&&!T[G[U-1]];--U);var D,S,I,j,z=v+5<<3,J=ir(f,X)+ir(o,Z)+a,N=ir(f,c)+ir(o,g)+a+14+3*U+ir(x,T)+(2*x[16]+3*x[17]+7*x[18]);if(z<=J&&z<=N)return ur(n,s,r.subarray(u,u+v));if(er(n,s,1+(N<J)),s+=2,N<J){D=W(c,h),S=c,I=W(g,d),j=g;var q=W(T,E);er(n,s,y-257),er(n,s+5,k-1),er(n,s+10,U-4),s+=14;for(A=0;A<U;++A)er(n,s+3*A,T[G[A]]);s+=3*U;for(var H=[p,b],K=0;K<2;++K){var L=H[K];for(A=0;A<L.length;++A){var P=31&L[A];er(n,s,q[P]),s+=T[P],P>15&&(er(n,s,L[A]>>>5&127),s+=L[A]>>>12)}}}else D=$,S=X,I=_,j=Z;for(A=0;A<i;++A)if(t[A]>255){P=t[A]>>>18&31;tr(n,s,D[P+257]),s+=S[P+257],P>7&&(er(n,s,t[A]>>>23&31),s+=B[P]);var Q=31&t[A];tr(n,s,I[Q]),s+=j[Q],Q>3&&(tr(n,s,t[A]>>>5&8191),s+=F[Q])}else tr(n,s,D[t[A]]),s+=S[t[A]];return tr(n,s,D[256]),s+S[256]},sr=new q([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lr=function(r,n,e,t,f){return function(r,n,e,t,f,o){var a=r.length,i=new N(t+a+5*(1+Math.floor(a/7e3))+f),u=i.subarray(t,i.length-f),v=0;if(!n||a<8)for(var s=0;s<=a;s+=65535){var l=s+65535;l<a?v=ur(u,v,r.subarray(s,l)):(u[s]=o,v=ur(u,v,r.subarray(s,a)))}else{for(var c=sr[n-1],h=c>>>13,w=8191&c,g=(1<<e)-1,d=new O(32768),m=new O(g+1),p=Math.ceil(e/3),y=2*p,M=function(n){return(r[n]^r[n+1]<<p^r[n+2]<<y)&g},b=new q(25e3),k=new O(288),x=new O(32),A=0,C=0,T=(s=0,0),E=0,U=0;s<a;++s){var D=M(s),S=32767&s,I=m[D];if(d[S]=I,m[D]=S,E<=s){var j=a-s;if((A>7e3||T>24576)&&j>423){v=vr(r,u,0,b,k,x,C,T,U,s-U,v),T=A=C=0,U=s;for(var z=0;z<286;++z)k[z]=0;for(z=0;z<30;++z)x[z]=0}var J=2,G=0,H=w,K=S-I&32767;if(j>2&&D==M(s-K))for(var L=Math.min(h,j)-1,Q=Math.min(32767,s),V=Math.min(258,j);K<=Q&&--H&&S!=I;){if(r[s+J]==r[s+J-K]){for(var W=0;W<V&&r[s+W]==r[s+W-K];++W);if(W>J){if(J=W,G=K,W>L)break;var X=Math.min(K,W-2),Y=0;for(z=0;z<X;++z){var Z=s-K+z+32768&32767,$=Z-d[Z]+32768&32767;$>Y&&(Y=$,I=Z)}}}K+=(S=I)-(I=d[S])+32768&32767}if(G){b[T++]=268435456|P[J]<<18|R[G];var _=31&P[J],er=31&R[G];C+=B[_]+F[er],++k[257+_],++x[er],E=s+J,++A}else b[T++]=r[s],++k[r[s]]}}v=vr(r,u,o,b,k,x,C,T,U,s-U,v)}return nr(i,0,t+rr(v)+f)}(r,null==n.level?6:n.level,null==n.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+n.mem,e,t,!0)};function cr(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var t=r,f=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)f+=t+=e[a];t%=65521,f%=65521}r=t,n=f},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var t,f,o,a=lr(r,n,2,4);return t=a,f=n.level,o=0==f?0:f<6?1:9==f?3:2,t[0]=120,t[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}var hr=r=>{const n={...r,v:"v1"};return function(r){for(var n="",e=0;e<r.length;){var t=r[e++];n+=String.fromCharCode(t)}return n}(cr(function(r,n){var e=r.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new N(r.length+(r.length>>>1)),f=0,o=function(r){t[f++]=r},a=0;a<e;++a){if(f+5>t.length){var i=new N(f+8+(e-a<<1));i.set(t),t=i}var u=r.charCodeAt(a);u<128||n?o(u):u<2048?(o(192|u>>>6),o(128|63&u)):u>55295&&u<57344?(o(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++a))>>>18),o(128|u>>>12&63),o(128|u>>>6&63),o(128|63&u)):(o(224|u>>>12),o(128|u>>>6&63),o(128|63&u))}return nr(t,0,f)}(JSON.stringify(n))))},wr=self;wr.onmessage=n=>{const e=n.data;if(!e||"number"!=typeof e.id||"pack-replay"!==e.op&&"encode-batch"!==e.op)return void(e&&"number"==typeof e.id&&wr.postMessage({id:e.id,ok:!1,error:"malformed message"}));const{id:t,op:f,payload:o}=e;try{if("pack-replay"===f){const r=o.events.map((r=>hr(r)));return void wr.postMessage({id:t,ok:!0,result:{packed:r}})}if("encode-batch"===f){const{json:n,compress:e}=o;if(!e){const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}try{const e=j(function(n,e){if(z)return z.encode(n);for(var t=n.length,f=new r(n.length+(n.length>>1)),o=0,a=function(r){f[o++]=r},i=0;i<t;++i){if(o+5>f.length){var u=new r(o+8+(t-i<<1));u.set(f),f=u}var v=n.charCodeAt(i);v<128||e?a(v):v<2048?(a(192|v>>6),a(128|63&v)):v>55295&&v<57344?(a(240|(v=65536+(1047552&v)|1023&n.charCodeAt(++i))>>18),a(128|v>>12&63),a(128|v>>6&63),a(128|63&v)):(a(224|v>>12),a(128|v>>6&63),a(128|63&v))}return p(f,0,o)}(n));return void wr.postMessage({id:t,ok:!0,result:{bytes:e,isCompressed:!0}},[e.buffer])}catch{const r=(new TextEncoder).encode(n);return void wr.postMessage({id:t,ok:!0,result:{bytes:r,isCompressed:!1}},[r.buffer])}}wr.postMessage({id:t,ok:!1,error:"unknown op"})}catch(r){wr.postMessage({id:t,ok:!1,error:r instanceof Error?r.message:String(r)})}}}();'],{type:"application/javascript"}),t=URL.createObjectURL(e);try{this.worker=new Worker(t),Promise.resolve().then((()=>URL.revokeObjectURL(t))),this.worker.onmessage=e=>this.handleMessage(e.data),this.worker.onerror=e=>this.handleFatalFailure("worker onerror",e.message),this.worker.onmessageerror=()=>this.logger.log("[worker-client] worker onmessageerror — single message dropped, worker still alive"),this.isAvailable=!0,this.logger.log("[worker-client] worker spawned")}catch(e){URL.revokeObjectURL(t),this.logger.log("[worker-client] failed to spawn worker, falling back to main thread:",e),this.worker=null,this.isAvailable=!1}}static getInstance(){return e.instance||(e.instance=new e),e.instance}static __resetForTests(){e.instance&&e.instance.terminate(),e.instance=null}static async withFallback(t,n,i){const r=e.getInstance();if(!r.isAvailable)return n();try{return await t(r)}catch(e){return d.getInstance().log(`[${i}] worker call failed, using inline fallback:`,e),n()}}packReplay(e){return this.dispatch("pack-replay",{events:e}).then((e=>e.packed))}encodeBatch(e,t){return this.dispatch("encode-batch",{json:e,compress:t}).then((e=>({data:e.bytes,isCompressed:e.isCompressed})))}terminate(){if(this.worker){try{this.worker.terminate()}catch(e){this.logger.log("[worker-client] failed to terminate worker:",e)}this.worker=null}this.isAvailable=!1,this.rejectAllPending(new Error("worker terminated")),e.instance===this&&(e.instance=null)}dispatch(e,t){if(!this.worker||!this.isAvailable)return Promise.reject(new Error("worker not available"));const n=this.nextId++,i=this.worker;return new Promise(((r,s)=>{const o=setTimeout((()=>{this.pending.has(n)&&(this.pending.delete(n),this.consecutiveTimeouts+=1,this.consecutiveTimeouts>=3&&this.handleFatalFailure("worker latched after 3 consecutive timeouts"),s(new Error("worker request timed out")))}),1500);this.pending.set(n,{resolve:r,reject:s,timeoutId:o});try{i.postMessage({id:n,op:e,payload:t})}catch(e){clearTimeout(o),this.pending.delete(n),s(e instanceof Error?e:new Error(String(e)))}}))}handleMessage(e){const t=this.pending.get(e.id);t&&(clearTimeout(t.timeoutId),this.pending.delete(e.id),this.consecutiveTimeouts=0,e.ok?t.resolve(e.result):t.reject(new Error(e.error)))}handleFatalFailure(e,t){if(this.logger.log(`[worker-client] ${e}${t?": "+t:""}`),this.isAvailable=!1,this.rejectAllPending(new Error(e)),this.worker){try{this.worker.terminate()}catch{}this.worker=null}}rejectAllPending(e){for(const t of this.pending.values())clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}};ge.instance=null;var ue=ge,fe=class{constructor(){this.logger=d.getInstance(),this.config=F.getInstance()}compressInline(n,i){if(!i)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}}}compressAsync(e,t){return ue.withFallback((n=>n.encodeBatch(e,t)),(()=>this.compressInline(e,t)),"transporter")}async send(e,{lifecycle:t=!1}={}){const n=this.config.getConfig();if(n)try{n?.options?.debug&&this.logger.log("Sending batch:",e,{groundcoverIgnore:!0});const i=n.apiKey,r=this.buildEndpoint();if(!i)return void this.logger.log("No API key found");const s=JSON.stringify(e),o=!!n?.options?.transport?.compression,{data:a,isCompressed:l}=t?this.compressInline(s,o):await this.compressAsync(s,o);fetch(r,{method:"POST",headers:{"Content-Type":"application/json",apikey:i,"Content-Encoding":l?"gzip":""},body:a}).catch((e=>{this.logger.log("Network error while sending batch:",e,{groundcoverIgnore:!0})}))}catch(e){n.options.debug&&this.logger.log("Failed to send batch:",e,{groundcoverIgnore:!0})}}buildEndpoint(){const e=this.config.getConfig();return e?`${e.getEndpoint()}/json/rum`:""}},pe=["navigation","dom.event"],ve=R.transport?.batchSize??10,me=R.transport?.batchTimeout??1e4;var ye=class e{constructor(){this.events=[],this.timeoutId=null,this.config=F.getInstance(),this.logger=d.getInstance(),this.initialized=!1,this.noClusterWarned=!1,this.onBeforeEnqueue=null,this.visibilityHandler=()=>{"hidden"===document.visibilityState&&this.flush({lifecycle:!0})},this.transporter=new fe}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",this.visibilityHandler),this.initialized=!0}catch(e){u(e)}}destroy(){try{null!==this.timeoutId&&(f.clearTimeout(this.timeoutId),this.timeoutId=null),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.events=[],this.initialized=!1}catch(e){u(e)}}setBeforeEnqueueHook(e){this.onBeforeEnqueue=e}addEvent(e){var t;if(e&&this.initialized)try{const n=this.config.getConfig()?.options?.beforeSend,i=this.config.getConfig()?.options?.enrichEvent;if(n&&!n(e))return;if(this.onBeforeEnqueue)try{this.onBeforeEnqueue(e)}catch(e){u(e)}i&&(e=i(e)),this.events.push(e);const r=(t=this.config.getConfig()?.options?.transport?.batchSize,"number"==typeof t&&Number.isFinite(t)&&t>=0?t:ve);this.events.length>=r&&!pe.includes(e.type)&&this.flush()}catch(e){u(e)}}flush({lifecycle:e=!1}={}){try{if(!this.initialized)return;if(!this.events?.length)return void this.scheduleFlush();if(!this.config.getConfig()?.cluster)return this.noClusterWarned||(this.noClusterWarned=!0,this.logger.log("[events-pool.flush] skipping flush: no cluster")),void this.scheduleFlush();this.noClusterWarned=!1;const t={sessionAttributes:this.getSessionAttributes(),events:this.events};e?this.transporter.send(t,{lifecycle:!0}):this.transporter.send(t),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&&(f.clearTimeout(this.timeoutId),this.timeoutId=null);const t=(e=this.config.getConfig()?.options?.transport?.batchTimeout,"number"==typeof e&&Number.isFinite(e)&&e>0?e:me);this.timeoutId=f.setTimeout((()=>{this.timeoutId=null,this.flush()}),t)}catch(e){u(e)}var e}detectBrowser(){const e=navigator.userAgent;let t="unknown",n="unknown";const i=navigator.platform||"unknown",r=/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:r}}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?.user||{},"service.name":t?.appId,userAgent:navigator.userAgent,browser:e}}};ye.instance=null;var be=ye,we=class{constructor(){this.logger=d.getInstance(),this.eventsPool=be.getInstance()}},Ee="undefined"!=typeof Element?Object.getOwnPropertyDescriptor(Element.prototype,"tagName")?.get:void 0;function ke(e,t){try{return e.getAttribute(t)||""}catch{return""}}function Se(e){try{const t=Ee?.call(e);return"string"==typeof t?t:""}catch{return""}}function Ie(e,t){try{return null!=e.closest?.(t)}catch{return!1}}function Te(e,t){return!!e&&("password"===e.type||function(e){return["id","name","class","aria-label","placeholder"].map((t=>ke(e,t))).filter(Boolean)}(e).some((e=>Q(e,t))))}function Re(e,t){return"allow"!==t.level&&(!!e&&(!!Ie(e,"[data-private]")||(!(!t.maskSelectors.length||!t.maskSelectors.some((t=>Ie(e,t))))||("mask-all"===t.level||function(e){const t=Se(e).toLowerCase();return"input"===t||"textarea"===t||"select"===t}(e)&&Te(e,t.sensitiveKeys)))))}var Me=class extends we{constructor(){super(...arguments),this.eventHandlers=[],this.capturedEvents=["click","change","keydown","select","submit"],this.config=F.getInstance(),this.getShouldMaskText=e=>Re(e.target,this.config.getPrivacy()),this.getKeyCode=(e,t)=>e instanceof KeyboardEvent&&e.code&&"Dead"!==e.key?t?"*":e.key:"",this.getText=(e,t)=>{const n=e.target;return t?"*":de({text:n?.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}),f?.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(!le())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,r=this.getShouldMaskText({target:i||null}),s=this.getKeyCode(e,r),o=this.getText(e,r);this.logger.log("[dom-events-listener.buildEvent] called");return he({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:ke(i,"id"),tagName:Se(i),className:ke(i,"class"),text:o}}})}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,r=t.priorityAttributes||["id","class","name","aria-label","type","title","alt"];if("html"===Se(e).toLowerCase())return"html";let s="",o=0,a=e;const l=[];for(;a&&a!==n&&a!==document.documentElement&&o<i;){let e=Se(a).toLowerCase();try{const t=a.getAttribute("id");if(t&&/^[a-zA-Z][\w-]*$/.test(t))return`#${t}`;if(a.classList?.length){const t=Array.from(a.classList).filter((e=>e&&"string"==typeof e)).map((e=>`.${e}`));t.length&&(e+=t.join(""))}for(const t of r)if("id"!==t&&"class"!==t)try{const n=a.getAttribute(t);n&&(e+=`[${t}="${n.replace(/"/g,'\\"')}"]`)}catch(e){}}catch(t){e=Se(a).toLowerCase()||"*"}l.unshift(e||"*"),s=l.join(" > ");try{if(1===n.querySelectorAll(s).length)return s}catch(e){l.shift(),s=l.join(" > ")}try{a=a.parentElement}catch(e){break}o++}return s||"*"}},Le=["log","info","warn","error","debug","assert","trace"],Ne=class extends we{constructor(){super(...arguments),this.originalConsole=null,this.isInitialized=!1,this.config=F.getInstance()}initialize(){if(!this.isInitialized)try{this.originalConsole=this.captureConsoleMethods(),Le.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;Le.forEach((e=>{this.originalConsole&&this.originalConsole[e]&&(console[e]=this.originalConsole[e])})),this.isInitialized=!1}catch(e){u(e)}}handleEvent(e,t){try{if(!le())return;const n=Array.isArray(e)?e:[e],i=this.formatMessage(n,t);if(!i||i?.includes("groundcoverIgnore"))return;const r=this.extractAttributes(n),s=this.buildEvent({message:i,level:t,attributes:r});this.queueEvent(s)}catch(e){u(e)}}buildEvent({message:e,level:t,attributes:n}){const{message:i,attributes:r}=re(this.config.getPrivacy(),e,n);return he({type:"log",attributes:{...r,message:de({text:i}),level:t}})}queueEvent(e){try{this.logger.log("[logs-events-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}extractAttributes(e){if(Array.isArray(e)&&0!==e.length)try{const t={};for(const n of e)null!==n&&"object"==typeof n&&"[object Object]"===Object.prototype.toString.call(n)&&Object.assign(t,n);return delete t.message,delete t.level,delete t.location,t}catch(e){return void 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{Le.forEach((t=>{console&&"function"==typeof console[t]&&(e[t]=console[t].bind(console))}))}catch(e){u(e)}return e}};function Ae(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 qe,xe=class extends we{constructor(){super(...arguments),this.maxBodyLength=5e3,this.config=F.getInstance(),this.idGenerator=new b,this.handleEvent=e=>{try{if(this.shouldIgnoreRequest(e.url))return;if(!le())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});const i=this.config.getPrivacy(),r={sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:"query"};try{t=new URL(e.url).pathname}catch(s){n=new URL(e.url,globalThis.location.href).href,i.shouldMaskNetworkQueryParams&&(t=ee(t,r))}i.shouldMaskNetworkQueryParams&&(n=ee(n,r)),this.logger.log("[network-events-listener.buildEvent] fullUrl",{fullUrl:n});const s=this.formatHeaders(e.request.headers),o=this.formatHeaders(e.response.headers),a=e.method?.toUpperCase()||"UNKNOWN",{traceId:l,spanId:c}=this.extractTraceIds(e.request.headers),h=(e,t)=>i.shouldMaskNetworkBodies?function(e,t={}){if(!e)return e;const n=e.trim();if(n.length<=$&&(n.startsWith("{")||n.startsWith("[")))try{const e=JSON.parse(n);return JSON.stringify(te("",e,[],t,0,new WeakSet))}catch{}return e.includes("=")&&!e.includes("{")?G(e,t):ne(e,t)}(e,{sensitiveKeys:i.sensitiveKeys,redact:i.redact,kind:t}):e,d=de({text:h(e.request.body,"request-body"),maxLength:this.maxBodyLength}),g=de({text:h(e.response.body,"response-body"),maxLength:this.maxBodyLength}),u={type:"HTTP",operation:{name:a},resource_name:t,status:e.status?.toString(),subType:a,url:{full:n},http:{route:t,path:t,method:e.method,status:e.status?.toString(),request:{headers:s,method:e.method},response:{headers:o,status_code:e.status?.toString()}},error:e?.error?.type?{type:e.error?.type||"Unknown error"}:void 0,gc:{request:{body:d},response:{body:g}}},f={type:"network",timestamp:e?.timestamp&&!Number.isNaN(e.timestamp)?v(e.timestamp):void 0,end_timestamp:e?.end_time&&!Number.isNaN(e.end_time)?v(e.end_time):void 0,span_name:`${e.method} ${t}`,attributes:u};return l&&(f.traceId=l),c&&(f.spanId=c),he(f)}}async getResponseBody(e){const t=e.body;if(!t)return"";const n=t.getReader(),i=new TextDecoder;let r="",s=0;for(;;){const{done:e,value:t}=await n.read();if(e)break;if(s+t.byteLength>=this.maxBodyLength){const e=t.subarray(0,this.maxBodyLength-s);r+=i.decode(e,{stream:!0}),n.cancel().catch((()=>{}));break}s+=t.byteLength,r+=i.decode(t,{stream:!0})}return r+=i.decode(),r}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 r;globalThis.XMLHttpRequest.prototype.open=function(n,i,s=!0,o,a){if(r=Date.now(),e.shouldIgnoreRequest(i.toString()))return t.apply(this,[n,i,s,o,a]);const l=new URL(i.toString(),globalThis.location.href).href;return this._requestMethod=n,this._requestUrl=l,this._requestHeaders={},t.apply(this,[n,i,s,o,a])},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?.tracing?.origin?.name&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),n&&(t?.options?.tracing?.traceIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&e.addHeaderToXhrRequest({request:this,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId}),Boolean(t?.options?.tracing?.propagationHeaders)&&t?.options?.tracing?.propagationHeaders?.forEach((t=>{e.addHeaderToXhrRequest({request:this,headerName:t,headerValue:n.traceparent})})),t?.options?.tracing?.propagationHeaders?.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=Ae(this._requestBody),s=Ae(""===this.responseType||"text"===this.responseType?this.responseText:this.response),o={timestamp:r,end_time:t,method:this._requestMethod,url:this._requestUrl,body:i,status:this.status,request:{headers:this._requestHeaders||{},body:i},response:{headers:n,body:s}};e.handleEvent(o)})),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?.tracing?.origin?.name&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.origin.name,headerValue:t.options.tracing.origin.value}),!n)return;t?.options?.tracing?.traceIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.traceIdHeaderName,headerValue:n.decimalTraceId}),t?.options?.tracing?.spanIdHeaderName&&this.addHeaderToFetchRequest({init:e,headerName:t.options.tracing.spanIdHeaderName,headerValue:n.decimalSpanId});const i=t?.options?.tracing?.propagationHeaders;(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,r]=t;r={...r||{}},t[1]=r;const s=i instanceof Request,o=r?.method||(s?i.method:"GET"),a=r?.body||"",l=i instanceof Request?i.url:i.toString();if(this.shouldIgnoreRequest(l))return e.apply(globalThis,t);const c=this.shouldAddTraceHeader(l);r||(t[1]={},r=t[1]),r.headers=this.normalizeHeaders(s?i.headers:void 0,r.headers),c&&this.addTraceHeaders(r);const h=this.extractHeadersRecord(r.headers),d=Ae(a);return e.apply(globalThis,t).then((e=>{const t=Date.now(),i={};e.headers.forEach(((e,t)=>{i[t]=e}));const r={method:o,url:l,timestamp:n,body:d,status:e.status,end_time:t,request:{headers:h,body:d},response:{headers:i,body:""}};try{i["content-type"]?.includes("text/event-stream")?(r.response.body="[unreadable response body]",this.handleEvent(r)):this.getResponseBody(e.clone()).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 r={method:o,url:l,body:d,status:0,end_time:t,request:{headers:h,body:d},response:{headers:{},body:""},error:{type:n}};throw this.handleEvent(r),e}))}}formatHeaders(e){const t=this.config.getPrivacy(),n="allow"===t.level,i=function(e,t={}){return e?Object.entries(e).reduce(((e,[n,i])=>{const r=n.toLowerCase(),s=J({key:n,value:i,path:[n],kind:"header",sensitive:K.includes(r)||U.test(r)||Q(n,t.sensitiveKeys)},t.redact);return e[n]=null===s?"":String(s),e}),{}):e}(e,{sensitiveKeys:n?void 0:t.sensitiveKeys,redact:n?void 0:t.redact});return Object.entries(i)?.reduce(((e,[t,n])=>(e[t]=de({text:n}),e)),{})}extractTraceIds(e){const t=this.config.getConfig();let n="",i="";if(t?.options?.tracing?.traceIdHeaderName){const i=e[t.options.tracing.traceIdHeaderName];i&&"string"==typeof i&&(n=i)}if(t?.options?.tracing?.spanIdHeaderName){const n=e[t.options.tracing.spanIdHeaderName];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?.tracing?.propagationHeaders?.length)for(const n of t.options.tracing.propagationHeaders){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(r){this.logger.log("[network-events-listener.getTraceIds] error",{error:r}),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?.tracing?.propagationUrls?.length)return!1;const n=t.options.tracing.propagationUrls?.some((t=>{const n=t.replace(/\*/g,".*"),i=new RegExp(`^${n}$`),r=e.startsWith("/")?new URL(e,globalThis.location.href).pathname:e;return i.test(r)}));return this.logger.log("[network-events-listener.shouldAddTraceHeader] result",{url:e,result:n}),n}},ze=class extends we{constructor(){super(...arguments),this.config=F.getInstance(),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(){f?.addEventListener("error",this.handleEvent),f?.addEventListener("unhandledrejection",this.handleEvent)}destroy(){f?.removeEventListener("error",this.handleEvent),f?.removeEventListener("unhandledrejection",this.handleEvent)}buildEvent(e,t){const n=this.config.getPrivacy(),i=n.shouldMaskErrors,r={sensitiveKeys:n.sensitiveKeys,redact:n.redact,kind:"error"},s=e.message||"Unknown error",o=i?ne(s,r):s,a=i&&t?.metadata?ie(t.metadata,r):t?.metadata;return he({type:"exception",attributes:{error_type:e.name||"Error",error_message:o,error_stacktrace:this.buildStackTrace(e),error_fingerprint:`${e.name}:${de({text:o,maxLength:400})}`,error_handled:t?.handled||!1,error_metadata:a}})}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:r}=t||{};n&&!e.fileName&&Object.defineProperty(e,"fileName",{value:n}),i&&!e.lineNumber&&Object.defineProperty(e,"lineNumber",{value:i}),r&&!e.columnNumber&&Object.defineProperty(e,"columnNumber",{value:r})}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[]}}},Ce=class extends we{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=f.location.href,this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState}catch(e){u(e)}}isInBrowserEnvironment(){try{return void 0!==f&&void 0!==f.location&&void 0!==f.history&&"function"==typeof f.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},f&&"function"==typeof f.addEventListener&&(f.addEventListener("popstate",this.popStateHandler),f.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),f&&"function"==typeof f.removeEventListener&&(f.removeEventListener("popstate",this.popStateHandler),f.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",f.location.href);const e=F.getInstance().getPrivacy(),t="allow"===e.level,n=f.location.href,i=this.activeNavigation?.metadata;return he({type:"navigation",attributes:{page_url:e.shouldMaskNetworkQueryParams?ee(n,{sensitiveKeys:e.sensitiveKeys,redact:e.redact,kind:"query"}):n,metadata:!t&&i?ie(i,{sensitiveKeys:e.sensitiveKeys,redact:e.redact}):i,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:f.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===f.location.href)return;let e,t;try{e=new URL(f.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=f.location.href,this.handleEvent())}catch(e){u(e)}}},_e=class extends we{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",f),"complete"===f?.document?.readyState?(this.logger.log("Page already loaded, triggering event immediately"),this.handleEvent()):f?.addEventListener("load",this.loadEventHandler)}catch(e){this.logger.log("[page-load-listener.initialize] error",e),u(e)}}destroy(){f?.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,r=t.duration,s=t.initiatorType;i.totalSize+=n,i.totalDuration+=r,i.byType[s]||(i.byType[s]={count:0,size:0,duration:0}),i.byType[s].count++,i.byType[s].size+=n,i.byType[s].duration+=r}));const r=F.getInstance().getPrivacy(),s=r.shouldMaskNetworkQueryParams,o={sensitiveKeys:r.sensitiveKeys,redact:r.redact,kind:"query"},a=f?.location?.href||"",l=f?.document?.referrer||"";return he({type:"pageload",attributes:{page_url:s?ee(a,o):a,page_load_time:t,page_referrer:s?ee(l,o):l,page_resources:i}})}queueEvent(e){try{this.logger.log("[page-load-listener.queueEvent] called"),e&&this.eventsPool.addEvent(e)}catch(e){u(e)}}},He=class extends we{constructor(){super(...arguments),this.handleEvent=e=>{try{if(!le())return;const t=this.buildEvent(e);this.queueEvent(t)}catch(e){u(e)}}}initialize(){i(this.handleEvent),r(this.handleEvent),s(this.handleEvent),o(this.handleEvent),a(this.handleEvent)}destroy(){}buildEvent(e){return he({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)}}},Pe=class{constructor(){this.logger=d.getInstance(),this.eventsPool=be.getInstance(),this.configManager=F.getInstance(),this.stopFn=null,this.isRecording=!1,this.events=[],this.startTime=0,this.batchSize=3,this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,this.sendTimerId=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?.replay?.blockedSelectors?.filter(Boolean),t=e?.length?e.join(", "):void 0,n=this.configManager.getPrivacy(),i=n.maskInputFn??("allow"===n.level?void 0:(e,t)=>Re(t,n)?"*".repeat(e.length):e);this.stopFn=l({...t?{blockSelector:t}:{},...n.maskTextSelector?{maskTextSelector:n.maskTextSelector}:{},maskAllInputs:n.maskInputs,...n.maskTextFn?{maskTextFn:n.maskTextFn}:{},...i?{maskInputFn:i}:{},slimDOMOptions:{script:!1,comment:!1,headWhitespace:!1},sampling:{mousemove:100,input:"last",scroll:150},checkoutEveryNms:3e4,emit:(e,t)=>{if(this.isRecording)try{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.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=f.setTimeout((()=>{this.sendTimerId=null,this.isRecording&&this.sendBatchAsync().catch((e=>{u(e),this.logger.log("[session-replay-listener] failed to send deferred batch:",e)}))}),0))}clearScheduledSend(){null!==this.sendTimerId&&(f.clearTimeout(this.sendTimerId),this.sendTimerId=null)}flushPendingSync(){this.clearScheduledSend(),0!==this.events.length&&this.sendBatchSync()}async sendBatchAsync(){if(0===this.events.length)return;const e=this.drainBatch(),t=this.configManager.getSessionId(),n=ue.getInstance();let i;if(n.isAvailable)try{i=await n.packReplay(e.events)}catch(t){u(t),this.logger.log("[session-replay-listener] worker pack failed, using inline fallback:",t),i=e.events.map((e=>c(e)))}else i=e.events.map((e=>c(e)));this.configManager.getSessionId()===t?this.enqueueReplayEvent(i,e.containsFullSnapshot,e.snapshotTimestamp):this.logger.log("[session-replay-listener] dropping packed batch: session rotated during pack",{drained:i.length})}sendBatchSync(){if(0===this.events.length)return;const e=this.drainBatch(),t=e.events.map((e=>c(e)));this.enqueueReplayEvent(t,e.containsFullSnapshot,e.snapshotTimestamp)}drainBatch(){const e=this.events,t=this.batchContainsFullSnapshot,n=this.fullSnapshotTimestamp;return this.events=[],this.batchContainsFullSnapshot=!1,this.fullSnapshotTimestamp=void 0,{events:e,containsFullSnapshot:t,snapshotTimestamp:n}}enqueueReplayEvent(e,t,n){try{const i={_gc_replay_data:{events:e}};t&&(i.replay_is_full_snapshot=!0,i.replay_full_snapshot_timestamp=n);const r=he({type:"replay",attributes:i});this.eventsPool.addEvent(r),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.clearScheduledSend(),this.stopFn?.(),this.isRecording=!1,this.events.length>0&&this.sendBatchSync(),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()}},De=["pointerdown","keydown","scroll","touchstart","mousemove"],Oe=class{constructor(e){this.logger=d.getInstance(),this.lastSignalMs=0,this.idleTimer=null,this.installed=!1,this.handleInput=()=>{const e=Date.now();if(!(e-this.lastSignalMs<3e4)){this.notePresence(e);try{this.callbacks.onPresence(e)}catch(e){u(e)}}},this.callbacks=e}initialize(){this.installed||(this.installed=!0,De.forEach((e=>{try{f.addEventListener?.(e,this.handleInput,{capture:!0,passive:!0})}catch(e){u(e)}})),this.armIdleTimer(),this.logger.log("[user-presence-monitor] installed"))}notePresence(e){this.lastSignalMs=e,this.armIdleTimer()}resetIdleTimer(){this.armIdleTimer()}armIdleTimer(){try{this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.idleTimer=setTimeout((()=>{this.idleTimer=null,this.logger.log("[user-presence-monitor] user idle for",T,"ms");try{this.callbacks.onIdle()}catch(e){u(e)}}),T)}catch(e){u(e)}}destroy(){if(this.installed){this.installed=!1,De.forEach((e=>{try{f.removeEventListener?.(e,this.handleInput,{capture:!0})}catch(e){u(e)}}));try{this.idleTimer&&clearTimeout(this.idleTimer)}catch(e){u(e)}finally{this.idleTimer=null}}}},Fe=new Set(["dom.event","navigation","pageload"]),je=class{constructor(){this.logger=d.getInstance(),this.eventsPool=be.getInstance(),this.configManager=F.getInstance(),this.idGenerator=new b,this.logEventsListener=null,this.domEventsListener=null,this.errorsEventsListener=null,this.networkEventsListener=null,this.navigationListener=null,this.performanceListener=null,this.pageLoadListener=null,this.sessionReplayListener=null,this.isRotating=!1,this.replayDesired=!1,this.presenceMonitor=null}instrument(){this.logger.log("[instrumentation-manager.instrument] called"),this.eventsPool.setBeforeEnqueueHook((e=>this.reconcileSessionOnEnqueue(e))),this.presenceMonitor?.destroy(),this.presenceMonitor=new Oe({onPresence:e=>this.reconcileSession(e,!0),onIdle:()=>this.pauseReplayOnIdle()}),this.presenceMonitor.initialize();const e=this.configManager.getConfig(),t=e?.options?.enabledEvents,n=!t||0===t.length,i=[];(n||t?.includes("pageload"))&&(this.pageLoadListener=new _e,this.pageLoadListener.initialize(),i.push("pageload")),(n||t?.includes("dom"))&&(this.domEventsListener=new Me,this.domEventsListener.initialize(),i.push("dom")),(n||t?.includes("logs"))&&(this.logEventsListener=new Ne,this.logEventsListener.initialize(),i.push("logs")),(n||t?.includes("exceptions"))&&(this.errorsEventsListener=new ze,this.errorsEventsListener.initialize(),i.push("exceptions")),(n||t?.includes("network"))&&(this.networkEventsListener=new xe,this.networkEventsListener.initialize(),i.push("network")),(n||t?.includes("performance"))&&(this.performanceListener=new He,this.performanceListener.initialize(),i.push("performance")),this.navigationListener=new Ce({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=he({type:"custom",attributes:{custom_event_name:e?.event,custom_event_attributes:e?.attributes}});this.eventsPool.addEvent(t)}catch(e){u(e)}}emitLog(e,t,n){if(this.logEventsListener){this.logger.log("[instrumentation-manager.emitLog] called",{message:e,level:t,attributes:n});try{const i={...n||{}};delete i.message,delete i.level,delete i.location;const{message:r,attributes:s}=re(F.getInstance().getPrivacy(),e,i),o=he({type:"log",attributes:{...s,message:de({text:r}),level:t}});this.eventsPool.addEvent(o)}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)}isReplayRecording(){return null!==this.sessionReplayListener}restartReplayForConfigChange(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] restarting replay to apply config change"),this.stopReplayListener(),this.startReplayListener())}startReplayRecording(){if(this.replayDesired=!0,this.isReplayRecording())return void this.logger.log("[instrumentation-manager] replay recording already started");const e=Date.now();(this.configManager.isSessionInactive(e)||this.configManager.isSessionExpired(e))&&this.rotateSession({reason:"replay start into stale session"}),this.startReplayListener(),this.presenceMonitor?.resetIdleTimer()}stopReplayRecording(){this.replayDesired=!1,this.stopReplayListener()}flushPendingReplay(){this.sessionReplayListener?.flushPendingSync()}syncReplayState(e){this.replayDesired&&e&&!this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] user present and replay desired — starting replay"),this.startReplayListener())}pauseReplayOnIdle(){this.isReplayRecording()&&(this.logger.log("[instrumentation-manager] pausing replay: user idle window elapsed"),this.stopReplayListener())}startReplayListener(){if(this.sessionReplayListener)this.logger.log("[instrumentation-manager] replay recording already started");else try{const e=new Pe;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)}}reconcileSession(e,t){if(this.isRotating)return;t&&this.configManager.isSessionInactive(e)&&this.rotateSession({reason:"inactivity gap"});const n=this.configManager.getSessionElapsedMs(e),i=this.configManager.getSessionMaxDuration(),r=n>=i;this.logger.log("[instrumentation-manager] session reconcile",{userPresent:t,elapsedMs:n,maxDurationMs:i,expired:r}),r&&this.rotateSession({reason:"max session duration"}),this.syncReplayState(t),t&&(this.configManager.setLastActivityMs(e),this.presenceMonitor?.notePresence(e))}reconcileSessionOnEnqueue(e){this.isRotating||("replay"!==e.type?this.reconcileSession(Date.now(),Fe.has(e.type)):this.logger.log("[instrumentation-manager] enqueue rotation check: ignoring replay event"))}rotateSession(e){if(this.isRotating)return;this.isRotating=!0;const t=this.configManager.getSessionId(),n=this.isReplayRecording();this.logger.log("[instrumentation-manager] session rotation start",{reason:e.reason,previousId:t,wasReplayActive:n});const i=(e,t)=>{try{this.logger.log(`[instrumentation-manager] session rotation: ${e}`),t()}catch(t){u(t),this.logger.log(`[instrumentation-manager] failed to ${e} during session rotation:`,t)}};try{i("stop replay",(()=>this.stopReplayListener())),i("flush events",(()=>this.eventsPool.flush())),i("rotate session ids",(()=>{const e=this.idGenerator.generateId();this.configManager.setSessionId(e),this.configManager.setSessionStartTime(v(Date.now())),this.logger.log("[instrumentation-manager] session id rotated",{from:t,to:e})})),i("sync replay",(()=>this.syncReplayState(n)))}finally{this.isRotating=!1,this.logger.log("[instrumentation-manager] session rotation complete",{reason:e.reason})}}stopReplayListener(){this.sessionReplayListener?(this.sessionReplayListener.stopRecording(),this.sessionReplayListener=null):this.logger.log("[instrumentation-manager] cannot stop replay recording: replay listener not initialized")}uninstrument(){this.eventsPool.setBeforeEnqueueHook(null),this.presenceMonitor?.destroy(),this.presenceMonitor=null,this.domEventsListener?.destroy(),this.logEventsListener?.destroy(),this.errorsEventsListener?.destroy(),this.networkEventsListener?.destroy(),this.navigationListener?.destroy(),this.performanceListener?.destroy(),this.pageLoadListener?.destroy(),this.sessionReplayListener?.destroy(),this.sessionReplayListener=null,this.replayDesired=!1}},Ke="gcSample",Ue=class{constructor(e){this.initialized=!1,this.logger=d.initialize({debug:e.options?.debug||!1,prefix:"[groundcover]"}),this.logger.log("[session-manager] initialize called"),this.instrumentationManager=new je,this.idGenerator=new b;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=F.getInstance();t.initialize(e);be.getInstance().initialize(),ue.getInstance();const n=e.sessionId,i=t.getSessionId();n&&n!==i?(t.setSessionId(n),t.setSessionStartTime(v(Date.now())),this.logger.log("[session-manager] using provided sessionId:",n)):n?(t.setSessionId(n),this.logger.log("[session-manager] continuing provided sessionId:",n)):i||t.setSessionId(this.idGenerator.generateId());const r=Date.now(),s=m(t.getSessionStartTime());if(s>0&&r-s>=-6e4){if(t.isSessionExpired(r)||t.isSessionInactive(r)){const e=t.isSessionExpired(r)?"persisted session past cap":"inactivity gap across reload",n=t.getSessionId(),i=this.idGenerator.generateId();t.setSessionId(i),t.setSessionStartTime(v(r)),this.logger.log(`[session-manager] init-time rotation: ${e}`,{from:n,to:i})}}else t.setSessionStartTime(v(r));this.instrumentationManager.instrument(),this.initialized=!0}getSamplingDecision(e){try{if(!e||1===e)return!0;const t=H(Ke);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 P(Ke,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");F.getInstance().updateConfig({user:e})}updateConfig(e){if(!this.initialized)return void this.logger.log("[session-manager] cannot update config: SDK not initialized");F.getInstance().updateConfig(e);const t=e.options,n=!!t&&"privacy"in t,i=!!t&&"object"==typeof t.replay&&null!==t.replay&&"blockedSelectors"in t.replay;(n||i)&&this.instrumentationManager.restartReplayForConfigChange()}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")}emitLog(e,t,n){this.initialized?this.instrumentationManager.emitLog(e,t,n):this.logger.log("[session-manager] Cannot emit log: SDK not initialized")}getSessionId(){return this.initialized?F.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{this.instrumentationManager.flushPendingReplay();const t=be.getInstance();await t.flushSync();const n=e||this.idGenerator.generateId(),i=F.getInstance();i.setSessionId(n),i.setSessionStartTime(v(Date.now())),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(),be.getInstance().destroy(),ue.getInstance().terminate(),F.getInstance().clearSessionState(),this.initialized=!1)}},Be=new class{constructor(e){this.manager=e}emit(e,t,n){this.manager&&this.manager.emitLog(t,e,n)}log(e,t){this.emit("log",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}debug(e,t){this.emit("debug",e,t)}trace(e,t){this.emit("trace",e,t)}};var Ye={init:function(e){try{qe=new Ue({cluster:e?.cluster||"",environment:e?.environment||"",namespace:e?.namespace,releaseId:e?.releaseId,dsn:e?.dsn||"",appId:e?.appId||"",user:e?.user,apiKey:e?.apiKey||"",options:e?.options,sessionId:e?.sessionId}),Be.manager=qe}catch(e){u(e)}},identifyUser:function(e){qe?qe.identifyUser(e):console.warn("[groundcover] identifyUser: groundcover is not initialized. please call init() first")},sendCustomEvent:function(e){qe&&qe.sendCustomEvent(e)},captureException:function(e,t){qe&&qe.captureException(e,t)},logger:Be,updateConfig:function(e){if(qe)try{qe.updateConfig(e)}catch(e){u(e)}},startNavigation:function(e){qe?qe.startNavigation(e):console.warn("[groundcover] startNavigation: groundcover is not initialized. please call init() first")},endNavigation:function(e){qe?qe.endNavigation(e):console.warn("[groundcover] endNavigation: groundcover is not initialized. please call init() first")},getSessionId:function(){return qe?qe.getSessionId():(console.warn("[groundcover] getSessionId: groundcover is not initialized. please call init() first"),"")},setSessionId:async function(e){if(qe)try{await qe.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(){qe?qe.startReplayRecording():console.warn("[groundcover] startReplayRecording: groundcover is not initialized. please call init() first")},stopReplayRecording:function(){qe?qe.stopReplayRecording():console.warn("[groundcover] stopReplayRecording: groundcover is not initialized. please call init() first")}};if("undefined"!=typeof window&&!window.groundcover)try{window.groundcover=Ye}catch(e){console.warn("[groundcover] Failed to expose groundcover on window:",e)}var $e=Ye;export{$e as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@groundcover/browser",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "groundcover Real User Monitoring (RUM) SDK for the browser — performance, errors, logs, distributed tracing and session replay",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",