@tracelog/lib 2.8.5 → 2.9.0-rc.107.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.
@@ -1,6 +1,6 @@
1
- const hr = 9e5;
2
- const fr = 120, mr = 49152, gr = 100, Er = 500, pr = 200;
3
- const Sr = 1e3, Tr = 500, Ir = 1e3;
1
+ const fr = 9e5;
2
+ const mr = 120, gr = 49152, pr = 100, Er = 500, Sr = 200;
3
+ const Tr = 1e3, Ir = 500, _r = 1e3;
4
4
  const b = "data-tlog", bt = [
5
5
  "button",
6
6
  "a",
@@ -49,7 +49,7 @@ const b = "data-tlog", bt = [
49
49
  "code",
50
50
  "otp"
51
51
  ];
52
- const E = {
52
+ const S = {
53
53
  INVALID_SESSION_TIMEOUT: "Session timeout must be between 30000ms (30 seconds) and 86400000ms (24 hours)",
54
54
  INVALID_SAMPLING_RATE: "Sampling rate must be between 0 and 1",
55
55
  INVALID_ERROR_SAMPLING_RATE: "Error sampling must be between 0 and 1",
@@ -79,7 +79,7 @@ const E = {
79
79
  /<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
80
80
  /<embed\b[^>]*>/gi,
81
81
  /<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi
82
- ], S = "tlog", X = `${S}:qa_mode`, Te = `${S}:uid`, rt = "tlog_mode", Ue = "qa", Fe = "qa_off", Ct = (r) => r ? `${S}:${r}:queue` : `${S}:queue`, Rt = (r) => r ? `${S}:${r}:rate_limit` : `${S}:rate_limit`, Nt = (r) => r ? `${S}:${r}:session` : `${S}:session`, Ot = (r) => r ? `${S}:${r}:broadcast` : `${S}:broadcast`, He = (r, e) => `${S}:${r}:session_counts:${e}`, xe = 10080 * 60 * 1e3, $e = `${S}:session_counts_last_cleanup`, Be = 3600 * 1e3, fe = (r) => r ? `${S}:${r}:identity` : `${S}:identity`, U = `${S}:pending_identity`;
82
+ ], I = "tlog", G = `${I}:qa_mode`, Ie = `${I}:uid`, rt = "tlog_mode", Ue = "qa", Fe = "qa_off", Ct = (r) => r ? `${I}:${r}:queue` : `${I}:queue`, Rt = (r) => r ? `${I}:${r}:rate_limit` : `${I}:rate_limit`, Nt = (r) => r ? `${I}:${r}:session` : `${I}:session`, Ot = (r) => r ? `${I}:${r}:broadcast` : `${I}:broadcast`, He = (r, e) => `${I}:${r}:session_counts:${e}`, xe = 10080 * 60 * 1e3, $e = `${I}:session_counts_last_cleanup`, Be = 3600 * 1e3, me = (r) => r ? `${I}:${r}:identity` : `${I}:identity`, F = `${I}:pending_identity`;
83
83
  var $ = /* @__PURE__ */ ((r) => (r.Localhost = "localhost:8080", r.Fail = "localhost:9999", r))($ || {}), A = /* @__PURE__ */ ((r) => (r.Mobile = "mobile", r.Tablet = "tablet", r.Desktop = "desktop", r.Unknown = "unknown", r))(A || {}), se = /* @__PURE__ */ ((r) => (r.EVENT = "event", r.QUEUE = "queue", r))(se || {});
84
84
  class O extends Error {
85
85
  constructor(e, t, s) {
@@ -93,13 +93,13 @@ class re extends Error {
93
93
  super(e), this.name = "RateLimitError", Error.captureStackTrace && Error.captureStackTrace(this, re);
94
94
  }
95
95
  }
96
- class ie extends Error {
96
+ class ne extends Error {
97
97
  constructor(e) {
98
- super(e), this.name = "TimeoutError", Error.captureStackTrace && Error.captureStackTrace(this, ie);
98
+ super(e), this.name = "TimeoutError", Error.captureStackTrace && Error.captureStackTrace(this, ne);
99
99
  }
100
100
  }
101
- var u = /* @__PURE__ */ ((r) => (r.PAGE_VIEW = "page_view", r.CLICK = "click", r.SCROLL = "scroll", r.SESSION_START = "session_start", r.CUSTOM = "custom", r.WEB_VITALS = "web_vitals", r.ERROR = "error", r.VIEWPORT_VISIBLE = "viewport_visible", r))(u || {}), Z = /* @__PURE__ */ ((r) => (r.UP = "up", r.DOWN = "down", r))(Z || {}), B = /* @__PURE__ */ ((r) => (r.JS_ERROR = "js_error", r.PROMISE_REJECTION = "promise_rejection", r))(B || {}), ne = /* @__PURE__ */ ((r) => (r.QA = "qa", r))(ne || {});
102
- const vr = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !0, _r = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !1;
101
+ var u = /* @__PURE__ */ ((r) => (r.PAGE_VIEW = "page_view", r.CLICK = "click", r.SCROLL = "scroll", r.SESSION_START = "session_start", r.CUSTOM = "custom", r.WEB_VITALS = "web_vitals", r.ERROR = "error", r.VIEWPORT_VISIBLE = "viewport_visible", r))(u || {}), Z = /* @__PURE__ */ ((r) => (r.UP = "up", r.DOWN = "down", r))(Z || {}), B = /* @__PURE__ */ ((r) => (r.JS_ERROR = "js_error", r.PROMISE_REJECTION = "promise_rejection", r))(B || {}), ie = /* @__PURE__ */ ((r) => (r.QA = "qa", r))(ie || {});
102
+ const vr = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !0, yr = (r) => r.type === u.SCROLL && "scroll_data" in r && r.scroll_data.is_primary === !1;
103
103
  class j extends Error {
104
104
  constructor(e, t, s) {
105
105
  super(e), this.errorCode = t, this.layer = s, this.name = this.constructor.name, Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
@@ -107,7 +107,7 @@ class j extends Error {
107
107
  errorCode;
108
108
  layer;
109
109
  }
110
- class m extends j {
110
+ class p extends j {
111
111
  constructor(e, t = "config") {
112
112
  super(e, "APP_CONFIG_INVALID", t);
113
113
  }
@@ -127,13 +127,13 @@ class N extends j {
127
127
  super(e, "INTEGRATION_INVALID", t);
128
128
  }
129
129
  }
130
- class yr extends j {
130
+ class wr extends j {
131
131
  constructor(e, t, s = "runtime") {
132
132
  super(e, "INITIALIZATION_TIMEOUT", s), this.timeoutMs = t;
133
133
  }
134
134
  timeoutMs;
135
135
  }
136
- const it = "background: #ff9800; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;", nt = "background: #9e9e9e; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;", Dt = "background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;", kt = (r, e) => {
136
+ const nt = "background: #ff9800; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;", it = "background: #9e9e9e; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;", Dt = "background: #d32f2f; color: white; font-weight: bold; padding: 2px 8px; border-radius: 3px;", kt = (r, e) => {
137
137
  if (e) {
138
138
  if (e instanceof Error) {
139
139
  const t = e.message.replace(/\s+at\s+.*$/gm, "").replace(/\s*\([^()]+:\d+:\d+\)/g, "");
@@ -156,30 +156,30 @@ const it = "background: #ff9800; color: white; font-weight: bold; padding: 2px 8
156
156
  if (typeof window > "u" || typeof sessionStorage > "u")
157
157
  return !1;
158
158
  try {
159
- return sessionStorage.getItem(X) === "true";
159
+ return sessionStorage.getItem(G) === "true";
160
160
  } catch {
161
161
  return !1;
162
162
  }
163
163
  }, a = (r, e, t) => {
164
- const { error: s, data: i, showToClient: n = !1, style: o, visibility: l } = t ?? {}, c = s ? kt(e, s) : `[TraceLog] ${e}`, d = r === "error" ? "error" : r === "warn" ? "warn" : "log";
165
- if (!Ut(l, n))
164
+ const { error: s, data: n, showToClient: i = !1, style: o, visibility: l } = t ?? {}, d = s ? kt(e, s) : `[TraceLog] ${e}`, c = r === "error" ? "error" : r === "warn" ? "warn" : "log";
165
+ if (!Ut(l, i))
166
166
  return;
167
- const g = Ft(l, o), I = i !== void 0 ? Ie(i) : void 0;
168
- Ht(d, c, g, I);
167
+ const g = Ft(l, o), m = n !== void 0 ? _e(n) : void 0;
168
+ Ht(c, d, g, m);
169
169
  }, Ut = (r, e) => r === "critical" ? !0 : r === "qa" || e ? Vt() : !1, Ft = (r, e) => e !== void 0 && e !== "" ? e : r === "critical" ? Dt : "", Ht = (r, e, t, s) => {
170
- const i = t !== void 0 && t !== "", n = i ? `%c${e}` : e;
171
- s !== void 0 ? i ? console[r](n, t, s) : console[r](n, s) : i ? console[r](n, t) : console[r](n);
172
- }, Ie = (r) => {
170
+ const n = t !== void 0 && t !== "", i = n ? `%c${e}` : e;
171
+ s !== void 0 ? n ? console[r](i, t, s) : console[r](i, s) : n ? console[r](i, t) : console[r](i);
172
+ }, _e = (r) => {
173
173
  const e = {}, t = ["token", "password", "secret", "key", "apikey", "api_key", "sessionid", "session_id"];
174
- for (const [s, i] of Object.entries(r)) {
175
- const n = s.toLowerCase();
176
- if (t.some((o) => n.includes(o))) {
174
+ for (const [s, n] of Object.entries(r)) {
175
+ const i = s.toLowerCase();
176
+ if (t.some((o) => i.includes(o))) {
177
177
  e[s] = "[REDACTED]";
178
178
  continue;
179
179
  }
180
- i !== null && typeof i == "object" && !Array.isArray(i) ? e[s] = Ie(i) : Array.isArray(i) ? e[s] = i.map(
181
- (o) => o !== null && typeof o == "object" && !Array.isArray(o) ? Ie(o) : o
182
- ) : e[s] = i;
180
+ n !== null && typeof n == "object" && !Array.isArray(n) ? e[s] = _e(n) : Array.isArray(n) ? e[s] = n.map(
181
+ (o) => o !== null && typeof o == "object" && !Array.isArray(o) ? _e(o) : o
182
+ ) : e[s] = n;
183
183
  }
184
184
  return e;
185
185
  };
@@ -201,10 +201,10 @@ const xt = () => {
201
201
  }, Bt = (r) => {
202
202
  const e = r.userAgentData?.brands;
203
203
  if (e != null && e.length > 0) {
204
- const i = e.filter((n) => !/not.?a.?brand|chromium/i.test(n.brand))[0];
205
- if (i != null) {
206
- const n = i.brand;
207
- return /google chrome/i.test(n) ? "Chrome" : /microsoft edge/i.test(n) ? "Edge" : /opera/i.test(n) ? "Opera" : n;
204
+ const n = e.filter((i) => !/not.?a.?brand|chromium/i.test(i.brand))[0];
205
+ if (n != null) {
206
+ const i = n.brand;
207
+ return /google chrome/i.test(i) ? "Chrome" : /microsoft edge/i.test(i) ? "Edge" : /opera/i.test(i) ? "Opera" : i;
208
208
  }
209
209
  }
210
210
  const t = navigator.userAgent;
@@ -213,16 +213,16 @@ const xt = () => {
213
213
  try {
214
214
  const r = navigator;
215
215
  if (r.userAgentData != null && typeof r.userAgentData.mobile == "boolean") {
216
- const c = r.userAgentData.platform;
217
- return c != null && c !== "" && /ipad|tablet/i.test(c) ? A.Tablet : r.userAgentData.mobile ? A.Mobile : A.Desktop;
216
+ const d = r.userAgentData.platform;
217
+ return d != null && d !== "" && /ipad|tablet/i.test(d) ? A.Tablet : r.userAgentData.mobile ? A.Mobile : A.Desktop;
218
218
  }
219
219
  xt();
220
- const e = window.innerWidth, t = ve?.matches ?? !1, s = ot?.matches ?? !1, i = "ontouchstart" in window || navigator.maxTouchPoints > 0, n = navigator.userAgent.toLowerCase(), o = /mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(n), l = /tablet|ipad|android(?!.*mobile)/.test(n);
221
- return e <= 767 || o && i ? A.Mobile : e >= 768 && e <= 1024 || l || t && s && i ? A.Tablet : A.Desktop;
220
+ const e = window.innerWidth, t = ve?.matches ?? !1, s = ot?.matches ?? !1, n = "ontouchstart" in window || navigator.maxTouchPoints > 0, i = navigator.userAgent.toLowerCase(), o = /mobile|android|iphone|ipod|blackberry|iemobile|opera mini/.test(i), l = /tablet|ipad|android(?!.*mobile)/.test(i);
221
+ return e <= 767 || o && n ? A.Mobile : e >= 768 && e <= 1024 || l || t && s && n ? A.Tablet : A.Desktop;
222
222
  } catch (r) {
223
223
  return a("debug", "Device detection failed, defaulting to desktop", { error: r }), A.Desktop;
224
224
  }
225
- }, Xt = () => {
225
+ }, Gt = () => {
226
226
  try {
227
227
  const r = navigator;
228
228
  return {
@@ -254,7 +254,7 @@ const xt = () => {
254
254
  /:\/\/[^:/]+:([^@]+)@/gi,
255
255
  // Sensitive URL query parameters (token=, password=, auth=, secret=, api_key=, etc.)
256
256
  /[?&](token|password|passwd|auth|secret|secret_key|private_key|auth_key|api_key|apikey|access_token)=[^&\s]+/gi
257
- ], Xe = 500, Ge = 2e3, je = 5e3, ee = 50, Gt = ee * 2, lt = 1, jt = 1e3, zt = 10, ze = 5e3, Kt = 6e4, Qt = 64, wr = {
257
+ ], Ge = 500, Xe = 2e3, je = 5e3, ee = 50, Xt = ee * 2, lt = 1, jt = 1e3, Kt = 10, Ke = 5e3, zt = 6e4, Qt = 64, br = {
258
258
  LCP: 2500,
259
259
  // Good: ≤ 2.5s
260
260
  FCP: 1800,
@@ -266,7 +266,7 @@ const xt = () => {
266
266
  TTFB: 800,
267
267
  // Good: ≤ 800ms
268
268
  LONG_TASK: 50
269
- }, Ke = {
269
+ }, ze = {
270
270
  LCP: 2500,
271
271
  // Needs improvement: > 2.5s (same as good boundary)
272
272
  FCP: 1800,
@@ -290,19 +290,19 @@ const xt = () => {
290
290
  TTFB: 1800,
291
291
  // Poor: > 1800ms
292
292
  LONG_TASK: 50
293
- }, _e = "needs-improvement", Qe = (r = _e) => {
293
+ }, ye = "needs-improvement", Qe = (r = ye) => {
294
294
  switch (r) {
295
295
  case "all":
296
296
  return { LCP: 0, FCP: 0, CLS: 0, INP: 0, TTFB: 0, LONG_TASK: 0 };
297
297
  // Track everything
298
298
  case "needs-improvement":
299
- return Ke;
299
+ return ze;
300
300
  case "poor":
301
301
  return Yt;
302
302
  default:
303
- return Ke;
303
+ return ze;
304
304
  }
305
- }, qt = 1e3, Jt = 50, Zt = "2.8.4", es = Zt, ct = () => typeof window < "u" && typeof sessionStorage < "u", ts = () => {
305
+ }, qt = 1e3, Jt = 50, Zt = "2.9.0", es = Zt, ct = () => typeof window < "u" && typeof sessionStorage < "u", ts = () => {
306
306
  try {
307
307
  const r = new URLSearchParams(window.location.search);
308
308
  r.delete(rt);
@@ -314,14 +314,14 @@ const xt = () => {
314
314
  if (!ct())
315
315
  return !1;
316
316
  try {
317
- const e = new URLSearchParams(window.location.search).get(rt), t = sessionStorage.getItem(X);
317
+ const e = new URLSearchParams(window.location.search).get(rt), t = sessionStorage.getItem(G);
318
318
  let s = null;
319
- return e === Ue ? (s = !0, sessionStorage.setItem(X, "true"), a("info", "QA Mode ACTIVE", {
320
- visibility: "qa",
321
- style: it
322
- })) : e === Fe && (s = !1, sessionStorage.setItem(X, "false"), a("info", "QA Mode DISABLED", {
319
+ return e === Ue ? (s = !0, sessionStorage.setItem(G, "true"), a("info", "QA Mode ACTIVE", {
323
320
  visibility: "qa",
324
321
  style: nt
322
+ })) : e === Fe && (s = !1, sessionStorage.setItem(G, "false"), a("info", "QA Mode DISABLED", {
323
+ visibility: "qa",
324
+ style: it
325
325
  })), (e === Ue || e === Fe) && ts(), s ?? t === "true";
326
326
  } catch {
327
327
  return !1;
@@ -329,14 +329,14 @@ const xt = () => {
329
329
  }, rs = (r) => {
330
330
  if (ct())
331
331
  try {
332
- sessionStorage.setItem(X, r ? "true" : "false"), a("info", r ? "QA Mode ACTIVE" : "QA Mode DISABLED", {
332
+ sessionStorage.setItem(G, r ? "true" : "false"), a("info", r ? "QA Mode ACTIVE" : "QA Mode DISABLED", {
333
333
  visibility: "qa",
334
- style: r ? it : nt
334
+ style: r ? nt : it
335
335
  });
336
336
  } catch {
337
337
  a("debug", "Cannot set QA mode: sessionStorage unavailable");
338
338
  }
339
- }, is = [
339
+ }, ns = [
340
340
  "co.uk",
341
341
  "org.uk",
342
342
  "com.au",
@@ -353,24 +353,24 @@ const xt = () => {
353
353
  if (e.length <= 2)
354
354
  return r.toLowerCase();
355
355
  const t = e.slice(-2).join(".");
356
- return is.includes(t) ? e.slice(-3).join(".") : e.slice(-2).join(".");
357
- }, ns = (r, e) => r === e ? !0 : Ye(r) === Ye(e), me = () => {
356
+ return ns.includes(t) ? e.slice(-3).join(".") : e.slice(-2).join(".");
357
+ }, is = (r, e) => r === e ? !0 : Ye(r) === Ye(e), ge = () => {
358
358
  const r = document.referrer;
359
359
  if (!r)
360
360
  return "Direct";
361
361
  try {
362
362
  const e = new URL(r).hostname.toLowerCase(), t = window.location.hostname.toLowerCase();
363
- return ns(e, t) ? "Direct" : r;
363
+ return is(e, t) ? "Direct" : r;
364
364
  } catch (e) {
365
365
  return a("debug", "Failed to parse referrer URL, using raw value", { error: e, data: { referrer: r } }), r;
366
366
  }
367
- }, ge = () => {
367
+ }, pe = () => {
368
368
  const r = new URLSearchParams(window.location.search), e = {};
369
369
  return Lt.forEach((s) => {
370
- const i = r.get(s);
371
- if (i) {
372
- const n = s.split("utm_")[1];
373
- e[n] = i;
370
+ const n = r.get(s);
371
+ if (n) {
372
+ const i = s.split("utm_")[1];
373
+ e[i] = n;
374
374
  }
375
375
  }), Object.keys(e).length ? e : void 0;
376
376
  }, dt = () => typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (r) => {
@@ -386,15 +386,15 @@ const os = () => {
386
386
  try {
387
387
  if (typeof crypto < "u" && crypto.getRandomValues) {
388
388
  const s = crypto.getRandomValues(new Uint8Array(3));
389
- s && (t = Array.from(s, (i) => i.toString(16).padStart(2, "0")).join(""));
389
+ s && (t = Array.from(s, (n) => n.toString(16).padStart(2, "0")).join(""));
390
390
  }
391
391
  } catch {
392
392
  }
393
393
  return t || (t = Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")), `${r}-${e}-${t}`;
394
394
  }, ut = (r, e = !1) => {
395
395
  try {
396
- const t = new URL(r), s = t.protocol === "https:", i = t.protocol === "http:";
397
- return s || e && i;
396
+ const t = new URL(r), s = t.protocol === "https:", n = t.protocol === "http:";
397
+ return s || e && n;
398
398
  } catch {
399
399
  return !1;
400
400
  }
@@ -412,13 +412,13 @@ const os = () => {
412
412
  throw new Error("Invalid hostname structure");
413
413
  if (s.length === 1)
414
414
  throw new Error("Single-part domain not supported for SaaS integration");
415
- let i;
416
- if (s.length === 2 ? i = s.join(".") : i = s.slice(-2).join("."), !i || i.split(".").length < 2)
415
+ let n;
416
+ if (s.length === 2 ? n = s.join(".") : n = s.slice(-2).join("."), !n || n.split(".").length < 2)
417
417
  throw new Error("Invalid domain structure for SaaS");
418
- const n = `https://${r}.${i}/collect`;
419
- if (!ut(n))
418
+ const i = `https://${r}.${n}/collect`;
419
+ if (!ut(i))
420
420
  throw new Error("Generated URL failed validation");
421
- return n;
421
+ return i;
422
422
  } catch (e) {
423
423
  throw new Error(`Invalid SaaS URL configuration: ${e instanceof Error ? e.message : String(e)}`);
424
424
  }
@@ -433,16 +433,16 @@ const os = () => {
433
433
  e.custom = t;
434
434
  }
435
435
  return e;
436
- }, ye = (r, e = []) => {
436
+ }, we = (r, e = []) => {
437
437
  if (!r || typeof r != "string")
438
438
  return a("warn", "Invalid URL provided to normalizeUrl", { data: { type: typeof r } }), r || "";
439
439
  try {
440
- const t = new URL(r), s = t.searchParams, i = [.../* @__PURE__ */ new Set([...At, ...e])];
441
- let n = !1;
440
+ const t = new URL(r), s = t.searchParams, n = [.../* @__PURE__ */ new Set([...At, ...e])];
441
+ let i = !1;
442
442
  const o = [];
443
- return i.forEach((c) => {
444
- s.has(c) && (s.delete(c), n = !0, o.push(c));
445
- }), !n && r.includes("?") ? r : (t.search = s.toString(), t.toString());
443
+ return n.forEach((d) => {
444
+ s.has(d) && (s.delete(d), i = !0, o.push(d));
445
+ }), !i && r.includes("?") ? r : (t.search = s.toString(), t.toString());
446
446
  } catch (t) {
447
447
  return a("warn", "URL normalization failed, returning original", { error: t, data: { urlLength: r?.length } }), r;
448
448
  }
@@ -452,9 +452,9 @@ const os = () => {
452
452
  let e = r;
453
453
  r.length > 1e3 && (e = r.slice(0, Math.max(0, 1e3)));
454
454
  let t = 0;
455
- for (const i of Mt) {
456
- const n = e;
457
- e = e.replace(i, ""), n !== e && t++;
455
+ for (const n of Mt) {
456
+ const i = e;
457
+ e = e.replace(n, ""), i !== e && t++;
458
458
  }
459
459
  return t > 0 && a("warn", "XSS patterns detected and removed", {
460
460
  data: {
@@ -462,7 +462,7 @@ const os = () => {
462
462
  valueLength: r.length
463
463
  }
464
464
  }), e.trim();
465
- }, we = (r, e = 0) => {
465
+ }, be = (r, e = 0) => {
466
466
  if (r == null)
467
467
  return null;
468
468
  if (typeof r == "string")
@@ -474,14 +474,14 @@ const os = () => {
474
474
  if (e > 10)
475
475
  return null;
476
476
  if (Array.isArray(r))
477
- return r.slice(0, 1e3).map((i) => we(i, e + 1)).filter((i) => i !== null);
477
+ return r.slice(0, 1e3).map((n) => be(n, e + 1)).filter((n) => n !== null);
478
478
  if (typeof r == "object") {
479
- const t = {}, i = Object.entries(r).slice(0, 200);
480
- for (const [n, o] of i) {
481
- const l = qe(n);
479
+ const t = {}, n = Object.entries(r).slice(0, 200);
480
+ for (const [i, o] of n) {
481
+ const l = qe(i);
482
482
  if (l) {
483
- const c = we(o, e + 1);
484
- c !== null && (t[l] = c);
483
+ const d = be(o, e + 1);
484
+ d !== null && (t[l] = d);
485
485
  }
486
486
  }
487
487
  return t;
@@ -491,7 +491,7 @@ const os = () => {
491
491
  if (typeof r != "object" || r === null)
492
492
  return {};
493
493
  try {
494
- const e = we(r);
494
+ const e = be(r);
495
495
  return typeof e == "object" && e !== null ? e : {};
496
496
  } catch (e) {
497
497
  const t = e instanceof Error ? e.message : String(e);
@@ -499,69 +499,69 @@ const os = () => {
499
499
  }
500
500
  }, ds = (r) => {
501
501
  if (r !== void 0 && (r === null || typeof r != "object"))
502
- throw new m("Configuration must be an object", "config");
502
+ throw new p("Configuration must be an object", "config");
503
503
  if (r) {
504
504
  if (r.sessionTimeout !== void 0 && (typeof r.sessionTimeout != "number" || r.sessionTimeout < 3e4 || r.sessionTimeout > 864e5))
505
- throw new Pt(E.INVALID_SESSION_TIMEOUT, "config");
505
+ throw new Pt(S.INVALID_SESSION_TIMEOUT, "config");
506
506
  if (r.globalMetadata !== void 0 && (typeof r.globalMetadata != "object" || r.globalMetadata === null))
507
- throw new m(E.INVALID_GLOBAL_METADATA, "config");
507
+ throw new p(S.INVALID_GLOBAL_METADATA, "config");
508
508
  if (r.integrations && hs(r.integrations), r.sensitiveQueryParams !== void 0) {
509
509
  if (!Array.isArray(r.sensitiveQueryParams))
510
- throw new m(E.INVALID_SENSITIVE_QUERY_PARAMS, "config");
510
+ throw new p(S.INVALID_SENSITIVE_QUERY_PARAMS, "config");
511
511
  for (const e of r.sensitiveQueryParams)
512
512
  if (typeof e != "string")
513
- throw new m("All sensitive query params must be strings", "config");
513
+ throw new p("All sensitive query params must be strings", "config");
514
514
  }
515
515
  if (r.errorSampling !== void 0 && (typeof r.errorSampling != "number" || r.errorSampling < 0 || r.errorSampling > 1))
516
- throw new We(E.INVALID_ERROR_SAMPLING_RATE, "config");
516
+ throw new We(S.INVALID_ERROR_SAMPLING_RATE, "config");
517
517
  if (r.samplingRate !== void 0 && (typeof r.samplingRate != "number" || r.samplingRate < 0 || r.samplingRate > 1))
518
- throw new We(E.INVALID_SAMPLING_RATE, "config");
518
+ throw new We(S.INVALID_SAMPLING_RATE, "config");
519
519
  if (r.primaryScrollSelector !== void 0) {
520
520
  if (typeof r.primaryScrollSelector != "string" || !r.primaryScrollSelector.trim())
521
- throw new m(E.INVALID_PRIMARY_SCROLL_SELECTOR, "config");
521
+ throw new p(S.INVALID_PRIMARY_SCROLL_SELECTOR, "config");
522
522
  if (r.primaryScrollSelector !== "window")
523
523
  try {
524
524
  document.querySelector(r.primaryScrollSelector);
525
525
  } catch {
526
- throw new m(
527
- `${E.INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX}: "${r.primaryScrollSelector}"`,
526
+ throw new p(
527
+ `${S.INVALID_PRIMARY_SCROLL_SELECTOR_SYNTAX}: "${r.primaryScrollSelector}"`,
528
528
  "config"
529
529
  );
530
530
  }
531
531
  }
532
532
  if (r.pageViewThrottleMs !== void 0 && (typeof r.pageViewThrottleMs != "number" || r.pageViewThrottleMs < 0))
533
- throw new m(E.INVALID_PAGE_VIEW_THROTTLE, "config");
533
+ throw new p(S.INVALID_PAGE_VIEW_THROTTLE, "config");
534
534
  if (r.clickThrottleMs !== void 0 && (typeof r.clickThrottleMs != "number" || r.clickThrottleMs < 0))
535
- throw new m(E.INVALID_CLICK_THROTTLE, "config");
535
+ throw new p(S.INVALID_CLICK_THROTTLE, "config");
536
536
  if (r.maxSameEventPerMinute !== void 0 && (typeof r.maxSameEventPerMinute != "number" || r.maxSameEventPerMinute <= 0))
537
- throw new m(E.INVALID_MAX_SAME_EVENT_PER_MINUTE, "config");
537
+ throw new p(S.INVALID_MAX_SAME_EVENT_PER_MINUTE, "config");
538
538
  if (r.sendIntervalMs !== void 0 && (!Number.isFinite(r.sendIntervalMs) || r.sendIntervalMs < 1e3 || r.sendIntervalMs > 6e4))
539
- throw new m(E.INVALID_SEND_INTERVAL, "config");
539
+ throw new p(S.INVALID_SEND_INTERVAL, "config");
540
540
  if (r.viewport !== void 0 && us(r.viewport), r.webVitalsMode !== void 0) {
541
541
  if (typeof r.webVitalsMode != "string")
542
- throw new m(
542
+ throw new p(
543
543
  `Invalid webVitalsMode type: ${typeof r.webVitalsMode}. Must be a string`,
544
544
  "config"
545
545
  );
546
546
  const e = ["all", "needs-improvement", "poor"];
547
547
  if (!e.includes(r.webVitalsMode))
548
- throw new m(
548
+ throw new p(
549
549
  `Invalid webVitalsMode: "${r.webVitalsMode}". Must be one of: ${e.join(", ")}`,
550
550
  "config"
551
551
  );
552
552
  }
553
553
  if (r.webVitalsThresholds !== void 0) {
554
554
  if (typeof r.webVitalsThresholds != "object" || r.webVitalsThresholds === null || Array.isArray(r.webVitalsThresholds))
555
- throw new m("webVitalsThresholds must be an object", "config");
555
+ throw new p("webVitalsThresholds must be an object", "config");
556
556
  const e = ["LCP", "FCP", "CLS", "INP", "TTFB", "LONG_TASK"];
557
557
  for (const [t, s] of Object.entries(r.webVitalsThresholds)) {
558
558
  if (!e.includes(t))
559
- throw new m(
559
+ throw new p(
560
560
  `Invalid Web Vitals threshold key: "${t}". Must be one of: ${e.join(", ")}`,
561
561
  "config"
562
562
  );
563
563
  if (typeof s != "number" || !Number.isFinite(s) || s < 0)
564
- throw new m(
564
+ throw new p(
565
565
  `Invalid Web Vitals threshold value for ${t}: ${s}. Must be a non-negative finite number`,
566
566
  "config"
567
567
  );
@@ -570,41 +570,41 @@ const os = () => {
570
570
  }
571
571
  }, us = (r) => {
572
572
  if (typeof r != "object" || r === null)
573
- throw new m(E.INVALID_VIEWPORT_CONFIG, "config");
573
+ throw new p(S.INVALID_VIEWPORT_CONFIG, "config");
574
574
  if (!r.elements || !Array.isArray(r.elements))
575
- throw new m(E.INVALID_VIEWPORT_ELEMENTS, "config");
575
+ throw new p(S.INVALID_VIEWPORT_ELEMENTS, "config");
576
576
  if (r.elements.length === 0)
577
- throw new m(E.INVALID_VIEWPORT_ELEMENTS, "config");
577
+ throw new p(S.INVALID_VIEWPORT_ELEMENTS, "config");
578
578
  const e = /* @__PURE__ */ new Set();
579
579
  for (const t of r.elements) {
580
580
  if (!t.selector || typeof t.selector != "string" || !t.selector.trim())
581
- throw new m(E.INVALID_VIEWPORT_ELEMENT, "config");
581
+ throw new p(S.INVALID_VIEWPORT_ELEMENT, "config");
582
582
  const s = t.selector.trim();
583
583
  if (e.has(s))
584
- throw new m(
584
+ throw new p(
585
585
  `Duplicate viewport selector found: "${s}". Each selector should appear only once.`,
586
586
  "config"
587
587
  );
588
588
  if (e.add(s), t.id !== void 0 && (typeof t.id != "string" || !t.id.trim()))
589
- throw new m(E.INVALID_VIEWPORT_ELEMENT_ID, "config");
589
+ throw new p(S.INVALID_VIEWPORT_ELEMENT_ID, "config");
590
590
  if (t.name !== void 0 && (typeof t.name != "string" || !t.name.trim()))
591
- throw new m(E.INVALID_VIEWPORT_ELEMENT_NAME, "config");
591
+ throw new p(S.INVALID_VIEWPORT_ELEMENT_NAME, "config");
592
592
  }
593
593
  if (r.threshold !== void 0 && (typeof r.threshold != "number" || r.threshold < 0 || r.threshold > 1))
594
- throw new m(E.INVALID_VIEWPORT_THRESHOLD, "config");
594
+ throw new p(S.INVALID_VIEWPORT_THRESHOLD, "config");
595
595
  if (r.minDwellTime !== void 0 && (typeof r.minDwellTime != "number" || r.minDwellTime < 0))
596
- throw new m(E.INVALID_VIEWPORT_MIN_DWELL_TIME, "config");
596
+ throw new p(S.INVALID_VIEWPORT_MIN_DWELL_TIME, "config");
597
597
  if (r.cooldownPeriod !== void 0 && (typeof r.cooldownPeriod != "number" || r.cooldownPeriod < 0))
598
- throw new m(E.INVALID_VIEWPORT_COOLDOWN_PERIOD, "config");
598
+ throw new p(S.INVALID_VIEWPORT_COOLDOWN_PERIOD, "config");
599
599
  if (r.maxTrackedElements !== void 0 && (typeof r.maxTrackedElements != "number" || r.maxTrackedElements <= 0))
600
- throw new m(E.INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS, "config");
600
+ throw new p(S.INVALID_VIEWPORT_MAX_TRACKED_ELEMENTS, "config");
601
601
  }, hs = (r) => {
602
602
  if (r) {
603
603
  if (r.tracelog && (!r.tracelog.projectId || typeof r.tracelog.projectId != "string" || r.tracelog.projectId.trim() === ""))
604
- throw new N(E.INVALID_TRACELOG_PROJECT_ID, "config");
604
+ throw new N(S.INVALID_TRACELOG_PROJECT_ID, "config");
605
605
  if (r.custom) {
606
606
  if (!r.custom.collectApiUrl || typeof r.custom.collectApiUrl != "string" || r.custom.collectApiUrl.trim() === "")
607
- throw new N(E.INVALID_CUSTOM_API_URL, "config");
607
+ throw new N(S.INVALID_CUSTOM_API_URL, "config");
608
608
  if (r.custom.allowHttp !== void 0 && typeof r.custom.allowHttp != "boolean")
609
609
  throw new N("allowHttp must be a boolean", "config");
610
610
  const e = r.custom.collectApiUrl.trim();
@@ -645,12 +645,12 @@ const os = () => {
645
645
  cooldownPeriod: e.viewport.cooldownPeriod ?? 6e4,
646
646
  maxTrackedElements: e.viewport.maxTrackedElements ?? 100
647
647
  }), e;
648
- }, be = (r, e = /* @__PURE__ */ new Set()) => {
648
+ }, Le = (r, e = /* @__PURE__ */ new Set()) => {
649
649
  if (r == null)
650
650
  return !0;
651
651
  const t = typeof r;
652
- return t === "string" || t === "number" || t === "boolean" ? !0 : t === "function" || t === "symbol" || t === "bigint" || e.has(r) ? !1 : (e.add(r), Array.isArray(r) ? r.every((s) => be(s, e)) : t === "object" ? Object.values(r).every((s) => be(s, e)) : !1);
653
- }, ms = (r) => typeof r != "object" || r === null ? !1 : be(r), ht = (r) => {
652
+ return t === "string" || t === "number" || t === "boolean" ? !0 : t === "function" || t === "symbol" || t === "bigint" || e.has(r) ? !1 : (e.add(r), Array.isArray(r) ? r.every((s) => Le(s, e)) : t === "object" ? Object.values(r).every((s) => Le(s, e)) : !1);
653
+ }, ms = (r) => typeof r != "object" || r === null ? !1 : Le(r), ht = (r) => {
654
654
  if (typeof r != "object" || r === null || Array.isArray(r)) return;
655
655
  const e = {};
656
656
  for (const [t, s] of Object.entries(r))
@@ -672,49 +672,49 @@ const os = () => {
672
672
  valid: !1,
673
673
  error: "Event name cannot be a reserved word"
674
674
  } : { valid: !0 }, Je = (r, e, t) => {
675
- const s = cs(e), i = t && t === "customEvent" ? `${t} "${r}" metadata error` : `${r} metadata error`;
675
+ const s = cs(e), n = t && t === "customEvent" ? `${t} "${r}" metadata error` : `${r} metadata error`;
676
676
  if (!ms(s))
677
677
  return {
678
678
  valid: !1,
679
- error: `${i}: object has invalid types. Valid types are string, number, boolean or string arrays.`
679
+ error: `${n}: object has invalid types. Valid types are string, number, boolean or string arrays.`
680
680
  };
681
- let n;
681
+ let i;
682
682
  try {
683
- n = JSON.stringify(s);
683
+ i = JSON.stringify(s);
684
684
  } catch {
685
685
  return {
686
686
  valid: !1,
687
- error: `${i}: object contains circular references or cannot be serialized.`
687
+ error: `${n}: object contains circular references or cannot be serialized.`
688
688
  };
689
689
  }
690
- if (new TextEncoder().encode(n).byteLength > 49152)
690
+ if (new TextEncoder().encode(i).byteLength > 49152)
691
691
  return {
692
692
  valid: !1,
693
- error: `${i}: object is too large (max ${49152 / 1024} KB).`
693
+ error: `${n}: object is too large (max ${49152 / 1024} KB).`
694
694
  };
695
695
  if (Object.keys(s).length > 100)
696
696
  return {
697
697
  valid: !1,
698
- error: `${i}: object has too many keys (max 100 keys).`
698
+ error: `${n}: object has too many keys (max 100 keys).`
699
699
  };
700
- for (const [c, d] of Object.entries(s)) {
701
- if (Array.isArray(d)) {
702
- if (d.length > 500)
700
+ for (const [d, c] of Object.entries(s)) {
701
+ if (Array.isArray(c)) {
702
+ if (c.length > 500)
703
703
  return {
704
704
  valid: !1,
705
- error: `${i}: array property "${c}" is too large (max 500 items).`
705
+ error: `${n}: array property "${d}" is too large (max 500 items).`
706
706
  };
707
- for (const f of d)
707
+ for (const f of c)
708
708
  if (typeof f == "string" && f.length > 500)
709
709
  return {
710
710
  valid: !1,
711
- error: `${i}: array property "${c}" contains strings that are too long (max 500 characters).`
711
+ error: `${n}: array property "${d}" contains strings that are too long (max 500 characters).`
712
712
  };
713
713
  }
714
- if (typeof d == "string" && d.length > 1e3)
714
+ if (typeof c == "string" && c.length > 1e3)
715
715
  return {
716
716
  valid: !1,
717
- error: `${i}: property "${c}" is too long (max 1000 characters).`
717
+ error: `${n}: property "${d}" is too long (max 1000 characters).`
718
718
  };
719
719
  }
720
720
  return {
@@ -723,19 +723,19 @@ const os = () => {
723
723
  };
724
724
  }, ft = (r, e, t) => {
725
725
  if (Array.isArray(e)) {
726
- const s = [], i = t && t === "customEvent" ? `${t} "${r}" metadata error` : `${r} metadata error`;
727
- for (let n = 0; n < e.length; n++) {
728
- const o = e[n];
726
+ const s = [], n = t && t === "customEvent" ? `${t} "${r}" metadata error` : `${r} metadata error`;
727
+ for (let i = 0; i < e.length; i++) {
728
+ const o = e[i];
729
729
  if (typeof o != "object" || o === null || Array.isArray(o))
730
730
  return {
731
731
  valid: !1,
732
- error: `${i}: array item at index ${n} must be an object.`
732
+ error: `${n}: array item at index ${i} must be an object.`
733
733
  };
734
734
  const l = Je(r, o, t);
735
735
  if (!l.valid)
736
736
  return {
737
737
  valid: !1,
738
- error: `${i}: array item at index ${n} is invalid: ${l.error}`
738
+ error: `${n}: array item at index ${i} is invalid: ${l.error}`
739
739
  };
740
740
  l.sanitizedMetadata && s.push(l.sanitizedMetadata);
741
741
  }
@@ -745,7 +745,7 @@ const os = () => {
745
745
  };
746
746
  }
747
747
  return Je(r, e, t);
748
- }, Es = (r, e) => {
748
+ }, ps = (r, e) => {
749
749
  const t = gs(r);
750
750
  if (!t.valid)
751
751
  return a("error", "Event name validation failed", {
@@ -761,7 +761,7 @@ const os = () => {
761
761
  }
762
762
  }), s;
763
763
  };
764
- class ps {
764
+ class Es {
765
765
  listeners = /* @__PURE__ */ new Map();
766
766
  /**
767
767
  * Subscribes to an event channel
@@ -814,8 +814,8 @@ class ps {
814
814
  off(e, t) {
815
815
  const s = this.listeners.get(e);
816
816
  if (s) {
817
- const i = s.indexOf(t);
818
- i > -1 && s.splice(i, 1);
817
+ const n = s.indexOf(t);
818
+ n > -1 && s.splice(n, 1);
819
819
  }
820
820
  }
821
821
  /**
@@ -848,8 +848,8 @@ class ps {
848
848
  */
849
849
  emit(e, t) {
850
850
  const s = this.listeners.get(e);
851
- s && s.forEach((i) => {
852
- i(t);
851
+ s && s.forEach((n) => {
852
+ n(t);
853
853
  });
854
854
  }
855
855
  /**
@@ -909,7 +909,7 @@ function gt(r, e, t) {
909
909
  }
910
910
  }
911
911
  const Ee = { config: {} };
912
- class _ {
912
+ class v {
913
913
  /**
914
914
  * Retrieves a value from global state.
915
915
  *
@@ -967,7 +967,7 @@ class _ {
967
967
  return { ...Ee };
968
968
  }
969
969
  }
970
- class Ze extends _ {
970
+ class Ze extends v {
971
971
  storeManager;
972
972
  integrationId;
973
973
  apiUrl;
@@ -1016,10 +1016,10 @@ class Ze extends _ {
1016
1016
  * @param customHeadersProvider - Optional callback for dynamic headers
1017
1017
  * @throws Error if integrationId and apiUrl are not both provided or both undefined
1018
1018
  */
1019
- constructor(e, t, s, i = {}, n = {}, o, l = "include") {
1019
+ constructor(e, t, s, n = {}, i = {}, o, l = "include") {
1020
1020
  if (super(), t && !s || !t && s)
1021
1021
  throw new Error("SenderManager: integrationId and apiUrl must either both be provided or both be undefined");
1022
- this.storeManager = e, this.integrationId = t, this.apiUrl = s, this.transformers = i, this.staticHeaders = n, this.customHeadersProvider = o, this.fetchCredentials = l, this.rateLimitedUntil = this.loadRateLimitCooldown();
1022
+ this.storeManager = e, this.integrationId = t, this.apiUrl = s, this.transformers = n, this.staticHeaders = i, this.customHeadersProvider = o, this.fetchCredentials = l, this.rateLimitedUntil = this.loadRateLimitCooldown();
1023
1023
  }
1024
1024
  /**
1025
1025
  * Get the integration ID for this sender
@@ -1100,8 +1100,8 @@ class Ze extends _ {
1100
1100
  try {
1101
1101
  const s = this.storeManager.getItem(t);
1102
1102
  if (s) {
1103
- const i = Number(s);
1104
- if (Number.isFinite(i) && i >= e)
1103
+ const n = Number(s);
1104
+ if (Number.isFinite(n) && n >= e)
1105
1105
  return;
1106
1106
  }
1107
1107
  this.storeManager.setItem(t, String(e));
@@ -1181,8 +1181,8 @@ class Ze extends _ {
1181
1181
  }
1182
1182
  }
1183
1183
  );
1184
- const t = this.ensureBatchMetadata(e), s = this.getPersistedData(), i = typeof s?.recoveryFailures == "number" && Number.isFinite(s.recoveryFailures) ? s.recoveryFailures : 0;
1185
- return this.persistEventsWithFailureCount(t, i, !0), !1;
1184
+ const t = this.ensureBatchMetadata(e), s = this.getPersistedData(), n = typeof s?.recoveryFailures == "number" && Number.isFinite(s.recoveryFailures) ? s.recoveryFailures : 0;
1185
+ return this.persistEventsWithFailureCount(t, n, !0), !1;
1186
1186
  }
1187
1187
  return this.apiUrl?.includes($.Fail) ? (a(
1188
1188
  "warn",
@@ -1231,10 +1231,10 @@ class Ze extends _ {
1231
1231
  async sendEventsQueue(e, t) {
1232
1232
  const s = this.ensureBatchMetadata(e);
1233
1233
  try {
1234
- const i = await this.send(s);
1235
- return i ? (this.clearPersistedEvents(), t?.onSuccess?.(s.events.length, s.events, s)) : (this.persistEvents(s), t?.onFailure?.()), i;
1236
- } catch (i) {
1237
- return i instanceof O ? (this.logPermanentError("Permanent error, not retrying", i), this.clearPersistedEvents(), t?.onFailure?.(), !1) : (this.persistEvents(s), t?.onFailure?.(), !1);
1234
+ const n = await this.send(s);
1235
+ return n ? (this.clearPersistedEvents(), t?.onSuccess?.(s.events.length, s.events, s)) : (this.persistEvents(s), t?.onFailure?.()), n;
1236
+ } catch (n) {
1237
+ return n instanceof O ? (this.logPermanentError("Permanent error, not retrying", n), this.clearPersistedEvents(), t?.onFailure?.(), !1) : (this.persistEvents(s), t?.onFailure?.(), !1);
1238
1238
  }
1239
1239
  }
1240
1240
  /**
@@ -1294,13 +1294,13 @@ class Ze extends _ {
1294
1294
  this.recoveryInProgress = !0;
1295
1295
  let t = null, s = 0;
1296
1296
  try {
1297
- const i = this.getPersistedData();
1298
- if (!i || !this.isDataRecent(i) || i.events.length === 0) {
1297
+ const n = this.getPersistedData();
1298
+ if (!n || !this.isDataRecent(n) || n.events.length === 0) {
1299
1299
  this.clearPersistedEvents();
1300
1300
  return;
1301
1301
  }
1302
- const n = i.recoveryFailures;
1303
- if (s = typeof n == "number" && Number.isFinite(n) && n >= 0 ? n : 0, s >= 3) {
1302
+ const i = n.recoveryFailures;
1303
+ if (s = typeof i == "number" && Number.isFinite(i) && i >= 0 ? i : 0, s >= 3) {
1304
1304
  a(
1305
1305
  "debug",
1306
1306
  `Discarding persisted events after ${s} failed recovery attempts${this.integrationId ? ` [${this.integrationId}]` : ""}`
@@ -1317,13 +1317,13 @@ class Ze extends _ {
1317
1317
  ), e?.onFailure?.();
1318
1318
  return;
1319
1319
  }
1320
- t = this.ensureBatchMetadata(this.createRecoveryBody(i)), await this.send(t) ? (this.clearPersistedEvents(), e?.onSuccess?.(i.events.length, i.events, t)) : (this.persistEventsWithFailureCount(t, s + 1, !0), e?.onFailure?.());
1321
- } catch (i) {
1322
- if (i instanceof O) {
1323
- this.logPermanentError("Permanent error during recovery, clearing persisted events", i), this.clearPersistedEvents(), e?.onFailure?.();
1320
+ t = this.ensureBatchMetadata(this.createRecoveryBody(n)), await this.send(t) ? (this.clearPersistedEvents(), e?.onSuccess?.(n.events.length, n.events, t)) : (this.persistEventsWithFailureCount(t, s + 1, !0), e?.onFailure?.());
1321
+ } catch (n) {
1322
+ if (n instanceof O) {
1323
+ this.logPermanentError("Permanent error during recovery, clearing persisted events", n), this.clearPersistedEvents(), e?.onFailure?.();
1324
1324
  return;
1325
1325
  }
1326
- a("error", "Failed to recover persisted events", { error: i }), t && this.persistEventsWithFailureCount(t, s + 1, !0), e?.onFailure?.();
1326
+ a("error", "Failed to recover persisted events", { error: n }), t && this.persistEventsWithFailureCount(t, s + 1, !0), e?.onFailure?.();
1327
1327
  } finally {
1328
1328
  this.recoveryInProgress = !1;
1329
1329
  }
@@ -1440,8 +1440,8 @@ class Ze extends _ {
1440
1440
  * @returns Promise that resolves after calculated delay
1441
1441
  */
1442
1442
  async backoffDelay(e) {
1443
- const t = 100 * Math.pow(2, e), s = Math.random() * 100, i = t + s;
1444
- return new Promise((n) => setTimeout(n, i));
1443
+ const t = 100 * Math.pow(2, e), s = Math.random() * 100, n = t + s;
1444
+ return new Promise((i) => setTimeout(i, n));
1445
1445
  }
1446
1446
  /**
1447
1447
  * Sends event queue with automatic retry logic for transient failures.
@@ -1486,76 +1486,76 @@ class Ze extends _ {
1486
1486
  const s = this.applyBeforeBatchTransformer(t);
1487
1487
  if (!s)
1488
1488
  return !0;
1489
- const i = this.ensureBatchMetadata(s, e._metadata?.idempotency_token);
1489
+ const n = this.ensureBatchMetadata(s, e._metadata?.idempotency_token);
1490
1490
  if (this.apiUrl?.includes($.Fail))
1491
1491
  return a("debug", `Fail mode: simulating network failure${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1492
- data: { events: i.events.length }
1492
+ data: { events: n.events.length }
1493
1493
  }), !1;
1494
1494
  if (this.apiUrl?.includes($.Localhost))
1495
1495
  return a("debug", `Success mode: simulating successful send${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1496
- data: { events: i.events.length }
1496
+ data: { events: n.events.length }
1497
1497
  }), !0;
1498
1498
  if (this.isRateLimited())
1499
1499
  return a("debug", `Rate-limit cooldown active, skipping send${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1500
1500
  data: {
1501
1501
  cooldownRemainingMs: this.rateLimitedUntil - Date.now(),
1502
- events: i.events.length
1502
+ events: n.events.length
1503
1503
  }
1504
1504
  }), !1;
1505
1505
  if (this.consecutiveNetworkFailures >= 3) {
1506
- const d = Date.now() - this.circuitOpenedAt;
1507
- if (d < 12e4)
1506
+ const c = Date.now() - this.circuitOpenedAt;
1507
+ if (c < 12e4)
1508
1508
  return a("debug", `Network circuit open, skipping send${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1509
1509
  data: {
1510
1510
  consecutiveNetworkFailures: this.consecutiveNetworkFailures,
1511
- cooldownRemainingMs: 12e4 - d
1511
+ cooldownRemainingMs: 12e4 - c
1512
1512
  }
1513
1513
  }), !1;
1514
1514
  }
1515
- const { url: n, payload: o } = this.prepareRequest(i);
1516
- let l = !0, c = !1;
1517
- for (let d = 1; d <= 3; d++)
1515
+ const { url: i, payload: o } = this.prepareRequest(n);
1516
+ let l = !0, d = !1;
1517
+ for (let c = 1; c <= 3; c++)
1518
1518
  try {
1519
- return (await this.sendWithTimeout(n, o)).ok ? (d > 1 && a(
1519
+ return (await this.sendWithTimeout(i, o)).ok ? (c > 1 && a(
1520
1520
  "info",
1521
- `Send succeeded after ${d - 1} retry attempt(s)${this.integrationId ? ` [${this.integrationId}]` : ""}`,
1521
+ `Send succeeded after ${c - 1} retry attempt(s)${this.integrationId ? ` [${this.integrationId}]` : ""}`,
1522
1522
  {
1523
- data: { events: i.events.length, attempt: d }
1523
+ data: { events: n.events.length, attempt: c }
1524
1524
  }
1525
1525
  ), this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0, !0) : !1;
1526
1526
  } catch (f) {
1527
- const g = d === 3;
1527
+ const g = c === 3;
1528
1528
  if (f instanceof O)
1529
1529
  throw this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0, f;
1530
1530
  if (f instanceof re) {
1531
- this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0, l = !1, c = !0, this.armRateLimitCooldown(Date.now() + 6e4), a("warn", `Rate limited, skipping retries${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1532
- data: { events: e.events.length, attempt: d, cooldownMs: 6e4 }
1531
+ this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0, l = !1, d = !0, this.armRateLimitCooldown(Date.now() + 6e4), a("warn", `Rate limited, skipping retries${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1532
+ data: { events: e.events.length, attempt: c, cooldownMs: 6e4 }
1533
1533
  });
1534
1534
  break;
1535
1535
  }
1536
- if (f instanceof ie || (l = !1), f instanceof TypeError || (c = !0), a(
1536
+ if (f instanceof ne || (l = !1), f instanceof TypeError || (d = !0), a(
1537
1537
  g ? "error" : "warn",
1538
- `Send attempt ${d} failed${this.integrationId ? ` [${this.integrationId}]` : ""}${g ? " (all retries exhausted)" : ", will retry"}`,
1538
+ `Send attempt ${c} failed${this.integrationId ? ` [${this.integrationId}]` : ""}${g ? " (all retries exhausted)" : ", will retry"}`,
1539
1539
  {
1540
1540
  error: f,
1541
1541
  data: {
1542
1542
  events: e.events.length,
1543
- url: n.replace(/\/\/[^/]+/, "//[DOMAIN]"),
1544
- attempt: d,
1543
+ url: i.replace(/\/\/[^/]+/, "//[DOMAIN]"),
1544
+ attempt: c,
1545
1545
  maxAttempts: 3
1546
1546
  }
1547
1547
  }
1548
1548
  ), !g) {
1549
- await this.backoffDelay(d);
1549
+ await this.backoffDelay(c);
1550
1550
  continue;
1551
1551
  }
1552
1552
  return l ? (a(
1553
1553
  "debug",
1554
1554
  `All retry attempts timed out, preserving batch for retry${this.integrationId ? ` [${this.integrationId}]` : ""}`,
1555
1555
  {
1556
- data: { events: i.events.length }
1556
+ data: { events: n.events.length }
1557
1557
  }
1558
- ), !1) : (c ? (this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0) : (this.consecutiveNetworkFailures = Math.min(
1558
+ ), !1) : (d ? (this.consecutiveNetworkFailures = 0, this.circuitOpenedAt = 0) : (this.consecutiveNetworkFailures = Math.min(
1559
1559
  this.consecutiveNetworkFailures + 1,
1560
1560
  3
1561
1561
  ), this.consecutiveNetworkFailures >= 3 && (this.circuitOpenedAt = Date.now())), !1);
@@ -1588,9 +1588,9 @@ class Ze extends _ {
1588
1588
  async sendWithTimeout(e, t) {
1589
1589
  const s = new AbortController();
1590
1590
  this.pendingControllers.add(s);
1591
- let i = !1;
1592
- const n = setTimeout(() => {
1593
- i = !0, s.abort();
1591
+ let n = !1;
1592
+ const i = setTimeout(() => {
1593
+ n = !0, s.abort();
1594
1594
  }, 15e3);
1595
1595
  try {
1596
1596
  const o = this.getCustomHeaders(), l = await fetch(e, {
@@ -1606,16 +1606,16 @@ class Ze extends _ {
1606
1606
  });
1607
1607
  if (!l.ok) {
1608
1608
  if (l.status >= 400 && l.status < 500 && l.status !== 408 && l.status !== 429) {
1609
- const d = await this.readTraceLogErrorCode(l), f = d ? `HTTP ${l.status}: ${l.statusText} (${d})` : `HTTP ${l.status}: ${l.statusText}`;
1610
- throw new O(f, l.status, d);
1609
+ const c = await this.readTraceLogErrorCode(l), f = c ? `HTTP ${l.status}: ${l.statusText} (${c})` : `HTTP ${l.status}: ${l.statusText}`;
1610
+ throw new O(f, l.status, c);
1611
1611
  }
1612
1612
  throw l.status === 429 ? new re(`HTTP 429: ${l.statusText}`) : new Error(`HTTP ${l.status}: ${l.statusText}`);
1613
1613
  }
1614
1614
  return l;
1615
1615
  } catch (o) {
1616
- throw o instanceof O ? o : i ? new ie("Request timed out") : o;
1616
+ throw o instanceof O ? o : n ? new ne("Request timed out") : o;
1617
1617
  } finally {
1618
- clearTimeout(n), this.pendingControllers.delete(s);
1618
+ clearTimeout(i), this.pendingControllers.delete(s);
1619
1619
  }
1620
1620
  }
1621
1621
  /**
@@ -1662,10 +1662,10 @@ class Ze extends _ {
1662
1662
  const t = this.ensureBatchMetadata(e), s = this.applyBeforeSendTransformer(t);
1663
1663
  if (!s)
1664
1664
  return !0;
1665
- const i = this.applyBeforeBatchTransformer(s);
1666
- if (!i)
1665
+ const n = this.applyBeforeBatchTransformer(s);
1666
+ if (!n)
1667
1667
  return !0;
1668
- const n = this.ensureBatchMetadata(i, t._metadata?.idempotency_token), { url: o, payload: l } = this.prepareRequest(n);
1668
+ const i = this.ensureBatchMetadata(n, t._metadata?.idempotency_token), { url: o, payload: l } = this.prepareRequest(i);
1669
1669
  if (l.length > 65536)
1670
1670
  return a(
1671
1671
  "warn",
@@ -1674,21 +1674,21 @@ class Ze extends _ {
1674
1674
  data: {
1675
1675
  size: l.length,
1676
1676
  limit: 65536,
1677
- events: n.events.length
1677
+ events: i.events.length
1678
1678
  }
1679
1679
  }
1680
1680
  ), this.persistEvents(t), !1;
1681
- const c = new Blob([l], { type: "application/json" });
1681
+ const d = new Blob([l], { type: "application/json" });
1682
1682
  if (!this.isSendBeaconAvailable())
1683
1683
  return a(
1684
1684
  "warn",
1685
1685
  `sendBeacon not available, persisting events for recovery${this.integrationId ? ` [${this.integrationId}]` : ""}`
1686
1686
  ), this.persistEvents(t), !1;
1687
- const d = navigator.sendBeacon(o, c);
1688
- return d || (a(
1687
+ const c = navigator.sendBeacon(o, d);
1688
+ return c || (a(
1689
1689
  "warn",
1690
1690
  `sendBeacon rejected request, persisting events for recovery${this.integrationId ? ` [${this.integrationId}]` : ""}`
1691
- ), this.persistEvents(t)), d;
1691
+ ), this.persistEvents(t)), c;
1692
1692
  }
1693
1693
  /**
1694
1694
  * Prepares request by enriching payload with metadata and serializing to JSON.
@@ -1756,11 +1756,11 @@ class Ze extends _ {
1756
1756
  * @private
1757
1757
  */
1758
1758
  computeContentToken(e) {
1759
- const t = e.events.map((n) => n.id).sort().join(","), s = `${e.user_id}|${e.session_id}|${t}`;
1760
- let i = 2166136261;
1761
- for (let n = 0; n < s.length; n++)
1762
- i ^= s.charCodeAt(n), i = Math.imul(i, 16777619) >>> 0;
1763
- return i.toString(16).padStart(8, "0");
1759
+ const t = e.events.map((i) => i.id).sort().join(","), s = `${e.user_id}|${e.session_id}|${t}`;
1760
+ let n = 2166136261;
1761
+ for (let i = 0; i < s.length; i++)
1762
+ n ^= s.charCodeAt(i), n = Math.imul(n, 16777619) >>> 0;
1763
+ return n.toString(16).padStart(8, "0");
1764
1764
  }
1765
1765
  /**
1766
1766
  * Retrieves persisted events from localStorage with error recovery.
@@ -1810,8 +1810,8 @@ class Ze extends _ {
1810
1810
  * @private
1811
1811
  */
1812
1812
  createRecoveryBody(e) {
1813
- const { timestamp: t, recoveryFailures: s, ...i } = e;
1814
- return i;
1813
+ const { timestamp: t, recoveryFailures: s, ...n } = e;
1814
+ return n;
1815
1815
  }
1816
1816
  /**
1817
1817
  * Persists failed events to localStorage for next-page-load recovery.
@@ -1850,9 +1850,9 @@ class Ze extends _ {
1850
1850
  */
1851
1851
  persistEventsWithFailureCount(e, t, s = !1) {
1852
1852
  try {
1853
- const i = this.getPersistedData();
1854
- if (!s && i && i.timestamp) {
1855
- const l = Date.now() - i.timestamp;
1853
+ const n = this.getPersistedData();
1854
+ if (!s && n && n.timestamp) {
1855
+ const l = Date.now() - n.timestamp;
1856
1856
  if (l < 1e3)
1857
1857
  return a(
1858
1858
  "debug",
@@ -1862,14 +1862,14 @@ class Ze extends _ {
1862
1862
  }
1863
1863
  ), !0;
1864
1864
  }
1865
- const n = {
1865
+ const i = {
1866
1866
  ...e,
1867
1867
  timestamp: Date.now(),
1868
1868
  ...t > 0 && { recoveryFailures: t }
1869
1869
  }, o = this.getQueueStorageKey();
1870
- return this.storeManager.setItem(o, JSON.stringify(n)), !!this.storeManager.getItem(o);
1871
- } catch (i) {
1872
- return a("debug", `Failed to persist events${this.integrationId ? ` [${this.integrationId}]` : ""}`, { error: i }), !1;
1870
+ return this.storeManager.setItem(o, JSON.stringify(i)), !!this.storeManager.getItem(o);
1871
+ } catch (n) {
1872
+ return a("debug", `Failed to persist events${this.integrationId ? ` [${this.integrationId}]` : ""}`, { error: n }), !1;
1873
1873
  }
1874
1874
  }
1875
1875
  clearPersistedEvents() {
@@ -1893,13 +1893,13 @@ class Ze extends _ {
1893
1893
  return typeof navigator < "u" && typeof navigator.sendBeacon == "function";
1894
1894
  }
1895
1895
  logPermanentError(e, t) {
1896
- const s = Date.now(), i = `${t.statusCode ?? "unknown"}:${t.responseCode ?? ""}`;
1897
- (!this.lastPermanentErrorLog || this.lastPermanentErrorLog.key !== i || s - this.lastPermanentErrorLog.timestamp >= Kt) && (a("error", `${e}${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1896
+ const s = Date.now(), n = `${t.statusCode ?? "unknown"}:${t.responseCode ?? ""}`;
1897
+ (!this.lastPermanentErrorLog || this.lastPermanentErrorLog.key !== n || s - this.lastPermanentErrorLog.timestamp >= zt) && (a("error", `${e}${this.integrationId ? ` [${this.integrationId}]` : ""}`, {
1898
1898
  data: { status: t.statusCode, code: t.responseCode, message: t.message }
1899
- }), this.lastPermanentErrorLog = { key: i, timestamp: s });
1899
+ }), this.lastPermanentErrorLog = { key: n, timestamp: s });
1900
1900
  }
1901
1901
  }
1902
- class Ts extends _ {
1902
+ class Ts extends v {
1903
1903
  bootTime;
1904
1904
  bootTimestamp;
1905
1905
  hasPerformanceNow;
@@ -2026,10 +2026,10 @@ class Ts extends _ {
2026
2026
  * ```
2027
2027
  */
2028
2028
  validateTimestamp(e) {
2029
- const s = this.now(), i = e - s;
2030
- return i > 12e4 ? {
2029
+ const s = this.now(), n = e - s;
2030
+ return n > 12e4 ? {
2031
2031
  valid: !1,
2032
- error: `Timestamp is ${(i / 1e3 / 60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`
2032
+ error: `Timestamp is ${(n / 1e3 / 60).toFixed(2)} minutes in the future (max allowed: 2 minutes)`
2033
2033
  } : { valid: !0 };
2034
2034
  }
2035
2035
  /**
@@ -2049,7 +2049,7 @@ class Ts extends _ {
2049
2049
  }
2050
2050
  }
2051
2051
  const Is = new Set(Object.values(u));
2052
- class vs extends _ {
2052
+ class _s extends v {
2053
2053
  dataSenders;
2054
2054
  emitter;
2055
2055
  transformers;
@@ -2087,7 +2087,7 @@ class vs extends _ {
2087
2087
  * @param customHeadersProvider - Optional callback for dynamic headers
2088
2088
  * @param fetchCredentials - Fetch credentials mode for custom backend. @default 'include'
2089
2089
  */
2090
- constructor(e, t = null, s = {}, i = {}, n, o = "include") {
2090
+ constructor(e, t = null, s = {}, n = {}, i, o = "include") {
2091
2091
  super(), this.emitter = t, this.transformers = s, this.timeManager = new Ts(), this.dataSenders = [];
2092
2092
  const l = this.get("collectApiUrls");
2093
2093
  l?.saas && this.dataSenders.push(new Ze(e, "saas", l.saas, s)), l?.custom && this.dataSenders.push(
@@ -2096,12 +2096,12 @@ class vs extends _ {
2096
2096
  "custom",
2097
2097
  l.custom,
2098
2098
  s,
2099
- i,
2100
2099
  n,
2100
+ i,
2101
2101
  o
2102
2102
  )
2103
- ), this.saveSessionCountsDebounced = this.debounce((c) => {
2104
- this.saveSessionCounts(c);
2103
+ ), this.saveSessionCountsDebounced = this.debounce((d) => {
2104
+ this.saveSessionCounts(d);
2105
2105
  }, 500), this.cleanupExpiredSessionCounts();
2106
2106
  }
2107
2107
  /**
@@ -2131,10 +2131,10 @@ class vs extends _ {
2131
2131
  async recoverPersistedEvents() {
2132
2132
  const e = this.dataSenders.map(
2133
2133
  async (t) => t.recoverPersistedEvents({
2134
- onSuccess: (s, i, n) => {
2135
- if (i && i.length > 0) {
2136
- const o = i.map((l) => l.id);
2137
- this.removeProcessedEvents(o), n && this.emitEventsQueue(n);
2134
+ onSuccess: (s, n, i) => {
2135
+ if (n && n.length > 0) {
2136
+ const o = n.map((l) => l.id);
2137
+ this.removeProcessedEvents(o), i && this.emitEventsQueue(i);
2138
2138
  }
2139
2139
  },
2140
2140
  onFailure: () => {
@@ -2207,12 +2207,12 @@ class vs extends _ {
2207
2207
  type: e,
2208
2208
  page_url: t,
2209
2209
  from_page_url: s,
2210
- scroll_data: i,
2211
- click_data: n,
2210
+ scroll_data: n,
2211
+ click_data: i,
2212
2212
  custom_event: o,
2213
2213
  web_vitals: l,
2214
- error_data: c,
2215
- viewport_data: d,
2214
+ error_data: d,
2215
+ viewport_data: c,
2216
2216
  page_view: f
2217
2217
  }) {
2218
2218
  if (!e) {
@@ -2233,112 +2233,112 @@ class vs extends _ {
2233
2233
  type: e,
2234
2234
  page_url: t,
2235
2235
  from_page_url: s,
2236
- scroll_data: i,
2237
- click_data: n,
2236
+ scroll_data: n,
2237
+ click_data: i,
2238
2238
  custom_event: o,
2239
2239
  web_vitals: l,
2240
- error_data: c,
2241
- viewport_data: d,
2240
+ error_data: d,
2241
+ viewport_data: c,
2242
2242
  page_view: f
2243
2243
  });
2244
2244
  return;
2245
2245
  }
2246
2246
  this.lastSessionId !== g && (this.lastSessionId = g, this.sessionEventCounts = this.loadSessionCounts(g));
2247
- const I = e === u.SESSION_START;
2248
- if (I && a("debug", "Processing SESSION_START event", {
2247
+ const m = e === u.SESSION_START;
2248
+ if (m && a("debug", "Processing SESSION_START event", {
2249
2249
  data: { sessionId: g }
2250
- }), !I && !this.checkRateLimit())
2250
+ }), !m && !this.checkRateLimit())
2251
2251
  return;
2252
- const p = e;
2253
- if (!I) {
2252
+ const E = e;
2253
+ if (!m) {
2254
2254
  if (this.sessionEventCounts.total >= 1e3) {
2255
2255
  a("warn", "Session event limit reached", {
2256
2256
  data: {
2257
- type: p,
2257
+ type: E,
2258
2258
  total: this.sessionEventCounts.total,
2259
2259
  limit: 1e3
2260
2260
  }
2261
2261
  });
2262
2262
  return;
2263
2263
  }
2264
- const v = this.getTypeLimitForEvent(p);
2265
- if (v) {
2266
- const he = this.sessionEventCounts[p];
2267
- if (he !== void 0 && he >= v) {
2264
+ const T = this.getTypeLimitForEvent(E);
2265
+ if (T) {
2266
+ const fe = this.sessionEventCounts[E];
2267
+ if (fe !== void 0 && fe >= T) {
2268
2268
  a("warn", "Session event type limit reached", {
2269
2269
  data: {
2270
- type: p,
2271
- count: he,
2272
- limit: v
2270
+ type: E,
2271
+ count: fe,
2272
+ limit: T
2273
2273
  }
2274
2274
  });
2275
2275
  return;
2276
2276
  }
2277
2277
  }
2278
2278
  }
2279
- if (p === u.CUSTOM && o?.name) {
2280
- const v = this.get("config")?.maxSameEventPerMinute ?? 60;
2281
- if (!this.checkPerEventRateLimit(o.name, v))
2279
+ if (E === u.CUSTOM && o?.name) {
2280
+ const T = this.get("config")?.maxSameEventPerMinute ?? 60;
2281
+ if (!this.checkPerEventRateLimit(o.name, T))
2282
2282
  return;
2283
2283
  }
2284
- const Ve = p === u.SESSION_START, Q = t || this.get("pageUrl"), x = this.buildEventPayload({
2285
- type: p,
2284
+ const he = E === u.SESSION_START, Q = t || this.get("pageUrl"), U = this.buildEventPayload({
2285
+ type: E,
2286
2286
  page_url: Q,
2287
2287
  from_page_url: s,
2288
- scroll_data: i,
2289
- click_data: n,
2288
+ scroll_data: n,
2289
+ click_data: i,
2290
2290
  custom_event: o,
2291
2291
  web_vitals: l,
2292
- error_data: c,
2293
- viewport_data: d,
2292
+ error_data: d,
2293
+ viewport_data: c,
2294
2294
  page_view: f
2295
2295
  });
2296
- if (x && !(!I && !this.shouldSample())) {
2297
- if (Ve) {
2298
- const v = this.get("sessionId");
2299
- if (!v) {
2296
+ if (U && !(!m && !this.shouldSample())) {
2297
+ if (he) {
2298
+ const T = this.get("sessionId");
2299
+ if (!T) {
2300
2300
  a("error", "Session start event requires sessionId - event will be ignored");
2301
2301
  return;
2302
2302
  }
2303
2303
  if (this.get("hasStartSession")) {
2304
2304
  a("debug", "Duplicate session_start detected", {
2305
- data: { sessionId: v }
2305
+ data: { sessionId: T }
2306
2306
  });
2307
2307
  return;
2308
2308
  }
2309
2309
  this.set("hasStartSession", !0);
2310
2310
  }
2311
- if (!this.isDuplicateEvent(x)) {
2312
- if (this.get("mode") === ne.QA) {
2313
- if (p === u.CUSTOM && o) {
2311
+ if (!this.isDuplicateEvent(U)) {
2312
+ if (this.get("mode") === ie.QA) {
2313
+ if (E === u.CUSTOM && o) {
2314
2314
  a("info", `Custom Event: ${o.name}`, {
2315
2315
  visibility: "qa",
2316
2316
  data: {
2317
2317
  name: o.name,
2318
2318
  ...o.metadata && { metadata: o.metadata }
2319
2319
  }
2320
- }), this.emitEvent(x);
2320
+ }), this.emitEvent(U);
2321
2321
  return;
2322
2322
  }
2323
- if (p === u.VIEWPORT_VISIBLE && d) {
2324
- const v = d.name || d.id || d.selector;
2325
- a("info", `Viewport Visible: ${v}`, {
2323
+ if (E === u.VIEWPORT_VISIBLE && c) {
2324
+ const T = c.name || c.id || c.selector;
2325
+ a("info", `Viewport Visible: ${T}`, {
2326
2326
  visibility: "qa",
2327
2327
  data: {
2328
- selector: d.selector,
2329
- ...d.name && { name: d.name },
2330
- ...d.id && { id: d.id },
2331
- visibilityRatio: d.visibilityRatio,
2332
- dwellTime: d.dwellTime
2328
+ selector: c.selector,
2329
+ ...c.name && { name: c.name },
2330
+ ...c.id && { id: c.id },
2331
+ visibilityRatio: c.visibilityRatio,
2332
+ dwellTime: c.dwellTime
2333
2333
  }
2334
- }), this.emitEvent(x);
2334
+ }), this.emitEvent(U);
2335
2335
  return;
2336
2336
  }
2337
2337
  }
2338
- if (this.addToQueue(x), !I) {
2339
- this.sessionEventCounts.total++, this.sessionEventCounts[p] !== void 0 && this.sessionEventCounts[p]++;
2340
- const v = this.get("sessionId");
2341
- v && this.saveSessionCountsDebounced && this.saveSessionCountsDebounced(v);
2338
+ if (this.addToQueue(U), !m) {
2339
+ this.sessionEventCounts.total++, this.sessionEventCounts[E] !== void 0 && this.sessionEventCounts[E]++;
2340
+ const T = this.get("sessionId");
2341
+ T && this.saveSessionCountsDebounced && this.saveSessionCountsDebounced(T);
2342
2342
  }
2343
2343
  }
2344
2344
  }
@@ -2514,7 +2514,7 @@ class vs extends _ {
2514
2514
  * @internal Used by test-bridge.ts for test inspection
2515
2515
  */
2516
2516
  getQueueEvents() {
2517
- return [...this.eventsQueue];
2517
+ return this.eventsQueue.map(({ _session_id: e, ...t }) => t);
2518
2518
  }
2519
2519
  /**
2520
2520
  * Triggers immediate queue flush (test utility).
@@ -2597,107 +2597,191 @@ class vs extends _ {
2597
2597
  isSuccessfulResult(e) {
2598
2598
  return e.status === "fulfilled" && e.value === !0;
2599
2599
  }
2600
+ /**
2601
+ * Groups the queue by frozen `_session_id`, preserving insertion order.
2602
+ * Single pass — `buildBatchesWithIds()` builds one batch + one eventIds list
2603
+ * per group, so the grouping cost is O(N) per flush regardless of session
2604
+ * count.
2605
+ *
2606
+ * **Self-heal**: any entry missing `_session_id` (an internal invariant
2607
+ * violation — `buildEventPayload` always stamps it) is removed from the
2608
+ * queue rather than left behind, otherwise a single corrupted entry would
2609
+ * keep `eventsQueue.length > 0` forever and re-trigger periodic sends.
2610
+ */
2611
+ groupQueuedEventsBySession() {
2612
+ const e = /* @__PURE__ */ new Map(), t = [];
2613
+ for (const s of this.eventsQueue) {
2614
+ if (!s._session_id) {
2615
+ a("debug", "Queued event missing _session_id, dropping", {
2616
+ data: { eventId: s.id, type: s.type }
2617
+ }), t.push(s.id);
2618
+ continue;
2619
+ }
2620
+ const n = e.get(s._session_id);
2621
+ n ? n.push(s) : e.set(s._session_id, [s]);
2622
+ }
2623
+ return t.length > 0 && this.removeProcessedEvents(t), e;
2624
+ }
2625
+ /**
2626
+ * Builds a parallel list of `(batch, eventIds)` for sending. The eventIds are
2627
+ * the original `_session_id`-tagged event IDs in the queue that map to this
2628
+ * batch — used for optimistic removal. We can't read them off the wrapper's
2629
+ * `events[]` because dedup may have removed some signatures.
2630
+ */
2631
+ buildBatchesWithIds() {
2632
+ const e = this.groupQueuedEventsBySession();
2633
+ if (e.size === 0) return [];
2634
+ const t = [];
2635
+ for (const [s, n] of e)
2636
+ t.push({
2637
+ batch: this.buildBatchFromGroup(s, n),
2638
+ eventIds: n.map((i) => i.id)
2639
+ });
2640
+ return t;
2641
+ }
2600
2642
  flushEvents(e) {
2601
2643
  if (this.eventsQueue.length === 0)
2602
2644
  return e ? !0 : Promise.resolve(!0);
2603
2645
  if (!e && this.sendInProgress)
2604
2646
  return a("debug", "Async flush skipped: send already in progress"), Promise.resolve(!1);
2605
- const t = this.buildEventsPayload(), s = [...this.eventsQueue], i = s.map((n) => n.id);
2606
- if (this.dataSenders.length === 0)
2607
- return this.removeProcessedEvents(i), this.clearSendTimeout(), this.emitEventsQueue(t), e ? !0 : Promise.resolve(!0);
2608
- if (e && this.sendInProgress)
2647
+ const t = this.buildBatchesWithIds();
2648
+ if (t.length === 0)
2649
+ return e ? !0 : Promise.resolve(!0);
2650
+ if (this.dataSenders.length === 0) {
2651
+ for (const { batch: s, eventIds: n } of t)
2652
+ this.removeProcessedEvents(n), this.emitEventsQueue(s);
2653
+ return this.clearSendTimeout(), e ? !0 : Promise.resolve(!0);
2654
+ }
2655
+ if (e && this.sendInProgress) {
2656
+ const s = t.reduce((n, i) => n + i.eventIds.length, 0);
2609
2657
  return a("debug", "Sync flush skipped: async send already in-flight, trusting fetch to deliver", {
2610
- data: { eventCount: i.length }
2658
+ data: { eventCount: s }
2611
2659
  }), !0;
2660
+ }
2612
2661
  if (e) {
2613
- const o = this.dataSenders.map((l) => l.sendEventsQueueSync(t)).some((l) => l);
2614
- return o ? (this.removeProcessedEvents(i), this.clearSendTimeout(), this.emitEventsQueue(t)) : (this.clearSendTimeout(), a("debug", "Sync flush complete failure, events kept in queue for retry", {
2615
- data: { eventCount: i.length }
2616
- })), o;
2617
- } else {
2618
- const n = this.dataSenders.map(
2619
- async (o) => o.sendEventsQueue(t, {
2620
- onSuccess: () => {
2621
- },
2622
- onFailure: () => {
2623
- }
2624
- })
2662
+ const s = t.map(({ batch: n, eventIds: i }) => this.sendBatchSync(n, i));
2663
+ return this.clearSendTimeout(), s.some(Boolean);
2664
+ }
2665
+ return (async () => {
2666
+ const s = await Promise.all(
2667
+ t.map(async ({ batch: n, eventIds: i }) => this.sendBatchAsync(n, i))
2625
2668
  );
2626
- return Promise.allSettled(n).then((o) => {
2627
- const l = o.some((c) => this.isSuccessfulResult(c));
2628
- return l ? (this.removeProcessedEvents(i), this.clearSendTimeout(), this.emitEventsQueue(t)) : a("debug", "Async flush complete failure, events kept in queue for retry", {
2629
- data: { eventCount: s.length }
2630
- }), l;
2669
+ return this.clearSendTimeout(), s.some(Boolean);
2670
+ })();
2671
+ }
2672
+ /**
2673
+ * Sends one batch synchronously across all integrations (sendBeacon path).
2674
+ * Optimistic removal: if any integration succeeds, we remove the batch's
2675
+ * events from the queue and emit it locally. Failures persist per-integration.
2676
+ */
2677
+ sendBatchSync(e, t) {
2678
+ const n = this.dataSenders.map((i) => i.sendEventsQueueSync(e)).some((i) => i);
2679
+ return n ? (this.removeProcessedEvents(t), this.emitEventsQueue(e)) : a("debug", "Sync send complete failure, events kept in queue for retry", {
2680
+ data: { eventCount: t.length, sessionId: e.session_id }
2681
+ }), n;
2682
+ }
2683
+ /**
2684
+ * Sends one batch asynchronously across all integrations (fetch path).
2685
+ */
2686
+ async sendBatchAsync(e, t) {
2687
+ const s = this.dataSenders.map(
2688
+ async (o) => o.sendEventsQueue(e, {
2689
+ onSuccess: () => {
2690
+ },
2691
+ onFailure: () => {
2692
+ }
2693
+ })
2694
+ ), n = await Promise.allSettled(s), i = n.some((o) => this.isSuccessfulResult(o));
2695
+ if (i) {
2696
+ this.removeProcessedEvents(t), this.emitEventsQueue(e);
2697
+ const o = n.filter((l) => !this.isSuccessfulResult(l)).length;
2698
+ o > 0 && a("debug", "Async send completed with some failures, removed from queue and persisted per-integration", {
2699
+ data: { eventCount: t.length, failedCount: o, sessionId: e.session_id }
2631
2700
  });
2632
- }
2701
+ } else
2702
+ a("debug", "Async send complete failure, events kept in queue for retry", {
2703
+ data: { eventCount: t.length, sessionId: e.session_id }
2704
+ });
2705
+ return i;
2633
2706
  }
2634
2707
  async sendEventsQueue() {
2635
- if (!(!this.get("sessionId") || this.eventsQueue.length === 0 || this.sendInProgress)) {
2708
+ if (!(this.eventsQueue.length === 0 || this.sendInProgress)) {
2636
2709
  this.sendInProgress = !0;
2637
2710
  try {
2638
- const e = this.buildEventsPayload();
2711
+ const e = this.buildBatchesWithIds();
2712
+ if (e.length === 0) return;
2639
2713
  if (this.dataSenders.length === 0) {
2640
- this.emitEventsQueue(e);
2714
+ for (const { batch: n } of e)
2715
+ this.emitEventsQueue(n);
2641
2716
  return;
2642
2717
  }
2643
- const t = [...this.eventsQueue], s = t.map((l) => l.id), i = this.dataSenders.map(
2644
- async (l) => l.sendEventsQueue(e, {
2645
- onSuccess: () => {
2646
- },
2647
- onFailure: () => {
2648
- }
2649
- })
2650
- ), n = await Promise.allSettled(i);
2651
- if (n.some((l) => this.isSuccessfulResult(l))) {
2652
- this.consecutiveSendFailures = 0, this.removeProcessedEvents(s), this.emitEventsQueue(e);
2653
- const l = n.filter((c) => !this.isSuccessfulResult(c)).length;
2654
- l > 0 && a("debug", "Periodic send completed with some failures, removed from queue and persisted per-integration", {
2655
- data: { eventCount: t.length, failedCount: l }
2656
- });
2657
- } else
2658
- this.consecutiveSendFailures = Math.min(this.consecutiveSendFailures + 1, 5), a("debug", "Periodic send complete failure, events kept in queue for retry", {
2659
- data: { eventCount: t.length }
2660
- });
2661
- this.eventsQueue.length === 0 ? this.clearSendTimeout() : this.scheduleSendTimeout();
2718
+ (await Promise.all(
2719
+ e.map(async ({ batch: n, eventIds: i }) => this.sendBatchAsync(n, i))
2720
+ )).some(Boolean) ? this.consecutiveSendFailures = 0 : this.consecutiveSendFailures = Math.min(this.consecutiveSendFailures + 1, 5), this.eventsQueue.length === 0 ? this.clearSendTimeout() : this.scheduleSendTimeout();
2662
2721
  } finally {
2663
2722
  this.sendInProgress = !1;
2664
2723
  }
2665
2724
  }
2666
2725
  }
2667
- buildEventsPayload() {
2668
- const e = /* @__PURE__ */ new Map(), t = [];
2669
- for (const c of this.eventsQueue) {
2670
- const d = this.createEventSignature(c);
2671
- e.has(d) || t.push(d), e.set(d, c);
2726
+ /**
2727
+ * Builds a single batch from a per-session group: dedup by signature,
2728
+ * SESSION_START first, then timestamp order, strip `_session_id`, apply
2729
+ * `beforeBatch` transformer when running standalone.
2730
+ *
2731
+ * **Why N batches per flush**: events freeze their `_session_id` at `track()`
2732
+ * time. If the session was renewed (idle timeout) between two `track()`
2733
+ * calls, the queue contains events from multiple sessions. `buildBatchesWithIds()`
2734
+ * emits one batch per session so the backend's `EventsQueueDto.session_id`
2735
+ * remains the single source of truth and stays consistent with the events it
2736
+ * carries.
2737
+ *
2738
+ * **Strip**: `_session_id` is removed from each event in the wrapper's
2739
+ * `events[]` because the backend uses `forbidNonWhitelisted: true` and would
2740
+ * reject the batch if the field leaked through.
2741
+ *
2742
+ * **Transformer note**: `beforeBatch` is invoked **once per session-batch**,
2743
+ * not once per flush. A queue spanning N sessions triggers N invocations.
2744
+ */
2745
+ buildBatchFromGroup(e, t) {
2746
+ const s = /* @__PURE__ */ new Map(), n = [];
2747
+ for (const m of t) {
2748
+ const E = this.createEventSignature(m);
2749
+ s.has(E) || n.push(E), s.set(E, m);
2672
2750
  }
2673
- const s = t.map((c) => e.get(c)).filter((c) => !!c).sort((c, d) => c.type === u.SESSION_START && d.type !== u.SESSION_START ? -1 : d.type === u.SESSION_START && c.type !== u.SESSION_START ? 1 : c.timestamp - d.timestamp);
2674
- let i = {
2751
+ const i = n.map((m) => s.get(m)).filter((m) => !!m).sort((m, E) => m.type === u.SESSION_START && E.type !== u.SESSION_START ? -1 : E.type === u.SESSION_START && m.type !== u.SESSION_START ? 1 : m.timestamp - E.timestamp).map(({ _session_id: m, ...E }) => E), o = this.get("config")?.globalMetadata, l = this.get("identity");
2752
+ let d = {
2675
2753
  user_id: this.get("userId"),
2676
- session_id: this.get("sessionId"),
2754
+ session_id: e,
2677
2755
  device: this.get("device"),
2678
- events: s,
2679
- ...this.get("config")?.globalMetadata && { global_metadata: this.get("config")?.globalMetadata },
2680
- ...this.get("identity") && { identify: this.get("identity") }
2756
+ events: i,
2757
+ ...o && { global_metadata: o },
2758
+ ...l && { identify: l }
2681
2759
  };
2682
- const n = this.get("collectApiUrls"), o = !!(n?.custom || n?.saas), l = this.transformers.beforeBatch;
2683
- if (!o && l) {
2684
- const c = gt(i, l, "EventManager");
2685
- c !== null && (i = c);
2760
+ const c = this.get("collectApiUrls"), f = !!(c?.custom || c?.saas), g = this.transformers.beforeBatch;
2761
+ if (!f && g) {
2762
+ const m = gt(d, g, "EventManager");
2763
+ m !== null && (d = m);
2686
2764
  }
2687
- return i;
2765
+ return d;
2688
2766
  }
2689
2767
  buildEventPayload(e) {
2690
- const t = e.page_url ?? this.get("pageUrl"), s = this.timeManager.now(), i = this.timeManager.validateTimestamp(s);
2691
- i.valid || a("warn", "Event timestamp validation failed", {
2692
- data: { type: e.type, error: i.error }
2768
+ const t = this.get("sessionId");
2769
+ if (!t)
2770
+ return a("error", "buildEventPayload reached without sessionId — event dropped", {
2771
+ data: { type: e.type },
2772
+ visibility: "critical"
2773
+ }), null;
2774
+ const s = e.page_url ?? this.get("pageUrl"), n = typeof s == "string" && s.length > 0 ? s : "unknown", i = this.timeManager.now(), o = this.timeManager.validateTimestamp(i);
2775
+ o.valid || a("warn", "Event timestamp validation failed", {
2776
+ data: { type: e.type, error: o.error }
2693
2777
  });
2694
- const n = this.get("sessionReferrer"), o = this.get("sessionUtm");
2695
- let l = {
2778
+ const l = this.get("sessionReferrer"), d = this.get("sessionUtm");
2779
+ let c = {
2696
2780
  id: os(),
2697
2781
  type: e.type,
2698
- page_url: t,
2699
- timestamp: s,
2700
- ...n && { referrer: n },
2782
+ page_url: n,
2783
+ timestamp: i,
2784
+ ...l && { referrer: l },
2701
2785
  ...e.from_page_url && { from_page_url: e.from_page_url },
2702
2786
  ...e.scroll_data && { scroll_data: e.scroll_data },
2703
2787
  ...e.click_data && { click_data: e.click_data },
@@ -2706,27 +2790,27 @@ class vs extends _ {
2706
2790
  ...e.error_data && { error_data: e.error_data },
2707
2791
  ...e.viewport_data && { viewport_data: e.viewport_data },
2708
2792
  ...e.page_view && { page_view: e.page_view },
2709
- ...o && { utm: o }
2793
+ ...d && { utm: d }
2710
2794
  };
2711
- const c = this.get("collectApiUrls"), d = !!c?.custom, f = !!c?.saas, g = d || f, I = d && f, p = this.transformers.beforeSend;
2712
- if (p && (!g || d && !I)) {
2713
- const Q = mt(l, p, "EventManager");
2714
- if (Q === null)
2795
+ const f = this.get("collectApiUrls"), g = !!f?.custom, m = !!f?.saas, E = g || m, he = g && m, Q = this.transformers.beforeSend;
2796
+ if (Q && (!E || g && !he)) {
2797
+ const T = mt(c, Q, "EventManager");
2798
+ if (T === null)
2715
2799
  return null;
2716
- l = Q;
2800
+ c = T;
2717
2801
  }
2718
- return l;
2802
+ return { ...c, _session_id: t };
2719
2803
  }
2720
2804
  isDuplicateEvent(e) {
2721
- const t = Date.now(), s = this.createEventFingerprint(e), i = this.recentEventFingerprints.get(s);
2722
- return i && t - i < 1e3 ? (this.recentEventFingerprints.set(s, t), !0) : (this.recentEventFingerprints.set(s, t), this.recentEventFingerprints.size > 1500 && this.pruneOldFingerprints(), this.recentEventFingerprints.size > 3e3 && (this.recentEventFingerprints.clear(), this.recentEventFingerprints.set(s, t), a("debug", "Event fingerprint cache exceeded hard limit, cleared", {
2805
+ const t = Date.now(), s = this.createEventFingerprint(e), n = this.recentEventFingerprints.get(s);
2806
+ return n && t - n < 1e3 ? (this.recentEventFingerprints.set(s, t), !0) : (this.recentEventFingerprints.set(s, t), this.recentEventFingerprints.size > 1500 && this.pruneOldFingerprints(), this.recentEventFingerprints.size > 3e3 && (this.recentEventFingerprints.clear(), this.recentEventFingerprints.set(s, t), a("debug", "Event fingerprint cache exceeded hard limit, cleared", {
2723
2807
  data: { hardLimit: 3e3 }
2724
2808
  })), !1);
2725
2809
  }
2726
2810
  pruneOldFingerprints() {
2727
2811
  const e = Date.now(), t = 1e3 * 10;
2728
- for (const [s, i] of this.recentEventFingerprints.entries())
2729
- e - i > t && this.recentEventFingerprints.delete(s);
2812
+ for (const [s, n] of this.recentEventFingerprints.entries())
2813
+ e - n > t && this.recentEventFingerprints.delete(s);
2730
2814
  a("debug", "Pruned old event fingerprints", {
2731
2815
  data: {
2732
2816
  remaining: this.recentEventFingerprints.size,
@@ -2737,8 +2821,8 @@ class vs extends _ {
2737
2821
  createEventFingerprint(e) {
2738
2822
  let t = `${e.type}_${e.page_url}`;
2739
2823
  if (e.click_data) {
2740
- const s = Math.round((e.click_data.x || 0) / 10) * 10, i = Math.round((e.click_data.y || 0) / 10) * 10;
2741
- t += `_click_${s}_${i}`;
2824
+ const s = Math.round((e.click_data.x || 0) / 10) * 10, n = Math.round((e.click_data.y || 0) / 10) * 10;
2825
+ t += `_click_${s}_${n}`;
2742
2826
  }
2743
2827
  return e.scroll_data && (t += `_scroll_${e.scroll_data.depth}_${e.scroll_data.direction}`), e.custom_event && (t += `_custom_${e.custom_event.name}`, e.custom_event.metadata && (t += `_${this.stableStringify(e.custom_event.metadata)}`)), e.web_vitals && (t += `_vitals_${e.web_vitals.type}`), e.error_data && (t += `_error_${e.error_data.type}_${e.error_data.message}`), t;
2744
2828
  }
@@ -2747,11 +2831,11 @@ class vs extends _ {
2747
2831
  }
2748
2832
  /** Deterministic JSON string with sorted keys to ensure consistent fingerprints regardless of property insertion order */
2749
2833
  stableStringify(e) {
2750
- return JSON.stringify(e, (t, s) => s && typeof s == "object" && !Array.isArray(s) ? Object.keys(s).sort().reduce((i, n) => (i[n] = s[n], i), {}) : s);
2834
+ return JSON.stringify(e, (t, s) => s && typeof s == "object" && !Array.isArray(s) ? Object.keys(s).sort().reduce((n, i) => (n[i] = s[i], n), {}) : s);
2751
2835
  }
2752
2836
  addToQueue(e) {
2753
2837
  if (this.emitEvent(e), this.eventsQueue.push(e), this.eventsQueue.length > 100) {
2754
- const t = this.eventsQueue.findIndex((i) => i.type !== u.SESSION_START), s = t >= 0 ? this.eventsQueue.splice(t, 1)[0] : this.eventsQueue.shift();
2838
+ const t = this.eventsQueue.findIndex((n) => n.type !== u.SESSION_START), s = t >= 0 ? this.eventsQueue.splice(t, 1)[0] : this.eventsQueue.shift();
2755
2839
  a("warn", "Event queue overflow, oldest non-critical event removed", {
2756
2840
  data: {
2757
2841
  maxLength: 100,
@@ -2785,14 +2869,14 @@ class vs extends _ {
2785
2869
  return e - this.rateLimitWindowStart > 1e3 && (this.rateLimitCounter = 0, this.rateLimitWindowStart = e), this.rateLimitCounter >= 50 ? !1 : (this.rateLimitCounter++, !0);
2786
2870
  }
2787
2871
  checkPerEventRateLimit(e, t) {
2788
- const s = Date.now(), n = (this.perEventRateLimits.get(e) ?? []).filter((o) => s - o < 6e4);
2789
- return n.length >= t ? (a("warn", "Per-event rate limit exceeded for custom event", {
2872
+ const s = Date.now(), i = (this.perEventRateLimits.get(e) ?? []).filter((o) => s - o < 6e4);
2873
+ return i.length >= t ? (a("warn", "Per-event rate limit exceeded for custom event", {
2790
2874
  data: {
2791
2875
  eventName: e,
2792
2876
  limit: t,
2793
2877
  window: `${6e4 / 1e3}s`
2794
2878
  }
2795
- }), !1) : (n.push(s), this.perEventRateLimits.set(e, n), !0);
2879
+ }), !1) : (i.push(s), this.perEventRateLimits.set(e, i), !0);
2796
2880
  }
2797
2881
  getTypeLimitForEvent(e) {
2798
2882
  return {
@@ -2808,7 +2892,10 @@ class vs extends _ {
2808
2892
  this.eventsQueue = this.eventsQueue.filter((s) => !t.has(s.id));
2809
2893
  }
2810
2894
  emitEvent(e) {
2811
- this.emitter && this.emitter.emit(se.EVENT, e);
2895
+ if (this.emitter) {
2896
+ const { _session_id: t, ...s } = e;
2897
+ this.emitter.emit(se.EVENT, s);
2898
+ }
2812
2899
  }
2813
2900
  emitEventsQueue(e) {
2814
2901
  this.emitter && this.emitter.emit(se.QUEUE, e);
@@ -2835,9 +2922,9 @@ class vs extends _ {
2835
2922
  */
2836
2923
  debounce(e, t) {
2837
2924
  let s = null;
2838
- return ((...i) => {
2925
+ return ((...n) => {
2839
2926
  s !== null && clearTimeout(s), s = setTimeout(() => {
2840
- e(...i), s = null;
2927
+ e(...n), s = null;
2841
2928
  }, t);
2842
2929
  });
2843
2930
  }
@@ -2889,27 +2976,27 @@ class vs extends _ {
2889
2976
  return this.getInitialCounts();
2890
2977
  const t = this.get("userId") || "anonymous", s = He(t, e);
2891
2978
  try {
2892
- const i = localStorage.getItem(s);
2893
- if (!i)
2979
+ const n = localStorage.getItem(s);
2980
+ if (!n)
2894
2981
  return this.getInitialCounts();
2895
- const n = JSON.parse(i);
2896
- return n._timestamp && Date.now() - n._timestamp > xe ? (a("debug", "Session counts expired, clearing", {
2897
- data: { sessionId: e, age: Date.now() - n._timestamp }
2898
- }), localStorage.removeItem(s), this.getInitialCounts()) : typeof n.total == "number" && typeof n[u.CLICK] == "number" && typeof n[u.PAGE_VIEW] == "number" && typeof n[u.CUSTOM] == "number" && typeof n[u.VIEWPORT_VISIBLE] == "number" && typeof n[u.SCROLL] == "number" ? {
2899
- total: n.total,
2900
- [u.CLICK]: n[u.CLICK],
2901
- [u.PAGE_VIEW]: n[u.PAGE_VIEW],
2902
- [u.CUSTOM]: n[u.CUSTOM],
2903
- [u.VIEWPORT_VISIBLE]: n[u.VIEWPORT_VISIBLE],
2904
- [u.SCROLL]: n[u.SCROLL]
2982
+ const i = JSON.parse(n);
2983
+ return i._timestamp && Date.now() - i._timestamp > xe ? (a("debug", "Session counts expired, clearing", {
2984
+ data: { sessionId: e, age: Date.now() - i._timestamp }
2985
+ }), localStorage.removeItem(s), this.getInitialCounts()) : typeof i.total == "number" && typeof i[u.CLICK] == "number" && typeof i[u.PAGE_VIEW] == "number" && typeof i[u.CUSTOM] == "number" && typeof i[u.VIEWPORT_VISIBLE] == "number" && typeof i[u.SCROLL] == "number" ? {
2986
+ total: i.total,
2987
+ [u.CLICK]: i[u.CLICK],
2988
+ [u.PAGE_VIEW]: i[u.PAGE_VIEW],
2989
+ [u.CUSTOM]: i[u.CUSTOM],
2990
+ [u.VIEWPORT_VISIBLE]: i[u.VIEWPORT_VISIBLE],
2991
+ [u.SCROLL]: i[u.SCROLL]
2905
2992
  } : (a("warn", "Invalid session counts structure in localStorage, resetting", {
2906
- data: { sessionId: e, parsed: n }
2993
+ data: { sessionId: e, parsed: i }
2907
2994
  }), localStorage.removeItem(s), a("debug", "Session counts removed due to invalid/corrupted data", {
2908
- data: { sessionId: e, parsed: n }
2995
+ data: { sessionId: e, parsed: i }
2909
2996
  }), this.getInitialCounts());
2910
- } catch (i) {
2997
+ } catch (n) {
2911
2998
  return a("warn", "Failed to load session counts from localStorage", {
2912
- error: i,
2999
+ error: n,
2913
3000
  data: { sessionId: e }
2914
3001
  }), this.getInitialCounts();
2915
3002
  }
@@ -2940,30 +3027,30 @@ class vs extends _ {
2940
3027
  try {
2941
3028
  const e = localStorage.getItem($e);
2942
3029
  if (e) {
2943
- const n = Date.now() - parseInt(e, 10);
2944
- if (n < Be) {
3030
+ const i = Date.now() - parseInt(e, 10);
3031
+ if (i < Be) {
2945
3032
  a("debug", "Skipping session counts cleanup (throttled)", {
2946
- data: { timeSinceLastCleanup: n, throttleMs: Be }
3033
+ data: { timeSinceLastCleanup: i, throttleMs: Be }
2947
3034
  });
2948
3035
  return;
2949
3036
  }
2950
3037
  }
2951
- const t = this.get("userId") || "anonymous", s = `${S}:${t}:session_counts:`, i = [];
2952
- for (let n = 0; n < localStorage.length; n++) {
2953
- const o = localStorage.key(n);
3038
+ const t = this.get("userId") || "anonymous", s = `${I}:${t}:session_counts:`, n = [];
3039
+ for (let i = 0; i < localStorage.length; i++) {
3040
+ const o = localStorage.key(i);
2954
3041
  if (o?.startsWith(s))
2955
3042
  try {
2956
3043
  const l = localStorage.getItem(o);
2957
3044
  if (l) {
2958
- const c = JSON.parse(l);
2959
- c._timestamp && Date.now() - c._timestamp > xe && i.push(o);
3045
+ const d = JSON.parse(l);
3046
+ d._timestamp && Date.now() - d._timestamp > xe && n.push(o);
2960
3047
  }
2961
3048
  } catch {
2962
3049
  }
2963
3050
  }
2964
- i.forEach((n) => {
2965
- localStorage.removeItem(n), a("debug", "Cleaned up expired session counts", { data: { key: n } });
2966
- }), i.length > 0 && a("info", `Cleaned up ${i.length} expired session counts entries`), localStorage.setItem($e, Date.now().toString());
3051
+ n.forEach((i) => {
3052
+ localStorage.removeItem(i), a("debug", "Cleaned up expired session counts", { data: { key: i } });
3053
+ }), n.length > 0 && a("info", `Cleaned up ${n.length} expired session counts entries`), localStorage.setItem($e, Date.now().toString());
2967
3054
  } catch (e) {
2968
3055
  a("warn", "Failed to cleanup expired session counts", { error: e });
2969
3056
  }
@@ -2999,21 +3086,21 @@ class vs extends _ {
2999
3086
  saveSessionCounts(e) {
3000
3087
  const t = this.get("userId") || "anonymous", s = He(t, e);
3001
3088
  try {
3002
- const i = {
3089
+ const n = {
3003
3090
  ...this.sessionEventCounts,
3004
3091
  _timestamp: Date.now(),
3005
3092
  _version: 1
3006
3093
  };
3007
- localStorage.setItem(s, JSON.stringify(i));
3008
- } catch (i) {
3094
+ localStorage.setItem(s, JSON.stringify(n));
3095
+ } catch (n) {
3009
3096
  a("warn", "Failed to persist session counts to localStorage", {
3010
- error: i,
3097
+ error: n,
3011
3098
  data: { sessionId: e }
3012
3099
  });
3013
3100
  }
3014
3101
  }
3015
3102
  }
3016
- class _s {
3103
+ class vs {
3017
3104
  /**
3018
3105
  * Gets or creates a unique user ID.
3019
3106
  *
@@ -3031,15 +3118,15 @@ class _s {
3031
3118
  * @returns Persistent unique user ID (UUID v4 format)
3032
3119
  */
3033
3120
  static getId(e) {
3034
- const t = e.getItem(Te);
3121
+ const t = e.getItem(Ie);
3035
3122
  if (t)
3036
3123
  return t;
3037
3124
  const s = dt();
3038
- return e.setItem(Te, s), s;
3125
+ return e.setItem(Ie, s), s;
3039
3126
  }
3040
3127
  }
3041
3128
  const ys = /^\d{13}-[a-z0-9]{9}$/;
3042
- class ws extends _ {
3129
+ class ws extends v {
3043
3130
  storageManager;
3044
3131
  eventManager;
3045
3132
  projectId;
@@ -3066,8 +3153,8 @@ class ws extends _ {
3066
3153
  }
3067
3154
  const e = this.getProjectId();
3068
3155
  this.broadcastChannel = new BroadcastChannel(Ot(e)), this.broadcastChannel.onmessage = (t) => {
3069
- const { action: s, sessionId: i, timestamp: n, projectId: o } = t.data ?? {};
3070
- o === e && (s === "session_start" && i && typeof n == "number" && n > Date.now() - 5e3 ? (this.set("sessionId", i), this.persistSession(i, n), this.isTracking && this.setupSessionTimeout()) : s && s !== "session_start" && a("debug", "Ignored BroadcastChannel message with unknown action", { data: { action: s } }));
3156
+ const { action: s, sessionId: n, timestamp: i, projectId: o } = t.data ?? {};
3157
+ o === e && (s === "session_start" && n && typeof i == "number" && i > Date.now() - 5e3 ? (this.set("sessionId", n), this.persistSession(n, i), this.isTracking && this.setupSessionTimeout()) : s && s !== "session_start" && a("debug", "Ignored BroadcastChannel message with unknown action", { data: { action: s } }));
3071
3158
  };
3072
3159
  }
3073
3160
  shareSession(e) {
@@ -3092,12 +3179,12 @@ class ws extends _ {
3092
3179
  const t = this.get("config")?.sessionTimeout ?? 9e5;
3093
3180
  return Date.now() - e.lastActivity > t ? (this.clearStoredSession(), null) : e.id;
3094
3181
  }
3095
- persistSession(e, t = Date.now(), s, i) {
3182
+ persistSession(e, t = Date.now(), s, n) {
3096
3183
  this.saveStoredSession({
3097
3184
  id: e,
3098
3185
  lastActivity: t,
3099
3186
  ...s && { referrer: s },
3100
- ...i && { utm: i }
3187
+ ...n && { utm: n }
3101
3188
  });
3102
3189
  }
3103
3190
  clearStoredSession() {
@@ -3108,18 +3195,18 @@ class ws extends _ {
3108
3195
  const e = this.getSessionStorageKey(), t = this.storageManager.getItem(e);
3109
3196
  if (t !== null)
3110
3197
  try {
3111
- const i = JSON.parse(t);
3112
- if (i.id && typeof i.lastActivity == "number")
3113
- return i;
3198
+ const n = JSON.parse(t);
3199
+ if (n.id && typeof n.lastActivity == "number")
3200
+ return n;
3114
3201
  } catch {
3115
3202
  this.storageManager.removeItem(e);
3116
3203
  }
3117
3204
  const s = this.storageManager.getSessionItem(e);
3118
3205
  if (s !== null)
3119
3206
  try {
3120
- const i = JSON.parse(s);
3121
- if (i.id && typeof i.lastActivity == "number")
3122
- return i;
3207
+ const n = JSON.parse(s);
3208
+ if (n.id && typeof n.lastActivity == "number")
3209
+ return n;
3123
3210
  } catch {
3124
3211
  this.storageManager.removeSessionItem(e);
3125
3212
  }
@@ -3193,31 +3280,31 @@ class ws extends _ {
3193
3280
  return;
3194
3281
  }
3195
3282
  const e = this.recoverSession(), t = e ?? this.generateSessionId();
3196
- let s, i;
3283
+ let s, n;
3197
3284
  if (e) {
3198
- const n = this.loadStoredSession();
3199
- s = n?.referrer ?? me(), i = n?.utm ?? ge();
3285
+ const i = this.loadStoredSession();
3286
+ s = i?.referrer ?? ge(), n = i?.utm ?? pe();
3200
3287
  } else
3201
- s = me(), i = ge();
3288
+ s = ge(), n = pe();
3202
3289
  a("debug", "Session tracking initialized", {
3203
3290
  data: {
3204
3291
  sessionId: t,
3205
3292
  wasRecovered: !!e,
3206
3293
  willEmitSessionStart: !e,
3207
3294
  sessionReferrer: s,
3208
- hasUtm: !!i
3295
+ hasUtm: !!n
3209
3296
  }
3210
3297
  }), this.isTracking = !0;
3211
3298
  try {
3212
- this.set("sessionId", t), this.set("sessionReferrer", s), this.set("sessionUtm", i), this.persistSession(t, Date.now(), s, i), this.initCrossTabSync(), this.shareSession(t), e ? a("debug", "Session recovered, skipping SESSION_START", {
3299
+ this.set("sessionId", t), this.set("sessionReferrer", s), this.set("sessionUtm", n), this.persistSession(t, Date.now(), s, n), this.initCrossTabSync(), this.shareSession(t), e ? a("debug", "Session recovered, skipping SESSION_START", {
3213
3300
  data: { sessionId: t }
3214
3301
  }) : (a("debug", "Emitting SESSION_START event", {
3215
3302
  data: { sessionId: t }
3216
3303
  }), this.eventManager.track({
3217
3304
  type: u.SESSION_START
3218
3305
  })), this.setupSessionTimeout(), this.setupActivityListeners(), this.setupLifecycleListeners();
3219
- } catch (n) {
3220
- throw this.isTracking = !1, this.clearSessionTimeout(), this.cleanupActivityListeners(), this.cleanupLifecycleListeners(), this.cleanupCrossTabSync(), this.set("sessionId", null), n;
3306
+ } catch (i) {
3307
+ throw this.isTracking = !1, this.clearSessionTimeout(), this.cleanupActivityListeners(), this.cleanupLifecycleListeners(), this.cleanupCrossTabSync(), this.set("sessionId", null), i;
3221
3308
  }
3222
3309
  }
3223
3310
  generateSessionId() {
@@ -3249,7 +3336,7 @@ class ws extends _ {
3249
3336
  */
3250
3337
  renewSession() {
3251
3338
  this.needsRenewal = !1;
3252
- const e = this.generateSessionId(), t = me(), s = ge();
3339
+ const e = this.generateSessionId(), t = ge(), s = pe();
3253
3340
  a("debug", "Renewing session after timeout", {
3254
3341
  data: { newSessionId: e }
3255
3342
  }), this.set("sessionId", e), this.set("sessionReferrer", t), this.set("sessionUtm", s), this.persistSession(e, Date.now(), t, s), this.cleanupCrossTabSync(), this.initCrossTabSync(), this.shareSession(e), this.eventManager.track({
@@ -3370,7 +3457,7 @@ class ws extends _ {
3370
3457
  this.clearSessionTimeout(), this.cleanupActivityListeners(), this.cleanupCrossTabSync(), this.cleanupLifecycleListeners(), this.isTracking = !1, this.needsRenewal = !1, this.set("hasStartSession", !1);
3371
3458
  }
3372
3459
  }
3373
- class bs extends _ {
3460
+ class bs extends v {
3374
3461
  eventManager;
3375
3462
  storageManager;
3376
3463
  sessionManager = null;
@@ -3458,7 +3545,7 @@ class bs extends _ {
3458
3545
  this.destroyed || (this.sessionManager && (this.sessionManager.destroy(), this.sessionManager = null), this.destroyed = !0);
3459
3546
  }
3460
3547
  }
3461
- class Ls extends _ {
3548
+ class Ls extends v {
3462
3549
  eventManager;
3463
3550
  onTrack;
3464
3551
  originalPushState;
@@ -3498,25 +3585,25 @@ class Ls extends _ {
3498
3585
  };
3499
3586
  }
3500
3587
  trackCurrentPage = () => {
3501
- const e = window.location.href, t = ye(e, this.get("config").sensitiveQueryParams);
3588
+ const e = window.location.href, t = we(e, this.get("config").sensitiveQueryParams);
3502
3589
  if (this.get("pageUrl") === t)
3503
3590
  return;
3504
- const s = Date.now(), i = this.get("config").pageViewThrottleMs ?? 1e3;
3505
- if (s - this.lastPageViewTime < i)
3591
+ const s = Date.now(), n = this.get("config").pageViewThrottleMs ?? 1e3;
3592
+ if (s - this.lastPageViewTime < n)
3506
3593
  return;
3507
3594
  this.lastPageViewTime = s, this.onTrack();
3508
- const n = this.get("pageUrl");
3595
+ const i = this.get("pageUrl");
3509
3596
  this.set("pageUrl", t);
3510
3597
  const o = this.extractPageViewData();
3511
3598
  this.eventManager.track({
3512
3599
  type: u.PAGE_VIEW,
3513
3600
  page_url: this.get("pageUrl"),
3514
- from_page_url: n,
3601
+ from_page_url: i,
3515
3602
  ...o && { page_view: o }
3516
3603
  });
3517
3604
  };
3518
3605
  trackInitialPageView() {
3519
- const e = ye(window.location.href, this.get("config").sensitiveQueryParams), t = this.extractPageViewData();
3606
+ const e = we(window.location.href, this.get("config").sensitiveQueryParams), t = this.extractPageViewData();
3520
3607
  this.lastPageViewTime = Date.now(), this.eventManager.track({
3521
3608
  type: u.PAGE_VIEW,
3522
3609
  page_url: e,
@@ -3524,17 +3611,17 @@ class Ls extends _ {
3524
3611
  }), this.onTrack();
3525
3612
  }
3526
3613
  extractPageViewData() {
3527
- const { pathname: e, search: t, hash: s } = window.location, { referrer: i } = document, { title: n } = document;
3528
- return !i && !n && !e && !t && !s ? void 0 : {
3529
- ...i && { referrer: i },
3530
- ...n && { title: n },
3614
+ const { pathname: e, search: t, hash: s } = window.location, { referrer: n } = document, { title: i } = document;
3615
+ return !n && !i && !e && !t && !s ? void 0 : {
3616
+ ...n && { referrer: n },
3617
+ ...i && { title: i },
3531
3618
  ...e && { pathname: e },
3532
3619
  ...t && { search: t },
3533
3620
  ...s && { hash: s }
3534
3621
  };
3535
3622
  }
3536
3623
  }
3537
- class As extends _ {
3624
+ class As extends v {
3538
3625
  eventManager;
3539
3626
  lastClickTimes = /* @__PURE__ */ new Map();
3540
3627
  clickHandler;
@@ -3557,17 +3644,17 @@ class As extends _ {
3557
3644
  */
3558
3645
  startTracking() {
3559
3646
  this.clickHandler || (this.clickHandler = (e) => {
3560
- const t = e, s = t.target, i = typeof HTMLElement < "u" && s instanceof HTMLElement ? s : typeof HTMLElement < "u" && s instanceof Node && s.parentElement instanceof HTMLElement ? s.parentElement : null;
3561
- if (!i) {
3647
+ const t = e, s = t.target, n = typeof HTMLElement < "u" && s instanceof HTMLElement ? s : typeof HTMLElement < "u" && s instanceof Node && s.parentElement instanceof HTMLElement ? s.parentElement : null;
3648
+ if (!n) {
3562
3649
  a("debug", "Click target not found or not an element");
3563
3650
  return;
3564
3651
  }
3565
- if (this.shouldIgnoreElement(i))
3652
+ if (this.shouldIgnoreElement(n))
3566
3653
  return;
3567
- const n = this.get("config")?.clickThrottleMs ?? 300;
3568
- if (n > 0 && !this.checkClickThrottle(i, n))
3654
+ const i = this.get("config")?.clickThrottleMs ?? 300;
3655
+ if (i > 0 && !this.checkClickThrottle(n, i))
3569
3656
  return;
3570
- const o = this.findTrackingElement(i), l = this.getRelevantClickElement(i), c = this.calculateClickCoordinates(t, i);
3657
+ const o = this.findTrackingElement(n), l = this.getRelevantClickElement(n), d = this.calculateClickCoordinates(t, n);
3571
3658
  if (o) {
3572
3659
  const f = this.extractTrackingData(o);
3573
3660
  if (f) {
@@ -3581,10 +3668,14 @@ class As extends _ {
3581
3668
  });
3582
3669
  }
3583
3670
  }
3584
- const d = this.generateClickData(i, l, c);
3671
+ if (!d) {
3672
+ a("debug", "Click skipped: invalid coordinates (likely synthetic)");
3673
+ return;
3674
+ }
3675
+ const c = this.generateClickData(n, l, d);
3585
3676
  this.eventManager.track({
3586
3677
  type: u.CLICK,
3587
- click_data: d
3678
+ click_data: c
3588
3679
  });
3589
3680
  }, window.addEventListener("click", this.clickHandler, !0));
3590
3681
  }
@@ -3605,15 +3696,15 @@ class As extends _ {
3605
3696
  * Returns true if the click should be tracked, false if throttled
3606
3697
  */
3607
3698
  checkClickThrottle(e, t) {
3608
- const s = this.getElementSignature(e), i = Date.now();
3609
- this.pruneThrottleCache(i);
3610
- const n = this.lastClickTimes.get(s);
3611
- return n !== void 0 && i - n < t ? (a("debug", "ClickHandler: Click suppressed by throttle", {
3699
+ const s = this.getElementSignature(e), n = Date.now();
3700
+ this.pruneThrottleCache(n);
3701
+ const i = this.lastClickTimes.get(s);
3702
+ return i !== void 0 && n - i < t ? (a("debug", "ClickHandler: Click suppressed by throttle", {
3612
3703
  data: {
3613
3704
  signature: s,
3614
- throttleRemaining: t - (i - n)
3705
+ throttleRemaining: t - (n - i)
3615
3706
  }
3616
- }), !1) : (this.lastClickTimes.set(s, i), !0);
3707
+ }), !1) : (this.lastClickTimes.set(s, n), !0);
3617
3708
  }
3618
3709
  /**
3619
3710
  * Prunes stale entries from the throttle cache to prevent memory leaks
@@ -3625,15 +3716,15 @@ class As extends _ {
3625
3716
  return;
3626
3717
  this.lastPruneTime = e;
3627
3718
  const t = e - 3e5;
3628
- for (const [s, i] of this.lastClickTimes.entries())
3629
- i < t && this.lastClickTimes.delete(s);
3719
+ for (const [s, n] of this.lastClickTimes.entries())
3720
+ n < t && this.lastClickTimes.delete(s);
3630
3721
  if (this.lastClickTimes.size > 1e3) {
3631
- const s = Array.from(this.lastClickTimes.entries()).sort((o, l) => o[1] - l[1]), i = this.lastClickTimes.size - 1e3, n = s.slice(0, i);
3632
- for (const [o] of n)
3722
+ const s = Array.from(this.lastClickTimes.entries()).sort((o, l) => o[1] - l[1]), n = this.lastClickTimes.size - 1e3, i = s.slice(0, n);
3723
+ for (const [o] of i)
3633
3724
  this.lastClickTimes.delete(o);
3634
3725
  a("debug", "ClickHandler: Pruned throttle cache", {
3635
3726
  data: {
3636
- removed: n.length,
3727
+ removed: i.length,
3637
3728
  remaining: this.lastClickTimes.size
3638
3729
  }
3639
3730
  });
@@ -3659,12 +3750,12 @@ class As extends _ {
3659
3750
  const t = [];
3660
3751
  let s = e;
3661
3752
  for (; s && s !== document.body; ) {
3662
- let i = s.tagName.toLowerCase();
3753
+ let n = s.tagName.toLowerCase();
3663
3754
  if (s.className) {
3664
- const n = s.className.split(" ")[0];
3665
- n && (i += `.${n}`);
3755
+ const i = s.className.split(" ")[0];
3756
+ i && (n += `.${i}`);
3666
3757
  }
3667
- t.unshift(i), s = s.parentElement;
3758
+ t.unshift(n), s = s.parentElement;
3668
3759
  }
3669
3760
  return t.join(">") || "unknown";
3670
3761
  }
@@ -3700,8 +3791,11 @@ class As extends _ {
3700
3791
  return Math.max(0, Math.min(1, Number(e.toFixed(3))));
3701
3792
  }
3702
3793
  calculateClickCoordinates(e, t) {
3703
- const s = t.getBoundingClientRect(), i = e.clientX, n = e.clientY, o = s.width > 0 ? this.clamp((i - s.left) / s.width) : 0, l = s.height > 0 ? this.clamp((n - s.top) / s.height) : 0;
3704
- return { x: i, y: n, relativeX: o, relativeY: l };
3794
+ const s = e.clientX, n = e.clientY;
3795
+ if (typeof s != "number" || typeof n != "number" || !Number.isFinite(s) || !Number.isFinite(n) || s === 0 && n === 0 && !e.isTrusted)
3796
+ return null;
3797
+ const i = t.getBoundingClientRect(), o = i.width > 0 ? this.clamp((s - i.left) / i.width) : 0, l = i.height > 0 ? this.clamp((n - i.top) / i.height) : 0;
3798
+ return { x: s, y: n, relativeX: o, relativeY: l };
3705
3799
  }
3706
3800
  extractTrackingData(e) {
3707
3801
  const t = e.getAttribute(`${b}-name`), s = e.getAttribute(`${b}-value`);
@@ -3713,22 +3807,22 @@ class As extends _ {
3713
3807
  };
3714
3808
  }
3715
3809
  generateClickData(e, t, s) {
3716
- const { x: i, y: n, relativeX: o, relativeY: l } = s, c = this.getRelevantText(e, t), d = this.extractElementAttributes(t);
3810
+ const { x: n, y: i, relativeX: o, relativeY: l } = s, d = this.getRelevantText(e, t), c = this.extractElementAttributes(t);
3717
3811
  return {
3718
- x: i,
3719
- y: n,
3812
+ x: n,
3813
+ y: i,
3720
3814
  relativeX: o,
3721
3815
  relativeY: l,
3722
3816
  tag: t.tagName.toLowerCase(),
3723
3817
  ...t.id && { id: t.id },
3724
3818
  ...t.className && { class: t.className },
3725
- ...c && { text: c },
3726
- ...d.href && { href: d.href },
3727
- ...d.title && { title: d.title },
3728
- ...d.alt && { alt: d.alt },
3729
- ...d.role && { role: d.role },
3730
- ...d["aria-label"] && { ariaLabel: d["aria-label"] },
3731
- ...Object.keys(d).length > 0 && { dataAttributes: d }
3819
+ ...d && { text: d },
3820
+ ...c.href && { href: c.href },
3821
+ ...c.title && { title: c.title },
3822
+ ...c.alt && { alt: c.alt },
3823
+ ...c.role && { role: c.role },
3824
+ ...c["aria-label"] && { ariaLabel: c["aria-label"] },
3825
+ ...Object.keys(c).length > 0 && { dataAttributes: c }
3732
3826
  };
3733
3827
  }
3734
3828
  /**
@@ -3753,17 +3847,17 @@ class As extends _ {
3753
3847
  sanitizeText(e) {
3754
3848
  let t = e;
3755
3849
  for (const s of at) {
3756
- const i = new RegExp(s.source, s.flags);
3757
- t = t.replace(i, "[REDACTED]");
3850
+ const n = new RegExp(s.source, s.flags);
3851
+ t = t.replace(n, "[REDACTED]");
3758
3852
  }
3759
3853
  return t;
3760
3854
  }
3761
3855
  getRelevantText(e, t) {
3762
- const s = e.textContent?.trim() ?? "", i = t.textContent?.trim() ?? "";
3763
- if (!s && !i)
3856
+ const s = e.textContent?.trim() ?? "", n = t.textContent?.trim() ?? "";
3857
+ if (!s && !n)
3764
3858
  return "";
3765
- let n = "";
3766
- return s && s.length <= 255 ? n = s : i.length <= 255 ? n = i : n = i.slice(0, 252) + "...", this.sanitizeText(n);
3859
+ let i = "";
3860
+ return s && s.length <= 255 ? i = s : n.length <= 255 ? i = n : i = n.slice(0, 252) + "...", this.sanitizeText(i);
3767
3861
  }
3768
3862
  extractElementAttributes(e) {
3769
3863
  const t = [
@@ -3778,9 +3872,9 @@ class As extends _ {
3778
3872
  "alt",
3779
3873
  "role"
3780
3874
  ], s = {};
3781
- for (const i of t) {
3782
- const n = e.getAttribute(i);
3783
- n && (s[i] = n);
3875
+ for (const n of t) {
3876
+ const i = e.getAttribute(n);
3877
+ i && (s[n] = i);
3784
3878
  }
3785
3879
  return s;
3786
3880
  }
@@ -3791,7 +3885,7 @@ class As extends _ {
3791
3885
  };
3792
3886
  }
3793
3887
  }
3794
- class Ms extends _ {
3888
+ class Ms extends v {
3795
3889
  eventManager;
3796
3890
  containers = [];
3797
3891
  limitWarningLogged = !1;
@@ -3838,8 +3932,8 @@ class Ms extends _ {
3838
3932
  const t = this.findScrollableElements();
3839
3933
  if (this.isWindowScrollable() && this.setupScrollContainer(window, "window"), t.length > 0) {
3840
3934
  for (const s of t) {
3841
- const i = this.getElementSelector(s);
3842
- this.setupScrollContainer(s, i);
3935
+ const n = this.getElementSelector(s);
3936
+ this.setupScrollContainer(s, n);
3843
3937
  }
3844
3938
  this.applyPrimaryScrollSelectorIfConfigured();
3845
3939
  return;
@@ -3860,18 +3954,18 @@ class Ms extends _ {
3860
3954
  if (!document.body)
3861
3955
  return [];
3862
3956
  const e = [], t = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, {
3863
- acceptNode: (i) => {
3864
- const n = i;
3865
- if (!n.isConnected || !n.offsetParent)
3957
+ acceptNode: (n) => {
3958
+ const i = n;
3959
+ if (!i.isConnected || !i.offsetParent)
3866
3960
  return NodeFilter.FILTER_SKIP;
3867
- const o = getComputedStyle(n);
3961
+ const o = getComputedStyle(i);
3868
3962
  return o.overflowY === "auto" || o.overflowY === "scroll" || o.overflow === "auto" || o.overflow === "scroll" ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
3869
3963
  }
3870
3964
  });
3871
3965
  let s;
3872
3966
  for (; (s = t.nextNode()) && e.length < 10; ) {
3873
- const i = s;
3874
- this.isElementScrollable(i) && e.push(i);
3967
+ const n = s;
3968
+ this.isElementScrollable(n) && e.push(n);
3875
3969
  }
3876
3970
  return e;
3877
3971
  }
@@ -3882,7 +3976,7 @@ class Ms extends _ {
3882
3976
  if (t.id)
3883
3977
  return `#${t.id}`;
3884
3978
  if (t.className && typeof t.className == "string") {
3885
- const s = t.className.split(" ").filter((i) => i.trim())[0];
3979
+ const s = t.className.split(" ").filter((n) => n.trim())[0];
3886
3980
  if (s)
3887
3981
  return `.${s}`;
3888
3982
  }
@@ -3892,42 +3986,42 @@ class Ms extends _ {
3892
3986
  return this.isWindowScrollable() ? e === window : this.containers.length === 0;
3893
3987
  }
3894
3988
  setupScrollContainer(e, t) {
3895
- if (this.containers.some((d) => d.element === e) || e !== window && !this.isElementScrollable(e))
3989
+ if (this.containers.some((c) => c.element === e) || e !== window && !this.isElementScrollable(e))
3896
3990
  return;
3897
- const i = this.getScrollTop(e), n = this.calculateScrollDepth(
3898
- i,
3991
+ const n = this.getScrollTop(e), i = this.calculateScrollDepth(
3992
+ n,
3899
3993
  this.getScrollHeight(e),
3900
3994
  this.getViewportHeight(e)
3901
3995
  ), o = this.determineIfPrimary(e), l = {
3902
3996
  element: e,
3903
3997
  selector: t,
3904
3998
  isPrimary: o,
3905
- lastScrollPos: i,
3906
- lastDepth: n,
3999
+ lastScrollPos: n,
4000
+ lastDepth: i,
3907
4001
  lastDirection: Z.DOWN,
3908
4002
  lastEventTime: 0,
3909
4003
  firstScrollEventTime: null,
3910
- maxDepthReached: n,
4004
+ maxDepthReached: i,
3911
4005
  debounceTimer: null,
3912
4006
  listener: null
3913
- }, c = () => {
4007
+ }, d = () => {
3914
4008
  this.get("suppressNextScroll") || (l.firstScrollEventTime === null && (l.firstScrollEventTime = Date.now()), this.clearContainerTimer(l), l.debounceTimer = window.setTimeout(() => {
3915
- const d = this.calculateScrollData(l);
3916
- if (d) {
4009
+ const c = this.calculateScrollData(l);
4010
+ if (c) {
3917
4011
  const f = Date.now();
3918
- this.processScrollEvent(l, d, f);
4012
+ this.processScrollEvent(l, c, f);
3919
4013
  }
3920
4014
  l.debounceTimer = null;
3921
4015
  }, 250));
3922
4016
  };
3923
- l.listener = c, this.containers.push(l), e === window ? window.addEventListener("scroll", c, { passive: !0 }) : e.addEventListener("scroll", c, { passive: !0 });
4017
+ l.listener = d, this.containers.push(l), e === window ? window.addEventListener("scroll", d, { passive: !0 }) : e.addEventListener("scroll", d, { passive: !0 });
3924
4018
  }
3925
4019
  processScrollEvent(e, t, s) {
3926
4020
  if (!this.shouldEmitScrollEvent(e, t, s))
3927
4021
  return;
3928
4022
  e.lastEventTime = s, e.lastDepth = t.depth, e.lastDirection = t.direction;
3929
- const i = this.get("scrollEventCount") ?? 0;
3930
- this.set("scrollEventCount", i + 1), this.eventManager.track({
4023
+ const n = this.get("scrollEventCount") ?? 0;
4024
+ this.set("scrollEventCount", n + 1), this.eventManager.track({
3931
4025
  type: u.SCROLL,
3932
4026
  scroll_data: {
3933
4027
  ...t,
@@ -3968,21 +4062,21 @@ class Ms extends _ {
3968
4062
  calculateScrollDepth(e, t, s) {
3969
4063
  if (t <= s)
3970
4064
  return 0;
3971
- const i = t - s;
3972
- return Math.min(100, Math.max(0, Math.floor(e / i * 100)));
4065
+ const n = t - s;
4066
+ return Math.min(100, Math.max(0, Math.floor(e / n * 100)));
3973
4067
  }
3974
4068
  calculateScrollData(e) {
3975
- const { element: t, lastScrollPos: s, lastEventTime: i } = e, n = this.getScrollTop(t), o = Date.now(), l = Math.abs(n - s);
4069
+ const { element: t, lastScrollPos: s, lastEventTime: n } = e, i = this.getScrollTop(t), o = Date.now(), l = Math.abs(i - s);
3976
4070
  if (l < 10 || t === window && !this.isWindowScrollable())
3977
4071
  return null;
3978
- const c = this.getViewportHeight(t), d = this.getScrollHeight(t), f = this.getScrollDirection(n, s), g = this.calculateScrollDepth(n, d, c);
3979
- let I;
3980
- i > 0 ? I = o - i : e.firstScrollEventTime !== null ? I = o - e.firstScrollEventTime : I = 250;
3981
- const p = Math.round(l / I * 1e3);
3982
- return g > e.maxDepthReached && (e.maxDepthReached = g), e.lastScrollPos = n, {
4072
+ const d = this.getViewportHeight(t), c = this.getScrollHeight(t), f = this.getScrollDirection(i, s), g = this.calculateScrollDepth(i, c, d);
4073
+ let m;
4074
+ n > 0 ? m = o - n : e.firstScrollEventTime !== null ? m = o - e.firstScrollEventTime : m = 250;
4075
+ const E = Math.round(l / m * 1e3);
4076
+ return g > e.maxDepthReached && (e.maxDepthReached = g), e.lastScrollPos = i, {
3983
4077
  depth: g,
3984
4078
  direction: f,
3985
- velocity: p,
4079
+ velocity: E,
3986
4080
  max_depth_reached: e.maxDepthReached
3987
4081
  };
3988
4082
  }
@@ -3996,30 +4090,30 @@ class Ms extends _ {
3996
4090
  return e === window ? document.documentElement.scrollHeight : e.scrollHeight;
3997
4091
  }
3998
4092
  isElementScrollable(e) {
3999
- const t = getComputedStyle(e), s = t.overflowY === "auto" || t.overflowY === "scroll" || t.overflow === "auto" || t.overflow === "scroll", i = e.scrollHeight > e.clientHeight;
4000
- return s && i;
4093
+ const t = getComputedStyle(e), s = t.overflowY === "auto" || t.overflowY === "scroll" || t.overflow === "auto" || t.overflow === "scroll", n = e.scrollHeight > e.clientHeight;
4094
+ return s && n;
4001
4095
  }
4002
4096
  applyPrimaryScrollSelector(e) {
4003
4097
  let t;
4004
4098
  if (e === "window")
4005
4099
  t = window;
4006
4100
  else {
4007
- const i = document.querySelector(e);
4008
- if (!(i instanceof HTMLElement)) {
4101
+ const n = document.querySelector(e);
4102
+ if (!(n instanceof HTMLElement)) {
4009
4103
  a("debug", `Selector "${e}" did not match an HTMLElement`);
4010
4104
  return;
4011
4105
  }
4012
- t = i;
4106
+ t = n;
4013
4107
  }
4014
- this.containers.forEach((i) => {
4015
- this.updateContainerPrimary(i, i.element === t);
4016
- }), !this.containers.some((i) => i.element === t) && t instanceof HTMLElement && this.isElementScrollable(t) && this.setupScrollContainer(t, e);
4108
+ this.containers.forEach((n) => {
4109
+ this.updateContainerPrimary(n, n.element === t);
4110
+ }), !this.containers.some((n) => n.element === t) && t instanceof HTMLElement && this.isElementScrollable(t) && this.setupScrollContainer(t, e);
4017
4111
  }
4018
4112
  updateContainerPrimary(e, t) {
4019
4113
  e.isPrimary = t;
4020
4114
  }
4021
4115
  }
4022
- class Cs extends _ {
4116
+ class Cs extends v {
4023
4117
  eventManager;
4024
4118
  trackedElements = /* @__PURE__ */ new Map();
4025
4119
  observer = null;
@@ -4071,8 +4165,8 @@ class Cs extends _ {
4071
4165
  let t = this.trackedElements.size;
4072
4166
  for (const s of this.config.elements)
4073
4167
  try {
4074
- const i = document.querySelectorAll(s.selector);
4075
- for (const n of Array.from(i)) {
4168
+ const n = document.querySelectorAll(s.selector);
4169
+ for (const i of Array.from(n)) {
4076
4170
  if (t >= e) {
4077
4171
  a("debug", "ViewportHandler: Maximum tracked elements reached", {
4078
4172
  data: {
@@ -4083,18 +4177,18 @@ class Cs extends _ {
4083
4177
  });
4084
4178
  return;
4085
4179
  }
4086
- n.hasAttribute(`${b}-ignore`) || this.trackedElements.has(n) || (this.trackedElements.set(n, {
4087
- element: n,
4180
+ i.hasAttribute(`${b}-ignore`) || this.trackedElements.has(i) || (this.trackedElements.set(i, {
4181
+ element: i,
4088
4182
  selector: s.selector,
4089
4183
  id: s.id,
4090
4184
  name: s.name,
4091
4185
  startTime: null,
4092
4186
  timeoutId: null,
4093
4187
  lastFiredTime: null
4094
- }), this.observer?.observe(n), t++);
4188
+ }), this.observer?.observe(i), t++);
4095
4189
  }
4096
- } catch (i) {
4097
- a("debug", `ViewportHandler: Invalid selector "${s.selector}"`, { error: i });
4190
+ } catch (n) {
4191
+ a("debug", `ViewportHandler: Invalid selector "${s.selector}"`, { error: n });
4098
4192
  }
4099
4193
  a("debug", "ViewportHandler: Elements tracked", {
4100
4194
  data: { count: t, limit: e }
@@ -4107,11 +4201,11 @@ class Cs extends _ {
4107
4201
  if (!this.config) return;
4108
4202
  const t = this.config.minDwellTime ?? 1e3;
4109
4203
  for (const s of e) {
4110
- const i = this.trackedElements.get(s.target);
4111
- i && (s.isIntersecting ? i.startTime === null && (i.startTime = performance.now(), i.timeoutId = window.setTimeout(() => {
4112
- const n = Math.round(s.intersectionRatio * 100) / 100;
4113
- this.fireViewportEvent(i, n);
4114
- }, t)) : i.startTime !== null && (i.timeoutId !== null && (window.clearTimeout(i.timeoutId), i.timeoutId = null), i.startTime = null));
4204
+ const n = this.trackedElements.get(s.target);
4205
+ n && (s.isIntersecting ? n.startTime === null && (n.startTime = performance.now(), n.timeoutId = window.setTimeout(() => {
4206
+ const i = Math.round(s.intersectionRatio * 100) / 100;
4207
+ this.fireViewportEvent(n, i);
4208
+ }, t)) : n.startTime !== null && (n.timeoutId !== null && (window.clearTimeout(n.timeoutId), n.timeoutId = null), n.startTime = null));
4115
4209
  }
4116
4210
  };
4117
4211
  /**
@@ -4122,12 +4216,12 @@ class Cs extends _ {
4122
4216
  const s = Math.round(performance.now() - e.startTime);
4123
4217
  if (e.element.hasAttribute(`${b}-ignore`))
4124
4218
  return;
4125
- const i = this.config?.cooldownPeriod ?? 6e4, n = Date.now();
4126
- if (e.lastFiredTime !== null && n - e.lastFiredTime < i) {
4219
+ const n = this.config?.cooldownPeriod ?? 6e4, i = Date.now();
4220
+ if (e.lastFiredTime !== null && i - e.lastFiredTime < n) {
4127
4221
  a("debug", "ViewportHandler: Event suppressed by cooldown period", {
4128
4222
  data: {
4129
4223
  selector: e.selector,
4130
- cooldownRemaining: i - (n - e.lastFiredTime)
4224
+ cooldownRemaining: n - (i - e.lastFiredTime)
4131
4225
  }
4132
4226
  }), e.startTime = null, e.timeoutId = null;
4133
4227
  return;
@@ -4142,7 +4236,7 @@ class Cs extends _ {
4142
4236
  this.eventManager.track({
4143
4237
  type: u.VIEWPORT_VISIBLE,
4144
4238
  viewport_data: o
4145
- }), e.startTime = null, e.timeoutId = null, e.lastFiredTime = n;
4239
+ }), e.startTime = null, e.timeoutId = null, e.lastFiredTime = i;
4146
4240
  }
4147
4241
  /**
4148
4242
  * Sets up MutationObserver to detect dynamically added elements
@@ -4172,58 +4266,75 @@ class Cs extends _ {
4172
4266
  cleanupRemovedNodes(e) {
4173
4267
  e.forEach((t) => {
4174
4268
  if (t.nodeType !== 1) return;
4175
- const s = t, i = this.trackedElements.get(s);
4176
- i && (i.timeoutId !== null && window.clearTimeout(i.timeoutId), this.observer?.unobserve(s), this.trackedElements.delete(s)), Array.from(this.trackedElements.keys()).filter((o) => s.contains(o)).forEach((o) => {
4269
+ const s = t, n = this.trackedElements.get(s);
4270
+ n && (n.timeoutId !== null && window.clearTimeout(n.timeoutId), this.observer?.unobserve(s), this.trackedElements.delete(s)), Array.from(this.trackedElements.keys()).filter((o) => s.contains(o)).forEach((o) => {
4177
4271
  const l = this.trackedElements.get(o);
4178
4272
  l && l.timeoutId !== null && window.clearTimeout(l.timeoutId), this.observer?.unobserve(o), this.trackedElements.delete(o);
4179
4273
  });
4180
4274
  });
4181
4275
  }
4182
4276
  }
4183
- const Rs = "tracelog_session_id";
4184
- class Ns extends _ {
4277
+ const Rs = "tracelog_session_id", Ns = "tracelog_user_id";
4278
+ class Os extends v {
4185
4279
  visibilityHandler = null;
4186
- lastSyncedSessionId = null;
4280
+ pageshowHandler = null;
4281
+ lastSyncedKey = null;
4187
4282
  activate() {
4188
- this.cleanupVisibilityListener(), this.syncCartAttribute(), this.setupVisibilityListener();
4283
+ this.cleanupListeners(), this.syncCartAttribute(), this.setupListeners();
4189
4284
  }
4190
4285
  deactivate() {
4191
- this.cleanupVisibilityListener(), this.lastSyncedSessionId = null;
4286
+ this.cleanupListeners(), this.lastSyncedKey = null;
4192
4287
  }
4193
- /** Re-syncs the cart attribute when session rotates (called by App on SESSION_START). */
4288
+ /** Re-syncs cart attributes when session rotates (called by App on SESSION_START). */
4194
4289
  onSessionChange() {
4195
4290
  this.syncCartAttribute();
4196
4291
  }
4197
4292
  syncCartAttribute() {
4198
4293
  const e = this.get("sessionId");
4199
- !e || e === this.lastSyncedSessionId || (this.lastSyncedSessionId = e, this.postCartUpdate(e));
4294
+ if (!e) return;
4295
+ const t = this.get("userId"), s = typeof t == "string" && t.length > 0 ? t : "", n = `${e}|${s}`;
4296
+ n !== this.lastSyncedKey && (this.lastSyncedKey = n, this.postCartUpdate(e, s));
4200
4297
  }
4201
- postCartUpdate(e) {
4298
+ postCartUpdate(e, t) {
4299
+ const s = { [Rs]: e };
4300
+ t.length > 0 && (s[Ns] = t);
4202
4301
  try {
4203
4302
  fetch("/cart/update.js", {
4204
4303
  method: "POST",
4205
4304
  headers: { "Content-Type": "application/json" },
4206
- body: JSON.stringify({ attributes: { [Rs]: e } }),
4305
+ body: JSON.stringify({ attributes: s }),
4207
4306
  credentials: "same-origin"
4208
- }).then((t) => {
4209
- t.ok || (this.lastSyncedSessionId = null, a("debug", "Shopify cart attribute update failed", { data: { status: t.status } }));
4307
+ }).then((n) => {
4308
+ n.ok || (this.lastSyncedKey = null, a("debug", "Shopify cart attribute update failed", { data: { status: n.status } }));
4210
4309
  }).catch(() => {
4211
- this.lastSyncedSessionId = null, a("debug", "Shopify cart attribute update failed");
4310
+ this.lastSyncedKey = null, a("debug", "Shopify cart attribute update failed");
4212
4311
  });
4213
4312
  } catch {
4214
- this.lastSyncedSessionId = null, a("debug", "Shopify cart attribute update failed");
4313
+ this.lastSyncedKey = null, a("debug", "Shopify cart attribute update failed");
4215
4314
  }
4216
4315
  }
4217
- setupVisibilityListener() {
4316
+ /**
4317
+ * Sync triggers (theme-agnostic):
4318
+ * - `visibilitychange`: catches tab refocus (long sessions, OAuth round-trips).
4319
+ * - `pageshow` with `event.persisted === true`: catches bfcache restore so a
4320
+ * user returning from an external checkout / Shop Pay window picks up the
4321
+ * current sessionId before any further interaction.
4322
+ *
4323
+ * Both triggers go through `syncCartAttribute()` which dedupes by
4324
+ * `sessionId|userId`, so spurious calls cost nothing.
4325
+ */
4326
+ setupListeners() {
4218
4327
  this.visibilityHandler = () => {
4219
4328
  document.hidden || this.syncCartAttribute();
4220
- }, document.addEventListener("visibilitychange", this.visibilityHandler);
4329
+ }, document.addEventListener("visibilitychange", this.visibilityHandler), this.pageshowHandler = (e) => {
4330
+ e.persisted && this.syncCartAttribute();
4331
+ }, window.addEventListener("pageshow", this.pageshowHandler);
4221
4332
  }
4222
- cleanupVisibilityListener() {
4223
- this.visibilityHandler && (document.removeEventListener("visibilitychange", this.visibilityHandler), this.visibilityHandler = null);
4333
+ cleanupListeners() {
4334
+ this.visibilityHandler && (document.removeEventListener("visibilitychange", this.visibilityHandler), this.visibilityHandler = null), this.pageshowHandler && (window.removeEventListener("pageshow", this.pageshowHandler), this.pageshowHandler = null);
4224
4335
  }
4225
4336
  }
4226
- class Os {
4337
+ class Ps {
4227
4338
  storage;
4228
4339
  sessionStorageRef;
4229
4340
  fallbackStorage = /* @__PURE__ */ new Map();
@@ -4392,19 +4503,19 @@ class Os {
4392
4503
  return !1;
4393
4504
  try {
4394
4505
  const e = [], t = [];
4395
- for (let n = 0; n < this.storage.length; n++) {
4396
- const o = this.storage.key(n);
4506
+ for (let i = 0; i < this.storage.length; i++) {
4507
+ const o = this.storage.key(i);
4397
4508
  o?.startsWith("tracelog_") && (e.push(o), o.startsWith("tracelog_persisted_events_") && t.push(o));
4398
4509
  }
4399
4510
  if (t.length > 0)
4400
- return t.forEach((n) => {
4511
+ return t.forEach((i) => {
4401
4512
  try {
4402
- this.storage.removeItem(n);
4513
+ this.storage.removeItem(i);
4403
4514
  } catch {
4404
4515
  }
4405
4516
  }), !0;
4406
- const s = ["tracelog_session_", "tracelog_user_id", "tracelog_device_id", "tracelog_config"], i = e.filter((n) => !s.some((o) => n.startsWith(o)));
4407
- return i.length > 0 ? (i.slice(0, 5).forEach((o) => {
4517
+ const s = ["tracelog_session_", "tracelog_user_id", "tracelog_device_id", "tracelog_config"], n = e.filter((i) => !s.some((o) => i.startsWith(o)));
4518
+ return n.length > 0 ? (n.slice(0, 5).forEach((o) => {
4408
4519
  try {
4409
4520
  this.storage.removeItem(o);
4410
4521
  } catch {
@@ -4506,7 +4617,7 @@ class Os {
4506
4617
  this.fallbackSessionStorage.delete(e);
4507
4618
  }
4508
4619
  }
4509
- class Ps extends _ {
4620
+ class Ds extends v {
4510
4621
  eventManager;
4511
4622
  reportedByNav = /* @__PURE__ */ new Map();
4512
4623
  navigationHistory = [];
@@ -4517,7 +4628,7 @@ class Ps extends _ {
4517
4628
  navigationCounter = 0;
4518
4629
  // Counter for handling simultaneous navigations edge case
4519
4630
  constructor(e) {
4520
- super(), this.eventManager = e, this.vitalThresholds = Qe(_e);
4631
+ super(), this.eventManager = e, this.vitalThresholds = Qe(ye);
4521
4632
  }
4522
4633
  /**
4523
4634
  * Starts tracking Web Vitals and performance metrics.
@@ -4534,7 +4645,7 @@ class Ps extends _ {
4534
4645
  * @returns Promise that resolves when tracking is initialized
4535
4646
  */
4536
4647
  async startTracking() {
4537
- const e = this.get("config"), t = e?.webVitalsMode ?? _e;
4648
+ const e = this.get("config"), t = e?.webVitalsMode ?? ye;
4538
4649
  this.vitalThresholds = Qe(t), e?.webVitalsThresholds && (this.vitalThresholds = { ...this.vitalThresholds, ...e.webVitalsThresholds }), await this.initWebVitals(), this.observeLongTasks();
4539
4650
  }
4540
4651
  /**
@@ -4559,8 +4670,8 @@ class Ps extends _ {
4559
4670
  this.reportTTFB(), this.safeObserve(
4560
4671
  "largest-contentful-paint",
4561
4672
  (s) => {
4562
- const i = s.getEntries(), n = i[i.length - 1];
4563
- n && this.sendVital({ type: "LCP", value: Number(n.startTime.toFixed(2)) });
4673
+ const n = s.getEntries(), i = n[n.length - 1];
4674
+ i && this.sendVital({ type: "LCP", value: Number(i.startTime.toFixed(2)) });
4564
4675
  },
4565
4676
  { type: "largest-contentful-paint", buffered: !0 },
4566
4677
  !0
@@ -4569,10 +4680,10 @@ class Ps extends _ {
4569
4680
  this.safeObserve(
4570
4681
  "layout-shift",
4571
4682
  (s) => {
4572
- const i = this.getNavigationId();
4573
- i !== t && (e = 0, t = i);
4574
- const n = s.getEntries();
4575
- for (const o of n) {
4683
+ const n = this.getNavigationId();
4684
+ n !== t && (e = 0, t = n);
4685
+ const i = s.getEntries();
4686
+ for (const o of i) {
4576
4687
  if (o.hadRecentInput === !0)
4577
4688
  continue;
4578
4689
  const l = typeof o.value == "number" ? o.value : 0;
@@ -4584,32 +4695,32 @@ class Ps extends _ {
4584
4695
  ), this.safeObserve(
4585
4696
  "paint",
4586
4697
  (s) => {
4587
- for (const i of s.getEntries())
4588
- i.name === "first-contentful-paint" && this.sendVital({ type: "FCP", value: Number(i.startTime.toFixed(2)) });
4698
+ for (const n of s.getEntries())
4699
+ n.name === "first-contentful-paint" && this.sendVital({ type: "FCP", value: Number(n.startTime.toFixed(2)) });
4589
4700
  },
4590
4701
  { type: "paint", buffered: !0 },
4591
4702
  !0
4592
4703
  ), this.safeObserve(
4593
4704
  "event",
4594
4705
  (s) => {
4595
- let i = 0;
4596
- const n = s.getEntries();
4597
- for (const o of n) {
4706
+ let n = 0;
4707
+ const i = s.getEntries();
4708
+ for (const o of i) {
4598
4709
  const l = (o.processingEnd ?? 0) - (o.startTime ?? 0);
4599
- i = Math.max(i, l);
4710
+ n = Math.max(n, l);
4600
4711
  }
4601
- i > 0 && this.sendVital({ type: "INP", value: Number(i.toFixed(2)) });
4712
+ n > 0 && this.sendVital({ type: "INP", value: Number(n.toFixed(2)) });
4602
4713
  },
4603
4714
  { type: "event", buffered: !0 }
4604
4715
  );
4605
4716
  }
4606
4717
  async initWebVitals() {
4607
4718
  try {
4608
- const { onLCP: e, onCLS: t, onFCP: s, onTTFB: i, onINP: n } = await Promise.resolve().then(() => ur), o = (l) => (c) => {
4609
- const d = Number(c.value.toFixed(2));
4610
- this.sendVital({ type: l, value: d });
4719
+ const { onLCP: e, onCLS: t, onFCP: s, onTTFB: n, onINP: i } = await Promise.resolve().then(() => hr), o = (l) => (d) => {
4720
+ const c = Number(d.value.toFixed(2));
4721
+ this.sendVital({ type: l, value: c });
4611
4722
  };
4612
- e(o("LCP"), { reportAllChanges: !1 }), t(o("CLS"), { reportAllChanges: !1 }), s(o("FCP"), { reportAllChanges: !1 }), i(o("TTFB"), { reportAllChanges: !1 }), n(o("INP"), { reportAllChanges: !1 });
4723
+ e(o("LCP"), { reportAllChanges: !1 }), t(o("CLS"), { reportAllChanges: !1 }), s(o("FCP"), { reportAllChanges: !1 }), n(o("TTFB"), { reportAllChanges: !1 }), i(o("INP"), { reportAllChanges: !1 });
4613
4724
  } catch (e) {
4614
4725
  a("debug", "Failed to load web-vitals library, using fallback", { error: e }), this.observeWebVitalsFallback();
4615
4726
  }
@@ -4631,8 +4742,8 @@ class Ps extends _ {
4631
4742
  (e) => {
4632
4743
  const t = e.getEntries();
4633
4744
  for (const s of t) {
4634
- const i = Number(s.duration.toFixed(2)), n = Date.now();
4635
- n - this.lastLongTaskSentAt >= qt && (this.shouldSendVital("LONG_TASK", i) && this.trackWebVital("LONG_TASK", i), this.lastLongTaskSentAt = n);
4745
+ const n = Number(s.duration.toFixed(2)), i = Date.now();
4746
+ i - this.lastLongTaskSentAt >= qt && (this.shouldSendVital("LONG_TASK", n) && this.trackWebVital("LONG_TASK", n), this.lastLongTaskSentAt = i);
4636
4747
  }
4637
4748
  },
4638
4749
  { type: "longtask", buffered: !0 }
@@ -4649,8 +4760,8 @@ class Ps extends _ {
4649
4760
  if (s)
4650
4761
  s.add(e.type);
4651
4762
  else if (this.reportedByNav.set(t, /* @__PURE__ */ new Set([e.type])), this.navigationHistory.push(t), this.navigationHistory.length > Jt) {
4652
- const n = this.navigationHistory.shift();
4653
- n && this.reportedByNav.delete(n);
4763
+ const i = this.navigationHistory.shift();
4764
+ i && this.reportedByNav.delete(i);
4654
4765
  }
4655
4766
  }
4656
4767
  this.trackWebVital(e.type, e.value);
@@ -4694,8 +4805,8 @@ class Ps extends _ {
4694
4805
  const e = performance.getEntriesByType("navigation")[0];
4695
4806
  if (!e)
4696
4807
  return null;
4697
- const t = e.startTime || performance.now(), s = ++this.navigationCounter, i = `${t.toFixed(2)}_${window.location.pathname}`;
4698
- return s > 1 ? `${i}_${s}` : i;
4808
+ const t = e.startTime || performance.now(), s = ++this.navigationCounter, n = `${t.toFixed(2)}_${window.location.pathname}`;
4809
+ return s > 1 ? `${n}_${s}` : n;
4699
4810
  } catch (e) {
4700
4811
  return a("debug", "Failed to get navigation ID", { error: e }), null;
4701
4812
  }
@@ -4705,29 +4816,29 @@ class Ps extends _ {
4705
4816
  const t = PerformanceObserver.supportedEntryTypes;
4706
4817
  return !t || t.includes(e);
4707
4818
  }
4708
- safeObserve(e, t, s, i = !1) {
4819
+ safeObserve(e, t, s, n = !1) {
4709
4820
  try {
4710
4821
  if (!this.isObserverSupported(e))
4711
4822
  return !1;
4712
- const n = new PerformanceObserver((o, l) => {
4823
+ const i = new PerformanceObserver((o, l) => {
4713
4824
  try {
4714
4825
  t(o, l);
4715
- } catch (c) {
4826
+ } catch (d) {
4716
4827
  a("debug", "Observer callback failed", {
4717
- error: c,
4828
+ error: d,
4718
4829
  data: { type: e }
4719
4830
  });
4720
4831
  }
4721
- if (i)
4832
+ if (n)
4722
4833
  try {
4723
4834
  l.disconnect();
4724
4835
  } catch {
4725
4836
  }
4726
4837
  });
4727
- return n.observe(s ?? { type: e, buffered: !0 }), i || this.observers.push(n), !0;
4728
- } catch (n) {
4838
+ return i.observe(s ?? { type: e, buffered: !0 }), n || this.observers.push(i), !0;
4839
+ } catch (i) {
4729
4840
  return a("debug", "Failed to create performance observer", {
4730
- error: n,
4841
+ error: i,
4731
4842
  data: { type: e }
4732
4843
  }), !1;
4733
4844
  }
@@ -4739,7 +4850,7 @@ class Ps extends _ {
4739
4850
  return !(typeof s == "number" && t <= s);
4740
4851
  }
4741
4852
  }
4742
- class ae extends _ {
4853
+ class ae extends v {
4743
4854
  eventManager;
4744
4855
  recentErrors = /* @__PURE__ */ new Map();
4745
4856
  errorBurstCounter = 0;
@@ -4775,11 +4886,11 @@ class ae extends _ {
4775
4886
  const e = Date.now();
4776
4887
  if (e < this.burstBackoffUntil)
4777
4888
  return !1;
4778
- if (e - this.burstWindowStart > jt && (this.errorBurstCounter = 0, this.burstWindowStart = e), this.errorBurstCounter++, this.errorBurstCounter > zt)
4779
- return this.burstBackoffUntil = e + ze, a("debug", "Error burst detected - entering cooldown", {
4889
+ if (e - this.burstWindowStart > jt && (this.errorBurstCounter = 0, this.burstWindowStart = e), this.errorBurstCounter++, this.errorBurstCounter > Kt)
4890
+ return this.burstBackoffUntil = e + Ke, a("debug", "Error burst detected - entering cooldown", {
4780
4891
  data: {
4781
4892
  errorsInWindow: this.errorBurstCounter,
4782
- cooldownMs: ze
4893
+ cooldownMs: Ke
4783
4894
  }
4784
4895
  }), !1;
4785
4896
  const s = this.get("config").errorSampling ?? lt;
@@ -4810,13 +4921,13 @@ class ae extends _ {
4810
4921
  const t = this.extractRejectionMessage(e.reason), s = this.sanitize(t);
4811
4922
  if (this.shouldSuppressError(B.PROMISE_REJECTION, s))
4812
4923
  return;
4813
- const i = e.reason instanceof Error && typeof e.reason.stack == "string" ? this.truncateStack(e.reason.stack) : void 0;
4924
+ const n = e.reason instanceof Error && typeof e.reason.stack == "string" ? this.truncateStack(e.reason.stack) : void 0;
4814
4925
  this.eventManager.track({
4815
4926
  type: u.ERROR,
4816
4927
  error_data: {
4817
4928
  type: B.PROMISE_REJECTION,
4818
4929
  message: s,
4819
- ...i !== void 0 && { stack: i }
4930
+ ...n !== void 0 && { stack: n }
4820
4931
  }
4821
4932
  });
4822
4933
  };
@@ -4834,46 +4945,46 @@ class ae extends _ {
4834
4945
  }
4835
4946
  }
4836
4947
  sanitize(e) {
4837
- const t = e.length > Xe ? e.slice(0, Xe) + "..." : e;
4948
+ const t = e.length > Ge ? e.slice(0, Ge) + "..." : e;
4838
4949
  return this.sanitizePii(t);
4839
4950
  }
4840
4951
  sanitizePii(e) {
4841
4952
  let t = e;
4842
4953
  for (const s of at) {
4843
- const i = new RegExp(s.source, s.flags);
4844
- t = t.replace(i, "[REDACTED]");
4954
+ const n = new RegExp(s.source, s.flags);
4955
+ t = t.replace(n, "[REDACTED]");
4845
4956
  }
4846
4957
  return t;
4847
4958
  }
4848
4959
  shouldSuppressError(e, t) {
4849
- const s = Date.now(), i = `${e}:${t}`, n = this.recentErrors.get(i);
4850
- return n !== void 0 && s - n < je ? (this.recentErrors.set(i, s), !0) : (this.recentErrors.set(i, s), this.recentErrors.size > Gt ? (this.recentErrors.clear(), this.recentErrors.set(i, s), !1) : (this.recentErrors.size > ee && this.pruneOldErrors(), !1));
4960
+ const s = Date.now(), n = `${e}:${t}`, i = this.recentErrors.get(n);
4961
+ return i !== void 0 && s - i < je ? (this.recentErrors.set(n, s), !0) : (this.recentErrors.set(n, s), this.recentErrors.size > Xt ? (this.recentErrors.clear(), this.recentErrors.set(n, s), !1) : (this.recentErrors.size > ee && this.pruneOldErrors(), !1));
4851
4962
  }
4852
4963
  static TRUNCATION_SUFFIX = `
4853
4964
  ...truncated`;
4854
4965
  truncateStack(e) {
4855
- if (e.length <= Ge) return this.sanitizePii(e);
4856
- const t = Ge - ae.TRUNCATION_SUFFIX.length, s = e.slice(0, t) + ae.TRUNCATION_SUFFIX;
4966
+ if (e.length <= Xe) return this.sanitizePii(e);
4967
+ const t = Xe - ae.TRUNCATION_SUFFIX.length, s = e.slice(0, t) + ae.TRUNCATION_SUFFIX;
4857
4968
  return this.sanitizePii(s);
4858
4969
  }
4859
4970
  pruneOldErrors() {
4860
4971
  const e = Date.now();
4861
- for (const [i, n] of this.recentErrors.entries())
4862
- e - n > je && this.recentErrors.delete(i);
4972
+ for (const [n, i] of this.recentErrors.entries())
4973
+ e - i > je && this.recentErrors.delete(n);
4863
4974
  if (this.recentErrors.size <= ee)
4864
4975
  return;
4865
- const t = Array.from(this.recentErrors.entries()).sort((i, n) => i[1] - n[1]), s = this.recentErrors.size - ee;
4866
- for (let i = 0; i < s; i += 1) {
4867
- const n = t[i];
4868
- n && this.recentErrors.delete(n[0]);
4976
+ const t = Array.from(this.recentErrors.entries()).sort((n, i) => n[1] - i[1]), s = this.recentErrors.size - ee;
4977
+ for (let n = 0; n < s; n += 1) {
4978
+ const i = t[n];
4979
+ i && this.recentErrors.delete(i[0]);
4869
4980
  }
4870
4981
  }
4871
4982
  }
4872
- class Ds extends _ {
4983
+ class ks extends v {
4873
4984
  isInitialized = !1;
4874
4985
  suppressNextScrollTimer = null;
4875
4986
  pageUnloadHandler = null;
4876
- emitter = new ps();
4987
+ emitter = new Es();
4877
4988
  transformers = {};
4878
4989
  customHeadersProvider;
4879
4990
  managers = {};
@@ -4892,19 +5003,19 @@ class Ds extends _ {
4892
5003
  async init(e = {}) {
4893
5004
  if (this.isInitialized)
4894
5005
  return { sessionId: this.get("sessionId") ?? "" };
4895
- this.managers.storage = new Os();
5006
+ this.managers.storage = new Ps();
4896
5007
  try {
4897
5008
  this.setupState(e);
4898
5009
  const t = e.integrations?.custom?.headers ?? {}, s = e.integrations?.custom?.fetchCredentials ?? "include";
4899
- return this.managers.event = new vs(
5010
+ return this.managers.event = new _s(
4900
5011
  this.managers.storage,
4901
5012
  this.emitter,
4902
5013
  this.transformers,
4903
5014
  t,
4904
5015
  this.customHeadersProvider,
4905
5016
  s
4906
- ), this.loadPersistedIdentity(), this.initializeHandlers(), this.setupPageLifecycleListeners(), await this.managers.event.recoverPersistedEvents().catch((i) => {
4907
- a("warn", "Failed to recover persisted events", { error: i });
5017
+ ), this.loadPersistedIdentity(), this.initializeHandlers(), this.setupPageLifecycleListeners(), await this.managers.event.recoverPersistedEvents().catch((n) => {
5018
+ a("warn", "Failed to recover persisted events", { error: n });
4908
5019
  }), this.isInitialized = !0, { sessionId: this.get("sessionId") ?? "" };
4909
5020
  } catch (t) {
4910
5021
  this.destroy(!0);
@@ -4926,11 +5037,11 @@ class Ds extends _ {
4926
5037
  }
4927
5038
  let s = t;
4928
5039
  t && typeof t == "object" && !Array.isArray(t) && Object.getPrototypeOf(t) !== Object.prototype && (s = Object.assign({}, t));
4929
- const { valid: i, error: n, sanitizedMetadata: o } = Es(e, s);
4930
- if (!i) {
4931
- if (this.get("mode") === ne.QA)
4932
- throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${n}`);
4933
- a("warn", `Custom event "${e}" dropped: ${n}`);
5040
+ const { valid: n, error: i, sanitizedMetadata: o } = ps(e, s);
5041
+ if (!n) {
5042
+ if (this.get("mode") === ie.QA)
5043
+ throw new Error(`[TraceLog] Custom event "${e}" validation failed: ${i}`);
5044
+ a("warn", `Custom event "${e}" dropped: ${i}`);
4934
5045
  return;
4935
5046
  }
4936
5047
  this.managers.event.track({
@@ -4996,14 +5107,14 @@ class Ds extends _ {
4996
5107
  }
4997
5108
  setupState(e = {}) {
4998
5109
  this.set("config", e);
4999
- const t = _s.getId(this.managers.storage);
5110
+ const t = vs.getId(this.managers.storage);
5000
5111
  this.set("userId", t);
5001
5112
  const s = ls(e);
5002
5113
  this.set("collectApiUrls", s);
5003
- const i = Xt();
5004
- this.set("device", i);
5005
- const n = ye(window.location.href, e.sensitiveQueryParams);
5006
- this.set("pageUrl", n), ss() && this.set("mode", ne.QA);
5114
+ const n = Gt();
5115
+ this.set("device", n);
5116
+ const i = we(window.location.href, e.sensitiveQueryParams);
5117
+ this.set("pageUrl", i), ss() && this.set("mode", ie.QA);
5007
5118
  }
5008
5119
  /**
5009
5120
  * Returns the current configuration object.
@@ -5071,11 +5182,11 @@ class Ds extends _ {
5071
5182
  const t = this.validateGlobalMetadata(e);
5072
5183
  if (!t.valid)
5073
5184
  throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);
5074
- const i = {
5185
+ const n = {
5075
5186
  ...this.get("config"),
5076
5187
  globalMetadata: e
5077
5188
  };
5078
- this.set("config", i), a("debug", "Global metadata updated (replaced)", { data: { keys: Object.keys(e) } });
5189
+ this.set("config", n), a("debug", "Global metadata updated (replaced)", { data: { keys: Object.keys(e) } });
5079
5190
  }
5080
5191
  /**
5081
5192
  * Merges new metadata with existing global metadata.
@@ -5088,12 +5199,12 @@ class Ds extends _ {
5088
5199
  const t = this.validateGlobalMetadata(e);
5089
5200
  if (!t.valid)
5090
5201
  throw new Error(`[TraceLog] Invalid global metadata: ${t.error}`);
5091
- const s = this.get("config"), n = {
5202
+ const s = this.get("config"), i = {
5092
5203
  ...s.globalMetadata ?? {},
5093
5204
  ...e
5094
5205
  }, o = {
5095
5206
  ...s,
5096
- globalMetadata: n
5207
+ globalMetadata: i
5097
5208
  };
5098
5209
  this.set("config", o), a("debug", "Global metadata updated (merged)", { data: { keys: Object.keys(e) } });
5099
5210
  }
@@ -5121,12 +5232,12 @@ class Ds extends _ {
5121
5232
  a("warn", "identify() userId exceeds 256 characters", { data: { length: e.trim().length } });
5122
5233
  return;
5123
5234
  }
5124
- const s = e.trim(), i = ht(t), n = {
5235
+ const s = e.trim(), n = ht(t), i = {
5125
5236
  userId: s,
5126
- ...i ? { traits: i } : {}
5237
+ ...n ? { traits: n } : {}
5127
5238
  };
5128
- this.set("identity", n), this.persistIdentity(n), a("debug", "Visitor identified", {
5129
- data: { userIdLength: s.length, traitKeys: i ? Object.keys(i) : [] }
5239
+ this.set("identity", i), this.persistIdentity(i), a("debug", "Visitor identified", {
5240
+ data: { userIdLength: s.length, traitKeys: n ? Object.keys(n) : [] }
5130
5241
  });
5131
5242
  }
5132
5243
  /**
@@ -5141,7 +5252,7 @@ class Ds extends _ {
5141
5252
  async resetIdentity() {
5142
5253
  await this.managers.event?.flushImmediately(), this.set("identity", void 0), this.clearPersistedIdentity();
5143
5254
  const e = dt();
5144
- this.managers.storage.setItem(Te, e), this.set("userId", e), this.set("hasStartSession", !1), this.set("sessionId", null), this.handlers.session?.stopTracking(), this.handlers.session?.startTracking(), a("debug", "Identity reset, new UUID generated");
5255
+ this.managers.storage.setItem(Ie, e), this.set("userId", e), this.set("hasStartSession", !1), this.set("sessionId", null), this.handlers.session?.stopTracking(), this.handlers.session?.startTracking(), a("debug", "Identity reset, new UUID generated");
5145
5256
  }
5146
5257
  /**
5147
5258
  * Returns the project ID used for identity storage scoping.
@@ -5155,7 +5266,7 @@ class Ds extends _ {
5155
5266
  */
5156
5267
  persistIdentity(e) {
5157
5268
  try {
5158
- const t = this.getProjectId(), s = fe(t);
5269
+ const t = this.getProjectId(), s = me(t);
5159
5270
  this.managers.storage.setItem(s, JSON.stringify(e));
5160
5271
  } catch {
5161
5272
  a("debug", "Failed to persist identity to localStorage");
@@ -5166,31 +5277,31 @@ class Ds extends _ {
5166
5277
  * Also migrates pending identity (set before init) to the project-scoped key.
5167
5278
  */
5168
5279
  loadPersistedIdentity() {
5169
- const e = this.managers.storage, t = this.getProjectId(), s = fe(t);
5280
+ const e = this.managers.storage, t = this.getProjectId(), s = me(t);
5170
5281
  try {
5171
- const i = e.getItem(U);
5172
- if (i) {
5173
- const n = JSON.parse(i);
5174
- if (e.removeItem(U), !this.isValidIdentityData(n)) {
5282
+ const n = e.getItem(F);
5283
+ if (n) {
5284
+ const i = JSON.parse(n);
5285
+ if (e.removeItem(F), !this.isValidIdentityData(i)) {
5175
5286
  a("debug", "Invalid pending identity in localStorage, discarded");
5176
5287
  return;
5177
5288
  }
5178
- const o = { ...n, userId: n.userId.trim() };
5289
+ const o = { ...i, userId: i.userId.trim() };
5179
5290
  e.setItem(s, JSON.stringify(o)), this.set("identity", o), a("debug", "Migrated pending identity to project-scoped key");
5180
5291
  return;
5181
5292
  }
5182
5293
  } catch {
5183
- e.removeItem(U);
5294
+ e.removeItem(F);
5184
5295
  }
5185
5296
  try {
5186
- const i = e.getItem(s);
5187
- if (i) {
5188
- const n = JSON.parse(i);
5189
- if (!this.isValidIdentityData(n)) {
5297
+ const n = e.getItem(s);
5298
+ if (n) {
5299
+ const i = JSON.parse(n);
5300
+ if (!this.isValidIdentityData(i)) {
5190
5301
  e.removeItem(s), a("debug", "Invalid persisted identity in localStorage, discarded");
5191
5302
  return;
5192
5303
  }
5193
- const o = { ...n, userId: n.userId.trim() };
5304
+ const o = { ...i, userId: i.userId.trim() };
5194
5305
  this.set("identity", o), a("debug", "Loaded persisted identity");
5195
5306
  }
5196
5307
  } catch {
@@ -5207,8 +5318,8 @@ class Ds extends _ {
5207
5318
  if (typeof t != "string" || t.trim().length === 0 || t.trim().length > 256) return !1;
5208
5319
  if (s !== void 0) {
5209
5320
  if (typeof s != "object" || s === null || Array.isArray(s)) return !1;
5210
- for (const i of Object.values(s))
5211
- if (typeof i != "string") return !1;
5321
+ for (const n of Object.values(s))
5322
+ if (typeof n != "string") return !1;
5212
5323
  }
5213
5324
  return !0;
5214
5325
  }
@@ -5218,7 +5329,7 @@ class Ds extends _ {
5218
5329
  clearPersistedIdentity() {
5219
5330
  try {
5220
5331
  const e = this.managers.storage, t = this.getProjectId();
5221
- e.removeItem(fe(t)), e.removeItem(U);
5332
+ e.removeItem(me(t)), e.removeItem(F);
5222
5333
  } catch {
5223
5334
  a("debug", "Failed to clear persisted identity");
5224
5335
  }
@@ -5239,38 +5350,38 @@ class Ds extends _ {
5239
5350
  this.set("suppressNextScroll", !1);
5240
5351
  }, 500);
5241
5352
  };
5242
- if (this.handlers.pageView = new Ls(this.managers.event, t), this.handlers.pageView.startTracking(), this.handlers.click = new As(this.managers.event), this.handlers.click.startTracking(), this.handlers.scroll = new Ms(this.managers.event), this.handlers.scroll.startTracking(), this.handlers.performance = new Ps(this.managers.event), this.handlers.performance.startTracking().catch((s) => {
5353
+ if (this.handlers.pageView = new Ls(this.managers.event, t), this.handlers.pageView.startTracking(), this.handlers.click = new As(this.managers.event), this.handlers.click.startTracking(), this.handlers.scroll = new Ms(this.managers.event), this.handlers.scroll.startTracking(), this.handlers.performance = new Ds(this.managers.event), this.handlers.performance.startTracking().catch((s) => {
5243
5354
  a("warn", "Failed to start performance tracking", { error: s });
5244
5355
  }), this.handlers.error = new ae(this.managers.event), this.handlers.error.startTracking(), e.viewport && (this.handlers.viewport = new Cs(this.managers.event), this.handlers.viewport.startTracking()), e.integrations?.tracelog?.shopify) {
5245
- const s = new Ns();
5246
- s.activate(), this.integrationInstances.shopifyCartLinker = s, this.emitter.on(se.EVENT, (i) => {
5247
- i.type === u.SESSION_START && s.onSessionChange();
5356
+ const s = new Os();
5357
+ s.activate(), this.integrationInstances.shopifyCartLinker = s, this.emitter.on(se.EVENT, (n) => {
5358
+ n.type === u.SESSION_START && s.onSessionChange();
5248
5359
  });
5249
5360
  }
5250
5361
  }
5251
5362
  }
5252
5363
  const k = [], M = [];
5253
- let D = null, h = null, R = !1, T = !1, P = null;
5254
- const ks = async (r) => typeof window > "u" || typeof document > "u" ? { sessionId: "" } : (T = !1, window.__traceLogDisabled === !0 ? { sessionId: "" } : h ? { sessionId: h.getSessionId() ?? "" } : (R && P || (R = !0, P = (async () => {
5364
+ let D = null, h = null, R = !1, _ = !1, P = null;
5365
+ const Vs = async (r) => typeof window > "u" || typeof document > "u" ? { sessionId: "" } : (_ = !1, window.__traceLogDisabled === !0 ? { sessionId: "" } : h ? { sessionId: h.getSessionId() ?? "" } : (R && P || (R = !0, P = (async () => {
5255
5366
  try {
5256
- const e = fs(r ?? {}), t = new Ds();
5367
+ const e = fs(r ?? {}), t = new ks();
5257
5368
  try {
5258
5369
  k.forEach(({ event: o, callback: l }) => {
5259
5370
  t.on(o, l);
5260
5371
  }), k.length = 0, M.forEach(({ hook: o, fn: l }) => {
5261
5372
  o === "beforeSend" ? t.setTransformer("beforeSend", l) : t.setTransformer("beforeBatch", l);
5262
5373
  }), M.length = 0, D && (t.setCustomHeaders(D), D = null);
5263
- const s = t.init(e), i = new Promise((o, l) => {
5374
+ const s = t.init(e), n = new Promise((o, l) => {
5264
5375
  setTimeout(() => {
5265
5376
  l(new Error("[TraceLog] Initialization timeout after 10000ms"));
5266
5377
  }, 1e4);
5267
- }), n = await Promise.race([s, i]);
5268
- return h = t, n;
5378
+ }), i = await Promise.race([s, n]);
5379
+ return h = t, i;
5269
5380
  } catch (s) {
5270
5381
  try {
5271
5382
  t.destroy(!0);
5272
- } catch (i) {
5273
- a("error", "Failed to cleanup partially initialized app", { error: i });
5383
+ } catch (n) {
5384
+ a("error", "Failed to cleanup partially initialized app", { error: n });
5274
5385
  }
5275
5386
  throw s;
5276
5387
  }
@@ -5279,15 +5390,15 @@ const ks = async (r) => typeof window > "u" || typeof document > "u" ? { session
5279
5390
  } finally {
5280
5391
  R = !1, P = null;
5281
5392
  }
5282
- })()), P)), Vs = (r, e) => {
5393
+ })()), P)), Us = (r, e) => {
5283
5394
  if (!(typeof window > "u" || typeof document > "u")) {
5284
5395
  if (!h)
5285
5396
  throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");
5286
- if (T)
5397
+ if (_)
5287
5398
  throw new Error("[TraceLog] Cannot send events while TraceLog is being destroyed");
5288
5399
  h.sendCustomEvent(r, e);
5289
5400
  }
5290
- }, Us = (r, e) => {
5401
+ }, Fs = (r, e) => {
5291
5402
  if (!(typeof window > "u" || typeof document > "u")) {
5292
5403
  if (!h || R) {
5293
5404
  k.push({ event: r, callback: e });
@@ -5295,7 +5406,7 @@ const ks = async (r) => typeof window > "u" || typeof document > "u" ? { session
5295
5406
  }
5296
5407
  h.on(r, e);
5297
5408
  }
5298
- }, Fs = (r, e) => {
5409
+ }, Hs = (r, e) => {
5299
5410
  if (!(typeof window > "u" || typeof document > "u")) {
5300
5411
  if (!h) {
5301
5412
  const t = k.findIndex((s) => s.event === r && s.callback === e);
@@ -5305,7 +5416,7 @@ const ks = async (r) => typeof window > "u" || typeof document > "u" ? { session
5305
5416
  h.off(r, e);
5306
5417
  }
5307
5418
  };
5308
- function Hs(r, e) {
5419
+ function xs(r, e) {
5309
5420
  if (!(typeof window > "u" || typeof document > "u")) {
5310
5421
  if (typeof e != "function")
5311
5422
  throw new Error(`[TraceLog] Transformer must be a function, received: ${typeof e}`);
@@ -5314,23 +5425,23 @@ function Hs(r, e) {
5314
5425
  t !== -1 && M.splice(t, 1), M.push({ hook: r, fn: e });
5315
5426
  return;
5316
5427
  }
5317
- if (T)
5428
+ if (_)
5318
5429
  throw new Error("[TraceLog] Cannot set transformers while TraceLog is being destroyed");
5319
5430
  r === "beforeSend" ? h.setTransformer("beforeSend", e) : h.setTransformer("beforeBatch", e);
5320
5431
  }
5321
5432
  }
5322
- const xs = (r) => {
5433
+ const $s = (r) => {
5323
5434
  if (!(typeof window > "u" || typeof document > "u")) {
5324
5435
  if (!h) {
5325
5436
  const e = M.findIndex((t) => t.hook === r);
5326
5437
  e !== -1 && M.splice(e, 1);
5327
5438
  return;
5328
5439
  }
5329
- if (T)
5440
+ if (_)
5330
5441
  throw new Error("[TraceLog] Cannot remove transformers while TraceLog is being destroyed");
5331
5442
  h.removeTransformer(r);
5332
5443
  }
5333
- }, $s = (r) => {
5444
+ }, Bs = (r) => {
5334
5445
  if (!(typeof window > "u" || typeof document > "u")) {
5335
5446
  if (typeof r != "function")
5336
5447
  throw new Error(`[TraceLog] Custom headers provider must be a function, received: ${typeof r}`);
@@ -5338,54 +5449,54 @@ const xs = (r) => {
5338
5449
  D = r;
5339
5450
  return;
5340
5451
  }
5341
- if (T)
5452
+ if (_)
5342
5453
  throw new Error("[TraceLog] Cannot set custom headers while TraceLog is being destroyed");
5343
5454
  h.setCustomHeaders(r);
5344
5455
  }
5345
- }, Bs = () => {
5456
+ }, Ws = () => {
5346
5457
  if (!(typeof window > "u" || typeof document > "u")) {
5347
5458
  if (!h) {
5348
5459
  D = null;
5349
5460
  return;
5350
5461
  }
5351
- if (T)
5462
+ if (_)
5352
5463
  throw new Error("[TraceLog] Cannot remove custom headers while TraceLog is being destroyed");
5353
5464
  h.removeCustomHeaders();
5354
5465
  }
5355
- }, Ws = () => typeof window > "u" || typeof document > "u" ? !1 : h !== null, Xs = () => typeof window > "u" || typeof document > "u" || !h ? null : h.getSessionId(), Gs = () => {
5466
+ }, Gs = () => typeof window > "u" || typeof document > "u" ? !1 : h !== null, Xs = () => typeof window > "u" || typeof document > "u" || !h ? null : h.getSessionId(), js = () => {
5356
5467
  if (!(typeof window > "u" || typeof document > "u")) {
5357
- if (T)
5468
+ if (_)
5358
5469
  throw new Error("[TraceLog] Destroy operation already in progress");
5359
5470
  if (!h) {
5360
- T = !1;
5471
+ _ = !1;
5361
5472
  return;
5362
5473
  }
5363
- T = !0;
5474
+ _ = !0;
5364
5475
  try {
5365
- h.destroy(), h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, T = !1;
5476
+ h.destroy(), h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, _ = !1;
5366
5477
  } catch (r) {
5367
- h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, T = !1, a("warn", "Error during destroy, forced cleanup completed", { error: r });
5478
+ h = null, R = !1, P = null, k.length = 0, M.length = 0, D = null, _ = !1, a("warn", "Error during destroy, forced cleanup completed", { error: r });
5368
5479
  }
5369
5480
  }
5370
- }, js = (r) => {
5481
+ }, Ks = (r) => {
5371
5482
  typeof window > "u" || typeof document > "u" || rs(r);
5372
5483
  }, zs = (r) => {
5373
5484
  if (!(typeof window > "u" || typeof document > "u")) {
5374
5485
  if (!h)
5375
5486
  throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");
5376
- if (T)
5487
+ if (_)
5377
5488
  throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");
5378
5489
  h.updateGlobalMetadata(r);
5379
5490
  }
5380
- }, Ks = (r) => {
5491
+ }, Qs = (r) => {
5381
5492
  if (!(typeof window > "u" || typeof document > "u")) {
5382
5493
  if (!h)
5383
5494
  throw new Error("[TraceLog] TraceLog not initialized. Please call init() first.");
5384
- if (T)
5495
+ if (_)
5385
5496
  throw new Error("[TraceLog] Cannot update metadata while TraceLog is being destroyed");
5386
5497
  h.mergeGlobalMetadata(r);
5387
5498
  }
5388
- }, Qs = (r, e) => {
5499
+ }, Ys = (r, e) => {
5389
5500
  if (!(typeof window > "u" || typeof document > "u")) {
5390
5501
  if (!r || typeof r != "string" || r.trim().length === 0) {
5391
5502
  a("warn", "identify() called with invalid userId");
@@ -5395,7 +5506,7 @@ const xs = (r) => {
5395
5506
  a("warn", "identify() userId exceeds 256 characters");
5396
5507
  return;
5397
5508
  }
5398
- if (T) {
5509
+ if (_) {
5399
5510
  a("warn", "Cannot identify while TraceLog is being destroyed");
5400
5511
  return;
5401
5512
  }
@@ -5408,61 +5519,61 @@ const xs = (r) => {
5408
5519
  userId: r.trim(),
5409
5520
  ...t ? { traits: t } : {}
5410
5521
  };
5411
- localStorage.setItem(U, JSON.stringify(s)), a("debug", "Identity persisted pre-init (will be applied on init)");
5522
+ localStorage.setItem(F, JSON.stringify(s)), a("debug", "Identity persisted pre-init (will be applied on init)");
5412
5523
  } catch {
5413
5524
  a("debug", "Failed to persist pre-init identity");
5414
5525
  }
5415
5526
  }
5416
- }, Ys = async () => {
5527
+ }, qs = async () => {
5417
5528
  if (!(typeof window > "u" || typeof document > "u")) {
5418
5529
  if (!h) {
5419
5530
  try {
5420
- localStorage.removeItem(U);
5531
+ localStorage.removeItem(F);
5421
5532
  } catch {
5422
5533
  }
5423
5534
  return;
5424
5535
  }
5425
- if (T)
5536
+ if (_)
5426
5537
  throw new Error("[TraceLog] Cannot reset identity while TraceLog is being destroyed");
5427
5538
  await h.resetIdentity();
5428
5539
  }
5429
- }, br = {
5430
- init: ks,
5431
- event: Vs,
5432
- on: Us,
5433
- off: Fs,
5434
- setTransformer: Hs,
5435
- removeTransformer: xs,
5436
- setCustomHeaders: $s,
5437
- removeCustomHeaders: Bs,
5438
- isInitialized: Ws,
5540
+ }, Lr = {
5541
+ init: Vs,
5542
+ event: Us,
5543
+ on: Fs,
5544
+ off: Hs,
5545
+ setTransformer: xs,
5546
+ removeTransformer: $s,
5547
+ setCustomHeaders: Bs,
5548
+ removeCustomHeaders: Ws,
5549
+ isInitialized: Gs,
5439
5550
  getSessionId: Xs,
5440
- destroy: Gs,
5441
- setQaMode: js,
5551
+ destroy: js,
5552
+ setQaMode: Ks,
5442
5553
  updateGlobalMetadata: zs,
5443
- mergeGlobalMetadata: Ks,
5444
- identify: Qs,
5445
- resetIdentity: Ys
5554
+ mergeGlobalMetadata: Qs,
5555
+ identify: Ys,
5556
+ resetIdentity: qs
5446
5557
  };
5447
- var Le, C, G, Et, le, pt = -1, V = function(r) {
5558
+ var Ae, C, X, pt, le, Et = -1, V = function(r) {
5448
5559
  addEventListener("pageshow", (function(e) {
5449
- e.persisted && (pt = e.timeStamp, r(e));
5560
+ e.persisted && (Et = e.timeStamp, r(e));
5450
5561
  }), !0);
5451
- }, Pe = function() {
5562
+ }, De = function() {
5452
5563
  var r = self.performance && performance.getEntriesByType && performance.getEntriesByType("navigation")[0];
5453
5564
  if (r && r.responseStart > 0 && r.responseStart < performance.now()) return r;
5454
5565
  }, de = function() {
5455
- var r = Pe();
5566
+ var r = De();
5456
5567
  return r && r.activationStart || 0;
5457
5568
  }, y = function(r, e) {
5458
- var t = Pe(), s = "navigate";
5459
- return pt >= 0 ? s = "back-forward-cache" : t && (document.prerendering || de() > 0 ? s = "prerender" : document.wasDiscarded ? s = "restore" : t.type && (s = t.type.replace(/_/g, "-"))), { name: r, value: e === void 0 ? -1 : e, rating: "good", delta: 0, entries: [], id: "v4-".concat(Date.now(), "-").concat(Math.floor(8999999999999 * Math.random()) + 1e12), navigationType: s };
5460
- }, H = function(r, e, t) {
5569
+ var t = De(), s = "navigate";
5570
+ return Et >= 0 ? s = "back-forward-cache" : t && (document.prerendering || de() > 0 ? s = "prerender" : document.wasDiscarded ? s = "restore" : t.type && (s = t.type.replace(/_/g, "-"))), { name: r, value: e === void 0 ? -1 : e, rating: "good", delta: 0, entries: [], id: "v4-".concat(Date.now(), "-").concat(Math.floor(8999999999999 * Math.random()) + 1e12), navigationType: s };
5571
+ }, x = function(r, e, t) {
5461
5572
  try {
5462
5573
  if (PerformanceObserver.supportedEntryTypes.includes(r)) {
5463
- var s = new PerformanceObserver((function(i) {
5574
+ var s = new PerformanceObserver((function(n) {
5464
5575
  Promise.resolve().then((function() {
5465
- e(i.getEntries());
5576
+ e(n.getEntries());
5466
5577
  }));
5467
5578
  }));
5468
5579
  return s.observe(Object.assign({ type: r, buffered: !0 }, t || {})), s;
@@ -5470,19 +5581,19 @@ var Le, C, G, Et, le, pt = -1, V = function(r) {
5470
5581
  } catch {
5471
5582
  }
5472
5583
  }, w = function(r, e, t, s) {
5473
- var i, n;
5584
+ var n, i;
5474
5585
  return function(o) {
5475
- e.value >= 0 && (o || s) && ((n = e.value - (i || 0)) || i === void 0) && (i = e.value, e.delta = n, e.rating = (function(l, c) {
5476
- return l > c[1] ? "poor" : l > c[0] ? "needs-improvement" : "good";
5586
+ e.value >= 0 && (o || s) && ((i = e.value - (n || 0)) || n === void 0) && (n = e.value, e.delta = i, e.rating = (function(l, d) {
5587
+ return l > d[1] ? "poor" : l > d[0] ? "needs-improvement" : "good";
5477
5588
  })(e.value, t), r(e));
5478
5589
  };
5479
- }, De = function(r) {
5590
+ }, ke = function(r) {
5480
5591
  requestAnimationFrame((function() {
5481
5592
  return requestAnimationFrame((function() {
5482
5593
  return r();
5483
5594
  }));
5484
5595
  }));
5485
- }, z = function(r) {
5596
+ }, K = function(r) {
5486
5597
  document.addEventListener("visibilitychange", (function() {
5487
5598
  document.visibilityState === "hidden" && r();
5488
5599
  }));
@@ -5491,71 +5602,71 @@ var Le, C, G, Et, le, pt = -1, V = function(r) {
5491
5602
  return function() {
5492
5603
  e || (r(), e = !0);
5493
5604
  };
5494
- }, F = -1, et = function() {
5605
+ }, H = -1, et = function() {
5495
5606
  return document.visibilityState !== "hidden" || document.prerendering ? 1 / 0 : 0;
5496
5607
  }, ce = function(r) {
5497
- document.visibilityState === "hidden" && F > -1 && (F = r.type === "visibilitychange" ? r.timeStamp : 0, qs());
5608
+ document.visibilityState === "hidden" && H > -1 && (H = r.type === "visibilitychange" ? r.timeStamp : 0, Js());
5498
5609
  }, tt = function() {
5499
5610
  addEventListener("visibilitychange", ce, !0), addEventListener("prerenderingchange", ce, !0);
5500
- }, qs = function() {
5611
+ }, Js = function() {
5501
5612
  removeEventListener("visibilitychange", ce, !0), removeEventListener("prerenderingchange", ce, !0);
5502
- }, ke = function() {
5503
- return F < 0 && (F = et(), tt(), V((function() {
5613
+ }, Ve = function() {
5614
+ return H < 0 && (H = et(), tt(), V((function() {
5504
5615
  setTimeout((function() {
5505
- F = et(), tt();
5616
+ H = et(), tt();
5506
5617
  }), 0);
5507
5618
  }))), { get firstHiddenTime() {
5508
- return F;
5619
+ return H;
5509
5620
  } };
5510
- }, K = function(r) {
5621
+ }, z = function(r) {
5511
5622
  document.prerendering ? addEventListener("prerenderingchange", (function() {
5512
5623
  return r();
5513
5624
  }), !0) : r();
5514
- }, Ae = [1800, 3e3], St = function(r, e) {
5515
- e = e || {}, K((function() {
5516
- var t, s = ke(), i = y("FCP"), n = H("paint", (function(o) {
5625
+ }, Me = [1800, 3e3], St = function(r, e) {
5626
+ e = e || {}, z((function() {
5627
+ var t, s = Ve(), n = y("FCP"), i = x("paint", (function(o) {
5517
5628
  o.forEach((function(l) {
5518
- l.name === "first-contentful-paint" && (n.disconnect(), l.startTime < s.firstHiddenTime && (i.value = Math.max(l.startTime - de(), 0), i.entries.push(l), t(!0)));
5629
+ l.name === "first-contentful-paint" && (i.disconnect(), l.startTime < s.firstHiddenTime && (n.value = Math.max(l.startTime - de(), 0), n.entries.push(l), t(!0)));
5519
5630
  }));
5520
5631
  }));
5521
- n && (t = w(r, i, Ae, e.reportAllChanges), V((function(o) {
5522
- i = y("FCP"), t = w(r, i, Ae, e.reportAllChanges), De((function() {
5523
- i.value = performance.now() - o.timeStamp, t(!0);
5632
+ i && (t = w(r, n, Me, e.reportAllChanges), V((function(o) {
5633
+ n = y("FCP"), t = w(r, n, Me, e.reportAllChanges), ke((function() {
5634
+ n.value = performance.now() - o.timeStamp, t(!0);
5524
5635
  }));
5525
5636
  })));
5526
5637
  }));
5527
- }, Me = [0.1, 0.25], Js = function(r, e) {
5638
+ }, Ce = [0.1, 0.25], Zs = function(r, e) {
5528
5639
  e = e || {}, St(ue((function() {
5529
- var t, s = y("CLS", 0), i = 0, n = [], o = function(c) {
5530
- c.forEach((function(d) {
5531
- if (!d.hadRecentInput) {
5532
- var f = n[0], g = n[n.length - 1];
5533
- i && d.startTime - g.startTime < 1e3 && d.startTime - f.startTime < 5e3 ? (i += d.value, n.push(d)) : (i = d.value, n = [d]);
5640
+ var t, s = y("CLS", 0), n = 0, i = [], o = function(d) {
5641
+ d.forEach((function(c) {
5642
+ if (!c.hadRecentInput) {
5643
+ var f = i[0], g = i[i.length - 1];
5644
+ n && c.startTime - g.startTime < 1e3 && c.startTime - f.startTime < 5e3 ? (n += c.value, i.push(c)) : (n = c.value, i = [c]);
5534
5645
  }
5535
- })), i > s.value && (s.value = i, s.entries = n, t());
5536
- }, l = H("layout-shift", o);
5537
- l && (t = w(r, s, Me, e.reportAllChanges), z((function() {
5646
+ })), n > s.value && (s.value = n, s.entries = i, t());
5647
+ }, l = x("layout-shift", o);
5648
+ l && (t = w(r, s, Ce, e.reportAllChanges), K((function() {
5538
5649
  o(l.takeRecords()), t(!0);
5539
5650
  })), V((function() {
5540
- i = 0, s = y("CLS", 0), t = w(r, s, Me, e.reportAllChanges), De((function() {
5651
+ n = 0, s = y("CLS", 0), t = w(r, s, Ce, e.reportAllChanges), ke((function() {
5541
5652
  return t();
5542
5653
  }));
5543
5654
  })), setTimeout(t, 0));
5544
5655
  })));
5545
- }, Tt = 0, pe = 1 / 0, J = 0, Zs = function(r) {
5656
+ }, Tt = 0, Se = 1 / 0, J = 0, er = function(r) {
5546
5657
  r.forEach((function(e) {
5547
- e.interactionId && (pe = Math.min(pe, e.interactionId), J = Math.max(J, e.interactionId), Tt = J ? (J - pe) / 7 + 1 : 0);
5658
+ e.interactionId && (Se = Math.min(Se, e.interactionId), J = Math.max(J, e.interactionId), Tt = J ? (J - Se) / 7 + 1 : 0);
5548
5659
  }));
5549
5660
  }, It = function() {
5550
- return Le ? Tt : performance.interactionCount || 0;
5551
- }, er = function() {
5552
- "interactionCount" in performance || Le || (Le = H("event", Zs, { type: "event", buffered: !0, durationThreshold: 0 }));
5553
- }, L = [], te = /* @__PURE__ */ new Map(), vt = 0, tr = function() {
5554
- var r = Math.min(L.length - 1, Math.floor((It() - vt) / 50));
5661
+ return Ae ? Tt : performance.interactionCount || 0;
5662
+ }, tr = function() {
5663
+ "interactionCount" in performance || Ae || (Ae = x("event", er, { type: "event", buffered: !0, durationThreshold: 0 }));
5664
+ }, L = [], te = /* @__PURE__ */ new Map(), _t = 0, sr = function() {
5665
+ var r = Math.min(L.length - 1, Math.floor((It() - _t) / 50));
5555
5666
  return L[r];
5556
- }, sr = [], rr = function(r) {
5557
- if (sr.forEach((function(i) {
5558
- return i(r);
5667
+ }, rr = [], nr = function(r) {
5668
+ if (rr.forEach((function(n) {
5669
+ return n(r);
5559
5670
  })), r.interactionId || r.entryType === "first-input") {
5560
5671
  var e = L[L.length - 1], t = te.get(r.interactionId);
5561
5672
  if (t || L.length < 10 || r.duration > e.latency) {
@@ -5564,147 +5675,147 @@ var Le, C, G, Et, le, pt = -1, V = function(r) {
5564
5675
  var s = { id: r.interactionId, latency: r.duration, entries: [r] };
5565
5676
  te.set(s.id, s), L.push(s);
5566
5677
  }
5567
- L.sort((function(i, n) {
5568
- return n.latency - i.latency;
5569
- })), L.length > 10 && L.splice(10).forEach((function(i) {
5570
- return te.delete(i.id);
5678
+ L.sort((function(n, i) {
5679
+ return i.latency - n.latency;
5680
+ })), L.length > 10 && L.splice(10).forEach((function(n) {
5681
+ return te.delete(n.id);
5571
5682
  }));
5572
5683
  }
5573
5684
  }
5574
- }, _t = function(r) {
5685
+ }, vt = function(r) {
5575
5686
  var e = self.requestIdleCallback || self.setTimeout, t = -1;
5576
- return r = ue(r), document.visibilityState === "hidden" ? r() : (t = e(r), z(r)), t;
5577
- }, Ce = [200, 500], ir = function(r, e) {
5578
- "PerformanceEventTiming" in self && "interactionId" in PerformanceEventTiming.prototype && (e = e || {}, K((function() {
5687
+ return r = ue(r), document.visibilityState === "hidden" ? r() : (t = e(r), K(r)), t;
5688
+ }, Re = [200, 500], ir = function(r, e) {
5689
+ "PerformanceEventTiming" in self && "interactionId" in PerformanceEventTiming.prototype && (e = e || {}, z((function() {
5579
5690
  var t;
5580
- er();
5581
- var s, i = y("INP"), n = function(l) {
5582
- _t((function() {
5583
- l.forEach(rr);
5584
- var c = tr();
5585
- c && c.latency !== i.value && (i.value = c.latency, i.entries = c.entries, s());
5691
+ tr();
5692
+ var s, n = y("INP"), i = function(l) {
5693
+ vt((function() {
5694
+ l.forEach(nr);
5695
+ var d = sr();
5696
+ d && d.latency !== n.value && (n.value = d.latency, n.entries = d.entries, s());
5586
5697
  }));
5587
- }, o = H("event", n, { durationThreshold: (t = e.durationThreshold) !== null && t !== void 0 ? t : 40 });
5588
- s = w(r, i, Ce, e.reportAllChanges), o && (o.observe({ type: "first-input", buffered: !0 }), z((function() {
5589
- n(o.takeRecords()), s(!0);
5698
+ }, o = x("event", i, { durationThreshold: (t = e.durationThreshold) !== null && t !== void 0 ? t : 40 });
5699
+ s = w(r, n, Re, e.reportAllChanges), o && (o.observe({ type: "first-input", buffered: !0 }), K((function() {
5700
+ i(o.takeRecords()), s(!0);
5590
5701
  })), V((function() {
5591
- vt = It(), L.length = 0, te.clear(), i = y("INP"), s = w(r, i, Ce, e.reportAllChanges);
5702
+ _t = It(), L.length = 0, te.clear(), n = y("INP"), s = w(r, n, Re, e.reportAllChanges);
5592
5703
  })));
5593
5704
  })));
5594
- }, Re = [2500, 4e3], Se = {}, nr = function(r, e) {
5595
- e = e || {}, K((function() {
5596
- var t, s = ke(), i = y("LCP"), n = function(c) {
5597
- e.reportAllChanges || (c = c.slice(-1)), c.forEach((function(d) {
5598
- d.startTime < s.firstHiddenTime && (i.value = Math.max(d.startTime - de(), 0), i.entries = [d], t());
5705
+ }, Ne = [2500, 4e3], Te = {}, or = function(r, e) {
5706
+ e = e || {}, z((function() {
5707
+ var t, s = Ve(), n = y("LCP"), i = function(d) {
5708
+ e.reportAllChanges || (d = d.slice(-1)), d.forEach((function(c) {
5709
+ c.startTime < s.firstHiddenTime && (n.value = Math.max(c.startTime - de(), 0), n.entries = [c], t());
5599
5710
  }));
5600
- }, o = H("largest-contentful-paint", n);
5711
+ }, o = x("largest-contentful-paint", i);
5601
5712
  if (o) {
5602
- t = w(r, i, Re, e.reportAllChanges);
5713
+ t = w(r, n, Ne, e.reportAllChanges);
5603
5714
  var l = ue((function() {
5604
- Se[i.id] || (n(o.takeRecords()), o.disconnect(), Se[i.id] = !0, t(!0));
5715
+ Te[n.id] || (i(o.takeRecords()), o.disconnect(), Te[n.id] = !0, t(!0));
5605
5716
  }));
5606
- ["keydown", "click"].forEach((function(c) {
5607
- addEventListener(c, (function() {
5608
- return _t(l);
5717
+ ["keydown", "click"].forEach((function(d) {
5718
+ addEventListener(d, (function() {
5719
+ return vt(l);
5609
5720
  }), { once: !0, capture: !0 });
5610
- })), z(l), V((function(c) {
5611
- i = y("LCP"), t = w(r, i, Re, e.reportAllChanges), De((function() {
5612
- i.value = performance.now() - c.timeStamp, Se[i.id] = !0, t(!0);
5721
+ })), K(l), V((function(d) {
5722
+ n = y("LCP"), t = w(r, n, Ne, e.reportAllChanges), ke((function() {
5723
+ n.value = performance.now() - d.timeStamp, Te[n.id] = !0, t(!0);
5613
5724
  }));
5614
5725
  }));
5615
5726
  }
5616
5727
  }));
5617
- }, Ne = [800, 1800], or = function r(e) {
5618
- document.prerendering ? K((function() {
5728
+ }, Oe = [800, 1800], ar = function r(e) {
5729
+ document.prerendering ? z((function() {
5619
5730
  return r(e);
5620
5731
  })) : document.readyState !== "complete" ? addEventListener("load", (function() {
5621
5732
  return r(e);
5622
5733
  }), !0) : setTimeout(e, 0);
5623
- }, ar = function(r, e) {
5734
+ }, lr = function(r, e) {
5624
5735
  e = e || {};
5625
- var t = y("TTFB"), s = w(r, t, Ne, e.reportAllChanges);
5626
- or((function() {
5627
- var i = Pe();
5628
- i && (t.value = Math.max(i.responseStart - de(), 0), t.entries = [i], s(!0), V((function() {
5629
- t = y("TTFB", 0), (s = w(r, t, Ne, e.reportAllChanges))(!0);
5736
+ var t = y("TTFB"), s = w(r, t, Oe, e.reportAllChanges);
5737
+ ar((function() {
5738
+ var n = De();
5739
+ n && (t.value = Math.max(n.responseStart - de(), 0), t.entries = [n], s(!0), V((function() {
5740
+ t = y("TTFB", 0), (s = w(r, t, Oe, e.reportAllChanges))(!0);
5630
5741
  })));
5631
5742
  }));
5632
- }, W = { passive: !0, capture: !0 }, lr = /* @__PURE__ */ new Date(), st = function(r, e) {
5633
- C || (C = e, G = r, Et = /* @__PURE__ */ new Date(), wt(removeEventListener), yt());
5743
+ }, W = { passive: !0, capture: !0 }, cr = /* @__PURE__ */ new Date(), st = function(r, e) {
5744
+ C || (C = e, X = r, pt = /* @__PURE__ */ new Date(), wt(removeEventListener), yt());
5634
5745
  }, yt = function() {
5635
- if (G >= 0 && G < Et - lr) {
5636
- var r = { entryType: "first-input", name: C.type, target: C.target, cancelable: C.cancelable, startTime: C.timeStamp, processingStart: C.timeStamp + G };
5746
+ if (X >= 0 && X < pt - cr) {
5747
+ var r = { entryType: "first-input", name: C.type, target: C.target, cancelable: C.cancelable, startTime: C.timeStamp, processingStart: C.timeStamp + X };
5637
5748
  le.forEach((function(e) {
5638
5749
  e(r);
5639
5750
  })), le = [];
5640
5751
  }
5641
- }, cr = function(r) {
5752
+ }, dr = function(r) {
5642
5753
  if (r.cancelable) {
5643
5754
  var e = (r.timeStamp > 1e12 ? /* @__PURE__ */ new Date() : performance.now()) - r.timeStamp;
5644
5755
  r.type == "pointerdown" ? (function(t, s) {
5645
- var i = function() {
5756
+ var n = function() {
5646
5757
  st(t, s), o();
5647
- }, n = function() {
5758
+ }, i = function() {
5648
5759
  o();
5649
5760
  }, o = function() {
5650
- removeEventListener("pointerup", i, W), removeEventListener("pointercancel", n, W);
5761
+ removeEventListener("pointerup", n, W), removeEventListener("pointercancel", i, W);
5651
5762
  };
5652
- addEventListener("pointerup", i, W), addEventListener("pointercancel", n, W);
5763
+ addEventListener("pointerup", n, W), addEventListener("pointercancel", i, W);
5653
5764
  })(e, r) : st(e, r);
5654
5765
  }
5655
5766
  }, wt = function(r) {
5656
5767
  ["mousedown", "keydown", "touchstart", "pointerdown"].forEach((function(e) {
5657
- return r(e, cr, W);
5768
+ return r(e, dr, W);
5658
5769
  }));
5659
- }, Oe = [100, 300], dr = function(r, e) {
5660
- e = e || {}, K((function() {
5661
- var t, s = ke(), i = y("FID"), n = function(c) {
5662
- c.startTime < s.firstHiddenTime && (i.value = c.processingStart - c.startTime, i.entries.push(c), t(!0));
5663
- }, o = function(c) {
5664
- c.forEach(n);
5665
- }, l = H("first-input", o);
5666
- t = w(r, i, Oe, e.reportAllChanges), l && (z(ue((function() {
5770
+ }, Pe = [100, 300], ur = function(r, e) {
5771
+ e = e || {}, z((function() {
5772
+ var t, s = Ve(), n = y("FID"), i = function(d) {
5773
+ d.startTime < s.firstHiddenTime && (n.value = d.processingStart - d.startTime, n.entries.push(d), t(!0));
5774
+ }, o = function(d) {
5775
+ d.forEach(i);
5776
+ }, l = x("first-input", o);
5777
+ t = w(r, n, Pe, e.reportAllChanges), l && (K(ue((function() {
5667
5778
  o(l.takeRecords()), l.disconnect();
5668
5779
  }))), V((function() {
5669
- var c;
5670
- i = y("FID"), t = w(r, i, Oe, e.reportAllChanges), le = [], G = -1, C = null, wt(addEventListener), c = n, le.push(c), yt();
5780
+ var d;
5781
+ n = y("FID"), t = w(r, n, Pe, e.reportAllChanges), le = [], X = -1, C = null, wt(addEventListener), d = i, le.push(d), yt();
5671
5782
  })));
5672
5783
  }));
5673
5784
  };
5674
- const ur = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5785
+ const hr = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
5675
5786
  __proto__: null,
5676
- CLSThresholds: Me,
5677
- FCPThresholds: Ae,
5678
- FIDThresholds: Oe,
5679
- INPThresholds: Ce,
5680
- LCPThresholds: Re,
5681
- TTFBThresholds: Ne,
5682
- onCLS: Js,
5787
+ CLSThresholds: Ce,
5788
+ FCPThresholds: Me,
5789
+ FIDThresholds: Pe,
5790
+ INPThresholds: Re,
5791
+ LCPThresholds: Ne,
5792
+ TTFBThresholds: Oe,
5793
+ onCLS: Zs,
5683
5794
  onFCP: St,
5684
- onFID: dr,
5795
+ onFID: ur,
5685
5796
  onINP: ir,
5686
- onLCP: nr,
5687
- onTTFB: ar
5797
+ onLCP: or,
5798
+ onTTFB: lr
5688
5799
  }, Symbol.toStringTag, { value: "Module" }));
5689
5800
  export {
5690
- m as AppConfigValidationError,
5691
- hr as DEFAULT_SESSION_TIMEOUT,
5692
- _e as DEFAULT_WEB_VITALS_MODE,
5801
+ p as AppConfigValidationError,
5802
+ fr as DEFAULT_SESSION_TIMEOUT,
5803
+ ye as DEFAULT_WEB_VITALS_MODE,
5693
5804
  A as DeviceType,
5694
5805
  se as EmitterEvent,
5695
5806
  B as ErrorType,
5696
5807
  u as EventType,
5697
- yr as InitializationTimeoutError,
5808
+ wr as InitializationTimeoutError,
5698
5809
  N as IntegrationValidationError,
5699
- Ir as MAX_ARRAY_LENGTH,
5810
+ _r as MAX_ARRAY_LENGTH,
5700
5811
  Er as MAX_CUSTOM_EVENT_ARRAY_SIZE,
5701
- gr as MAX_CUSTOM_EVENT_KEYS,
5702
- fr as MAX_CUSTOM_EVENT_NAME_LENGTH,
5703
- mr as MAX_CUSTOM_EVENT_STRING_SIZE,
5704
- pr as MAX_NESTED_OBJECT_KEYS,
5705
- Sr as MAX_STRING_LENGTH,
5706
- Tr as MAX_STRING_LENGTH_IN_ARRAY,
5707
- ne as Mode,
5812
+ pr as MAX_CUSTOM_EVENT_KEYS,
5813
+ mr as MAX_CUSTOM_EVENT_NAME_LENGTH,
5814
+ gr as MAX_CUSTOM_EVENT_STRING_SIZE,
5815
+ Sr as MAX_NESTED_OBJECT_KEYS,
5816
+ Tr as MAX_STRING_LENGTH,
5817
+ Ir as MAX_STRING_LENGTH_IN_ARRAY,
5818
+ ie as Mode,
5708
5819
  at as PII_PATTERNS,
5709
5820
  O as PermanentError,
5710
5821
  re as RateLimitError,
@@ -5712,13 +5823,13 @@ export {
5712
5823
  Z as ScrollDirection,
5713
5824
  Pt as SessionTimeoutValidationError,
5714
5825
  $ as SpecialApiUrl,
5715
- ie as TimeoutError,
5826
+ ne as TimeoutError,
5716
5827
  j as TraceLogValidationError,
5717
- wr as WEB_VITALS_GOOD_THRESHOLDS,
5718
- Ke as WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS,
5828
+ br as WEB_VITALS_GOOD_THRESHOLDS,
5829
+ ze as WEB_VITALS_NEEDS_IMPROVEMENT_THRESHOLDS,
5719
5830
  Yt as WEB_VITALS_POOR_THRESHOLDS,
5720
5831
  Qe as getWebVitalsThresholds,
5721
5832
  vr as isPrimaryScrollEvent,
5722
- _r as isSecondaryScrollEvent,
5723
- br as tracelog
5833
+ yr as isSecondaryScrollEvent,
5834
+ Lr as tracelog
5724
5835
  };